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\DBUnexpectedError
;
32 use Wikimedia\Rdbms\DBExpectedError
;
37 class DatabaseOracle
extends Database
{
39 protected $mLastResult = null;
41 /** @var int The number of rows affected as an integer */
42 protected $mAffectedRows;
45 private $ignoreDupValOnIndex = false;
47 /** @var bool|array */
48 private $sequenceData = null;
50 /** @var string Character set for Oracle database */
51 private $defaultCharset = 'AL32UTF8';
54 private $mFieldInfoCache = [];
56 /** @var string[] Map of (reserved table name => alternate table name) */
57 private $keywordTableMap = [];
60 * @see Database::__construct()
61 * @param array $params Additional parameters include:
62 * - keywordTableMap : Map of reserved table names to alternative table names to use
64 public function __construct( array $params ) {
65 $this->keywordTableMap
= $params['keywordTableMap'] ??
[];
66 $params['tablePrefix'] = strtoupper( $params['tablePrefix'] );
67 parent
::__construct( $params );
70 function __destruct() {
72 AtEase
::suppressWarnings();
74 AtEase
::restoreWarnings();
82 function implicitOrderby() {
86 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
87 if ( !function_exists( 'oci_connect' ) ) {
88 throw $this->newExceptionAfterConnectError(
89 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
90 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
97 if ( $schema !== null ) {
98 // This uses the *database* aspect of $domain for schema, not the domain schema
99 throw $this->newExceptionAfterConnectError(
100 "Got schema '$schema'; not supported. " .
101 "The database component '$dbName' is actually interpreted as the Oracle schema."
106 $this->password
= $password;
107 if ( strlen( $server ) ) {
108 // Transparent Network Substrate (TNS) endpoint
109 $this->server
= $server;
110 // Database name, defaulting to the user name
111 $realDatabase = strlen( $dbName ) ?
$dbName : $user;
113 // Backward compatibility; $server used to be null and $dbName was the TNS
114 $this->server
= $dbName;
115 $realDatabase = $user;
117 $session_mode = ( $this->flags
& DBO_SYSDBA
) ? OCI_SYSDBA
: OCI_DEFAULT
;
119 $this->installErrorHandler();
121 $this->conn
= $this->getFlag( DBO_PERSISTENT
)
126 $this->defaultCharset
,
133 $this->defaultCharset
,
136 } catch ( Exception
$e ) {
137 $this->restoreErrorHandler();
138 throw $this->newExceptionAfterConnectError( $e->getMessage() );
140 $error = $this->restoreErrorHandler();
142 if ( !$this->conn
) {
143 throw $this->newExceptionAfterConnectError( $error ?
: $this->lastError() );
147 if ( $this->user
!= $realDatabase ) {
148 // Change current schema for the entire session
149 $this->selectDomain( new DatabaseDomain(
151 $this->currentDomain
->getSchema(),
152 $this->currentDomain
->getTablePrefix()
155 $this->currentDomain
= new DatabaseDomain( $realDatabase, null, $tablePrefix );
158 'NLS_TIMESTAMP_FORMAT' => 'DD-MM-YYYY HH24:MI:SS.FF6',
159 'NLS_TIMESTAMP_TZ_FORMAT' => 'DD-MM-YYYY HH24:MI:SS.FF6',
160 'NLS_NUMERIC_CHARACTERS' => '.,'
162 foreach ( $set as $var => $val ) {
164 "ALTER SESSION SET {$var}=" . $this->addQuotes( $val ),
166 self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_NO_RETRY
169 } catch ( Exception
$e ) {
170 throw $this->newExceptionAfterConnectError( $e->getMessage() );
175 * Closes a database connection, if it is open
176 * Returns success, true if already closed
179 protected function closeConnection() {
180 return oci_close( $this->conn
);
183 function execFlags() {
184 return $this->trxLevel() ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
189 * @return bool|mixed|ORAResult
191 protected function doQuery( $sql ) {
192 if ( !mb_check_encoding( (string)$sql, 'UTF-8' ) ) {
193 throw new DBUnexpectedError( $this, "SQL encoding is invalid\n$sql" );
196 // handle some oracle specifics
197 // remove AS column/table/subquery namings
198 if ( !$this->getFlag( DBO_DDLMODE
) ) {
199 $sql = preg_replace( '/ as /i', ' ', $sql );
202 // Oracle has issues with UNION clause if the statement includes LOB fields
203 // So we do a UNION ALL and then filter the results array with array_unique
204 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
205 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
206 // you have to select data from plan table after explain
207 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
211 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
217 Wikimedia\
suppressWarnings();
219 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
220 if ( $stmt === false ) {
221 $e = oci_error( $this->conn
);
222 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
227 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
228 $e = oci_error( $stmt );
229 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
230 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
236 Wikimedia\restoreWarnings
();
238 if ( $explain_count > 0 ) {
239 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
240 'WHERE statement_id = \'' . $explain_id . '\'' );
241 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
242 return new ORAResult( $this, $stmt, $union_unique );
244 $this->mAffectedRows
= oci_num_rows( $stmt );
250 function queryIgnore( $sql, $fname = '' ) {
251 return $this->query( $sql, $fname, true );
255 * Frees resources associated with the LOB descriptor
256 * @param IResultWrapper|ORAResult $res
258 function freeResult( $res ) {
259 ResultWrapper
::unwrap( $res )->free();
263 * @param IResultWrapper|ORAResult $res
264 * @return stdClass|bool
266 function fetchObject( $res ) {
267 return ResultWrapper
::unwrap( $res )->fetchObject();
271 * @param IResultWrapper|ORAResult $res
272 * @return stdClass|bool
274 function fetchRow( $res ) {
275 return ResultWrapper
::unwrap( $res )->fetchRow();
279 * @param IResultWrapper|ORAResult $res
282 function numRows( $res ) {
283 return ResultWrapper
::unwrap( $res )->numRows();
287 * @param IResultWrapper|ORAResult $res
290 function numFields( $res ) {
291 return ResultWrapper
::unwrap( $res )->numFields();
294 function fieldName( $stmt, $n ) {
295 return oci_field_name( $stmt, $n );
298 function insertId() {
299 $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
300 $row = $this->fetchRow( $res );
301 return is_null( $row[0] ) ?
null : (int)$row[0];
308 function dataSeek( $res, $row ) {
309 if ( $res instanceof ORAResult
) {
312 ResultWrapper
::unwrap( $res )->seek( $row );
316 function lastError() {
317 if ( $this->conn
=== false ) {
320 $e = oci_error( $this->conn
);
323 return $e['message'];
326 function lastErrno() {
327 if ( $this->conn
=== false ) {
330 $e = oci_error( $this->conn
);
336 protected function fetchAffectedRowCount() {
337 return $this->mAffectedRows
;
341 * Returns information about an index
342 * If errors are explicitly ignored, returns NULL on failure
343 * @param string $table
344 * @param string $index
345 * @param string $fname
348 function indexInfo( $table, $index, $fname = __METHOD__
) {
352 function indexUnique( $table, $index, $fname = __METHOD__
) {
356 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
357 if ( !count( $a ) ) {
361 if ( !is_array( $options ) ) {
362 $options = [ $options ];
365 if ( in_array( 'IGNORE', $options ) ) {
366 $this->ignoreDupValOnIndex
= true;
369 if ( !is_array( reset( $a ) ) ) {
373 foreach ( $a as &$row ) {
374 $this->insertOneRow( $table, $row, $fname );
377 if ( in_array( 'IGNORE', $options ) ) {
378 $this->ignoreDupValOnIndex
= false;
384 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
385 $col_info = $this->fieldInfoMulti( $table, $col );
386 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
389 if ( is_numeric( $col ) ) {
394 } elseif ( $includeCol ) {
398 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
402 if ( $val === 'NULL' ) {
406 if ( $val === null ) {
408 $col_info != false &&
409 $col_info->isNullable() == 0 &&
410 $col_info->defaultValue() != null
424 * @param string $table
426 * @param string $fname
428 * @throws DBUnexpectedError
430 private function insertOneRow( $table, $row, $fname ) {
431 $table = $this->tableName( $table );
432 // "INSERT INTO tables (a, b, c)"
433 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
436 // for each value, append ":key"
438 foreach ( $row as $col => &$val ) {
444 if ( $this->isQuotedIdentifier( $val ) ) {
445 $sql .= $this->removeIdentifierQuotes( $val );
448 $sql .= $this->fieldBindStatement( $table, $col, $val );
453 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
454 if ( $stmt === false ) {
455 $e = oci_error( $this->conn
);
456 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
460 foreach ( $row as $col => &$val ) {
461 $col_info = $this->fieldInfoMulti( $table, $col );
462 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
464 if ( $val === null ) {
465 // do nothing ... null was inserted in statement creation
466 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
467 if ( is_object( $val ) ) {
468 $val = $val->fetch();
471 // backward compatibility
473 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
474 strtolower( $val ) == 'infinity'
476 $val = $this->getInfinity();
479 $val = $this->getVerifiedUTF8( $val );
480 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
481 $e = oci_error( $stmt );
482 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
487 /** @var OCI_Lob[] $lob */
488 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
489 if ( $lob[$col] === false ) {
490 $e = oci_error( $stmt );
491 throw new DBUnexpectedError(
493 "Cannot create LOB descriptor: " . $e['message']
497 if ( is_object( $val ) ) {
498 $val = $val->fetch();
501 if ( $col_type == 'BLOB' ) {
502 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
503 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
505 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
506 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
511 Wikimedia\
suppressWarnings();
513 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
514 $e = oci_error( $stmt );
515 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
516 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
520 $this->mAffectedRows
= oci_num_rows( $stmt );
523 $this->mAffectedRows
= oci_num_rows( $stmt );
526 Wikimedia\restoreWarnings
();
528 if ( isset( $lob ) ) {
529 foreach ( $lob as $lob_v ) {
534 if ( !$this->trxLevel() ) {
535 oci_commit( $this->conn
);
538 return oci_free_statement( $stmt );
541 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
542 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
544 $destTable = $this->tableName( $destTable );
546 $sequenceData = $this->getSequenceData( $destTable );
547 if ( $sequenceData !== false &&
548 !isset( $varMap[$sequenceData['column']] )
550 $varMap[$sequenceData['column']] =
551 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
554 // count-alias subselect fields to avoid abigious definition errors
556 foreach ( $varMap as &$val ) {
557 $val .= ' field' . $i;
561 $selectSql = $this->selectSQLText(
563 array_values( $varMap ),
570 $sql = "INSERT INTO $destTable (" .
571 implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
573 if ( in_array( 'IGNORE', $insertOptions ) ) {
574 $this->ignoreDupValOnIndex
= true;
577 $this->query( $sql, $fname );
579 if ( in_array( 'IGNORE', $insertOptions ) ) {
580 $this->ignoreDupValOnIndex
= false;
584 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
587 if ( $rows === [] ) {
588 return true; // nothing to do
591 if ( !is_array( reset( $rows ) ) ) {
595 $sequenceData = $this->getSequenceData( $table );
596 if ( $sequenceData !== false ) {
597 // add sequence column to each list of columns, when not set
598 foreach ( $rows as &$row ) {
599 if ( !isset( $row[$sequenceData['column']] ) ) {
600 $row[$sequenceData['column']] =
601 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
602 $sequenceData['sequence'] . '\')' );
607 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
610 public function tableName( $name, $format = 'quoted' ) {
611 // Replace reserved words with better ones
612 $name = $this->remappedTableName( $name );
614 return strtoupper( parent
::tableName( $name, $format ) );
618 * @param string $name
619 * @return string Value of $name or remapped name if $name is a reserved keyword
621 public function remappedTableName( $name ) {
622 return $this->keywordTableMap
[$name] ??
$name;
625 function tableNameInternal( $name ) {
626 $name = $this->tableName( $name );
628 return preg_replace( '/.*\.(.*)/', '$1', $name );
632 * Return sequence_name if table has a sequence
634 * @param string $table
635 * @return string[]|bool
637 private function getSequenceData( $table ) {
638 if ( $this->sequenceData
== null ) {
639 $dbname = $this->currentDomain
->getDatabase();
640 $prefix = $this->currentDomain
->getTablePrefix();
641 // See https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm
642 $decodeArgs = [ 'atc.table_name' ]; // the switch
643 foreach ( $this->keywordTableMap
as $reserved => $alternative ) {
644 $search = strtoupper( $prefix . $alternative ); // case
645 $replace = strtoupper( $prefix . $reserved ); // result
646 $decodeArgs[] = $this->addQuotes( $search );
647 $decodeArgs[] = $this->addQuotes( $replace );
649 $decodeArgs[] = [ 'atc.table_name' ]; // default
650 $decodeArgs = implode( ', ', $decodeArgs );
652 $result = $this->doQuery(
653 "SELECT lower(asq.sequence_name), lower(atc.table_name), lower(atc.column_name)
654 FROM all_sequences asq, all_tab_columns atc
655 WHERE decode({$decodeArgs}) || '_' ||
656 atc.column_name || '_SEQ' = '{$prefix}' || asq.sequence_name
657 AND asq.sequence_owner = upper('{$dbname}')
658 AND atc.owner = upper('{$dbname}')"
661 while ( ( $row = $result->fetchRow() ) !== false ) {
662 $this->sequenceData
[$row[1]] = [
663 'sequence' => $row[0],
668 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
670 return $this->sequenceData
[$table] ??
false;
674 * Returns the size of a text field, or -1 for "unlimited"
676 * @param string $table
677 * @param string $field
680 function textFieldSize( $table, $field ) {
681 $fieldInfoData = $this->fieldInfo( $table, $field );
683 return $fieldInfoData->maxLength();
686 function limitResult( $sql, $limit, $offset = false ) {
687 if ( $offset === false ) {
691 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
694 function encodeBlob( $b ) {
695 return new Blob( $b );
698 function unionQueries( $sqls, $all ) {
699 $glue = ' UNION ALL ';
701 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
702 'FROM (' . implode( $glue, $sqls ) . ')';
705 function wasDeadlock() {
706 return $this->lastErrno() == 'OCI-00060';
709 function duplicateTableStructure( $oldName, $newName, $temporary = false,
712 $temporary = $temporary ?
'TRUE' : 'FALSE';
713 $tablePrefix = $this->currentDomain
->getTablePrefix();
715 $newName = strtoupper( $newName );
716 $oldName = strtoupper( $oldName );
718 $tabName = substr( $newName, strlen( $tablePrefix ) );
719 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
720 $newPrefix = strtoupper( $tablePrefix );
722 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
723 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
726 function listTables( $prefix = null, $fname = __METHOD__
) {
728 if ( !empty( $prefix ) ) {
729 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
732 $owner = strtoupper( $this->getDBname() );
733 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
734 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
736 // dirty code ... i know
738 $endArray[] = strtoupper( $prefix . 'MWUSER' );
739 $endArray[] = strtoupper( $prefix . 'PAGE' );
740 $endArray[] = strtoupper( $prefix . 'IMAGE' );
741 $fixedOrderTabs = $endArray;
742 while ( ( $row = $result->fetchRow() ) !== false ) {
743 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
744 $endArray[] = $row['table_name'];
751 public function dropTable( $tableName, $fName = __METHOD__
) {
752 $tableName = $this->tableName( $tableName );
753 if ( !$this->tableExists( $tableName ) ) {
757 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
760 public function timestamp( $ts = 0 ) {
761 $t = new ConvertibleTimestamp( $ts );
762 // Let errors bubble up to avoid putting garbage in the DB
763 return $t->getTimestamp( TS_ORACLE
);
767 * Return aggregated value function call
769 * @param array $valuedata
770 * @param string $valuename
773 public function aggregateValue( $valuedata, $valuename = 'value' ) {
778 * @return string Wikitext of a link to the server software's web site
780 public function getSoftwareLink() {
781 return '[{{int:version-db-oracle-url}} Oracle]';
785 * @return string Version information from the database
787 function getServerVersion() {
788 // better version number, fallback on driver
789 $rset = $this->doQuery(
790 'SELECT version FROM product_component_version ' .
791 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
793 $row = $rset->fetchRow();
795 return oci_server_version( $this->conn
);
798 return $row['version'];
802 * Query whether a given index exists
803 * @param string $table
804 * @param string $index
805 * @param string $fname
808 function indexExists( $table, $index, $fname = __METHOD__
) {
809 $table = $this->tableName( $table );
810 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
811 $index = strtoupper( $index );
812 $owner = strtoupper( $this->getDBname() );
813 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
814 $res = $this->doQuery( $sql );
816 $count = $res->numRows();
826 * Query whether a given table exists (in the given schema, or the default mw one if not given)
827 * @param string $table
828 * @param string $fname
831 function tableExists( $table, $fname = __METHOD__
) {
832 $table = $this->tableName( $table );
833 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
834 $owner = $this->addQuotes( strtoupper( $this->getDBname() ) );
835 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
836 $res = $this->doQuery( $sql );
837 if ( $res && $res->numRows() > 0 ) {
849 * Function translates mysql_fetch_field() functionality on ORACLE.
850 * Caching is present for reducing query time.
851 * For internal calls. Use fieldInfo for normal usage.
852 * Returns false if the field doesn't exist
854 * @param array|string $table
855 * @param string $field
856 * @return ORAField|ORAResult|false
858 private function fieldInfoMulti( $table, $field ) {
859 $field = strtoupper( $field );
860 if ( is_array( $table ) ) {
861 $table = array_map( [ $this, 'tableNameInternal' ], $table );
862 $tableWhere = 'IN (';
863 foreach ( $table as &$singleTable ) {
864 $singleTable = $this->removeIdentifierQuotes( $singleTable );
865 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
866 return $this->mFieldInfoCache
["$singleTable.$field"];
868 $tableWhere .= '\'' . $singleTable . '\',';
870 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
872 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
873 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
874 return $this->mFieldInfoCache
["$table.$field"];
876 $tableWhere = '= \'' . $table . '\'';
879 $fieldInfoStmt = oci_parse(
881 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
882 $tableWhere . ' and column_name = \'' . $field . '\''
884 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
885 $e = oci_error( $fieldInfoStmt );
886 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
890 $res = new ORAResult( $this, $fieldInfoStmt );
891 if ( $res->numRows() == 0 ) {
892 if ( is_array( $table ) ) {
893 foreach ( $table as &$singleTable ) {
894 $this->mFieldInfoCache
["$singleTable.$field"] = false;
897 $this->mFieldInfoCache
["$table.$field"] = false;
899 $fieldInfoTemp = null;
901 $fieldInfoTemp = new ORAField( $res->fetchRow() );
902 $table = $fieldInfoTemp->tableName();
903 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
907 return $fieldInfoTemp;
911 * @throws DBUnexpectedError
912 * @param string $table
913 * @param string $field
916 function fieldInfo( $table, $field ) {
917 if ( is_array( $table ) ) {
918 throw new DBUnexpectedError(
920 'DatabaseOracle::fieldInfo called with table array!'
924 return $this->fieldInfoMulti( $table, $field );
927 protected function doBegin( $fname = __METHOD__
) {
928 $this->query( 'SET CONSTRAINTS ALL DEFERRED' );
931 protected function doCommit( $fname = __METHOD__
) {
932 if ( $this->trxLevel() ) {
933 $ret = oci_commit( $this->conn
);
935 throw new DBUnexpectedError( $this, $this->lastError() );
937 $this->query( 'SET CONSTRAINTS ALL IMMEDIATE' );
941 protected function doRollback( $fname = __METHOD__
) {
942 if ( $this->trxLevel() ) {
943 oci_rollback( $this->conn
);
944 $ignoreErrors = true;
945 $this->query( 'SET CONSTRAINTS ALL IMMEDIATE', $fname, $ignoreErrors );
949 function sourceStream(
951 callable
$lineCallback = null,
952 callable
$resultCallback = null,
953 $fname = __METHOD__
, callable
$inputCallback = null
957 $dollarquote = false;
960 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
961 while ( !feof( $fp ) ) {
962 if ( $lineCallback ) {
965 $line = trim( fgets( $fp, 1024 ) );
966 $sl = strlen( $line ) - 1;
971 if ( $line[0] == '-' && $line[1] == '-' ) {
975 // Allow dollar quoting for function declarations
976 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
977 if ( $dollarquote ) {
978 $dollarquote = false;
979 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
984 } elseif ( !$dollarquote ) {
985 if ( $line[$sl] == ';' && ( $sl < 2 ||
$line[$sl - 1] != ';' ) ) {
987 $line = substr( $line, 0, $sl );
997 $cmd = str_replace( ';;', ";", $cmd );
998 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
999 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1000 $replacements[$defines[2]] = $defines[1];
1003 foreach ( $replacements as $mwVar => $scVar ) {
1004 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1007 $cmd = $this->replaceVars( $cmd );
1008 if ( $inputCallback ) {
1009 $inputCallback( $cmd );
1011 $res = $this->doQuery( $cmd );
1012 if ( $resultCallback ) {
1013 call_user_func( $resultCallback, $res, $this );
1016 if ( $res === false ) {
1017 $err = $this->lastError();
1019 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1031 protected function doSelectDomain( DatabaseDomain
$domain ) {
1032 if ( $domain->getSchema() !== null ) {
1033 // We use the *database* aspect of $domain for schema, not the domain schema
1034 throw new DBExpectedError(
1036 __CLASS__
. ": domain '{$domain->getId()}' has a schema component; " .
1037 "the database component is actually interpreted as the Oracle schema."
1041 $database = $domain->getDatabase();
1042 if ( $database === null ||
$database === $this->user
) {
1043 // Backward compatibility
1044 $this->currentDomain
= $domain;
1049 // https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj32268.html
1050 $encDatabase = $this->addIdentifierQuotes( strtoupper( $database ) );
1051 $sql = "ALTER SESSION SET CURRENT_SCHEMA=$encDatabase";
1052 $stmt = oci_parse( $this->conn
, $sql );
1053 Wikimedia\
suppressWarnings();
1054 $success = oci_execute( $stmt );
1055 Wikimedia\restoreWarnings
();
1057 // Update that domain fields on success (no exception thrown)
1058 $this->currentDomain
= $domain;
1060 $e = oci_error( $stmt );
1061 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1067 function strencode( $s ) {
1068 return str_replace( "'", "''", $s );
1071 function addQuotes( $s ) {
1072 return "'" . $this->strencode( $this->getVerifiedUTF8( $s ) ) . "'";
1075 public function addIdentifierQuotes( $s ) {
1076 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1083 public function removeIdentifierQuotes( $s ) {
1084 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1087 public function isQuotedIdentifier( $s ) {
1088 return strpos( $s, '/*Q*/' ) !== false;
1091 private function wrapFieldForWhere( $table, &$col, &$val ) {
1092 $col_info = $this->fieldInfoMulti( $table, $col );
1093 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1094 if ( $col_type == 'CLOB' ) {
1095 $col = 'TO_CHAR(' . $col . ')';
1096 $val = $this->getVerifiedUTF8( $val );
1097 } elseif ( $col_type == 'VARCHAR2' ) {
1098 $val = $this->getVerifiedUTF8( $val );
1102 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1104 foreach ( $conds as $col => $val ) {
1105 if ( is_array( $val ) ) {
1106 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1108 if ( is_numeric( $col ) && $parentCol != null ) {
1109 $this->wrapFieldForWhere( $table, $parentCol, $val );
1111 $this->wrapFieldForWhere( $table, $col, $val );
1113 $conds2[$col] = $val;
1120 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1121 $options = [], $join_conds = []
1123 if ( is_array( $conds ) ) {
1124 $conds = $this->wrapConditionsForWhere( $table, $conds );
1127 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1131 * Returns an optional USE INDEX clause to go after the table, and a
1132 * string to go at the end of the query
1134 * @param array $options An associative array of options to be turned into
1135 * an SQL query, valid keys are listed in the function.
1138 function makeSelectOptions( $options ) {
1139 $preLimitTail = $postLimitTail = '';
1143 foreach ( $options as $key => $option ) {
1144 if ( is_numeric( $key ) ) {
1145 $noKeyOptions[$option] = true;
1149 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1151 $preLimitTail .= $this->makeOrderBy( $options );
1153 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1154 $postLimitTail .= ' FOR UPDATE';
1157 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1158 $startOpts .= 'DISTINCT';
1161 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1162 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1167 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1168 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1173 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1176 public function delete( $table, $conds, $fname = __METHOD__
) {
1177 global $wgActorTableSchemaMigrationStage;
1179 if ( is_array( $conds ) ) {
1180 $conds = $this->wrapConditionsForWhere( $table, $conds );
1182 // a hack for deleting pages, users and images (which have non-nullable FKs)
1183 // all deletions on these tables have transactions so final failure rollbacks these updates
1184 // @todo: Normalize the schema to match MySQL, no special FKs and such
1185 $table = $this->tableName( $table );
1186 if ( $table == $this->tableName( 'user' ) &&
1187 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
)
1189 $this->update( 'archive', [ 'ar_user' => 0 ],
1190 [ 'ar_user' => $conds['user_id'] ], $fname );
1191 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1192 [ 'ipb_user' => $conds['user_id'] ], $fname );
1193 $this->update( 'image', [ 'img_user' => 0 ],
1194 [ 'img_user' => $conds['user_id'] ], $fname );
1195 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1196 [ 'oi_user' => $conds['user_id'] ], $fname );
1197 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1198 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1199 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1200 [ 'fa_user' => $conds['user_id'] ], $fname );
1201 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1202 [ 'us_user' => $conds['user_id'] ], $fname );
1203 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1204 [ 'rc_user' => $conds['user_id'] ], $fname );
1205 $this->update( 'logging', [ 'log_user' => 0 ],
1206 [ 'log_user' => $conds['user_id'] ], $fname );
1207 } elseif ( $table == $this->tableName( 'image' ) ) {
1208 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1209 [ 'oi_name' => $conds['img_name'] ], $fname );
1212 return parent
::delete( $table, $conds, $fname );
1216 * @param string $table
1217 * @param array $values
1218 * @param array $conds
1219 * @param string $fname
1220 * @param array $options
1222 * @throws DBUnexpectedError
1224 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1225 $table = $this->tableName( $table );
1226 $opts = $this->makeUpdateOptions( $options );
1227 $sql = "UPDATE $opts $table SET ";
1230 foreach ( $values as $col => &$val ) {
1231 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1234 $sqlSet = ', ' . $sqlSet;
1241 if ( $conds !== [] && $conds !== '*' ) {
1242 $conds = $this->wrapConditionsForWhere( $table, $conds );
1243 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1246 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
1247 if ( $stmt === false ) {
1248 $e = oci_error( $this->conn
);
1249 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1253 foreach ( $values as $col => &$val ) {
1254 $col_info = $this->fieldInfoMulti( $table, $col );
1255 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1257 if ( $val === null ) {
1258 // do nothing ... null was inserted in statement creation
1259 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1260 if ( is_object( $val ) ) {
1261 $val = $val->getData();
1265 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
1266 strtolower( $val ) == 'infinity'
1268 $val = '31-12-2030 12:00:00.000000';
1271 $val = $this->getVerifiedUTF8( $val );
1272 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1273 $e = oci_error( $stmt );
1274 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1279 /** @var OCI_Lob[] $lob */
1280 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
1281 if ( $lob[$col] === false ) {
1282 $e = oci_error( $stmt );
1283 throw new DBUnexpectedError(
1285 "Cannot create LOB descriptor: " . $e['message']
1289 if ( is_object( $val ) ) {
1290 $val = $val->getData();
1293 if ( $col_type == 'BLOB' ) {
1294 $lob[$col]->writeTemporary( $val );
1295 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1297 $lob[$col]->writeTemporary( $val );
1298 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1303 Wikimedia\
suppressWarnings();
1305 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1306 $e = oci_error( $stmt );
1307 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1308 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1312 $this->mAffectedRows
= oci_num_rows( $stmt );
1315 $this->mAffectedRows
= oci_num_rows( $stmt );
1318 Wikimedia\restoreWarnings
();
1320 if ( isset( $lob ) ) {
1321 foreach ( $lob as $lob_v ) {
1326 if ( !$this->trxLevel() ) {
1327 oci_commit( $this->conn
);
1330 return oci_free_statement( $stmt );
1333 function bitNot( $field ) {
1334 // expecting bit-fields smaller than 4bytes
1335 return 'BITNOT(' . $field . ')';
1338 function bitAnd( $fieldLeft, $fieldRight ) {
1339 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1342 function bitOr( $fieldLeft, $fieldRight ) {
1343 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1346 public function buildGroupConcatField(
1347 $delim, $table, $field, $conds = '', $join_conds = []
1349 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1351 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1354 public function buildSubstring( $input, $startPosition, $length = null ) {
1355 $this->assertBuildSubstringParams( $startPosition, $length );
1356 $params = [ $input, $startPosition ];
1357 if ( $length !== null ) {
1358 $params[] = $length;
1360 return 'SUBSTR(' . implode( ',', $params ) . ')';
1364 * @param string $field Field or column to cast
1368 public function buildStringCast( $field ) {
1369 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1372 public function getInfinity() {
1373 return '31-12-2030 12:00:00.000000';
1380 private function getVerifiedUTF8( $s ) {
1381 if ( mb_check_encoding( (string)$s, 'UTF-8' ) ) {
1385 throw new DBUnexpectedError( $this, "Non BLOB/CLOB field must be UTF-8." );