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 implicitGroupby() {
86 function implicitOrderby() {
90 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
91 if ( !function_exists( 'oci_connect' ) ) {
92 throw $this->newExceptionAfterConnectError(
93 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
94 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
101 if ( $schema !== null ) {
102 // This uses the *database* aspect of $domain for schema, not the domain schema
103 throw $this->newExceptionAfterConnectError(
104 "Got schema '$schema'; not supported. " .
105 "The database component '$dbName' is actually interpreted as the Oracle schema."
110 $this->password
= $password;
111 if ( strlen( $server ) ) {
112 // Transparent Network Substrate (TNS) endpoint
113 $this->server
= $server;
114 // Database name, defaulting to the user name
115 $realDatabase = strlen( $dbName ) ?
$dbName : $user;
117 // Backward compatibility; $server used to be null and $dbName was the TNS
118 $this->server
= $dbName;
119 $realDatabase = $user;
121 $session_mode = ( $this->flags
& DBO_SYSDBA
) ? OCI_SYSDBA
: OCI_DEFAULT
;
123 $this->installErrorHandler();
125 $this->conn
= $this->getFlag( DBO_PERSISTENT
)
130 $this->defaultCharset
,
137 $this->defaultCharset
,
140 } catch ( Exception
$e ) {
141 $this->restoreErrorHandler();
142 throw $this->newExceptionAfterConnectError( $e->getMessage() );
144 $error = $this->restoreErrorHandler();
146 if ( !$this->conn
) {
147 throw $this->newExceptionAfterConnectError( $error ?
: $this->lastError() );
151 if ( $this->user
!= $realDatabase ) {
152 // Change current schema for the entire session
153 $this->selectDomain( new DatabaseDomain(
155 $this->currentDomain
->getSchema(),
156 $this->currentDomain
->getTablePrefix()
159 $this->currentDomain
= new DatabaseDomain( $realDatabase, null, $tablePrefix );
162 'NLS_TIMESTAMP_FORMAT' => 'DD-MM-YYYY HH24:MI:SS.FF6',
163 'NLS_TIMESTAMP_TZ_FORMAT' => 'DD-MM-YYYY HH24:MI:SS.FF6',
164 'NLS_NUMERIC_CHARACTERS' => '.,'
166 foreach ( $set as $var => $val ) {
168 "ALTER SESSION SET {$var}=" . $this->addQuotes( $val ),
170 self
::QUERY_IGNORE_DBO_TRX | self
::QUERY_NO_RETRY
173 } catch ( Exception
$e ) {
174 throw $this->newExceptionAfterConnectError( $e->getMessage() );
179 * Closes a database connection, if it is open
180 * Returns success, true if already closed
183 protected function closeConnection() {
184 return oci_close( $this->conn
);
187 function execFlags() {
188 return $this->trxLevel() ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
193 * @return bool|mixed|ORAResult
195 protected function doQuery( $sql ) {
196 if ( !mb_check_encoding( (string)$sql, 'UTF-8' ) ) {
197 throw new DBUnexpectedError( $this, "SQL encoding is invalid\n$sql" );
200 // handle some oracle specifics
201 // remove AS column/table/subquery namings
202 if ( !$this->getFlag( DBO_DDLMODE
) ) {
203 $sql = preg_replace( '/ as /i', ' ', $sql );
206 // Oracle has issues with UNION clause if the statement includes LOB fields
207 // So we do a UNION ALL and then filter the results array with array_unique
208 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
209 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
210 // you have to select data from plan table after explain
211 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
215 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
221 Wikimedia\
suppressWarnings();
223 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
224 if ( $stmt === false ) {
225 $e = oci_error( $this->conn
);
226 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
231 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
232 $e = oci_error( $stmt );
233 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
234 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
240 Wikimedia\restoreWarnings
();
242 if ( $explain_count > 0 ) {
243 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
244 'WHERE statement_id = \'' . $explain_id . '\'' );
245 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
246 return new ORAResult( $this, $stmt, $union_unique );
248 $this->mAffectedRows
= oci_num_rows( $stmt );
254 function queryIgnore( $sql, $fname = '' ) {
255 return $this->query( $sql, $fname, true );
259 * Frees resources associated with the LOB descriptor
260 * @param IResultWrapper|ORAResult $res
262 function freeResult( $res ) {
263 ResultWrapper
::unwrap( $res )->free();
267 * @param IResultWrapper|ORAResult $res
268 * @return stdClass|bool
270 function fetchObject( $res ) {
271 return ResultWrapper
::unwrap( $res )->fetchObject();
275 * @param IResultWrapper|ORAResult $res
276 * @return stdClass|bool
278 function fetchRow( $res ) {
279 return ResultWrapper
::unwrap( $res )->fetchRow();
283 * @param IResultWrapper|ORAResult $res
286 function numRows( $res ) {
287 return ResultWrapper
::unwrap( $res )->numRows();
291 * @param IResultWrapper|ORAResult $res
294 function numFields( $res ) {
295 return ResultWrapper
::unwrap( $res )->numFields();
298 function fieldName( $stmt, $n ) {
299 return oci_field_name( $stmt, $n );
302 function insertId() {
303 $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
304 $row = $this->fetchRow( $res );
305 return is_null( $row[0] ) ?
null : (int)$row[0];
312 function dataSeek( $res, $row ) {
313 if ( $res instanceof ORAResult
) {
316 ResultWrapper
::unwrap( $res )->seek( $row );
320 function lastError() {
321 if ( $this->conn
=== false ) {
324 $e = oci_error( $this->conn
);
327 return $e['message'];
330 function lastErrno() {
331 if ( $this->conn
=== false ) {
334 $e = oci_error( $this->conn
);
340 protected function fetchAffectedRowCount() {
341 return $this->mAffectedRows
;
345 * Returns information about an index
346 * If errors are explicitly ignored, returns NULL on failure
347 * @param string $table
348 * @param string $index
349 * @param string $fname
352 function indexInfo( $table, $index, $fname = __METHOD__
) {
356 function indexUnique( $table, $index, $fname = __METHOD__
) {
360 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
361 if ( !count( $a ) ) {
365 if ( !is_array( $options ) ) {
366 $options = [ $options ];
369 if ( in_array( 'IGNORE', $options ) ) {
370 $this->ignoreDupValOnIndex
= true;
373 if ( !is_array( reset( $a ) ) ) {
377 foreach ( $a as &$row ) {
378 $this->insertOneRow( $table, $row, $fname );
381 if ( in_array( 'IGNORE', $options ) ) {
382 $this->ignoreDupValOnIndex
= false;
388 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
389 $col_info = $this->fieldInfoMulti( $table, $col );
390 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
393 if ( is_numeric( $col ) ) {
398 } elseif ( $includeCol ) {
402 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
406 if ( $val === 'NULL' ) {
410 if ( $val === null ) {
412 $col_info != false &&
413 $col_info->isNullable() == 0 &&
414 $col_info->defaultValue() != null
428 * @param string $table
430 * @param string $fname
432 * @throws DBUnexpectedError
434 private function insertOneRow( $table, $row, $fname ) {
435 $table = $this->tableName( $table );
436 // "INSERT INTO tables (a, b, c)"
437 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
440 // for each value, append ":key"
442 foreach ( $row as $col => &$val ) {
448 if ( $this->isQuotedIdentifier( $val ) ) {
449 $sql .= $this->removeIdentifierQuotes( $val );
452 $sql .= $this->fieldBindStatement( $table, $col, $val );
457 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
458 if ( $stmt === false ) {
459 $e = oci_error( $this->conn
);
460 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
464 foreach ( $row as $col => &$val ) {
465 $col_info = $this->fieldInfoMulti( $table, $col );
466 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
468 if ( $val === null ) {
469 // do nothing ... null was inserted in statement creation
470 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
471 if ( is_object( $val ) ) {
472 $val = $val->fetch();
475 // backward compatibility
477 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
478 strtolower( $val ) == 'infinity'
480 $val = $this->getInfinity();
483 $val = $this->getVerifiedUTF8( $val );
484 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
485 $e = oci_error( $stmt );
486 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
491 /** @var OCI_Lob[] $lob */
492 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
493 if ( $lob[$col] === false ) {
494 $e = oci_error( $stmt );
495 throw new DBUnexpectedError(
497 "Cannot create LOB descriptor: " . $e['message']
501 if ( is_object( $val ) ) {
502 $val = $val->fetch();
505 if ( $col_type == 'BLOB' ) {
506 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
507 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
509 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
510 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
515 Wikimedia\
suppressWarnings();
517 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
518 $e = oci_error( $stmt );
519 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
520 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
524 $this->mAffectedRows
= oci_num_rows( $stmt );
527 $this->mAffectedRows
= oci_num_rows( $stmt );
530 Wikimedia\restoreWarnings
();
532 if ( isset( $lob ) ) {
533 foreach ( $lob as $lob_v ) {
538 if ( !$this->trxLevel() ) {
539 oci_commit( $this->conn
);
542 return oci_free_statement( $stmt );
545 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
546 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
548 $destTable = $this->tableName( $destTable );
550 $sequenceData = $this->getSequenceData( $destTable );
551 if ( $sequenceData !== false &&
552 !isset( $varMap[$sequenceData['column']] )
554 $varMap[$sequenceData['column']] =
555 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
558 // count-alias subselect fields to avoid abigious definition errors
560 foreach ( $varMap as &$val ) {
561 $val .= ' field' . $i;
565 $selectSql = $this->selectSQLText(
567 array_values( $varMap ),
574 $sql = "INSERT INTO $destTable (" .
575 implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
577 if ( in_array( 'IGNORE', $insertOptions ) ) {
578 $this->ignoreDupValOnIndex
= true;
581 $this->query( $sql, $fname );
583 if ( in_array( 'IGNORE', $insertOptions ) ) {
584 $this->ignoreDupValOnIndex
= false;
588 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
591 if ( $rows === [] ) {
592 return true; // nothing to do
595 if ( !is_array( reset( $rows ) ) ) {
599 $sequenceData = $this->getSequenceData( $table );
600 if ( $sequenceData !== false ) {
601 // add sequence column to each list of columns, when not set
602 foreach ( $rows as &$row ) {
603 if ( !isset( $row[$sequenceData['column']] ) ) {
604 $row[$sequenceData['column']] =
605 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
606 $sequenceData['sequence'] . '\')' );
611 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
614 public function tableName( $name, $format = 'quoted' ) {
615 // Replace reserved words with better ones
616 $name = $this->remappedTableName( $name );
618 return strtoupper( parent
::tableName( $name, $format ) );
622 * @param string $name
623 * @return string Value of $name or remapped name if $name is a reserved keyword
625 public function remappedTableName( $name ) {
626 return $this->keywordTableMap
[$name] ??
$name;
629 function tableNameInternal( $name ) {
630 $name = $this->tableName( $name );
632 return preg_replace( '/.*\.(.*)/', '$1', $name );
636 * Return sequence_name if table has a sequence
638 * @param string $table
639 * @return string[]|bool
641 private function getSequenceData( $table ) {
642 if ( $this->sequenceData
== null ) {
643 $dbname = $this->currentDomain
->getDatabase();
644 $prefix = $this->currentDomain
->getTablePrefix();
645 // See https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm
646 $decodeArgs = [ 'atc.table_name' ]; // the switch
647 foreach ( $this->keywordTableMap
as $reserved => $alternative ) {
648 $search = strtoupper( $prefix . $alternative ); // case
649 $replace = strtoupper( $prefix . $reserved ); // result
650 $decodeArgs[] = $this->addQuotes( $search );
651 $decodeArgs[] = $this->addQuotes( $replace );
653 $decodeArgs[] = [ 'atc.table_name' ]; // default
654 $decodeArgs = implode( ', ', $decodeArgs );
656 $result = $this->doQuery(
657 "SELECT lower(asq.sequence_name), lower(atc.table_name), lower(atc.column_name)
658 FROM all_sequences asq, all_tab_columns atc
659 WHERE decode({$decodeArgs}) || '_' ||
660 atc.column_name || '_SEQ' = '{$prefix}' || asq.sequence_name
661 AND asq.sequence_owner = upper('{$dbname}')
662 AND atc.owner = upper('{$dbname}')"
665 while ( ( $row = $result->fetchRow() ) !== false ) {
666 $this->sequenceData
[$row[1]] = [
667 'sequence' => $row[0],
672 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
674 return $this->sequenceData
[$table] ??
false;
678 * Returns the size of a text field, or -1 for "unlimited"
680 * @param string $table
681 * @param string $field
684 function textFieldSize( $table, $field ) {
685 $fieldInfoData = $this->fieldInfo( $table, $field );
687 return $fieldInfoData->maxLength();
690 function limitResult( $sql, $limit, $offset = false ) {
691 if ( $offset === false ) {
695 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
698 function encodeBlob( $b ) {
699 return new Blob( $b );
702 function unionQueries( $sqls, $all ) {
703 $glue = ' UNION ALL ';
705 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
706 'FROM (' . implode( $glue, $sqls ) . ')';
709 function wasDeadlock() {
710 return $this->lastErrno() == 'OCI-00060';
713 function duplicateTableStructure( $oldName, $newName, $temporary = false,
716 $temporary = $temporary ?
'TRUE' : 'FALSE';
717 $tablePrefix = $this->currentDomain
->getTablePrefix();
719 $newName = strtoupper( $newName );
720 $oldName = strtoupper( $oldName );
722 $tabName = substr( $newName, strlen( $tablePrefix ) );
723 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
724 $newPrefix = strtoupper( $tablePrefix );
726 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
727 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
730 function listTables( $prefix = null, $fname = __METHOD__
) {
732 if ( !empty( $prefix ) ) {
733 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
736 $owner = strtoupper( $this->getDBname() );
737 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
738 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
740 // dirty code ... i know
742 $endArray[] = strtoupper( $prefix . 'MWUSER' );
743 $endArray[] = strtoupper( $prefix . 'PAGE' );
744 $endArray[] = strtoupper( $prefix . 'IMAGE' );
745 $fixedOrderTabs = $endArray;
746 while ( ( $row = $result->fetchRow() ) !== false ) {
747 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
748 $endArray[] = $row['table_name'];
755 public function dropTable( $tableName, $fName = __METHOD__
) {
756 $tableName = $this->tableName( $tableName );
757 if ( !$this->tableExists( $tableName ) ) {
761 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
764 public function timestamp( $ts = 0 ) {
765 $t = new ConvertibleTimestamp( $ts );
766 // Let errors bubble up to avoid putting garbage in the DB
767 return $t->getTimestamp( TS_ORACLE
);
771 * Return aggregated value function call
773 * @param array $valuedata
774 * @param string $valuename
777 public function aggregateValue( $valuedata, $valuename = 'value' ) {
782 * @return string Wikitext of a link to the server software's web site
784 public function getSoftwareLink() {
785 return '[{{int:version-db-oracle-url}} Oracle]';
789 * @return string Version information from the database
791 function getServerVersion() {
792 // better version number, fallback on driver
793 $rset = $this->doQuery(
794 'SELECT version FROM product_component_version ' .
795 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
797 $row = $rset->fetchRow();
799 return oci_server_version( $this->conn
);
802 return $row['version'];
806 * Query whether a given index exists
807 * @param string $table
808 * @param string $index
809 * @param string $fname
812 function indexExists( $table, $index, $fname = __METHOD__
) {
813 $table = $this->tableName( $table );
814 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
815 $index = strtoupper( $index );
816 $owner = strtoupper( $this->getDBname() );
817 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
818 $res = $this->doQuery( $sql );
820 $count = $res->numRows();
830 * Query whether a given table exists (in the given schema, or the default mw one if not given)
831 * @param string $table
832 * @param string $fname
835 function tableExists( $table, $fname = __METHOD__
) {
836 $table = $this->tableName( $table );
837 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
838 $owner = $this->addQuotes( strtoupper( $this->getDBname() ) );
839 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
840 $res = $this->doQuery( $sql );
841 if ( $res && $res->numRows() > 0 ) {
853 * Function translates mysql_fetch_field() functionality on ORACLE.
854 * Caching is present for reducing query time.
855 * For internal calls. Use fieldInfo for normal usage.
856 * Returns false if the field doesn't exist
858 * @param array|string $table
859 * @param string $field
860 * @return ORAField|ORAResult|false
862 private function fieldInfoMulti( $table, $field ) {
863 $field = strtoupper( $field );
864 if ( is_array( $table ) ) {
865 $table = array_map( [ $this, 'tableNameInternal' ], $table );
866 $tableWhere = 'IN (';
867 foreach ( $table as &$singleTable ) {
868 $singleTable = $this->removeIdentifierQuotes( $singleTable );
869 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
870 return $this->mFieldInfoCache
["$singleTable.$field"];
872 $tableWhere .= '\'' . $singleTable . '\',';
874 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
876 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
877 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
878 return $this->mFieldInfoCache
["$table.$field"];
880 $tableWhere = '= \'' . $table . '\'';
883 $fieldInfoStmt = oci_parse(
885 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
886 $tableWhere . ' and column_name = \'' . $field . '\''
888 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
889 $e = oci_error( $fieldInfoStmt );
890 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
894 $res = new ORAResult( $this, $fieldInfoStmt );
895 if ( $res->numRows() == 0 ) {
896 if ( is_array( $table ) ) {
897 foreach ( $table as &$singleTable ) {
898 $this->mFieldInfoCache
["$singleTable.$field"] = false;
901 $this->mFieldInfoCache
["$table.$field"] = false;
903 $fieldInfoTemp = null;
905 $fieldInfoTemp = new ORAField( $res->fetchRow() );
906 $table = $fieldInfoTemp->tableName();
907 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
911 return $fieldInfoTemp;
915 * @throws DBUnexpectedError
916 * @param string $table
917 * @param string $field
920 function fieldInfo( $table, $field ) {
921 if ( is_array( $table ) ) {
922 throw new DBUnexpectedError(
924 'DatabaseOracle::fieldInfo called with table array!'
928 return $this->fieldInfoMulti( $table, $field );
931 protected function doBegin( $fname = __METHOD__
) {
932 $this->query( 'SET CONSTRAINTS ALL DEFERRED' );
935 protected function doCommit( $fname = __METHOD__
) {
936 if ( $this->trxLevel() ) {
937 $ret = oci_commit( $this->conn
);
939 throw new DBUnexpectedError( $this, $this->lastError() );
941 $this->query( 'SET CONSTRAINTS ALL IMMEDIATE' );
945 protected function doRollback( $fname = __METHOD__
) {
946 if ( $this->trxLevel() ) {
947 oci_rollback( $this->conn
);
948 $ignoreErrors = true;
949 $this->query( 'SET CONSTRAINTS ALL IMMEDIATE', $fname, $ignoreErrors );
953 function sourceStream(
955 callable
$lineCallback = null,
956 callable
$resultCallback = null,
957 $fname = __METHOD__
, callable
$inputCallback = null
961 $dollarquote = false;
964 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
965 while ( !feof( $fp ) ) {
966 if ( $lineCallback ) {
969 $line = trim( fgets( $fp, 1024 ) );
970 $sl = strlen( $line ) - 1;
975 if ( $line[0] == '-' && $line[1] == '-' ) {
979 // Allow dollar quoting for function declarations
980 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
981 if ( $dollarquote ) {
982 $dollarquote = false;
983 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
988 } elseif ( !$dollarquote ) {
989 if ( $line[$sl] == ';' && ( $sl < 2 ||
$line[$sl - 1] != ';' ) ) {
991 $line = substr( $line, 0, $sl );
1001 $cmd = str_replace( ';;', ";", $cmd );
1002 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1003 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1004 $replacements[$defines[2]] = $defines[1];
1007 foreach ( $replacements as $mwVar => $scVar ) {
1008 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1011 $cmd = $this->replaceVars( $cmd );
1012 if ( $inputCallback ) {
1013 $inputCallback( $cmd );
1015 $res = $this->doQuery( $cmd );
1016 if ( $resultCallback ) {
1017 call_user_func( $resultCallback, $res, $this );
1020 if ( $res === false ) {
1021 $err = $this->lastError();
1023 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1035 protected function doSelectDomain( DatabaseDomain
$domain ) {
1036 if ( $domain->getSchema() !== null ) {
1037 // We use the *database* aspect of $domain for schema, not the domain schema
1038 throw new DBExpectedError(
1040 __CLASS__
. ": domain '{$domain->getId()}' has a schema component; " .
1041 "the database component is actually interpreted as the Oracle schema."
1045 $database = $domain->getDatabase();
1046 if ( $database === null ||
$database === $this->user
) {
1047 // Backward compatibility
1048 $this->currentDomain
= $domain;
1053 // https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj32268.html
1054 $encDatabase = $this->addIdentifierQuotes( strtoupper( $database ) );
1055 $sql = "ALTER SESSION SET CURRENT_SCHEMA=$encDatabase";
1056 $stmt = oci_parse( $this->conn
, $sql );
1057 Wikimedia\
suppressWarnings();
1058 $success = oci_execute( $stmt );
1059 Wikimedia\restoreWarnings
();
1061 // Update that domain fields on success (no exception thrown)
1062 $this->currentDomain
= $domain;
1064 $e = oci_error( $stmt );
1065 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1071 function strencode( $s ) {
1072 return str_replace( "'", "''", $s );
1075 function addQuotes( $s ) {
1076 return "'" . $this->strencode( $this->getVerifiedUTF8( $s ) ) . "'";
1079 public function addIdentifierQuotes( $s ) {
1080 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1087 public function removeIdentifierQuotes( $s ) {
1088 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1091 public function isQuotedIdentifier( $s ) {
1092 return strpos( $s, '/*Q*/' ) !== false;
1095 private function wrapFieldForWhere( $table, &$col, &$val ) {
1096 $col_info = $this->fieldInfoMulti( $table, $col );
1097 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1098 if ( $col_type == 'CLOB' ) {
1099 $col = 'TO_CHAR(' . $col . ')';
1100 $val = $this->getVerifiedUTF8( $val );
1101 } elseif ( $col_type == 'VARCHAR2' ) {
1102 $val = $this->getVerifiedUTF8( $val );
1106 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1108 foreach ( $conds as $col => $val ) {
1109 if ( is_array( $val ) ) {
1110 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1112 if ( is_numeric( $col ) && $parentCol != null ) {
1113 $this->wrapFieldForWhere( $table, $parentCol, $val );
1115 $this->wrapFieldForWhere( $table, $col, $val );
1117 $conds2[$col] = $val;
1124 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1125 $options = [], $join_conds = []
1127 if ( is_array( $conds ) ) {
1128 $conds = $this->wrapConditionsForWhere( $table, $conds );
1131 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1135 * Returns an optional USE INDEX clause to go after the table, and a
1136 * string to go at the end of the query
1138 * @param array $options An associative array of options to be turned into
1139 * an SQL query, valid keys are listed in the function.
1142 function makeSelectOptions( $options ) {
1143 $preLimitTail = $postLimitTail = '';
1147 foreach ( $options as $key => $option ) {
1148 if ( is_numeric( $key ) ) {
1149 $noKeyOptions[$option] = true;
1153 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1155 $preLimitTail .= $this->makeOrderBy( $options );
1157 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1158 $postLimitTail .= ' FOR UPDATE';
1161 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1162 $startOpts .= 'DISTINCT';
1165 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1166 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1171 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1172 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1177 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1180 public function delete( $table, $conds, $fname = __METHOD__
) {
1181 global $wgActorTableSchemaMigrationStage;
1183 if ( is_array( $conds ) ) {
1184 $conds = $this->wrapConditionsForWhere( $table, $conds );
1186 // a hack for deleting pages, users and images (which have non-nullable FKs)
1187 // all deletions on these tables have transactions so final failure rollbacks these updates
1188 // @todo: Normalize the schema to match MySQL, no special FKs and such
1189 $table = $this->tableName( $table );
1190 if ( $table == $this->tableName( 'user' ) &&
1191 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
)
1193 $this->update( 'archive', [ 'ar_user' => 0 ],
1194 [ 'ar_user' => $conds['user_id'] ], $fname );
1195 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1196 [ 'ipb_user' => $conds['user_id'] ], $fname );
1197 $this->update( 'image', [ 'img_user' => 0 ],
1198 [ 'img_user' => $conds['user_id'] ], $fname );
1199 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1200 [ 'oi_user' => $conds['user_id'] ], $fname );
1201 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1202 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1203 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1204 [ 'fa_user' => $conds['user_id'] ], $fname );
1205 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1206 [ 'us_user' => $conds['user_id'] ], $fname );
1207 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1208 [ 'rc_user' => $conds['user_id'] ], $fname );
1209 $this->update( 'logging', [ 'log_user' => 0 ],
1210 [ 'log_user' => $conds['user_id'] ], $fname );
1211 } elseif ( $table == $this->tableName( 'image' ) ) {
1212 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1213 [ 'oi_name' => $conds['img_name'] ], $fname );
1216 return parent
::delete( $table, $conds, $fname );
1220 * @param string $table
1221 * @param array $values
1222 * @param array $conds
1223 * @param string $fname
1224 * @param array $options
1226 * @throws DBUnexpectedError
1228 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1229 $table = $this->tableName( $table );
1230 $opts = $this->makeUpdateOptions( $options );
1231 $sql = "UPDATE $opts $table SET ";
1234 foreach ( $values as $col => &$val ) {
1235 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1238 $sqlSet = ', ' . $sqlSet;
1245 if ( $conds !== [] && $conds !== '*' ) {
1246 $conds = $this->wrapConditionsForWhere( $table, $conds );
1247 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1250 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
1251 if ( $stmt === false ) {
1252 $e = oci_error( $this->conn
);
1253 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1257 foreach ( $values as $col => &$val ) {
1258 $col_info = $this->fieldInfoMulti( $table, $col );
1259 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1261 if ( $val === null ) {
1262 // do nothing ... null was inserted in statement creation
1263 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1264 if ( is_object( $val ) ) {
1265 $val = $val->getData();
1269 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
1270 strtolower( $val ) == 'infinity'
1272 $val = '31-12-2030 12:00:00.000000';
1275 $val = $this->getVerifiedUTF8( $val );
1276 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1277 $e = oci_error( $stmt );
1278 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1283 /** @var OCI_Lob[] $lob */
1284 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
1285 if ( $lob[$col] === false ) {
1286 $e = oci_error( $stmt );
1287 throw new DBUnexpectedError(
1289 "Cannot create LOB descriptor: " . $e['message']
1293 if ( is_object( $val ) ) {
1294 $val = $val->getData();
1297 if ( $col_type == 'BLOB' ) {
1298 $lob[$col]->writeTemporary( $val );
1299 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1301 $lob[$col]->writeTemporary( $val );
1302 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1307 Wikimedia\
suppressWarnings();
1309 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1310 $e = oci_error( $stmt );
1311 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1312 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1316 $this->mAffectedRows
= oci_num_rows( $stmt );
1319 $this->mAffectedRows
= oci_num_rows( $stmt );
1322 Wikimedia\restoreWarnings
();
1324 if ( isset( $lob ) ) {
1325 foreach ( $lob as $lob_v ) {
1330 if ( !$this->trxLevel() ) {
1331 oci_commit( $this->conn
);
1334 return oci_free_statement( $stmt );
1337 function bitNot( $field ) {
1338 // expecting bit-fields smaller than 4bytes
1339 return 'BITNOT(' . $field . ')';
1342 function bitAnd( $fieldLeft, $fieldRight ) {
1343 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1346 function bitOr( $fieldLeft, $fieldRight ) {
1347 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1350 public function buildGroupConcatField(
1351 $delim, $table, $field, $conds = '', $join_conds = []
1353 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1355 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1358 public function buildSubstring( $input, $startPosition, $length = null ) {
1359 $this->assertBuildSubstringParams( $startPosition, $length );
1360 $params = [ $input, $startPosition ];
1361 if ( $length !== null ) {
1362 $params[] = $length;
1364 return 'SUBSTR(' . implode( ',', $params ) . ')';
1368 * @param string $field Field or column to cast
1372 public function buildStringCast( $field ) {
1373 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1376 public function getInfinity() {
1377 return '31-12-2030 12:00:00.000000';
1384 private function getVerifiedUTF8( $s ) {
1385 if ( mb_check_encoding( (string)$s, 'UTF-8' ) ) {
1389 throw new DBUnexpectedError( $this, "Non BLOB/CLOB field must be UTF-8." );