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 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 " .
102 $this->password
= $password;
104 // Backward compatibility (server used to be null and TNS was supplied in dbname)
105 $this->server
= $dbName;
106 $realDatabase = $user;
108 // $server now holds the TNS endpoint
109 $this->server
= $server;
110 // $dbName is schema name if different from username
111 $realDatabase = $dbName ?
: $user;
114 if ( !strlen( $user ) ) { # e.g. the class is being loaded
118 $session_mode = ( $this->flags
& DBO_SYSDBA
) ? OCI_SYSDBA
: OCI_DEFAULT
;
120 Wikimedia\
suppressWarnings();
121 if ( $this->flags
& DBO_PERSISTENT
) {
122 $this->conn
= oci_pconnect(
126 $this->defaultCharset
,
129 } elseif ( $this->flags
& DBO_DEFAULT
) {
130 $this->conn
= oci_new_connect(
134 $this->defaultCharset
,
138 $this->conn
= oci_connect(
142 $this->defaultCharset
,
146 Wikimedia\restoreWarnings
();
148 if ( $this->user
!= $realDatabase ) {
149 // change current schema in session
150 $this->selectDB( $realDatabase );
152 $this->currentDomain
= new DatabaseDomain(
159 if ( !$this->conn
) {
160 throw new DBConnectionError( $this, $this->lastError() );
163 # removed putenv calls because they interfere with the system globaly
164 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
165 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
166 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
168 return (bool)$this->conn
;
172 * Closes a database connection, if it is open
173 * Returns success, true if already closed
176 protected function closeConnection() {
177 return oci_close( $this->conn
);
180 function execFlags() {
181 return $this->trxLevel() ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
186 * @return bool|mixed|ORAResult
188 protected function doQuery( $sql ) {
189 if ( !mb_check_encoding( (string)$sql, 'UTF-8' ) ) {
190 throw new DBUnexpectedError( $this, "SQL encoding is invalid\n$sql" );
193 // handle some oracle specifics
194 // remove AS column/table/subquery namings
195 if ( !$this->getFlag( DBO_DDLMODE
) ) {
196 $sql = preg_replace( '/ as /i', ' ', $sql );
199 // Oracle has issues with UNION clause if the statement includes LOB fields
200 // So we do a UNION ALL and then filter the results array with array_unique
201 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
202 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
203 // you have to select data from plan table after explain
204 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
208 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
214 Wikimedia\
suppressWarnings();
216 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
217 if ( $stmt === false ) {
218 $e = oci_error( $this->conn
);
219 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
224 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
225 $e = oci_error( $stmt );
226 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
227 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
233 Wikimedia\restoreWarnings
();
235 if ( $explain_count > 0 ) {
236 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
237 'WHERE statement_id = \'' . $explain_id . '\'' );
238 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
239 return new ORAResult( $this, $stmt, $union_unique );
241 $this->mAffectedRows
= oci_num_rows( $stmt );
247 function queryIgnore( $sql, $fname = '' ) {
248 return $this->query( $sql, $fname, true );
252 * Frees resources associated with the LOB descriptor
253 * @param IResultWrapper|ORAResult $res
255 function freeResult( $res ) {
256 ResultWrapper
::unwrap( $res )->free();
260 * @param IResultWrapper|ORAResult $res
261 * @return stdClass|bool
263 function fetchObject( $res ) {
264 return ResultWrapper
::unwrap( $res )->fetchObject();
268 * @param IResultWrapper|ORAResult $res
269 * @return stdClass|bool
271 function fetchRow( $res ) {
272 return ResultWrapper
::unwrap( $res )->fetchRow();
276 * @param IResultWrapper|ORAResult $res
279 function numRows( $res ) {
280 return ResultWrapper
::unwrap( $res )->numRows();
284 * @param IResultWrapper|ORAResult $res
287 function numFields( $res ) {
288 return ResultWrapper
::unwrap( $res )->numFields();
291 function fieldName( $stmt, $n ) {
292 return oci_field_name( $stmt, $n );
295 function insertId() {
296 $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
297 $row = $this->fetchRow( $res );
298 return is_null( $row[0] ) ?
null : (int)$row[0];
305 function dataSeek( $res, $row ) {
306 if ( $res instanceof ORAResult
) {
309 ResultWrapper
::unwrap( $res )->seek( $row );
313 function lastError() {
314 if ( $this->conn
=== false ) {
317 $e = oci_error( $this->conn
);
320 return $e['message'];
323 function lastErrno() {
324 if ( $this->conn
=== false ) {
327 $e = oci_error( $this->conn
);
333 protected function fetchAffectedRowCount() {
334 return $this->mAffectedRows
;
338 * Returns information about an index
339 * If errors are explicitly ignored, returns NULL on failure
340 * @param string $table
341 * @param string $index
342 * @param string $fname
345 function indexInfo( $table, $index, $fname = __METHOD__
) {
349 function indexUnique( $table, $index, $fname = __METHOD__
) {
353 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
354 if ( !count( $a ) ) {
358 if ( !is_array( $options ) ) {
359 $options = [ $options ];
362 if ( in_array( 'IGNORE', $options ) ) {
363 $this->ignoreDupValOnIndex
= true;
366 if ( !is_array( reset( $a ) ) ) {
370 foreach ( $a as &$row ) {
371 $this->insertOneRow( $table, $row, $fname );
374 if ( in_array( 'IGNORE', $options ) ) {
375 $this->ignoreDupValOnIndex
= false;
381 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
382 $col_info = $this->fieldInfoMulti( $table, $col );
383 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
386 if ( is_numeric( $col ) ) {
391 } elseif ( $includeCol ) {
395 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
399 if ( $val === 'NULL' ) {
403 if ( $val === null ) {
405 $col_info != false &&
406 $col_info->isNullable() == 0 &&
407 $col_info->defaultValue() != null
421 * @param string $table
423 * @param string $fname
425 * @throws DBUnexpectedError
427 private function insertOneRow( $table, $row, $fname ) {
428 $table = $this->tableName( $table );
429 // "INSERT INTO tables (a, b, c)"
430 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
433 // for each value, append ":key"
435 foreach ( $row as $col => &$val ) {
441 if ( $this->isQuotedIdentifier( $val ) ) {
442 $sql .= $this->removeIdentifierQuotes( $val );
445 $sql .= $this->fieldBindStatement( $table, $col, $val );
450 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
451 if ( $stmt === false ) {
452 $e = oci_error( $this->conn
);
453 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
457 foreach ( $row as $col => &$val ) {
458 $col_info = $this->fieldInfoMulti( $table, $col );
459 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
461 if ( $val === null ) {
462 // do nothing ... null was inserted in statement creation
463 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
464 if ( is_object( $val ) ) {
465 $val = $val->fetch();
468 // backward compatibility
470 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
471 strtolower( $val ) == 'infinity'
473 $val = $this->getInfinity();
476 $val = $this->getVerifiedUTF8( $val );
477 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
478 $e = oci_error( $stmt );
479 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
484 /** @var OCI_Lob[] $lob */
485 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
486 if ( $lob[$col] === false ) {
487 $e = oci_error( $stmt );
488 throw new DBUnexpectedError(
490 "Cannot create LOB descriptor: " . $e['message']
494 if ( is_object( $val ) ) {
495 $val = $val->fetch();
498 if ( $col_type == 'BLOB' ) {
499 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
500 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
502 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
503 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
508 Wikimedia\
suppressWarnings();
510 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
511 $e = oci_error( $stmt );
512 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
513 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
517 $this->mAffectedRows
= oci_num_rows( $stmt );
520 $this->mAffectedRows
= oci_num_rows( $stmt );
523 Wikimedia\restoreWarnings
();
525 if ( isset( $lob ) ) {
526 foreach ( $lob as $lob_v ) {
531 if ( !$this->trxLevel() ) {
532 oci_commit( $this->conn
);
535 return oci_free_statement( $stmt );
538 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
539 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
541 $destTable = $this->tableName( $destTable );
543 $sequenceData = $this->getSequenceData( $destTable );
544 if ( $sequenceData !== false &&
545 !isset( $varMap[$sequenceData['column']] )
547 $varMap[$sequenceData['column']] =
548 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
551 // count-alias subselect fields to avoid abigious definition errors
553 foreach ( $varMap as &$val ) {
554 $val .= ' field' . $i;
558 $selectSql = $this->selectSQLText(
560 array_values( $varMap ),
567 $sql = "INSERT INTO $destTable (" .
568 implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
570 if ( in_array( 'IGNORE', $insertOptions ) ) {
571 $this->ignoreDupValOnIndex
= true;
574 $this->query( $sql, $fname );
576 if ( in_array( 'IGNORE', $insertOptions ) ) {
577 $this->ignoreDupValOnIndex
= false;
581 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
584 if ( $rows === [] ) {
585 return true; // nothing to do
588 if ( !is_array( reset( $rows ) ) ) {
592 $sequenceData = $this->getSequenceData( $table );
593 if ( $sequenceData !== false ) {
594 // add sequence column to each list of columns, when not set
595 foreach ( $rows as &$row ) {
596 if ( !isset( $row[$sequenceData['column']] ) ) {
597 $row[$sequenceData['column']] =
598 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
599 $sequenceData['sequence'] . '\')' );
604 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
607 public function tableName( $name, $format = 'quoted' ) {
608 // Replace reserved words with better ones
609 $name = $this->remappedTableName( $name );
611 return strtoupper( parent
::tableName( $name, $format ) );
615 * @param string $name
616 * @return string Value of $name or remapped name if $name is a reserved keyword
618 public function remappedTableName( $name ) {
619 return $this->keywordTableMap
[$name] ??
$name;
622 function tableNameInternal( $name ) {
623 $name = $this->tableName( $name );
625 return preg_replace( '/.*\.(.*)/', '$1', $name );
629 * Return sequence_name if table has a sequence
631 * @param string $table
632 * @return string[]|bool
634 private function getSequenceData( $table ) {
635 if ( $this->sequenceData
== null ) {
636 $dbname = $this->currentDomain
->getDatabase();
637 $prefix = $this->currentDomain
->getTablePrefix();
638 // See https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm
639 $decodeArgs = [ 'atc.table_name' ]; // the switch
640 foreach ( $this->keywordTableMap
as $reserved => $alternative ) {
641 $search = strtoupper( $prefix . $alternative ); // case
642 $replace = strtoupper( $prefix . $reserved ); // result
643 $decodeArgs[] = $this->addQuotes( $search );
644 $decodeArgs[] = $this->addQuotes( $replace );
646 $decodeArgs[] = [ 'atc.table_name' ]; // default
647 $decodeArgs = implode( ', ', $decodeArgs );
649 $result = $this->doQuery(
650 "SELECT lower(asq.sequence_name), lower(atc.table_name), lower(atc.column_name)
651 FROM all_sequences asq, all_tab_columns atc
652 WHERE decode({$decodeArgs}) || '_' ||
653 atc.column_name || '_SEQ' = '{$prefix}' || asq.sequence_name
654 AND asq.sequence_owner = upper('{$dbname}')
655 AND atc.owner = upper('{$dbname}')"
658 while ( ( $row = $result->fetchRow() ) !== false ) {
659 $this->sequenceData
[$row[1]] = [
660 'sequence' => $row[0],
665 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
667 return $this->sequenceData
[$table] ??
false;
671 * Returns the size of a text field, or -1 for "unlimited"
673 * @param string $table
674 * @param string $field
677 function textFieldSize( $table, $field ) {
678 $fieldInfoData = $this->fieldInfo( $table, $field );
680 return $fieldInfoData->maxLength();
683 function limitResult( $sql, $limit, $offset = false ) {
684 if ( $offset === false ) {
688 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
691 function encodeBlob( $b ) {
692 return new Blob( $b );
695 function unionQueries( $sqls, $all ) {
696 $glue = ' UNION ALL ';
698 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
699 'FROM (' . implode( $glue, $sqls ) . ')';
702 function wasDeadlock() {
703 return $this->lastErrno() == 'OCI-00060';
706 function duplicateTableStructure( $oldName, $newName, $temporary = false,
709 $temporary = $temporary ?
'TRUE' : 'FALSE';
710 $tablePrefix = $this->currentDomain
->getTablePrefix();
712 $newName = strtoupper( $newName );
713 $oldName = strtoupper( $oldName );
715 $tabName = substr( $newName, strlen( $tablePrefix ) );
716 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
717 $newPrefix = strtoupper( $tablePrefix );
719 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
720 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
723 function listTables( $prefix = null, $fname = __METHOD__
) {
725 if ( !empty( $prefix ) ) {
726 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
729 $owner = strtoupper( $this->getDBname() );
730 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
731 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
733 // dirty code ... i know
735 $endArray[] = strtoupper( $prefix . 'MWUSER' );
736 $endArray[] = strtoupper( $prefix . 'PAGE' );
737 $endArray[] = strtoupper( $prefix . 'IMAGE' );
738 $fixedOrderTabs = $endArray;
739 while ( ( $row = $result->fetchRow() ) !== false ) {
740 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
741 $endArray[] = $row['table_name'];
748 public function dropTable( $tableName, $fName = __METHOD__
) {
749 $tableName = $this->tableName( $tableName );
750 if ( !$this->tableExists( $tableName ) ) {
754 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
757 public function timestamp( $ts = 0 ) {
758 $t = new ConvertibleTimestamp( $ts );
759 // Let errors bubble up to avoid putting garbage in the DB
760 return $t->getTimestamp( TS_ORACLE
);
764 * Return aggregated value function call
766 * @param array $valuedata
767 * @param string $valuename
770 public function aggregateValue( $valuedata, $valuename = 'value' ) {
775 * @return string Wikitext of a link to the server software's web site
777 public function getSoftwareLink() {
778 return '[{{int:version-db-oracle-url}} Oracle]';
782 * @return string Version information from the database
784 function getServerVersion() {
785 // better version number, fallback on driver
786 $rset = $this->doQuery(
787 'SELECT version FROM product_component_version ' .
788 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
790 $row = $rset->fetchRow();
792 return oci_server_version( $this->conn
);
795 return $row['version'];
799 * Query whether a given index exists
800 * @param string $table
801 * @param string $index
802 * @param string $fname
805 function indexExists( $table, $index, $fname = __METHOD__
) {
806 $table = $this->tableName( $table );
807 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
808 $index = strtoupper( $index );
809 $owner = strtoupper( $this->getDBname() );
810 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
811 $res = $this->doQuery( $sql );
813 $count = $res->numRows();
823 * Query whether a given table exists (in the given schema, or the default mw one if not given)
824 * @param string $table
825 * @param string $fname
828 function tableExists( $table, $fname = __METHOD__
) {
829 $table = $this->tableName( $table );
830 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
831 $owner = $this->addQuotes( strtoupper( $this->getDBname() ) );
832 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
833 $res = $this->doQuery( $sql );
834 if ( $res && $res->numRows() > 0 ) {
846 * Function translates mysql_fetch_field() functionality on ORACLE.
847 * Caching is present for reducing query time.
848 * For internal calls. Use fieldInfo for normal usage.
849 * Returns false if the field doesn't exist
851 * @param array|string $table
852 * @param string $field
853 * @return ORAField|ORAResult|false
855 private function fieldInfoMulti( $table, $field ) {
856 $field = strtoupper( $field );
857 if ( is_array( $table ) ) {
858 $table = array_map( [ $this, 'tableNameInternal' ], $table );
859 $tableWhere = 'IN (';
860 foreach ( $table as &$singleTable ) {
861 $singleTable = $this->removeIdentifierQuotes( $singleTable );
862 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
863 return $this->mFieldInfoCache
["$singleTable.$field"];
865 $tableWhere .= '\'' . $singleTable . '\',';
867 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
869 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
870 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
871 return $this->mFieldInfoCache
["$table.$field"];
873 $tableWhere = '= \'' . $table . '\'';
876 $fieldInfoStmt = oci_parse(
878 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
879 $tableWhere . ' and column_name = \'' . $field . '\''
881 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
882 $e = oci_error( $fieldInfoStmt );
883 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
887 $res = new ORAResult( $this, $fieldInfoStmt );
888 if ( $res->numRows() == 0 ) {
889 if ( is_array( $table ) ) {
890 foreach ( $table as &$singleTable ) {
891 $this->mFieldInfoCache
["$singleTable.$field"] = false;
894 $this->mFieldInfoCache
["$table.$field"] = false;
896 $fieldInfoTemp = null;
898 $fieldInfoTemp = new ORAField( $res->fetchRow() );
899 $table = $fieldInfoTemp->tableName();
900 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
904 return $fieldInfoTemp;
908 * @throws DBUnexpectedError
909 * @param string $table
910 * @param string $field
913 function fieldInfo( $table, $field ) {
914 if ( is_array( $table ) ) {
915 throw new DBUnexpectedError(
917 'DatabaseOracle::fieldInfo called with table array!'
921 return $this->fieldInfoMulti( $table, $field );
924 protected function doBegin( $fname = __METHOD__
) {
925 $this->query( 'SET CONSTRAINTS ALL DEFERRED' );
928 protected function doCommit( $fname = __METHOD__
) {
929 if ( $this->trxLevel() ) {
930 $ret = oci_commit( $this->conn
);
932 throw new DBUnexpectedError( $this, $this->lastError() );
934 $this->query( 'SET CONSTRAINTS ALL IMMEDIATE' );
938 protected function doRollback( $fname = __METHOD__
) {
939 if ( $this->trxLevel() ) {
940 oci_rollback( $this->conn
);
941 $ignoreErrors = true;
942 $this->query( 'SET CONSTRAINTS ALL IMMEDIATE', $fname, $ignoreErrors );
946 function sourceStream(
948 callable
$lineCallback = null,
949 callable
$resultCallback = null,
950 $fname = __METHOD__
, callable
$inputCallback = null
954 $dollarquote = false;
957 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
958 while ( !feof( $fp ) ) {
959 if ( $lineCallback ) {
962 $line = trim( fgets( $fp, 1024 ) );
963 $sl = strlen( $line ) - 1;
968 if ( $line[0] == '-' && $line[1] == '-' ) {
972 // Allow dollar quoting for function declarations
973 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
974 if ( $dollarquote ) {
975 $dollarquote = false;
976 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
981 } elseif ( !$dollarquote ) {
982 if ( $line[$sl] == ';' && ( $sl < 2 ||
$line[$sl - 1] != ';' ) ) {
984 $line = substr( $line, 0, $sl );
994 $cmd = str_replace( ';;', ";", $cmd );
995 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
996 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
997 $replacements[$defines[2]] = $defines[1];
1000 foreach ( $replacements as $mwVar => $scVar ) {
1001 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1004 $cmd = $this->replaceVars( $cmd );
1005 if ( $inputCallback ) {
1006 $inputCallback( $cmd );
1008 $res = $this->doQuery( $cmd );
1009 if ( $resultCallback ) {
1010 call_user_func( $resultCallback, $res, $this );
1013 if ( $res === false ) {
1014 $err = $this->lastError();
1016 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1028 protected function doSelectDomain( DatabaseDomain
$domain ) {
1029 if ( $domain->getSchema() !== null ) {
1030 // We use the *database* aspect of $domain for schema, not the domain schema
1031 throw new DBExpectedError( $this, __CLASS__
. ": domain schemas are not supported." );
1034 $database = $domain->getDatabase();
1035 if ( $database === null ||
$database === $this->user
) {
1036 // Backward compatibility
1037 $this->currentDomain
= $domain;
1042 // https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj32268.html
1043 $encDatabase = $this->addIdentifierQuotes( strtoupper( $database ) );
1044 $sql = "ALTER SESSION SET CURRENT_SCHEMA=$encDatabase";
1045 $stmt = oci_parse( $this->conn
, $sql );
1046 Wikimedia\
suppressWarnings();
1047 $success = oci_execute( $stmt );
1048 Wikimedia\restoreWarnings
();
1050 // Update that domain fields on success (no exception thrown)
1051 $this->currentDomain
= $domain;
1053 $e = oci_error( $stmt );
1054 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1060 function strencode( $s ) {
1061 return str_replace( "'", "''", $s );
1064 function addQuotes( $s ) {
1065 return "'" . $this->strencode( $this->getVerifiedUTF8( $s ) ) . "'";
1068 public function addIdentifierQuotes( $s ) {
1069 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1076 public function removeIdentifierQuotes( $s ) {
1077 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1080 public function isQuotedIdentifier( $s ) {
1081 return strpos( $s, '/*Q*/' ) !== false;
1084 private function wrapFieldForWhere( $table, &$col, &$val ) {
1085 $col_info = $this->fieldInfoMulti( $table, $col );
1086 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1087 if ( $col_type == 'CLOB' ) {
1088 $col = 'TO_CHAR(' . $col . ')';
1089 $val = $this->getVerifiedUTF8( $val );
1090 } elseif ( $col_type == 'VARCHAR2' ) {
1091 $val = $this->getVerifiedUTF8( $val );
1095 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1097 foreach ( $conds as $col => $val ) {
1098 if ( is_array( $val ) ) {
1099 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1101 if ( is_numeric( $col ) && $parentCol != null ) {
1102 $this->wrapFieldForWhere( $table, $parentCol, $val );
1104 $this->wrapFieldForWhere( $table, $col, $val );
1106 $conds2[$col] = $val;
1113 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1114 $options = [], $join_conds = []
1116 if ( is_array( $conds ) ) {
1117 $conds = $this->wrapConditionsForWhere( $table, $conds );
1120 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1124 * Returns an optional USE INDEX clause to go after the table, and a
1125 * string to go at the end of the query
1127 * @param array $options An associative array of options to be turned into
1128 * an SQL query, valid keys are listed in the function.
1131 function makeSelectOptions( $options ) {
1132 $preLimitTail = $postLimitTail = '';
1136 foreach ( $options as $key => $option ) {
1137 if ( is_numeric( $key ) ) {
1138 $noKeyOptions[$option] = true;
1142 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1144 $preLimitTail .= $this->makeOrderBy( $options );
1146 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1147 $postLimitTail .= ' FOR UPDATE';
1150 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1151 $startOpts .= 'DISTINCT';
1154 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1155 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1160 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1161 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1166 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1169 public function delete( $table, $conds, $fname = __METHOD__
) {
1170 global $wgActorTableSchemaMigrationStage;
1172 if ( is_array( $conds ) ) {
1173 $conds = $this->wrapConditionsForWhere( $table, $conds );
1175 // a hack for deleting pages, users and images (which have non-nullable FKs)
1176 // all deletions on these tables have transactions so final failure rollbacks these updates
1177 // @todo: Normalize the schema to match MySQL, no special FKs and such
1178 $table = $this->tableName( $table );
1179 if ( $table == $this->tableName( 'user' ) &&
1180 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
)
1182 $this->update( 'archive', [ 'ar_user' => 0 ],
1183 [ 'ar_user' => $conds['user_id'] ], $fname );
1184 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1185 [ 'ipb_user' => $conds['user_id'] ], $fname );
1186 $this->update( 'image', [ 'img_user' => 0 ],
1187 [ 'img_user' => $conds['user_id'] ], $fname );
1188 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1189 [ 'oi_user' => $conds['user_id'] ], $fname );
1190 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1191 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1192 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1193 [ 'fa_user' => $conds['user_id'] ], $fname );
1194 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1195 [ 'us_user' => $conds['user_id'] ], $fname );
1196 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1197 [ 'rc_user' => $conds['user_id'] ], $fname );
1198 $this->update( 'logging', [ 'log_user' => 0 ],
1199 [ 'log_user' => $conds['user_id'] ], $fname );
1200 } elseif ( $table == $this->tableName( 'image' ) ) {
1201 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1202 [ 'oi_name' => $conds['img_name'] ], $fname );
1205 return parent
::delete( $table, $conds, $fname );
1209 * @param string $table
1210 * @param array $values
1211 * @param array $conds
1212 * @param string $fname
1213 * @param array $options
1215 * @throws DBUnexpectedError
1217 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1218 $table = $this->tableName( $table );
1219 $opts = $this->makeUpdateOptions( $options );
1220 $sql = "UPDATE $opts $table SET ";
1223 foreach ( $values as $col => &$val ) {
1224 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1227 $sqlSet = ', ' . $sqlSet;
1234 if ( $conds !== [] && $conds !== '*' ) {
1235 $conds = $this->wrapConditionsForWhere( $table, $conds );
1236 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1239 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
1240 if ( $stmt === false ) {
1241 $e = oci_error( $this->conn
);
1242 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1246 foreach ( $values as $col => &$val ) {
1247 $col_info = $this->fieldInfoMulti( $table, $col );
1248 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1250 if ( $val === null ) {
1251 // do nothing ... null was inserted in statement creation
1252 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1253 if ( is_object( $val ) ) {
1254 $val = $val->getData();
1258 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
1259 strtolower( $val ) == 'infinity'
1261 $val = '31-12-2030 12:00:00.000000';
1264 $val = $this->getVerifiedUTF8( $val );
1265 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1266 $e = oci_error( $stmt );
1267 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1272 /** @var OCI_Lob[] $lob */
1273 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
1274 if ( $lob[$col] === false ) {
1275 $e = oci_error( $stmt );
1276 throw new DBUnexpectedError(
1278 "Cannot create LOB descriptor: " . $e['message']
1282 if ( is_object( $val ) ) {
1283 $val = $val->getData();
1286 if ( $col_type == 'BLOB' ) {
1287 $lob[$col]->writeTemporary( $val );
1288 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1290 $lob[$col]->writeTemporary( $val );
1291 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1296 Wikimedia\
suppressWarnings();
1298 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1299 $e = oci_error( $stmt );
1300 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1301 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1305 $this->mAffectedRows
= oci_num_rows( $stmt );
1308 $this->mAffectedRows
= oci_num_rows( $stmt );
1311 Wikimedia\restoreWarnings
();
1313 if ( isset( $lob ) ) {
1314 foreach ( $lob as $lob_v ) {
1319 if ( !$this->trxLevel() ) {
1320 oci_commit( $this->conn
);
1323 return oci_free_statement( $stmt );
1326 function bitNot( $field ) {
1327 // expecting bit-fields smaller than 4bytes
1328 return 'BITNOT(' . $field . ')';
1331 function bitAnd( $fieldLeft, $fieldRight ) {
1332 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1335 function bitOr( $fieldLeft, $fieldRight ) {
1336 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1339 public function buildGroupConcatField(
1340 $delim, $table, $field, $conds = '', $join_conds = []
1342 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1344 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1347 public function buildSubstring( $input, $startPosition, $length = null ) {
1348 $this->assertBuildSubstringParams( $startPosition, $length );
1349 $params = [ $input, $startPosition ];
1350 if ( $length !== null ) {
1351 $params[] = $length;
1353 return 'SUBSTR(' . implode( ',', $params ) . ')';
1357 * @param string $field Field or column to cast
1361 public function buildStringCast( $field ) {
1362 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1365 public function getInfinity() {
1366 return '31-12-2030 12:00:00.000000';
1373 private function getVerifiedUTF8( $s ) {
1374 if ( mb_check_encoding( (string)$s, 'UTF-8' ) ) {
1378 throw new DBUnexpectedError( $this, "Non BLOB/CLOB field must be UTF-8." );