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 if ( $res instanceof ResultWrapper
) {
264 * @param IResultWrapper|ORAResult $res
265 * @return stdClass|bool
267 function fetchObject( $res ) {
268 if ( $res instanceof ResultWrapper
) {
272 return $res->fetchObject();
276 * @param IResultWrapper|ORAResult $res
277 * @return stdClass|bool
279 function fetchRow( $res ) {
280 if ( $res instanceof ResultWrapper
) {
284 return $res->fetchRow();
288 * @param IResultWrapper|ORAResult $res
291 function numRows( $res ) {
292 if ( $res instanceof ResultWrapper
) {
296 return $res->numRows();
300 * @param IResultWrapper|ORAResult $res
303 function numFields( $res ) {
304 if ( $res instanceof ResultWrapper
) {
308 return $res->numFields();
311 function fieldName( $stmt, $n ) {
312 return oci_field_name( $stmt, $n );
315 function insertId() {
316 $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
317 $row = $this->fetchRow( $res );
318 return is_null( $row[0] ) ?
null : (int)$row[0];
325 function dataSeek( $res, $row ) {
326 if ( $res instanceof ORAResult
) {
329 $res->result
->seek( $row );
333 function lastError() {
334 if ( $this->conn
=== false ) {
337 $e = oci_error( $this->conn
);
340 return $e['message'];
343 function lastErrno() {
344 if ( $this->conn
=== false ) {
347 $e = oci_error( $this->conn
);
353 protected function fetchAffectedRowCount() {
354 return $this->mAffectedRows
;
358 * Returns information about an index
359 * If errors are explicitly ignored, returns NULL on failure
360 * @param string $table
361 * @param string $index
362 * @param string $fname
365 function indexInfo( $table, $index, $fname = __METHOD__
) {
369 function indexUnique( $table, $index, $fname = __METHOD__
) {
373 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
374 if ( !count( $a ) ) {
378 if ( !is_array( $options ) ) {
379 $options = [ $options ];
382 if ( in_array( 'IGNORE', $options ) ) {
383 $this->ignoreDupValOnIndex
= true;
386 if ( !is_array( reset( $a ) ) ) {
390 foreach ( $a as &$row ) {
391 $this->insertOneRow( $table, $row, $fname );
394 if ( in_array( 'IGNORE', $options ) ) {
395 $this->ignoreDupValOnIndex
= false;
401 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
402 $col_info = $this->fieldInfoMulti( $table, $col );
403 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
406 if ( is_numeric( $col ) ) {
411 } elseif ( $includeCol ) {
415 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
419 if ( $val === 'NULL' ) {
423 if ( $val === null ) {
425 $col_info != false &&
426 $col_info->isNullable() == 0 &&
427 $col_info->defaultValue() != null
441 * @param string $table
443 * @param string $fname
445 * @throws DBUnexpectedError
447 private function insertOneRow( $table, $row, $fname ) {
448 $table = $this->tableName( $table );
449 // "INSERT INTO tables (a, b, c)"
450 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
453 // for each value, append ":key"
455 foreach ( $row as $col => &$val ) {
461 if ( $this->isQuotedIdentifier( $val ) ) {
462 $sql .= $this->removeIdentifierQuotes( $val );
465 $sql .= $this->fieldBindStatement( $table, $col, $val );
470 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
471 if ( $stmt === false ) {
472 $e = oci_error( $this->conn
);
473 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
477 foreach ( $row as $col => &$val ) {
478 $col_info = $this->fieldInfoMulti( $table, $col );
479 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
481 if ( $val === null ) {
482 // do nothing ... null was inserted in statement creation
483 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
484 if ( is_object( $val ) ) {
485 $val = $val->fetch();
488 // backward compatibility
490 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
491 strtolower( $val ) == 'infinity'
493 $val = $this->getInfinity();
496 $val = $this->getVerifiedUTF8( $val );
497 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
498 $e = oci_error( $stmt );
499 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
504 /** @var OCI_Lob[] $lob */
505 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
506 if ( $lob[$col] === false ) {
507 $e = oci_error( $stmt );
508 throw new DBUnexpectedError(
510 "Cannot create LOB descriptor: " . $e['message']
514 if ( is_object( $val ) ) {
515 $val = $val->fetch();
518 if ( $col_type == 'BLOB' ) {
519 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
520 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
522 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
523 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
528 Wikimedia\
suppressWarnings();
530 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
531 $e = oci_error( $stmt );
532 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
533 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
537 $this->mAffectedRows
= oci_num_rows( $stmt );
540 $this->mAffectedRows
= oci_num_rows( $stmt );
543 Wikimedia\restoreWarnings
();
545 if ( isset( $lob ) ) {
546 foreach ( $lob as $lob_v ) {
551 if ( !$this->trxLevel() ) {
552 oci_commit( $this->conn
);
555 return oci_free_statement( $stmt );
558 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
559 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
561 $destTable = $this->tableName( $destTable );
563 $sequenceData = $this->getSequenceData( $destTable );
564 if ( $sequenceData !== false &&
565 !isset( $varMap[$sequenceData['column']] )
567 $varMap[$sequenceData['column']] =
568 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
571 // count-alias subselect fields to avoid abigious definition errors
573 foreach ( $varMap as &$val ) {
574 $val .= ' field' . $i;
578 $selectSql = $this->selectSQLText(
580 array_values( $varMap ),
587 $sql = "INSERT INTO $destTable (" .
588 implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
590 if ( in_array( 'IGNORE', $insertOptions ) ) {
591 $this->ignoreDupValOnIndex
= true;
594 $this->query( $sql, $fname );
596 if ( in_array( 'IGNORE', $insertOptions ) ) {
597 $this->ignoreDupValOnIndex
= false;
601 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
604 if ( $rows === [] ) {
605 return true; // nothing to do
608 if ( !is_array( reset( $rows ) ) ) {
612 $sequenceData = $this->getSequenceData( $table );
613 if ( $sequenceData !== false ) {
614 // add sequence column to each list of columns, when not set
615 foreach ( $rows as &$row ) {
616 if ( !isset( $row[$sequenceData['column']] ) ) {
617 $row[$sequenceData['column']] =
618 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
619 $sequenceData['sequence'] . '\')' );
624 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
627 public function tableName( $name, $format = 'quoted' ) {
628 // Replace reserved words with better ones
629 $name = $this->remappedTableName( $name );
631 return strtoupper( parent
::tableName( $name, $format ) );
635 * @param string $name
636 * @return string Value of $name or remapped name if $name is a reserved keyword
638 public function remappedTableName( $name ) {
639 return $this->keywordTableMap
[$name] ??
$name;
642 function tableNameInternal( $name ) {
643 $name = $this->tableName( $name );
645 return preg_replace( '/.*\.(.*)/', '$1', $name );
649 * Return sequence_name if table has a sequence
651 * @param string $table
652 * @return string[]|bool
654 private function getSequenceData( $table ) {
655 if ( $this->sequenceData
== null ) {
656 $dbname = $this->currentDomain
->getDatabase();
657 $prefix = $this->currentDomain
->getTablePrefix();
658 // See https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm
659 $decodeArgs = [ 'atc.table_name' ]; // the switch
660 foreach ( $this->keywordTableMap
as $reserved => $alternative ) {
661 $search = strtoupper( $prefix . $alternative ); // case
662 $replace = strtoupper( $prefix . $reserved ); // result
663 $decodeArgs[] = $this->addQuotes( $search );
664 $decodeArgs[] = $this->addQuotes( $replace );
666 $decodeArgs[] = [ 'atc.table_name' ]; // default
667 $decodeArgs = implode( ', ', $decodeArgs );
669 $result = $this->doQuery(
670 "SELECT lower(asq.sequence_name), lower(atc.table_name), lower(atc.column_name)
671 FROM all_sequences asq, all_tab_columns atc
672 WHERE decode({$decodeArgs}) || '_' ||
673 atc.column_name || '_SEQ' = '{$prefix}' || asq.sequence_name
674 AND asq.sequence_owner = upper('{$dbname}')
675 AND atc.owner = upper('{$dbname}')"
678 while ( ( $row = $result->fetchRow() ) !== false ) {
679 $this->sequenceData
[$row[1]] = [
680 'sequence' => $row[0],
685 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
687 return $this->sequenceData
[$table] ??
false;
691 * Returns the size of a text field, or -1 for "unlimited"
693 * @param string $table
694 * @param string $field
697 function textFieldSize( $table, $field ) {
698 $fieldInfoData = $this->fieldInfo( $table, $field );
700 return $fieldInfoData->maxLength();
703 function limitResult( $sql, $limit, $offset = false ) {
704 if ( $offset === false ) {
708 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
711 function encodeBlob( $b ) {
712 return new Blob( $b );
715 function unionQueries( $sqls, $all ) {
716 $glue = ' UNION ALL ';
718 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
719 'FROM (' . implode( $glue, $sqls ) . ')';
722 function wasDeadlock() {
723 return $this->lastErrno() == 'OCI-00060';
726 function duplicateTableStructure( $oldName, $newName, $temporary = false,
729 $temporary = $temporary ?
'TRUE' : 'FALSE';
730 $tablePrefix = $this->currentDomain
->getTablePrefix();
732 $newName = strtoupper( $newName );
733 $oldName = strtoupper( $oldName );
735 $tabName = substr( $newName, strlen( $tablePrefix ) );
736 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
737 $newPrefix = strtoupper( $tablePrefix );
739 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
740 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
743 function listTables( $prefix = null, $fname = __METHOD__
) {
745 if ( !empty( $prefix ) ) {
746 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
749 $owner = strtoupper( $this->getDBname() );
750 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
751 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
753 // dirty code ... i know
755 $endArray[] = strtoupper( $prefix . 'MWUSER' );
756 $endArray[] = strtoupper( $prefix . 'PAGE' );
757 $endArray[] = strtoupper( $prefix . 'IMAGE' );
758 $fixedOrderTabs = $endArray;
759 while ( ( $row = $result->fetchRow() ) !== false ) {
760 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
761 $endArray[] = $row['table_name'];
768 public function dropTable( $tableName, $fName = __METHOD__
) {
769 $tableName = $this->tableName( $tableName );
770 if ( !$this->tableExists( $tableName ) ) {
774 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
777 public function timestamp( $ts = 0 ) {
778 $t = new ConvertibleTimestamp( $ts );
779 // Let errors bubble up to avoid putting garbage in the DB
780 return $t->getTimestamp( TS_ORACLE
);
784 * Return aggregated value function call
786 * @param array $valuedata
787 * @param string $valuename
790 public function aggregateValue( $valuedata, $valuename = 'value' ) {
795 * @return string Wikitext of a link to the server software's web site
797 public function getSoftwareLink() {
798 return '[{{int:version-db-oracle-url}} Oracle]';
802 * @return string Version information from the database
804 function getServerVersion() {
805 // better version number, fallback on driver
806 $rset = $this->doQuery(
807 'SELECT version FROM product_component_version ' .
808 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
810 $row = $rset->fetchRow();
812 return oci_server_version( $this->conn
);
815 return $row['version'];
819 * Query whether a given index exists
820 * @param string $table
821 * @param string $index
822 * @param string $fname
825 function indexExists( $table, $index, $fname = __METHOD__
) {
826 $table = $this->tableName( $table );
827 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
828 $index = strtoupper( $index );
829 $owner = strtoupper( $this->getDBname() );
830 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
831 $res = $this->doQuery( $sql );
833 $count = $res->numRows();
843 * Query whether a given table exists (in the given schema, or the default mw one if not given)
844 * @param string $table
845 * @param string $fname
848 function tableExists( $table, $fname = __METHOD__
) {
849 $table = $this->tableName( $table );
850 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
851 $owner = $this->addQuotes( strtoupper( $this->getDBname() ) );
852 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
853 $res = $this->doQuery( $sql );
854 if ( $res && $res->numRows() > 0 ) {
866 * Function translates mysql_fetch_field() functionality on ORACLE.
867 * Caching is present for reducing query time.
868 * For internal calls. Use fieldInfo for normal usage.
869 * Returns false if the field doesn't exist
871 * @param array|string $table
872 * @param string $field
873 * @return ORAField|ORAResult|false
875 private function fieldInfoMulti( $table, $field ) {
876 $field = strtoupper( $field );
877 if ( is_array( $table ) ) {
878 $table = array_map( [ $this, 'tableNameInternal' ], $table );
879 $tableWhere = 'IN (';
880 foreach ( $table as &$singleTable ) {
881 $singleTable = $this->removeIdentifierQuotes( $singleTable );
882 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
883 return $this->mFieldInfoCache
["$singleTable.$field"];
885 $tableWhere .= '\'' . $singleTable . '\',';
887 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
889 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
890 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
891 return $this->mFieldInfoCache
["$table.$field"];
893 $tableWhere = '= \'' . $table . '\'';
896 $fieldInfoStmt = oci_parse(
898 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
899 $tableWhere . ' and column_name = \'' . $field . '\''
901 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
902 $e = oci_error( $fieldInfoStmt );
903 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
907 $res = new ORAResult( $this, $fieldInfoStmt );
908 if ( $res->numRows() == 0 ) {
909 if ( is_array( $table ) ) {
910 foreach ( $table as &$singleTable ) {
911 $this->mFieldInfoCache
["$singleTable.$field"] = false;
914 $this->mFieldInfoCache
["$table.$field"] = false;
916 $fieldInfoTemp = null;
918 $fieldInfoTemp = new ORAField( $res->fetchRow() );
919 $table = $fieldInfoTemp->tableName();
920 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
924 return $fieldInfoTemp;
928 * @throws DBUnexpectedError
929 * @param string $table
930 * @param string $field
933 function fieldInfo( $table, $field ) {
934 if ( is_array( $table ) ) {
935 throw new DBUnexpectedError(
937 'DatabaseOracle::fieldInfo called with table array!'
941 return $this->fieldInfoMulti( $table, $field );
944 protected function doBegin( $fname = __METHOD__
) {
945 $this->query( 'SET CONSTRAINTS ALL DEFERRED' );
948 protected function doCommit( $fname = __METHOD__
) {
949 if ( $this->trxLevel() ) {
950 $ret = oci_commit( $this->conn
);
952 throw new DBUnexpectedError( $this, $this->lastError() );
954 $this->query( 'SET CONSTRAINTS ALL IMMEDIATE' );
958 protected function doRollback( $fname = __METHOD__
) {
959 if ( $this->trxLevel() ) {
960 oci_rollback( $this->conn
);
961 $ignoreErrors = true;
962 $this->query( 'SET CONSTRAINTS ALL IMMEDIATE', $fname, $ignoreErrors );
966 function sourceStream(
968 callable
$lineCallback = null,
969 callable
$resultCallback = null,
970 $fname = __METHOD__
, callable
$inputCallback = null
974 $dollarquote = false;
977 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
978 while ( !feof( $fp ) ) {
979 if ( $lineCallback ) {
982 $line = trim( fgets( $fp, 1024 ) );
983 $sl = strlen( $line ) - 1;
988 if ( $line[0] == '-' && $line[1] == '-' ) {
992 // Allow dollar quoting for function declarations
993 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
994 if ( $dollarquote ) {
995 $dollarquote = false;
996 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1001 } elseif ( !$dollarquote ) {
1002 if ( $line[$sl] == ';' && ( $sl < 2 ||
$line[$sl - 1] != ';' ) ) {
1004 $line = substr( $line, 0, $sl );
1014 $cmd = str_replace( ';;', ";", $cmd );
1015 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1016 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1017 $replacements[$defines[2]] = $defines[1];
1020 foreach ( $replacements as $mwVar => $scVar ) {
1021 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1024 $cmd = $this->replaceVars( $cmd );
1025 if ( $inputCallback ) {
1026 $inputCallback( $cmd );
1028 $res = $this->doQuery( $cmd );
1029 if ( $resultCallback ) {
1030 call_user_func( $resultCallback, $res, $this );
1033 if ( $res === false ) {
1034 $err = $this->lastError();
1036 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1048 protected function doSelectDomain( DatabaseDomain
$domain ) {
1049 if ( $domain->getSchema() !== null ) {
1050 // We use the *database* aspect of $domain for schema, not the domain schema
1051 throw new DBExpectedError( $this, __CLASS__
. ": domain schemas are not supported." );
1054 $database = $domain->getDatabase();
1055 if ( $database === null ||
$database === $this->user
) {
1056 // Backward compatibility
1057 $this->currentDomain
= $domain;
1062 // https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj32268.html
1063 $encDatabase = $this->addIdentifierQuotes( strtoupper( $database ) );
1064 $sql = "ALTER SESSION SET CURRENT_SCHEMA=$encDatabase";
1065 $stmt = oci_parse( $this->conn
, $sql );
1066 Wikimedia\
suppressWarnings();
1067 $success = oci_execute( $stmt );
1068 Wikimedia\restoreWarnings
();
1070 // Update that domain fields on success (no exception thrown)
1071 $this->currentDomain
= $domain;
1073 $e = oci_error( $stmt );
1074 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1080 function strencode( $s ) {
1081 return str_replace( "'", "''", $s );
1084 function addQuotes( $s ) {
1085 return "'" . $this->strencode( $this->getVerifiedUTF8( $s ) ) . "'";
1088 public function addIdentifierQuotes( $s ) {
1089 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1096 public function removeIdentifierQuotes( $s ) {
1097 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1100 public function isQuotedIdentifier( $s ) {
1101 return strpos( $s, '/*Q*/' ) !== false;
1104 private function wrapFieldForWhere( $table, &$col, &$val ) {
1105 $col_info = $this->fieldInfoMulti( $table, $col );
1106 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1107 if ( $col_type == 'CLOB' ) {
1108 $col = 'TO_CHAR(' . $col . ')';
1109 $val = $this->getVerifiedUTF8( $val );
1110 } elseif ( $col_type == 'VARCHAR2' ) {
1111 $val = $this->getVerifiedUTF8( $val );
1115 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1117 foreach ( $conds as $col => $val ) {
1118 if ( is_array( $val ) ) {
1119 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1121 if ( is_numeric( $col ) && $parentCol != null ) {
1122 $this->wrapFieldForWhere( $table, $parentCol, $val );
1124 $this->wrapFieldForWhere( $table, $col, $val );
1126 $conds2[$col] = $val;
1133 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1134 $options = [], $join_conds = []
1136 if ( is_array( $conds ) ) {
1137 $conds = $this->wrapConditionsForWhere( $table, $conds );
1140 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1144 * Returns an optional USE INDEX clause to go after the table, and a
1145 * string to go at the end of the query
1147 * @param array $options An associative array of options to be turned into
1148 * an SQL query, valid keys are listed in the function.
1151 function makeSelectOptions( $options ) {
1152 $preLimitTail = $postLimitTail = '';
1156 foreach ( $options as $key => $option ) {
1157 if ( is_numeric( $key ) ) {
1158 $noKeyOptions[$option] = true;
1162 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1164 $preLimitTail .= $this->makeOrderBy( $options );
1166 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1167 $postLimitTail .= ' FOR UPDATE';
1170 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1171 $startOpts .= 'DISTINCT';
1174 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1175 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1180 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1181 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1186 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1189 public function delete( $table, $conds, $fname = __METHOD__
) {
1190 global $wgActorTableSchemaMigrationStage;
1192 if ( is_array( $conds ) ) {
1193 $conds = $this->wrapConditionsForWhere( $table, $conds );
1195 // a hack for deleting pages, users and images (which have non-nullable FKs)
1196 // all deletions on these tables have transactions so final failure rollbacks these updates
1197 // @todo: Normalize the schema to match MySQL, no special FKs and such
1198 $table = $this->tableName( $table );
1199 if ( $table == $this->tableName( 'user' ) &&
1200 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
)
1202 $this->update( 'archive', [ 'ar_user' => 0 ],
1203 [ 'ar_user' => $conds['user_id'] ], $fname );
1204 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1205 [ 'ipb_user' => $conds['user_id'] ], $fname );
1206 $this->update( 'image', [ 'img_user' => 0 ],
1207 [ 'img_user' => $conds['user_id'] ], $fname );
1208 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1209 [ 'oi_user' => $conds['user_id'] ], $fname );
1210 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1211 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1212 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1213 [ 'fa_user' => $conds['user_id'] ], $fname );
1214 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1215 [ 'us_user' => $conds['user_id'] ], $fname );
1216 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1217 [ 'rc_user' => $conds['user_id'] ], $fname );
1218 $this->update( 'logging', [ 'log_user' => 0 ],
1219 [ 'log_user' => $conds['user_id'] ], $fname );
1220 } elseif ( $table == $this->tableName( 'image' ) ) {
1221 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1222 [ 'oi_name' => $conds['img_name'] ], $fname );
1225 return parent
::delete( $table, $conds, $fname );
1229 * @param string $table
1230 * @param array $values
1231 * @param array $conds
1232 * @param string $fname
1233 * @param array $options
1235 * @throws DBUnexpectedError
1237 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1238 $table = $this->tableName( $table );
1239 $opts = $this->makeUpdateOptions( $options );
1240 $sql = "UPDATE $opts $table SET ";
1243 foreach ( $values as $col => &$val ) {
1244 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1247 $sqlSet = ', ' . $sqlSet;
1254 if ( $conds !== [] && $conds !== '*' ) {
1255 $conds = $this->wrapConditionsForWhere( $table, $conds );
1256 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1259 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
1260 if ( $stmt === false ) {
1261 $e = oci_error( $this->conn
);
1262 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1266 foreach ( $values as $col => &$val ) {
1267 $col_info = $this->fieldInfoMulti( $table, $col );
1268 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1270 if ( $val === null ) {
1271 // do nothing ... null was inserted in statement creation
1272 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1273 if ( is_object( $val ) ) {
1274 $val = $val->getData();
1278 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
1279 strtolower( $val ) == 'infinity'
1281 $val = '31-12-2030 12:00:00.000000';
1284 $val = $this->getVerifiedUTF8( $val );
1285 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1286 $e = oci_error( $stmt );
1287 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1292 /** @var OCI_Lob[] $lob */
1293 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
1294 if ( $lob[$col] === false ) {
1295 $e = oci_error( $stmt );
1296 throw new DBUnexpectedError(
1298 "Cannot create LOB descriptor: " . $e['message']
1302 if ( is_object( $val ) ) {
1303 $val = $val->getData();
1306 if ( $col_type == 'BLOB' ) {
1307 $lob[$col]->writeTemporary( $val );
1308 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1310 $lob[$col]->writeTemporary( $val );
1311 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1316 Wikimedia\
suppressWarnings();
1318 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1319 $e = oci_error( $stmt );
1320 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1321 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1325 $this->mAffectedRows
= oci_num_rows( $stmt );
1328 $this->mAffectedRows
= oci_num_rows( $stmt );
1331 Wikimedia\restoreWarnings
();
1333 if ( isset( $lob ) ) {
1334 foreach ( $lob as $lob_v ) {
1339 if ( !$this->trxLevel() ) {
1340 oci_commit( $this->conn
);
1343 return oci_free_statement( $stmt );
1346 function bitNot( $field ) {
1347 // expecting bit-fields smaller than 4bytes
1348 return 'BITNOT(' . $field . ')';
1351 function bitAnd( $fieldLeft, $fieldRight ) {
1352 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1355 function bitOr( $fieldLeft, $fieldRight ) {
1356 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1359 public function buildGroupConcatField(
1360 $delim, $table, $field, $conds = '', $join_conds = []
1362 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1364 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1367 public function buildSubstring( $input, $startPosition, $length = null ) {
1368 $this->assertBuildSubstringParams( $startPosition, $length );
1369 $params = [ $input, $startPosition ];
1370 if ( $length !== null ) {
1371 $params[] = $length;
1373 return 'SUBSTR(' . implode( ',', $params ) . ')';
1377 * @param string $field Field or column to cast
1381 public function buildStringCast( $field ) {
1382 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1385 public function getInfinity() {
1386 return '31-12-2030 12:00:00.000000';
1393 private function getVerifiedUTF8( $s ) {
1394 if ( mb_check_encoding( (string)$s, 'UTF-8' ) ) {
1398 throw new DBUnexpectedError( $this, "Non BLOB/CLOB field must be UTF-8." );