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\Timestamp\ConvertibleTimestamp
;
25 use Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\DatabaseDomain
;
27 use Wikimedia\Rdbms\Blob
;
28 use Wikimedia\Rdbms\ResultWrapper
;
29 use Wikimedia\Rdbms\IResultWrapper
;
30 use Wikimedia\Rdbms\DBConnectionError
;
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 function __construct( array $params ) {
65 $this->keywordTableMap
= $params['keywordTableMap'] ??
[];
66 $params['tablePrefix'] = strtoupper( $params['tablePrefix'] );
67 parent
::__construct( $params );
70 function __destruct() {
71 if ( $this->opened
) {
72 Wikimedia\
suppressWarnings();
74 Wikimedia\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 new DBConnectionError(
94 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
95 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
101 $this->password
= $password;
103 // Backward compatibility (server used to be null and TNS was supplied in dbname)
104 $this->server
= $dbName;
105 $realDatabase = $user;
107 // $server now holds the TNS endpoint
108 $this->server
= $server;
109 // $dbName is schema name if different from username
110 $realDatabase = $dbName ?
: $user;
113 if ( !strlen( $user ) ) { # e.g. the class is being loaded
117 $session_mode = ( $this->flags
& DBO_SYSDBA
) ? OCI_SYSDBA
: OCI_DEFAULT
;
119 Wikimedia\
suppressWarnings();
120 if ( $this->flags
& DBO_PERSISTENT
) {
121 $this->conn
= oci_pconnect(
125 $this->defaultCharset
,
128 } elseif ( $this->flags
& DBO_DEFAULT
) {
129 $this->conn
= oci_new_connect(
133 $this->defaultCharset
,
137 $this->conn
= oci_connect(
141 $this->defaultCharset
,
145 Wikimedia\restoreWarnings
();
147 if ( $this->user
!= $realDatabase ) {
148 // change current schema in session
149 $this->selectDB( $realDatabase );
151 $this->currentDomain
= new DatabaseDomain(
158 if ( !$this->conn
) {
159 throw new DBConnectionError( $this, $this->lastError() );
162 $this->opened
= true;
164 # removed putenv calls because they interfere with the system globaly
165 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
166 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
167 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
169 return (bool)$this->conn
;
173 * Closes a database connection, if it is open
174 * Returns success, true if already closed
177 protected function closeConnection() {
178 return oci_close( $this->conn
);
181 function execFlags() {
182 return $this->trxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
187 * @return bool|mixed|ORAResult
189 protected function doQuery( $sql ) {
190 if ( !mb_check_encoding( (string)$sql, 'UTF-8' ) ) {
191 throw new DBUnexpectedError( $this, "SQL encoding is invalid\n$sql" );
194 // handle some oracle specifics
195 // remove AS column/table/subquery namings
196 if ( !$this->getFlag( DBO_DDLMODE
) ) {
197 $sql = preg_replace( '/ as /i', ' ', $sql );
200 // Oracle has issues with UNION clause if the statement includes LOB fields
201 // So we do a UNION ALL and then filter the results array with array_unique
202 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
203 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
204 // you have to select data from plan table after explain
205 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
209 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
215 Wikimedia\
suppressWarnings();
217 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
218 if ( $stmt === false ) {
219 $e = oci_error( $this->conn
);
220 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
225 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
226 $e = oci_error( $stmt );
227 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
228 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
234 Wikimedia\restoreWarnings
();
236 if ( $explain_count > 0 ) {
237 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
238 'WHERE statement_id = \'' . $explain_id . '\'' );
239 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
240 return new ORAResult( $this, $stmt, $union_unique );
242 $this->mAffectedRows
= oci_num_rows( $stmt );
248 function queryIgnore( $sql, $fname = '' ) {
249 return $this->query( $sql, $fname, true );
253 * Frees resources associated with the LOB descriptor
254 * @param IResultWrapper|ORAResult $res
256 function freeResult( $res ) {
257 if ( $res instanceof ResultWrapper
) {
265 * @param IResultWrapper|ORAResult $res
266 * @return stdClass|bool
268 function fetchObject( $res ) {
269 if ( $res instanceof ResultWrapper
) {
273 return $res->fetchObject();
277 * @param IResultWrapper|ORAResult $res
278 * @return stdClass|bool
280 function fetchRow( $res ) {
281 if ( $res instanceof ResultWrapper
) {
285 return $res->fetchRow();
289 * @param IResultWrapper|ORAResult $res
292 function numRows( $res ) {
293 if ( $res instanceof ResultWrapper
) {
297 return $res->numRows();
301 * @param IResultWrapper|ORAResult $res
304 function numFields( $res ) {
305 if ( $res instanceof ResultWrapper
) {
309 return $res->numFields();
312 function fieldName( $stmt, $n ) {
313 return oci_field_name( $stmt, $n );
316 function insertId() {
317 $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
318 $row = $this->fetchRow( $res );
319 return is_null( $row[0] ) ?
null : (int)$row[0];
326 function dataSeek( $res, $row ) {
327 if ( $res instanceof ORAResult
) {
330 $res->result
->seek( $row );
334 function lastError() {
335 if ( $this->conn
=== false ) {
338 $e = oci_error( $this->conn
);
341 return $e['message'];
344 function lastErrno() {
345 if ( $this->conn
=== false ) {
348 $e = oci_error( $this->conn
);
354 protected function fetchAffectedRowCount() {
355 return $this->mAffectedRows
;
359 * Returns information about an index
360 * If errors are explicitly ignored, returns NULL on failure
361 * @param string $table
362 * @param string $index
363 * @param string $fname
366 function indexInfo( $table, $index, $fname = __METHOD__
) {
370 function indexUnique( $table, $index, $fname = __METHOD__
) {
374 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
375 if ( !count( $a ) ) {
379 if ( !is_array( $options ) ) {
380 $options = [ $options ];
383 if ( in_array( 'IGNORE', $options ) ) {
384 $this->ignoreDupValOnIndex
= true;
387 if ( !is_array( reset( $a ) ) ) {
391 foreach ( $a as &$row ) {
392 $this->insertOneRow( $table, $row, $fname );
395 if ( in_array( 'IGNORE', $options ) ) {
396 $this->ignoreDupValOnIndex
= false;
402 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
403 $col_info = $this->fieldInfoMulti( $table, $col );
404 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
407 if ( is_numeric( $col ) ) {
412 } elseif ( $includeCol ) {
416 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
420 if ( $val === 'NULL' ) {
424 if ( $val === null ) {
426 $col_info != false &&
427 $col_info->isNullable() == 0 &&
428 $col_info->defaultValue() != null
442 * @param string $table
444 * @param string $fname
446 * @throws DBUnexpectedError
448 private function insertOneRow( $table, $row, $fname ) {
449 $table = $this->tableName( $table );
450 // "INSERT INTO tables (a, b, c)"
451 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
454 // for each value, append ":key"
456 foreach ( $row as $col => &$val ) {
462 if ( $this->isQuotedIdentifier( $val ) ) {
463 $sql .= $this->removeIdentifierQuotes( $val );
466 $sql .= $this->fieldBindStatement( $table, $col, $val );
471 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
472 if ( $stmt === false ) {
473 $e = oci_error( $this->conn
);
474 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
478 foreach ( $row as $col => &$val ) {
479 $col_info = $this->fieldInfoMulti( $table, $col );
480 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
482 if ( $val === null ) {
483 // do nothing ... null was inserted in statement creation
484 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
485 if ( is_object( $val ) ) {
486 $val = $val->fetch();
489 // backward compatibility
491 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
492 strtolower( $val ) == 'infinity'
494 $val = $this->getInfinity();
497 $val = $this->getVerifiedUTF8( $val );
498 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
499 $e = oci_error( $stmt );
500 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
505 /** @var OCI_Lob[] $lob */
506 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
507 if ( $lob[$col] === false ) {
508 $e = oci_error( $stmt );
509 throw new DBUnexpectedError(
511 "Cannot create LOB descriptor: " . $e['message']
515 if ( is_object( $val ) ) {
516 $val = $val->fetch();
519 if ( $col_type == 'BLOB' ) {
520 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
521 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
523 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
524 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
529 Wikimedia\
suppressWarnings();
531 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
532 $e = oci_error( $stmt );
533 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
534 $this->reportQueryError( $e['message'], $e['code'], $sql, $fname );
538 $this->mAffectedRows
= oci_num_rows( $stmt );
541 $this->mAffectedRows
= oci_num_rows( $stmt );
544 Wikimedia\restoreWarnings
();
546 if ( isset( $lob ) ) {
547 foreach ( $lob as $lob_v ) {
552 if ( !$this->trxLevel
) {
553 oci_commit( $this->conn
);
556 return oci_free_statement( $stmt );
559 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
560 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
562 $destTable = $this->tableName( $destTable );
564 $sequenceData = $this->getSequenceData( $destTable );
565 if ( $sequenceData !== false &&
566 !isset( $varMap[$sequenceData['column']] )
568 $varMap[$sequenceData['column']] =
569 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
572 // count-alias subselect fields to avoid abigious definition errors
574 foreach ( $varMap as &$val ) {
575 $val .= ' field' . $i;
579 $selectSql = $this->selectSQLText(
581 array_values( $varMap ),
588 $sql = "INSERT INTO $destTable (" .
589 implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
591 if ( in_array( 'IGNORE', $insertOptions ) ) {
592 $this->ignoreDupValOnIndex
= true;
595 $this->query( $sql, $fname );
597 if ( in_array( 'IGNORE', $insertOptions ) ) {
598 $this->ignoreDupValOnIndex
= false;
602 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
605 if ( $rows === [] ) {
606 return true; // nothing to do
609 if ( !is_array( reset( $rows ) ) ) {
613 $sequenceData = $this->getSequenceData( $table );
614 if ( $sequenceData !== false ) {
615 // add sequence column to each list of columns, when not set
616 foreach ( $rows as &$row ) {
617 if ( !isset( $row[$sequenceData['column']] ) ) {
618 $row[$sequenceData['column']] =
619 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
620 $sequenceData['sequence'] . '\')' );
625 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
628 public function tableName( $name, $format = 'quoted' ) {
629 // Replace reserved words with better ones
630 $name = $this->remappedTableName( $name );
632 return strtoupper( parent
::tableName( $name, $format ) );
636 * @param string $name
637 * @return string Value of $name or remapped name if $name is a reserved keyword
639 public function remappedTableName( $name ) {
640 return $this->keywordTableMap
[$name] ??
$name;
643 function tableNameInternal( $name ) {
644 $name = $this->tableName( $name );
646 return preg_replace( '/.*\.(.*)/', '$1', $name );
650 * Return sequence_name if table has a sequence
652 * @param string $table
653 * @return string[]|bool
655 private function getSequenceData( $table ) {
656 if ( $this->sequenceData
== null ) {
657 $dbname = $this->currentDomain
->getDatabase();
658 $prefix = $this->currentDomain
->getTablePrefix();
659 // See https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm
660 $decodeArgs = [ 'atc.table_name' ]; // the switch
661 foreach ( $this->keywordTableMap
as $reserved => $alternative ) {
662 $search = strtoupper( $prefix . $alternative ); // case
663 $replace = strtoupper( $prefix . $reserved ); // result
664 $decodeArgs[] = $this->addQuotes( $search );
665 $decodeArgs[] = $this->addQuotes( $replace );
667 $decodeArgs[] = [ 'atc.table_name' ]; // default
668 $decodeArgs = implode( ', ', $decodeArgs );
670 $result = $this->doQuery(
671 "SELECT lower(asq.sequence_name), lower(atc.table_name), lower(atc.column_name)
672 FROM all_sequences asq, all_tab_columns atc
673 WHERE decode({$decodeArgs}) || '_' ||
674 atc.column_name || '_SEQ' = '{$prefix}' || asq.sequence_name
675 AND asq.sequence_owner = upper('{$dbname}')
676 AND atc.owner = upper('{$dbname}')"
679 while ( ( $row = $result->fetchRow() ) !== false ) {
680 $this->sequenceData
[$row[1]] = [
681 'sequence' => $row[0],
686 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
688 return $this->sequenceData
[$table] ??
false;
692 * Returns the size of a text field, or -1 for "unlimited"
694 * @param string $table
695 * @param string $field
698 function textFieldSize( $table, $field ) {
699 $fieldInfoData = $this->fieldInfo( $table, $field );
701 return $fieldInfoData->maxLength();
704 function limitResult( $sql, $limit, $offset = false ) {
705 if ( $offset === false ) {
709 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
712 function encodeBlob( $b ) {
713 return new Blob( $b );
716 function unionQueries( $sqls, $all ) {
717 $glue = ' UNION ALL ';
719 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
720 'FROM (' . implode( $glue, $sqls ) . ')';
723 function wasDeadlock() {
724 return $this->lastErrno() == 'OCI-00060';
727 function duplicateTableStructure( $oldName, $newName, $temporary = false,
730 $temporary = $temporary ?
'TRUE' : 'FALSE';
731 $tablePrefix = $this->currentDomain
->getTablePrefix();
733 $newName = strtoupper( $newName );
734 $oldName = strtoupper( $oldName );
736 $tabName = substr( $newName, strlen( $tablePrefix ) );
737 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
738 $newPrefix = strtoupper( $tablePrefix );
740 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
741 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
744 function listTables( $prefix = null, $fname = __METHOD__
) {
746 if ( !empty( $prefix ) ) {
747 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
750 $owner = strtoupper( $this->getDBname() );
751 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
752 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
754 // dirty code ... i know
756 $endArray[] = strtoupper( $prefix . 'MWUSER' );
757 $endArray[] = strtoupper( $prefix . 'PAGE' );
758 $endArray[] = strtoupper( $prefix . 'IMAGE' );
759 $fixedOrderTabs = $endArray;
760 while ( ( $row = $result->fetchRow() ) !== false ) {
761 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
762 $endArray[] = $row['table_name'];
769 public function dropTable( $tableName, $fName = __METHOD__
) {
770 $tableName = $this->tableName( $tableName );
771 if ( !$this->tableExists( $tableName ) ) {
775 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
778 public function timestamp( $ts = 0 ) {
779 $t = new ConvertibleTimestamp( $ts );
780 // Let errors bubble up to avoid putting garbage in the DB
781 return $t->getTimestamp( TS_ORACLE
);
785 * Return aggregated value function call
787 * @param array $valuedata
788 * @param string $valuename
791 public function aggregateValue( $valuedata, $valuename = 'value' ) {
796 * @return string Wikitext of a link to the server software's web site
798 public function getSoftwareLink() {
799 return '[{{int:version-db-oracle-url}} Oracle]';
803 * @return string Version information from the database
805 function getServerVersion() {
806 // better version number, fallback on driver
807 $rset = $this->doQuery(
808 'SELECT version FROM product_component_version ' .
809 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
811 $row = $rset->fetchRow();
813 return oci_server_version( $this->conn
);
816 return $row['version'];
820 * Query whether a given index exists
821 * @param string $table
822 * @param string $index
823 * @param string $fname
826 function indexExists( $table, $index, $fname = __METHOD__
) {
827 $table = $this->tableName( $table );
828 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
829 $index = strtoupper( $index );
830 $owner = strtoupper( $this->getDBname() );
831 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
832 $res = $this->doQuery( $sql );
834 $count = $res->numRows();
844 * Query whether a given table exists (in the given schema, or the default mw one if not given)
845 * @param string $table
846 * @param string $fname
849 function tableExists( $table, $fname = __METHOD__
) {
850 $table = $this->tableName( $table );
851 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
852 $owner = $this->addQuotes( strtoupper( $this->getDBname() ) );
853 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
854 $res = $this->doQuery( $sql );
855 if ( $res && $res->numRows() > 0 ) {
867 * Function translates mysql_fetch_field() functionality on ORACLE.
868 * Caching is present for reducing query time.
869 * For internal calls. Use fieldInfo for normal usage.
870 * Returns false if the field doesn't exist
872 * @param array|string $table
873 * @param string $field
874 * @return ORAField|ORAResult|false
876 private function fieldInfoMulti( $table, $field ) {
877 $field = strtoupper( $field );
878 if ( is_array( $table ) ) {
879 $table = array_map( [ $this, 'tableNameInternal' ], $table );
880 $tableWhere = 'IN (';
881 foreach ( $table as &$singleTable ) {
882 $singleTable = $this->removeIdentifierQuotes( $singleTable );
883 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
884 return $this->mFieldInfoCache
["$singleTable.$field"];
886 $tableWhere .= '\'' . $singleTable . '\',';
888 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
890 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
891 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
892 return $this->mFieldInfoCache
["$table.$field"];
894 $tableWhere = '= \'' . $table . '\'';
897 $fieldInfoStmt = oci_parse(
899 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
900 $tableWhere . ' and column_name = \'' . $field . '\''
902 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
903 $e = oci_error( $fieldInfoStmt );
904 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
908 $res = new ORAResult( $this, $fieldInfoStmt );
909 if ( $res->numRows() == 0 ) {
910 if ( is_array( $table ) ) {
911 foreach ( $table as &$singleTable ) {
912 $this->mFieldInfoCache
["$singleTable.$field"] = false;
915 $this->mFieldInfoCache
["$table.$field"] = false;
917 $fieldInfoTemp = null;
919 $fieldInfoTemp = new ORAField( $res->fetchRow() );
920 $table = $fieldInfoTemp->tableName();
921 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
925 return $fieldInfoTemp;
929 * @throws DBUnexpectedError
930 * @param string $table
931 * @param string $field
934 function fieldInfo( $table, $field ) {
935 if ( is_array( $table ) ) {
936 throw new DBUnexpectedError(
938 'DatabaseOracle::fieldInfo called with table array!'
942 return $this->fieldInfoMulti( $table, $field );
945 protected function doBegin( $fname = __METHOD__
) {
947 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
950 protected function doCommit( $fname = __METHOD__
) {
951 if ( $this->trxLevel
) {
952 $ret = oci_commit( $this->conn
);
954 throw new DBUnexpectedError( $this, $this->lastError() );
957 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
961 protected function doRollback( $fname = __METHOD__
) {
962 if ( $this->trxLevel
) {
963 oci_rollback( $this->conn
);
965 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
969 function sourceStream(
971 callable
$lineCallback = null,
972 callable
$resultCallback = null,
973 $fname = __METHOD__
, callable
$inputCallback = null
977 $dollarquote = false;
980 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
981 while ( !feof( $fp ) ) {
982 if ( $lineCallback ) {
985 $line = trim( fgets( $fp, 1024 ) );
986 $sl = strlen( $line ) - 1;
991 if ( $line[0] == '-' && $line[1] == '-' ) {
995 // Allow dollar quoting for function declarations
996 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
997 if ( $dollarquote ) {
998 $dollarquote = false;
999 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1002 $dollarquote = true;
1004 } elseif ( !$dollarquote ) {
1005 if ( $line[$sl] == ';' && ( $sl < 2 ||
$line[$sl - 1] != ';' ) ) {
1007 $line = substr( $line, 0, $sl );
1017 $cmd = str_replace( ';;', ";", $cmd );
1018 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1019 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1020 $replacements[$defines[2]] = $defines[1];
1023 foreach ( $replacements as $mwVar => $scVar ) {
1024 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1027 $cmd = $this->replaceVars( $cmd );
1028 if ( $inputCallback ) {
1029 $inputCallback( $cmd );
1031 $res = $this->doQuery( $cmd );
1032 if ( $resultCallback ) {
1033 call_user_func( $resultCallback, $res, $this );
1036 if ( $res === false ) {
1037 $err = $this->lastError();
1039 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1051 protected function doSelectDomain( DatabaseDomain
$domain ) {
1052 if ( $domain->getSchema() !== null ) {
1053 // We use the *database* aspect of $domain for schema, not the domain schema
1054 throw new DBExpectedError( $this, __CLASS__
. ": domain schemas are not supported." );
1057 $database = $domain->getDatabase();
1058 if ( $database === null ||
$database === $this->user
) {
1059 // Backward compatibility
1060 $this->currentDomain
= $domain;
1065 // https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj32268.html
1066 $encDatabase = $this->addIdentifierQuotes( strtoupper( $database ) );
1067 $sql = "ALTER SESSION SET CURRENT_SCHEMA=$encDatabase";
1068 $stmt = oci_parse( $this->conn
, $sql );
1069 Wikimedia\
suppressWarnings();
1070 $success = oci_execute( $stmt );
1071 Wikimedia\restoreWarnings
();
1073 // Update that domain fields on success (no exception thrown)
1074 $this->currentDomain
= $domain;
1076 $e = oci_error( $stmt );
1077 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1083 function strencode( $s ) {
1084 return str_replace( "'", "''", $s );
1087 function addQuotes( $s ) {
1088 return "'" . $this->strencode( $this->getVerifiedUTF8( $s ) ) . "'";
1091 public function addIdentifierQuotes( $s ) {
1092 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1099 public function removeIdentifierQuotes( $s ) {
1100 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1103 public function isQuotedIdentifier( $s ) {
1104 return strpos( $s, '/*Q*/' ) !== false;
1107 private function wrapFieldForWhere( $table, &$col, &$val ) {
1108 $col_info = $this->fieldInfoMulti( $table, $col );
1109 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1110 if ( $col_type == 'CLOB' ) {
1111 $col = 'TO_CHAR(' . $col . ')';
1112 $val = $this->getVerifiedUTF8( $val );
1113 } elseif ( $col_type == 'VARCHAR2' ) {
1114 $val = $this->getVerifiedUTF8( $val );
1118 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1120 foreach ( $conds as $col => $val ) {
1121 if ( is_array( $val ) ) {
1122 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1124 if ( is_numeric( $col ) && $parentCol != null ) {
1125 $this->wrapFieldForWhere( $table, $parentCol, $val );
1127 $this->wrapFieldForWhere( $table, $col, $val );
1129 $conds2[$col] = $val;
1136 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1137 $options = [], $join_conds = []
1139 if ( is_array( $conds ) ) {
1140 $conds = $this->wrapConditionsForWhere( $table, $conds );
1143 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1147 * Returns an optional USE INDEX clause to go after the table, and a
1148 * string to go at the end of the query
1150 * @param array $options An associative array of options to be turned into
1151 * an SQL query, valid keys are listed in the function.
1154 function makeSelectOptions( $options ) {
1155 $preLimitTail = $postLimitTail = '';
1159 foreach ( $options as $key => $option ) {
1160 if ( is_numeric( $key ) ) {
1161 $noKeyOptions[$option] = true;
1165 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1167 $preLimitTail .= $this->makeOrderBy( $options );
1169 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1170 $postLimitTail .= ' FOR UPDATE';
1173 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1174 $startOpts .= 'DISTINCT';
1177 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1178 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1183 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1184 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1189 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1192 public function delete( $table, $conds, $fname = __METHOD__
) {
1193 global $wgActorTableSchemaMigrationStage;
1195 if ( is_array( $conds ) ) {
1196 $conds = $this->wrapConditionsForWhere( $table, $conds );
1198 // a hack for deleting pages, users and images (which have non-nullable FKs)
1199 // all deletions on these tables have transactions so final failure rollbacks these updates
1200 // @todo: Normalize the schema to match MySQL, no special FKs and such
1201 $table = $this->tableName( $table );
1202 if ( $table == $this->tableName( 'user' ) &&
1203 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
)
1205 $this->update( 'archive', [ 'ar_user' => 0 ],
1206 [ 'ar_user' => $conds['user_id'] ], $fname );
1207 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1208 [ 'ipb_user' => $conds['user_id'] ], $fname );
1209 $this->update( 'image', [ 'img_user' => 0 ],
1210 [ 'img_user' => $conds['user_id'] ], $fname );
1211 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1212 [ 'oi_user' => $conds['user_id'] ], $fname );
1213 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1214 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1215 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1216 [ 'fa_user' => $conds['user_id'] ], $fname );
1217 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1218 [ 'us_user' => $conds['user_id'] ], $fname );
1219 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1220 [ 'rc_user' => $conds['user_id'] ], $fname );
1221 $this->update( 'logging', [ 'log_user' => 0 ],
1222 [ 'log_user' => $conds['user_id'] ], $fname );
1223 } elseif ( $table == $this->tableName( 'image' ) ) {
1224 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1225 [ 'oi_name' => $conds['img_name'] ], $fname );
1228 return parent
::delete( $table, $conds, $fname );
1232 * @param string $table
1233 * @param array $values
1234 * @param array $conds
1235 * @param string $fname
1236 * @param array $options
1238 * @throws DBUnexpectedError
1240 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1241 $table = $this->tableName( $table );
1242 $opts = $this->makeUpdateOptions( $options );
1243 $sql = "UPDATE $opts $table SET ";
1246 foreach ( $values as $col => &$val ) {
1247 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1250 $sqlSet = ', ' . $sqlSet;
1257 if ( $conds !== [] && $conds !== '*' ) {
1258 $conds = $this->wrapConditionsForWhere( $table, $conds );
1259 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1262 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
1263 if ( $stmt === false ) {
1264 $e = oci_error( $this->conn
);
1265 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1269 foreach ( $values as $col => &$val ) {
1270 $col_info = $this->fieldInfoMulti( $table, $col );
1271 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1273 if ( $val === null ) {
1274 // do nothing ... null was inserted in statement creation
1275 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1276 if ( is_object( $val ) ) {
1277 $val = $val->getData();
1281 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
1282 strtolower( $val ) == 'infinity'
1284 $val = '31-12-2030 12:00:00.000000';
1287 $val = $this->getVerifiedUTF8( $val );
1288 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1289 $e = oci_error( $stmt );
1290 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1295 /** @var OCI_Lob[] $lob */
1296 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
1297 if ( $lob[$col] === false ) {
1298 $e = oci_error( $stmt );
1299 throw new DBUnexpectedError(
1301 "Cannot create LOB descriptor: " . $e['message']
1305 if ( is_object( $val ) ) {
1306 $val = $val->getData();
1309 if ( $col_type == 'BLOB' ) {
1310 $lob[$col]->writeTemporary( $val );
1311 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1313 $lob[$col]->writeTemporary( $val );
1314 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1319 Wikimedia\
suppressWarnings();
1321 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1322 $e = oci_error( $stmt );
1323 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1324 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1328 $this->mAffectedRows
= oci_num_rows( $stmt );
1331 $this->mAffectedRows
= oci_num_rows( $stmt );
1334 Wikimedia\restoreWarnings
();
1336 if ( isset( $lob ) ) {
1337 foreach ( $lob as $lob_v ) {
1342 if ( !$this->trxLevel
) {
1343 oci_commit( $this->conn
);
1346 return oci_free_statement( $stmt );
1349 function bitNot( $field ) {
1350 // expecting bit-fields smaller than 4bytes
1351 return 'BITNOT(' . $field . ')';
1354 function bitAnd( $fieldLeft, $fieldRight ) {
1355 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1358 function bitOr( $fieldLeft, $fieldRight ) {
1359 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1362 public function buildGroupConcatField(
1363 $delim, $table, $field, $conds = '', $join_conds = []
1365 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1367 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1370 public function buildSubstring( $input, $startPosition, $length = null ) {
1371 $this->assertBuildSubstringParams( $startPosition, $length );
1372 $params = [ $input, $startPosition ];
1373 if ( $length !== null ) {
1374 $params[] = $length;
1376 return 'SUBSTR(' . implode( ',', $params ) . ')';
1380 * @param string $field Field or column to cast
1384 public function buildStringCast( $field ) {
1385 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1388 public function getInfinity() {
1389 return '31-12-2030 12:00:00.000000';
1396 private function getVerifiedUTF8( $s ) {
1397 if ( mb_check_encoding( (string)$s, 'UTF-8' ) ) {
1401 throw new DBUnexpectedError( $this, "Non BLOB/CLOB field must be UTF-8." );