3 * This is the Oracle database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use Wikimedia\AtEase\AtEase
;
25 use Wikimedia\Timestamp\ConvertibleTimestamp
;
26 use Wikimedia\Rdbms\Database
;
27 use Wikimedia\Rdbms\DatabaseDomain
;
28 use Wikimedia\Rdbms\Blob
;
29 use Wikimedia\Rdbms\ResultWrapper
;
30 use Wikimedia\Rdbms\IResultWrapper
;
31 use Wikimedia\Rdbms\DBConnectionError
;
32 use Wikimedia\Rdbms\DBUnexpectedError
;
33 use Wikimedia\Rdbms\DBExpectedError
;
38 class DatabaseOracle
extends Database
{
40 protected $mLastResult = null;
42 /** @var int The number of rows affected as an integer */
43 protected $mAffectedRows;
46 private $ignoreDupValOnIndex = false;
48 /** @var bool|array */
49 private $sequenceData = null;
51 /** @var string Character set for Oracle database */
52 private $defaultCharset = 'AL32UTF8';
55 private $mFieldInfoCache = [];
57 /** @var string[] Map of (reserved table name => alternate table name) */
58 private $keywordTableMap = [];
61 * @see Database::__construct()
62 * @param array $params Additional parameters include:
63 * - keywordTableMap : Map of reserved table names to alternative table names to use
65 public function __construct( array $params ) {
66 $this->keywordTableMap
= $params['keywordTableMap'] ??
[];
67 $params['tablePrefix'] = strtoupper( $params['tablePrefix'] );
68 parent
::__construct( $params );
71 function __destruct() {
73 AtEase
::suppressWarnings();
75 AtEase
::restoreWarnings();
83 function implicitGroupby() {
87 function implicitOrderby() {
91 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
92 if ( !function_exists( 'oci_connect' ) ) {
93 throw new DBConnectionError(
95 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
96 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
100 if ( $schema !== null ) {
101 // We use the *database* aspect of $domain for schema, not the domain schema
102 throw new DBExpectedError(
104 __CLASS__
. ": cannot use schema '$schema'; " .
105 "the database component '$dbName' is actually interpreted as the Oracle schema."
111 $this->password
= $password;
113 // Backward compatibility (server used to be null and TNS was supplied in dbname)
114 $this->server
= $dbName;
115 $realDatabase = $user;
117 // $server now holds the TNS endpoint
118 $this->server
= $server;
119 // $dbName is schema name if different from username
120 $realDatabase = $dbName ?
: $user;
123 if ( !strlen( $user ) ) { # e.g. the class is being loaded
127 $session_mode = ( $this->flags
& DBO_SYSDBA
) ? OCI_SYSDBA
: OCI_DEFAULT
;
129 Wikimedia\
suppressWarnings();
130 if ( $this->flags
& DBO_PERSISTENT
) {
131 $this->conn
= oci_pconnect(
135 $this->defaultCharset
,
138 } elseif ( $this->flags
& DBO_DEFAULT
) {
139 $this->conn
= oci_new_connect(
143 $this->defaultCharset
,
147 $this->conn
= oci_connect(
151 $this->defaultCharset
,
155 Wikimedia\restoreWarnings
();
157 if ( $this->user
!= $realDatabase ) {
158 // change current schema in session
159 $this->selectDB( $realDatabase );
161 $this->currentDomain
= new DatabaseDomain(
168 if ( !$this->conn
) {
169 throw new DBConnectionError( $this, $this->lastError() );
172 # removed putenv calls because they interfere with the system globaly
173 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
174 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
175 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
177 return (bool)$this->conn
;
181 * Closes a database connection, if it is open
182 * Returns success, true if already closed
185 protected function closeConnection() {
186 return oci_close( $this->conn
);
189 function execFlags() {
190 return $this->trxLevel() ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
195 * @return bool|mixed|ORAResult
197 protected function doQuery( $sql ) {
198 if ( !mb_check_encoding( (string)$sql, 'UTF-8' ) ) {
199 throw new DBUnexpectedError( $this, "SQL encoding is invalid\n$sql" );
202 // handle some oracle specifics
203 // remove AS column/table/subquery namings
204 if ( !$this->getFlag( DBO_DDLMODE
) ) {
205 $sql = preg_replace( '/ as /i', ' ', $sql );
208 // Oracle has issues with UNION clause if the statement includes LOB fields
209 // So we do a UNION ALL and then filter the results array with array_unique
210 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
211 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
212 // you have to select data from plan table after explain
213 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
217 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
223 Wikimedia\
suppressWarnings();
225 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
226 if ( $stmt === false ) {
227 $e = oci_error( $this->conn
);
228 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
233 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
234 $e = oci_error( $stmt );
235 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
236 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
242 Wikimedia\restoreWarnings
();
244 if ( $explain_count > 0 ) {
245 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
246 'WHERE statement_id = \'' . $explain_id . '\'' );
247 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
248 return new ORAResult( $this, $stmt, $union_unique );
250 $this->mAffectedRows
= oci_num_rows( $stmt );
256 function queryIgnore( $sql, $fname = '' ) {
257 return $this->query( $sql, $fname, true );
261 * Frees resources associated with the LOB descriptor
262 * @param IResultWrapper|ORAResult $res
264 function freeResult( $res ) {
265 ResultWrapper
::unwrap( $res )->free();
269 * @param IResultWrapper|ORAResult $res
270 * @return stdClass|bool
272 function fetchObject( $res ) {
273 return ResultWrapper
::unwrap( $res )->fetchObject();
277 * @param IResultWrapper|ORAResult $res
278 * @return stdClass|bool
280 function fetchRow( $res ) {
281 return ResultWrapper
::unwrap( $res )->fetchRow();
285 * @param IResultWrapper|ORAResult $res
288 function numRows( $res ) {
289 return ResultWrapper
::unwrap( $res )->numRows();
293 * @param IResultWrapper|ORAResult $res
296 function numFields( $res ) {
297 return ResultWrapper
::unwrap( $res )->numFields();
300 function fieldName( $stmt, $n ) {
301 return oci_field_name( $stmt, $n );
304 function insertId() {
305 $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
306 $row = $this->fetchRow( $res );
307 return is_null( $row[0] ) ?
null : (int)$row[0];
314 function dataSeek( $res, $row ) {
315 if ( $res instanceof ORAResult
) {
318 ResultWrapper
::unwrap( $res )->seek( $row );
322 function lastError() {
323 if ( $this->conn
=== false ) {
326 $e = oci_error( $this->conn
);
329 return $e['message'];
332 function lastErrno() {
333 if ( $this->conn
=== false ) {
336 $e = oci_error( $this->conn
);
342 protected function fetchAffectedRowCount() {
343 return $this->mAffectedRows
;
347 * Returns information about an index
348 * If errors are explicitly ignored, returns NULL on failure
349 * @param string $table
350 * @param string $index
351 * @param string $fname
354 function indexInfo( $table, $index, $fname = __METHOD__
) {
358 function indexUnique( $table, $index, $fname = __METHOD__
) {
362 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
363 if ( !count( $a ) ) {
367 if ( !is_array( $options ) ) {
368 $options = [ $options ];
371 if ( in_array( 'IGNORE', $options ) ) {
372 $this->ignoreDupValOnIndex
= true;
375 if ( !is_array( reset( $a ) ) ) {
379 foreach ( $a as &$row ) {
380 $this->insertOneRow( $table, $row, $fname );
383 if ( in_array( 'IGNORE', $options ) ) {
384 $this->ignoreDupValOnIndex
= false;
390 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
391 $col_info = $this->fieldInfoMulti( $table, $col );
392 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
395 if ( is_numeric( $col ) ) {
400 } elseif ( $includeCol ) {
404 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
408 if ( $val === 'NULL' ) {
412 if ( $val === null ) {
414 $col_info != false &&
415 $col_info->isNullable() == 0 &&
416 $col_info->defaultValue() != null
430 * @param string $table
432 * @param string $fname
434 * @throws DBUnexpectedError
436 private function insertOneRow( $table, $row, $fname ) {
437 $table = $this->tableName( $table );
438 // "INSERT INTO tables (a, b, c)"
439 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
442 // for each value, append ":key"
444 foreach ( $row as $col => &$val ) {
450 if ( $this->isQuotedIdentifier( $val ) ) {
451 $sql .= $this->removeIdentifierQuotes( $val );
454 $sql .= $this->fieldBindStatement( $table, $col, $val );
459 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
460 if ( $stmt === false ) {
461 $e = oci_error( $this->conn
);
462 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
466 foreach ( $row as $col => &$val ) {
467 $col_info = $this->fieldInfoMulti( $table, $col );
468 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
470 if ( $val === null ) {
471 // do nothing ... null was inserted in statement creation
472 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
473 if ( is_object( $val ) ) {
474 $val = $val->fetch();
477 // backward compatibility
479 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
480 strtolower( $val ) == 'infinity'
482 $val = $this->getInfinity();
485 $val = $this->getVerifiedUTF8( $val );
486 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
487 $e = oci_error( $stmt );
488 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
493 /** @var OCI_Lob[] $lob */
494 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
495 if ( $lob[$col] === false ) {
496 $e = oci_error( $stmt );
497 throw new DBUnexpectedError(
499 "Cannot create LOB descriptor: " . $e['message']
503 if ( is_object( $val ) ) {
504 $val = $val->fetch();
507 if ( $col_type == 'BLOB' ) {
508 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
509 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
511 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
512 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
517 Wikimedia\
suppressWarnings();
519 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
520 $e = oci_error( $stmt );
521 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
522 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
526 $this->mAffectedRows
= oci_num_rows( $stmt );
529 $this->mAffectedRows
= oci_num_rows( $stmt );
532 Wikimedia\restoreWarnings
();
534 if ( isset( $lob ) ) {
535 foreach ( $lob as $lob_v ) {
540 if ( !$this->trxLevel() ) {
541 oci_commit( $this->conn
);
544 return oci_free_statement( $stmt );
547 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
548 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
550 $destTable = $this->tableName( $destTable );
552 $sequenceData = $this->getSequenceData( $destTable );
553 if ( $sequenceData !== false &&
554 !isset( $varMap[$sequenceData['column']] )
556 $varMap[$sequenceData['column']] =
557 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
560 // count-alias subselect fields to avoid abigious definition errors
562 foreach ( $varMap as &$val ) {
563 $val .= ' field' . $i;
567 $selectSql = $this->selectSQLText(
569 array_values( $varMap ),
576 $sql = "INSERT INTO $destTable (" .
577 implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
579 if ( in_array( 'IGNORE', $insertOptions ) ) {
580 $this->ignoreDupValOnIndex
= true;
583 $this->query( $sql, $fname );
585 if ( in_array( 'IGNORE', $insertOptions ) ) {
586 $this->ignoreDupValOnIndex
= false;
590 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
593 if ( $rows === [] ) {
594 return true; // nothing to do
597 if ( !is_array( reset( $rows ) ) ) {
601 $sequenceData = $this->getSequenceData( $table );
602 if ( $sequenceData !== false ) {
603 // add sequence column to each list of columns, when not set
604 foreach ( $rows as &$row ) {
605 if ( !isset( $row[$sequenceData['column']] ) ) {
606 $row[$sequenceData['column']] =
607 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
608 $sequenceData['sequence'] . '\')' );
613 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
616 public function tableName( $name, $format = 'quoted' ) {
617 // Replace reserved words with better ones
618 $name = $this->remappedTableName( $name );
620 return strtoupper( parent
::tableName( $name, $format ) );
624 * @param string $name
625 * @return string Value of $name or remapped name if $name is a reserved keyword
627 public function remappedTableName( $name ) {
628 return $this->keywordTableMap
[$name] ??
$name;
631 function tableNameInternal( $name ) {
632 $name = $this->tableName( $name );
634 return preg_replace( '/.*\.(.*)/', '$1', $name );
638 * Return sequence_name if table has a sequence
640 * @param string $table
641 * @return string[]|bool
643 private function getSequenceData( $table ) {
644 if ( $this->sequenceData
== null ) {
645 $dbname = $this->currentDomain
->getDatabase();
646 $prefix = $this->currentDomain
->getTablePrefix();
647 // See https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm
648 $decodeArgs = [ 'atc.table_name' ]; // the switch
649 foreach ( $this->keywordTableMap
as $reserved => $alternative ) {
650 $search = strtoupper( $prefix . $alternative ); // case
651 $replace = strtoupper( $prefix . $reserved ); // result
652 $decodeArgs[] = $this->addQuotes( $search );
653 $decodeArgs[] = $this->addQuotes( $replace );
655 $decodeArgs[] = [ 'atc.table_name' ]; // default
656 $decodeArgs = implode( ', ', $decodeArgs );
658 $result = $this->doQuery(
659 "SELECT lower(asq.sequence_name), lower(atc.table_name), lower(atc.column_name)
660 FROM all_sequences asq, all_tab_columns atc
661 WHERE decode({$decodeArgs}) || '_' ||
662 atc.column_name || '_SEQ' = '{$prefix}' || asq.sequence_name
663 AND asq.sequence_owner = upper('{$dbname}')
664 AND atc.owner = upper('{$dbname}')"
667 while ( ( $row = $result->fetchRow() ) !== false ) {
668 $this->sequenceData
[$row[1]] = [
669 'sequence' => $row[0],
674 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
676 return $this->sequenceData
[$table] ??
false;
680 * Returns the size of a text field, or -1 for "unlimited"
682 * @param string $table
683 * @param string $field
686 function textFieldSize( $table, $field ) {
687 $fieldInfoData = $this->fieldInfo( $table, $field );
689 return $fieldInfoData->maxLength();
692 function limitResult( $sql, $limit, $offset = false ) {
693 if ( $offset === false ) {
697 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
700 function encodeBlob( $b ) {
701 return new Blob( $b );
704 function unionQueries( $sqls, $all ) {
705 $glue = ' UNION ALL ';
707 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
708 'FROM (' . implode( $glue, $sqls ) . ')';
711 function wasDeadlock() {
712 return $this->lastErrno() == 'OCI-00060';
715 function duplicateTableStructure( $oldName, $newName, $temporary = false,
718 $temporary = $temporary ?
'TRUE' : 'FALSE';
719 $tablePrefix = $this->currentDomain
->getTablePrefix();
721 $newName = strtoupper( $newName );
722 $oldName = strtoupper( $oldName );
724 $tabName = substr( $newName, strlen( $tablePrefix ) );
725 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
726 $newPrefix = strtoupper( $tablePrefix );
728 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
729 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
732 function listTables( $prefix = null, $fname = __METHOD__
) {
734 if ( !empty( $prefix ) ) {
735 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
738 $owner = strtoupper( $this->getDBname() );
739 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
740 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
742 // dirty code ... i know
744 $endArray[] = strtoupper( $prefix . 'MWUSER' );
745 $endArray[] = strtoupper( $prefix . 'PAGE' );
746 $endArray[] = strtoupper( $prefix . 'IMAGE' );
747 $fixedOrderTabs = $endArray;
748 while ( ( $row = $result->fetchRow() ) !== false ) {
749 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
750 $endArray[] = $row['table_name'];
757 public function dropTable( $tableName, $fName = __METHOD__
) {
758 $tableName = $this->tableName( $tableName );
759 if ( !$this->tableExists( $tableName ) ) {
763 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
766 public function timestamp( $ts = 0 ) {
767 $t = new ConvertibleTimestamp( $ts );
768 // Let errors bubble up to avoid putting garbage in the DB
769 return $t->getTimestamp( TS_ORACLE
);
773 * Return aggregated value function call
775 * @param array $valuedata
776 * @param string $valuename
779 public function aggregateValue( $valuedata, $valuename = 'value' ) {
784 * @return string Wikitext of a link to the server software's web site
786 public function getSoftwareLink() {
787 return '[{{int:version-db-oracle-url}} Oracle]';
791 * @return string Version information from the database
793 function getServerVersion() {
794 // better version number, fallback on driver
795 $rset = $this->doQuery(
796 'SELECT version FROM product_component_version ' .
797 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
799 $row = $rset->fetchRow();
801 return oci_server_version( $this->conn
);
804 return $row['version'];
808 * Query whether a given index exists
809 * @param string $table
810 * @param string $index
811 * @param string $fname
814 function indexExists( $table, $index, $fname = __METHOD__
) {
815 $table = $this->tableName( $table );
816 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
817 $index = strtoupper( $index );
818 $owner = strtoupper( $this->getDBname() );
819 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
820 $res = $this->doQuery( $sql );
822 $count = $res->numRows();
832 * Query whether a given table exists (in the given schema, or the default mw one if not given)
833 * @param string $table
834 * @param string $fname
837 function tableExists( $table, $fname = __METHOD__
) {
838 $table = $this->tableName( $table );
839 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
840 $owner = $this->addQuotes( strtoupper( $this->getDBname() ) );
841 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
842 $res = $this->doQuery( $sql );
843 if ( $res && $res->numRows() > 0 ) {
855 * Function translates mysql_fetch_field() functionality on ORACLE.
856 * Caching is present for reducing query time.
857 * For internal calls. Use fieldInfo for normal usage.
858 * Returns false if the field doesn't exist
860 * @param array|string $table
861 * @param string $field
862 * @return ORAField|ORAResult|false
864 private function fieldInfoMulti( $table, $field ) {
865 $field = strtoupper( $field );
866 if ( is_array( $table ) ) {
867 $table = array_map( [ $this, 'tableNameInternal' ], $table );
868 $tableWhere = 'IN (';
869 foreach ( $table as &$singleTable ) {
870 $singleTable = $this->removeIdentifierQuotes( $singleTable );
871 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
872 return $this->mFieldInfoCache
["$singleTable.$field"];
874 $tableWhere .= '\'' . $singleTable . '\',';
876 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
878 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
879 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
880 return $this->mFieldInfoCache
["$table.$field"];
882 $tableWhere = '= \'' . $table . '\'';
885 $fieldInfoStmt = oci_parse(
887 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
888 $tableWhere . ' and column_name = \'' . $field . '\''
890 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
891 $e = oci_error( $fieldInfoStmt );
892 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
896 $res = new ORAResult( $this, $fieldInfoStmt );
897 if ( $res->numRows() == 0 ) {
898 if ( is_array( $table ) ) {
899 foreach ( $table as &$singleTable ) {
900 $this->mFieldInfoCache
["$singleTable.$field"] = false;
903 $this->mFieldInfoCache
["$table.$field"] = false;
905 $fieldInfoTemp = null;
907 $fieldInfoTemp = new ORAField( $res->fetchRow() );
908 $table = $fieldInfoTemp->tableName();
909 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
913 return $fieldInfoTemp;
917 * @throws DBUnexpectedError
918 * @param string $table
919 * @param string $field
922 function fieldInfo( $table, $field ) {
923 if ( is_array( $table ) ) {
924 throw new DBUnexpectedError(
926 'DatabaseOracle::fieldInfo called with table array!'
930 return $this->fieldInfoMulti( $table, $field );
933 protected function doBegin( $fname = __METHOD__
) {
934 $this->query( 'SET CONSTRAINTS ALL DEFERRED' );
937 protected function doCommit( $fname = __METHOD__
) {
938 if ( $this->trxLevel() ) {
939 $ret = oci_commit( $this->conn
);
941 throw new DBUnexpectedError( $this, $this->lastError() );
943 $this->query( 'SET CONSTRAINTS ALL IMMEDIATE' );
947 protected function doRollback( $fname = __METHOD__
) {
948 if ( $this->trxLevel() ) {
949 oci_rollback( $this->conn
);
950 $ignoreErrors = true;
951 $this->query( 'SET CONSTRAINTS ALL IMMEDIATE', $fname, $ignoreErrors );
955 function sourceStream(
957 callable
$lineCallback = null,
958 callable
$resultCallback = null,
959 $fname = __METHOD__
, callable
$inputCallback = null
963 $dollarquote = false;
966 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
967 while ( !feof( $fp ) ) {
968 if ( $lineCallback ) {
971 $line = trim( fgets( $fp, 1024 ) );
972 $sl = strlen( $line ) - 1;
977 if ( $line[0] == '-' && $line[1] == '-' ) {
981 // Allow dollar quoting for function declarations
982 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
983 if ( $dollarquote ) {
984 $dollarquote = false;
985 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
990 } elseif ( !$dollarquote ) {
991 if ( $line[$sl] == ';' && ( $sl < 2 ||
$line[$sl - 1] != ';' ) ) {
993 $line = substr( $line, 0, $sl );
1003 $cmd = str_replace( ';;', ";", $cmd );
1004 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1005 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1006 $replacements[$defines[2]] = $defines[1];
1009 foreach ( $replacements as $mwVar => $scVar ) {
1010 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1013 $cmd = $this->replaceVars( $cmd );
1014 if ( $inputCallback ) {
1015 $inputCallback( $cmd );
1017 $res = $this->doQuery( $cmd );
1018 if ( $resultCallback ) {
1019 call_user_func( $resultCallback, $res, $this );
1022 if ( $res === false ) {
1023 $err = $this->lastError();
1025 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1037 protected function doSelectDomain( DatabaseDomain
$domain ) {
1038 if ( $domain->getSchema() !== null ) {
1039 // We use the *database* aspect of $domain for schema, not the domain schema
1040 throw new DBExpectedError(
1042 __CLASS__
. ": domain '{$domain->getId()}' has a schema component; " .
1043 "the database component is actually interpreted as the Oracle schema."
1047 $database = $domain->getDatabase();
1048 if ( $database === null ||
$database === $this->user
) {
1049 // Backward compatibility
1050 $this->currentDomain
= $domain;
1055 // https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj32268.html
1056 $encDatabase = $this->addIdentifierQuotes( strtoupper( $database ) );
1057 $sql = "ALTER SESSION SET CURRENT_SCHEMA=$encDatabase";
1058 $stmt = oci_parse( $this->conn
, $sql );
1059 Wikimedia\
suppressWarnings();
1060 $success = oci_execute( $stmt );
1061 Wikimedia\restoreWarnings
();
1063 // Update that domain fields on success (no exception thrown)
1064 $this->currentDomain
= $domain;
1066 $e = oci_error( $stmt );
1067 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1073 function strencode( $s ) {
1074 return str_replace( "'", "''", $s );
1077 function addQuotes( $s ) {
1078 return "'" . $this->strencode( $this->getVerifiedUTF8( $s ) ) . "'";
1081 public function addIdentifierQuotes( $s ) {
1082 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1089 public function removeIdentifierQuotes( $s ) {
1090 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1093 public function isQuotedIdentifier( $s ) {
1094 return strpos( $s, '/*Q*/' ) !== false;
1097 private function wrapFieldForWhere( $table, &$col, &$val ) {
1098 $col_info = $this->fieldInfoMulti( $table, $col );
1099 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1100 if ( $col_type == 'CLOB' ) {
1101 $col = 'TO_CHAR(' . $col . ')';
1102 $val = $this->getVerifiedUTF8( $val );
1103 } elseif ( $col_type == 'VARCHAR2' ) {
1104 $val = $this->getVerifiedUTF8( $val );
1108 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1110 foreach ( $conds as $col => $val ) {
1111 if ( is_array( $val ) ) {
1112 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1114 if ( is_numeric( $col ) && $parentCol != null ) {
1115 $this->wrapFieldForWhere( $table, $parentCol, $val );
1117 $this->wrapFieldForWhere( $table, $col, $val );
1119 $conds2[$col] = $val;
1126 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1127 $options = [], $join_conds = []
1129 if ( is_array( $conds ) ) {
1130 $conds = $this->wrapConditionsForWhere( $table, $conds );
1133 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1137 * Returns an optional USE INDEX clause to go after the table, and a
1138 * string to go at the end of the query
1140 * @param array $options An associative array of options to be turned into
1141 * an SQL query, valid keys are listed in the function.
1144 function makeSelectOptions( $options ) {
1145 $preLimitTail = $postLimitTail = '';
1149 foreach ( $options as $key => $option ) {
1150 if ( is_numeric( $key ) ) {
1151 $noKeyOptions[$option] = true;
1155 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1157 $preLimitTail .= $this->makeOrderBy( $options );
1159 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1160 $postLimitTail .= ' FOR UPDATE';
1163 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1164 $startOpts .= 'DISTINCT';
1167 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1168 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1173 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1174 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1179 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1182 public function delete( $table, $conds, $fname = __METHOD__
) {
1183 global $wgActorTableSchemaMigrationStage;
1185 if ( is_array( $conds ) ) {
1186 $conds = $this->wrapConditionsForWhere( $table, $conds );
1188 // a hack for deleting pages, users and images (which have non-nullable FKs)
1189 // all deletions on these tables have transactions so final failure rollbacks these updates
1190 // @todo: Normalize the schema to match MySQL, no special FKs and such
1191 $table = $this->tableName( $table );
1192 if ( $table == $this->tableName( 'user' ) &&
1193 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
)
1195 $this->update( 'archive', [ 'ar_user' => 0 ],
1196 [ 'ar_user' => $conds['user_id'] ], $fname );
1197 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1198 [ 'ipb_user' => $conds['user_id'] ], $fname );
1199 $this->update( 'image', [ 'img_user' => 0 ],
1200 [ 'img_user' => $conds['user_id'] ], $fname );
1201 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1202 [ 'oi_user' => $conds['user_id'] ], $fname );
1203 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1204 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1205 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1206 [ 'fa_user' => $conds['user_id'] ], $fname );
1207 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1208 [ 'us_user' => $conds['user_id'] ], $fname );
1209 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1210 [ 'rc_user' => $conds['user_id'] ], $fname );
1211 $this->update( 'logging', [ 'log_user' => 0 ],
1212 [ 'log_user' => $conds['user_id'] ], $fname );
1213 } elseif ( $table == $this->tableName( 'image' ) ) {
1214 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1215 [ 'oi_name' => $conds['img_name'] ], $fname );
1218 return parent
::delete( $table, $conds, $fname );
1222 * @param string $table
1223 * @param array $values
1224 * @param array $conds
1225 * @param string $fname
1226 * @param array $options
1228 * @throws DBUnexpectedError
1230 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1231 $table = $this->tableName( $table );
1232 $opts = $this->makeUpdateOptions( $options );
1233 $sql = "UPDATE $opts $table SET ";
1236 foreach ( $values as $col => &$val ) {
1237 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1240 $sqlSet = ', ' . $sqlSet;
1247 if ( $conds !== [] && $conds !== '*' ) {
1248 $conds = $this->wrapConditionsForWhere( $table, $conds );
1249 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1252 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
1253 if ( $stmt === false ) {
1254 $e = oci_error( $this->conn
);
1255 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1259 foreach ( $values as $col => &$val ) {
1260 $col_info = $this->fieldInfoMulti( $table, $col );
1261 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1263 if ( $val === null ) {
1264 // do nothing ... null was inserted in statement creation
1265 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1266 if ( is_object( $val ) ) {
1267 $val = $val->getData();
1271 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
1272 strtolower( $val ) == 'infinity'
1274 $val = '31-12-2030 12:00:00.000000';
1277 $val = $this->getVerifiedUTF8( $val );
1278 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1279 $e = oci_error( $stmt );
1280 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1285 /** @var OCI_Lob[] $lob */
1286 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
1287 if ( $lob[$col] === false ) {
1288 $e = oci_error( $stmt );
1289 throw new DBUnexpectedError(
1291 "Cannot create LOB descriptor: " . $e['message']
1295 if ( is_object( $val ) ) {
1296 $val = $val->getData();
1299 if ( $col_type == 'BLOB' ) {
1300 $lob[$col]->writeTemporary( $val );
1301 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1303 $lob[$col]->writeTemporary( $val );
1304 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1309 Wikimedia\
suppressWarnings();
1311 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1312 $e = oci_error( $stmt );
1313 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1314 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1318 $this->mAffectedRows
= oci_num_rows( $stmt );
1321 $this->mAffectedRows
= oci_num_rows( $stmt );
1324 Wikimedia\restoreWarnings
();
1326 if ( isset( $lob ) ) {
1327 foreach ( $lob as $lob_v ) {
1332 if ( !$this->trxLevel() ) {
1333 oci_commit( $this->conn
);
1336 return oci_free_statement( $stmt );
1339 function bitNot( $field ) {
1340 // expecting bit-fields smaller than 4bytes
1341 return 'BITNOT(' . $field . ')';
1344 function bitAnd( $fieldLeft, $fieldRight ) {
1345 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1348 function bitOr( $fieldLeft, $fieldRight ) {
1349 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1352 public function buildGroupConcatField(
1353 $delim, $table, $field, $conds = '', $join_conds = []
1355 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1357 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1360 public function buildSubstring( $input, $startPosition, $length = null ) {
1361 $this->assertBuildSubstringParams( $startPosition, $length );
1362 $params = [ $input, $startPosition ];
1363 if ( $length !== null ) {
1364 $params[] = $length;
1366 return 'SUBSTR(' . implode( ',', $params ) . ')';
1370 * @param string $field Field or column to cast
1374 public function buildStringCast( $field ) {
1375 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1378 public function getInfinity() {
1379 return '31-12-2030 12:00:00.000000';
1386 private function getVerifiedUTF8( $s ) {
1387 if ( mb_check_encoding( (string)$s, 'UTF-8' ) ) {
1391 throw new DBUnexpectedError( $this, "Non BLOB/CLOB field must be UTF-8." );