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 MediaWiki\MediaWikiServices
;
25 use Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\DatabaseDomain
;
27 use Wikimedia\Rdbms\Blob
;
28 use Wikimedia\Rdbms\ResultWrapper
;
29 use Wikimedia\Rdbms\DBConnectionError
;
30 use Wikimedia\Rdbms\DBUnexpectedError
;
31 use Wikimedia\Rdbms\DBExpectedError
;
36 class DatabaseOracle
extends Database
{
38 protected $mLastResult = null;
40 /** @var int The number of rows affected as an integer */
41 protected $mAffectedRows;
44 private $ignoreDupValOnIndex = false;
46 /** @var bool|array */
47 private $sequenceData = null;
49 /** @var string Character set for Oracle database */
50 private $defaultCharset = 'AL32UTF8';
53 private $mFieldInfoCache = [];
55 function __construct( array $p ) {
58 if ( $p['tablePrefix'] == 'get from global' ) {
59 $p['tablePrefix'] = $wgDBprefix;
61 $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
62 parent
::__construct( $p );
63 Hooks
::run( 'DatabaseOraclePostInit', [ $this ] );
66 function __destruct() {
67 if ( $this->opened
) {
68 Wikimedia\
suppressWarnings();
70 Wikimedia\restoreWarnings
();
78 function implicitGroupby() {
82 function implicitOrderby() {
86 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
87 global $wgDBOracleDRCP;
89 if ( !function_exists( 'oci_connect' ) ) {
90 throw new DBConnectionError(
92 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
93 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
99 $this->password
= $password;
101 // Backward compatibility (server used to be null and TNS was supplied in dbname)
102 $this->server
= $dbName;
103 $realDatabase = $user;
105 // $server now holds the TNS endpoint
106 $this->server
= $server;
107 // $dbName is schema name if different from username
108 $realDatabase = $dbName ?
: $user;
111 if ( !strlen( $user ) ) { # e.g. the class is being loaded
115 if ( $wgDBOracleDRCP ) {
116 $this->setFlag( DBO_PERSISTENT
);
119 $session_mode = $this->flags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
121 Wikimedia\
suppressWarnings();
122 if ( $this->flags
& DBO_PERSISTENT
) {
123 $this->conn
= oci_pconnect(
127 $this->defaultCharset
,
130 } elseif ( $this->flags
& DBO_DEFAULT
) {
131 $this->conn
= oci_new_connect(
135 $this->defaultCharset
,
139 $this->conn
= oci_connect(
143 $this->defaultCharset
,
147 Wikimedia\restoreWarnings
();
149 if ( $this->user
!= $realDatabase ) {
150 // change current schema in session
151 $this->selectDB( $realDatabase );
153 $this->currentDomain
= new DatabaseDomain(
160 if ( !$this->conn
) {
161 throw new DBConnectionError( $this, $this->lastError() );
164 $this->opened
= true;
166 # removed putenv calls because they interfere with the system globaly
167 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
168 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
169 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
171 return (bool)$this->conn
;
175 * Closes a database connection, if it is open
176 * Returns success, true if already closed
179 protected function closeConnection() {
180 return oci_close( $this->conn
);
183 function execFlags() {
184 return $this->trxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
189 * @return bool|mixed|ORAResult
191 protected function doQuery( $sql ) {
192 wfDebug( "SQL: [$sql]\n" );
193 if ( !StringUtils
::isUtf8( $sql ) ) {
194 throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
197 // handle some oracle specifics
198 // remove AS column/table/subquery namings
199 if ( !$this->getFlag( DBO_DDLMODE
) ) {
200 $sql = preg_replace( '/ as /i', ' ', $sql );
203 // Oracle has issues with UNION clause if the statement includes LOB fields
204 // So we do a UNION ALL and then filter the results array with array_unique
205 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
206 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
207 // you have to select data from plan table after explain
208 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
212 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
218 Wikimedia\
suppressWarnings();
220 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
221 if ( $stmt === false ) {
222 $e = oci_error( $this->conn
);
223 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
228 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
229 $e = oci_error( $stmt );
230 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
231 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
237 Wikimedia\restoreWarnings
();
239 if ( $explain_count > 0 ) {
240 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
241 'WHERE statement_id = \'' . $explain_id . '\'' );
242 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
243 return new ORAResult( $this, $stmt, $union_unique );
245 $this->mAffectedRows
= oci_num_rows( $stmt );
251 function queryIgnore( $sql, $fname = '' ) {
252 return $this->query( $sql, $fname, true );
256 * Frees resources associated with the LOB descriptor
257 * @param ResultWrapper|ORAResult $res
259 function freeResult( $res ) {
260 if ( $res instanceof ResultWrapper
) {
268 * @param ResultWrapper|ORAResult $res
271 function fetchObject( $res ) {
272 if ( $res instanceof ResultWrapper
) {
276 return $res->fetchObject();
280 * @param ResultWrapper|ORAResult $res
283 function fetchRow( $res ) {
284 if ( $res instanceof ResultWrapper
) {
288 return $res->fetchRow();
292 * @param ResultWrapper|ORAResult $res
295 function numRows( $res ) {
296 if ( $res instanceof ResultWrapper
) {
300 return $res->numRows();
304 * @param ResultWrapper|ORAResult $res
307 function numFields( $res ) {
308 if ( $res instanceof ResultWrapper
) {
312 return $res->numFields();
315 function fieldName( $stmt, $n ) {
316 return oci_field_name( $stmt, $n );
319 function insertId() {
320 $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
321 $row = $this->fetchRow( $res );
322 return is_null( $row[0] ) ?
null : (int)$row[0];
329 function dataSeek( $res, $row ) {
330 if ( $res instanceof ORAResult
) {
333 $res->result
->seek( $row );
337 function lastError() {
338 if ( $this->conn
=== false ) {
341 $e = oci_error( $this->conn
);
344 return $e['message'];
347 function lastErrno() {
348 if ( $this->conn
=== false ) {
351 $e = oci_error( $this->conn
);
357 protected function fetchAffectedRowCount() {
358 return $this->mAffectedRows
;
362 * Returns information about an index
363 * If errors are explicitly ignored, returns NULL on failure
364 * @param string $table
365 * @param string $index
366 * @param string $fname
369 function indexInfo( $table, $index, $fname = __METHOD__
) {
373 function indexUnique( $table, $index, $fname = __METHOD__
) {
377 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
378 if ( !count( $a ) ) {
382 if ( !is_array( $options ) ) {
383 $options = [ $options ];
386 if ( in_array( 'IGNORE', $options ) ) {
387 $this->ignoreDupValOnIndex
= true;
390 if ( !is_array( reset( $a ) ) ) {
394 foreach ( $a as &$row ) {
395 $this->insertOneRow( $table, $row, $fname );
398 if ( in_array( 'IGNORE', $options ) ) {
399 $this->ignoreDupValOnIndex
= false;
405 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
406 $col_info = $this->fieldInfoMulti( $table, $col );
407 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
410 if ( is_numeric( $col ) ) {
415 } elseif ( $includeCol ) {
419 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
423 if ( $val === 'NULL' ) {
427 if ( $val === null ) {
428 if ( $col_info != false && $col_info->isNullable() == 0 && $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, __METHOD__
);
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
489 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
490 $val = $this->getInfinity();
493 $val = MediaWikiServices
::getInstance()->getContentLanguage()->
494 checkTitleEncoding( $val );
495 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
496 $e = oci_error( $stmt );
497 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
502 /** @var OCI_Lob[] $lob */
503 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
504 if ( $lob[$col] === false ) {
505 $e = oci_error( $stmt );
506 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
509 if ( is_object( $val ) ) {
510 $val = $val->fetch();
513 if ( $col_type == 'BLOB' ) {
514 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
515 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
517 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
518 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
523 Wikimedia\
suppressWarnings();
525 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
526 $e = oci_error( $stmt );
527 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
528 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
532 $this->mAffectedRows
= oci_num_rows( $stmt );
535 $this->mAffectedRows
= oci_num_rows( $stmt );
538 Wikimedia\restoreWarnings
();
540 if ( isset( $lob ) ) {
541 foreach ( $lob as $lob_v ) {
546 if ( !$this->trxLevel
) {
547 oci_commit( $this->conn
);
550 return oci_free_statement( $stmt );
553 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
554 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
556 $destTable = $this->tableName( $destTable );
558 $sequenceData = $this->getSequenceData( $destTable );
559 if ( $sequenceData !== false &&
560 !isset( $varMap[$sequenceData['column']] )
562 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
565 // count-alias subselect fields to avoid abigious definition errors
567 foreach ( $varMap as &$val ) {
568 $val = $val . ' field' . ( $i++
);
571 $selectSql = $this->selectSQLText(
573 array_values( $varMap ),
580 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
582 if ( in_array( 'IGNORE', $insertOptions ) ) {
583 $this->ignoreDupValOnIndex
= true;
586 $this->query( $sql, $fname );
588 if ( in_array( 'IGNORE', $insertOptions ) ) {
589 $this->ignoreDupValOnIndex
= false;
593 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
596 if ( $rows === [] ) {
597 return true; // nothing to do
600 if ( !is_array( reset( $rows ) ) ) {
604 $sequenceData = $this->getSequenceData( $table );
605 if ( $sequenceData !== false ) {
606 // add sequence column to each list of columns, when not set
607 foreach ( $rows as &$row ) {
608 if ( !isset( $row[$sequenceData['column']] ) ) {
609 $row[$sequenceData['column']] =
610 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
611 $sequenceData['sequence'] . '\')' );
616 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
619 function tableName( $name, $format = 'quoted' ) {
621 Replace reserved words with better ones
622 Using uppercase because that's the only way Oracle can handle
630 $name = 'PAGECONTENT';
634 return strtoupper( parent
::tableName( $name, $format ) );
637 function tableNameInternal( $name ) {
638 $name = $this->tableName( $name );
640 return preg_replace( '/.*\.(.*)/', '$1', $name );
644 * Return sequence_name if table has a sequence
646 * @param string $table
649 private function getSequenceData( $table ) {
650 if ( $this->sequenceData
== null ) {
651 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
652 lower(atc.table_name),
653 lower(atc.column_name)
654 FROM all_sequences asq, all_tab_columns atc
657 '{$this->tablePrefix}MWUSER',
658 '{$this->tablePrefix}USER',
661 atc.column_name || '_SEQ' = '{$this->tablePrefix}' || asq.sequence_name
662 AND asq.sequence_owner = upper('{$this->getDBname()}')
663 AND atc.owner = upper('{$this->getDBname()}')" );
665 while ( ( $row = $result->fetchRow() ) !== false ) {
666 $this->sequenceData
[$row[1]] = [
667 'sequence' => $row[0],
672 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
674 return $this->sequenceData
[$table] ??
false;
678 * Returns the size of a text field, or -1 for "unlimited"
680 * @param string $table
681 * @param string $field
684 function textFieldSize( $table, $field ) {
685 $fieldInfoData = $this->fieldInfo( $table, $field );
687 return $fieldInfoData->maxLength();
690 function limitResult( $sql, $limit, $offset = false ) {
691 if ( $offset === false ) {
695 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
698 function encodeBlob( $b ) {
699 return new Blob( $b );
702 function decodeBlob( $b ) {
703 if ( $b instanceof Blob
) {
710 function unionQueries( $sqls, $all ) {
711 $glue = ' UNION ALL ';
713 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
714 'FROM (' . implode( $glue, $sqls ) . ')';
717 function wasDeadlock() {
718 return $this->lastErrno() == 'OCI-00060';
721 function duplicateTableStructure( $oldName, $newName, $temporary = false,
724 $temporary = $temporary ?
'TRUE' : 'FALSE';
726 $newName = strtoupper( $newName );
727 $oldName = strtoupper( $oldName );
729 $tabName = substr( $newName, strlen( $this->tablePrefix
) );
730 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
731 $newPrefix = strtoupper( $this->tablePrefix
);
733 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
734 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
737 function listTables( $prefix = null, $fname = __METHOD__
) {
739 if ( !empty( $prefix ) ) {
740 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
743 $owner = strtoupper( $this->getDBname() );
744 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
745 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
747 // dirty code ... i know
749 $endArray[] = strtoupper( $prefix . 'MWUSER' );
750 $endArray[] = strtoupper( $prefix . 'PAGE' );
751 $endArray[] = strtoupper( $prefix . 'IMAGE' );
752 $fixedOrderTabs = $endArray;
753 while ( ( $row = $result->fetchRow() ) !== false ) {
754 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
755 $endArray[] = $row['table_name'];
762 public function dropTable( $tableName, $fName = __METHOD__
) {
763 $tableName = $this->tableName( $tableName );
764 if ( !$this->tableExists( $tableName ) ) {
768 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
771 function timestamp( $ts = 0 ) {
772 return wfTimestamp( TS_ORACLE
, $ts );
776 * Return aggregated value function call
778 * @param array $valuedata
779 * @param string $valuename
782 public function aggregateValue( $valuedata, $valuename = 'value' ) {
787 * @return string Wikitext of a link to the server software's web site
789 public function getSoftwareLink() {
790 return '[{{int:version-db-oracle-url}} Oracle]';
794 * @return string Version information from the database
796 function getServerVersion() {
797 // better version number, fallback on driver
798 $rset = $this->doQuery(
799 'SELECT version FROM product_component_version ' .
800 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
802 $row = $rset->fetchRow();
804 return oci_server_version( $this->conn
);
807 return $row['version'];
811 * Query whether a given index exists
812 * @param string $table
813 * @param string $index
814 * @param string $fname
817 function indexExists( $table, $index, $fname = __METHOD__
) {
818 $table = $this->tableName( $table );
819 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
820 $index = strtoupper( $index );
821 $owner = strtoupper( $this->getDBname() );
822 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
823 $res = $this->doQuery( $sql );
825 $count = $res->numRows();
835 * Query whether a given table exists (in the given schema, or the default mw one if not given)
836 * @param string $table
837 * @param string $fname
840 function tableExists( $table, $fname = __METHOD__
) {
841 $table = $this->tableName( $table );
842 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
843 $owner = $this->addQuotes( strtoupper( $this->getDBname() ) );
844 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
845 $res = $this->doQuery( $sql );
846 if ( $res && $res->numRows() > 0 ) {
858 * Function translates mysql_fetch_field() functionality on ORACLE.
859 * Caching is present for reducing query time.
860 * For internal calls. Use fieldInfo for normal usage.
861 * Returns false if the field doesn't exist
863 * @param array|string $table
864 * @param string $field
865 * @return ORAField|ORAResult|false
867 private function fieldInfoMulti( $table, $field ) {
868 $field = strtoupper( $field );
869 if ( is_array( $table ) ) {
870 $table = array_map( [ $this, 'tableNameInternal' ], $table );
871 $tableWhere = 'IN (';
872 foreach ( $table as &$singleTable ) {
873 $singleTable = $this->removeIdentifierQuotes( $singleTable );
874 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
875 return $this->mFieldInfoCache
["$singleTable.$field"];
877 $tableWhere .= '\'' . $singleTable . '\',';
879 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
881 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
882 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
883 return $this->mFieldInfoCache
["$table.$field"];
885 $tableWhere = '= \'' . $table . '\'';
888 $fieldInfoStmt = oci_parse(
890 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
891 $tableWhere . ' and column_name = \'' . $field . '\''
893 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
894 $e = oci_error( $fieldInfoStmt );
895 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
899 $res = new ORAResult( $this, $fieldInfoStmt );
900 if ( $res->numRows() == 0 ) {
901 if ( is_array( $table ) ) {
902 foreach ( $table as &$singleTable ) {
903 $this->mFieldInfoCache
["$singleTable.$field"] = false;
906 $this->mFieldInfoCache
["$table.$field"] = false;
908 $fieldInfoTemp = null;
910 $fieldInfoTemp = new ORAField( $res->fetchRow() );
911 $table = $fieldInfoTemp->tableName();
912 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
916 return $fieldInfoTemp;
920 * @throws DBUnexpectedError
921 * @param string $table
922 * @param string $field
925 function fieldInfo( $table, $field ) {
926 if ( is_array( $table ) ) {
927 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
930 return $this->fieldInfoMulti( $table, $field );
933 protected function doBegin( $fname = __METHOD__
) {
935 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
938 protected function doCommit( $fname = __METHOD__
) {
939 if ( $this->trxLevel
) {
940 $ret = oci_commit( $this->conn
);
942 throw new DBUnexpectedError( $this, $this->lastError() );
945 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
949 protected function doRollback( $fname = __METHOD__
) {
950 if ( $this->trxLevel
) {
951 oci_rollback( $this->conn
);
953 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
957 function sourceStream(
959 callable
$lineCallback = null,
960 callable
$resultCallback = null,
961 $fname = __METHOD__
, callable
$inputCallback = null
965 $dollarquote = false;
968 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
969 while ( !feof( $fp ) ) {
970 if ( $lineCallback ) {
971 call_user_func( $lineCallback );
973 $line = trim( fgets( $fp, 1024 ) );
974 $sl = strlen( $line ) - 1;
979 if ( $line[0] == '-' && $line[1] == '-' ) {
983 // Allow dollar quoting for function declarations
984 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
985 if ( $dollarquote ) {
986 $dollarquote = false;
987 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
992 } elseif ( !$dollarquote ) {
993 if ( $line[$sl] == ';' && ( $sl < 2 ||
$line[$sl - 1] != ';' ) ) {
995 $line = substr( $line, 0, $sl );
1005 $cmd = str_replace( ';;', ";", $cmd );
1006 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1007 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1008 $replacements[$defines[2]] = $defines[1];
1011 foreach ( $replacements as $mwVar => $scVar ) {
1012 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1015 $cmd = $this->replaceVars( $cmd );
1016 if ( $inputCallback ) {
1017 call_user_func( $inputCallback, $cmd );
1019 $res = $this->doQuery( $cmd );
1020 if ( $resultCallback ) {
1021 call_user_func( $resultCallback, $res, $this );
1024 if ( $res === false ) {
1025 $err = $this->lastError();
1027 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1039 protected function doSelectDomain( DatabaseDomain
$domain ) {
1040 if ( $domain->getSchema() !== null ) {
1041 // We use the *database* aspect of $domain for schema, not the domain schema
1042 throw new DBExpectedError( $this, __CLASS__
. ": domain schemas are not supported." );
1045 $database = $domain->getDatabase();
1046 if ( $database === null ||
$database === $this->user
) {
1047 // Backward compatibility
1048 $this->currentDomain
= $domain;
1053 // https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj32268.html
1054 $encDatabase = $this->addIdentifierQuotes( strtoupper( $database ) );
1055 $sql = "ALTER SESSION SET CURRENT_SCHEMA=$encDatabase";
1056 $stmt = oci_parse( $this->conn
, $sql );
1057 Wikimedia\
suppressWarnings();
1058 $success = oci_execute( $stmt );
1059 Wikimedia\restoreWarnings
();
1061 // Update that domain fields on success (no exception thrown)
1062 $this->currentDomain
= $domain;
1064 $e = oci_error( $stmt );
1065 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1071 function strencode( $s ) {
1072 return str_replace( "'", "''", $s );
1075 function addQuotes( $s ) {
1076 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1077 if ( isset( $contLang->mLoaded
) && $contLang->mLoaded
) {
1078 $s = $contLang->checkTitleEncoding( $s );
1081 return "'" . $this->strencode( $s ) . "'";
1084 public function addIdentifierQuotes( $s ) {
1085 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1092 public function removeIdentifierQuotes( $s ) {
1093 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1096 public function isQuotedIdentifier( $s ) {
1097 return strpos( $s, '/*Q*/' ) !== false;
1100 private function wrapFieldForWhere( $table, &$col, &$val ) {
1101 $col_info = $this->fieldInfoMulti( $table, $col );
1102 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1103 if ( $col_type == 'CLOB' ) {
1104 $col = 'TO_CHAR(' . $col . ')';
1106 MediaWikiServices
::getInstance()->getContentLanguage()->checkTitleEncoding( $val );
1107 } elseif ( $col_type == 'VARCHAR2' ) {
1109 MediaWikiServices
::getInstance()->getContentLanguage()->checkTitleEncoding( $val );
1113 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1115 foreach ( $conds as $col => $val ) {
1116 if ( is_array( $val ) ) {
1117 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1119 if ( is_numeric( $col ) && $parentCol != null ) {
1120 $this->wrapFieldForWhere( $table, $parentCol, $val );
1122 $this->wrapFieldForWhere( $table, $col, $val );
1124 $conds2[$col] = $val;
1131 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1132 $options = [], $join_conds = []
1134 if ( is_array( $conds ) ) {
1135 $conds = $this->wrapConditionsForWhere( $table, $conds );
1138 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1142 * Returns an optional USE INDEX clause to go after the table, and a
1143 * string to go at the end of the query
1145 * @param array $options An associative array of options to be turned into
1146 * an SQL query, valid keys are listed in the function.
1149 function makeSelectOptions( $options ) {
1150 $preLimitTail = $postLimitTail = '';
1154 foreach ( $options as $key => $option ) {
1155 if ( is_numeric( $key ) ) {
1156 $noKeyOptions[$option] = true;
1160 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1162 $preLimitTail .= $this->makeOrderBy( $options );
1164 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1165 $postLimitTail .= ' FOR UPDATE';
1168 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1169 $startOpts .= 'DISTINCT';
1172 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1173 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1178 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1179 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1184 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1187 public function delete( $table, $conds, $fname = __METHOD__
) {
1188 global $wgActorTableSchemaMigrationStage;
1190 if ( is_array( $conds ) ) {
1191 $conds = $this->wrapConditionsForWhere( $table, $conds );
1193 // a hack for deleting pages, users and images (which have non-nullable FKs)
1194 // all deletions on these tables have transactions so final failure rollbacks these updates
1195 // @todo: Normalize the schema to match MySQL, no special FKs and such
1196 $table = $this->tableName( $table );
1197 if ( $table == $this->tableName( 'user' ) &&
1198 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
)
1200 $this->update( 'archive', [ 'ar_user' => 0 ],
1201 [ 'ar_user' => $conds['user_id'] ], $fname );
1202 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1203 [ 'ipb_user' => $conds['user_id'] ], $fname );
1204 $this->update( 'image', [ 'img_user' => 0 ],
1205 [ 'img_user' => $conds['user_id'] ], $fname );
1206 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1207 [ 'oi_user' => $conds['user_id'] ], $fname );
1208 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1209 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1210 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1211 [ 'fa_user' => $conds['user_id'] ], $fname );
1212 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1213 [ 'us_user' => $conds['user_id'] ], $fname );
1214 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1215 [ 'rc_user' => $conds['user_id'] ], $fname );
1216 $this->update( 'logging', [ 'log_user' => 0 ],
1217 [ 'log_user' => $conds['user_id'] ], $fname );
1218 } elseif ( $table == $this->tableName( 'image' ) ) {
1219 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1220 [ 'oi_name' => $conds['img_name'] ], $fname );
1223 return parent
::delete( $table, $conds, $fname );
1227 * @param string $table
1228 * @param array $values
1229 * @param array $conds
1230 * @param string $fname
1231 * @param array $options
1233 * @throws DBUnexpectedError
1235 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1236 $table = $this->tableName( $table );
1237 $opts = $this->makeUpdateOptions( $options );
1238 $sql = "UPDATE $opts $table SET ";
1241 foreach ( $values as $col => &$val ) {
1242 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1245 $sqlSet = ', ' . $sqlSet;
1252 if ( $conds !== [] && $conds !== '*' ) {
1253 $conds = $this->wrapConditionsForWhere( $table, $conds );
1254 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1257 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
1258 if ( $stmt === false ) {
1259 $e = oci_error( $this->conn
);
1260 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1264 foreach ( $values as $col => &$val ) {
1265 $col_info = $this->fieldInfoMulti( $table, $col );
1266 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1268 if ( $val === null ) {
1269 // do nothing ... null was inserted in statement creation
1270 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1271 if ( is_object( $val ) ) {
1272 $val = $val->getData();
1275 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1276 $val = '31-12-2030 12:00:00.000000';
1279 $val = MediaWikiServices
::getInstance()->getContentLanguage()->
1280 checkTitleEncoding( $val );
1281 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1282 $e = oci_error( $stmt );
1283 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1288 /** @var OCI_Lob[] $lob */
1289 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
1290 if ( $lob[$col] === false ) {
1291 $e = oci_error( $stmt );
1292 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1295 if ( is_object( $val ) ) {
1296 $val = $val->getData();
1299 if ( $col_type == 'BLOB' ) {
1300 $lob[$col]->writeTemporary( $val );
1301 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1303 $lob[$col]->writeTemporary( $val );
1304 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1309 Wikimedia\
suppressWarnings();
1311 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1312 $e = oci_error( $stmt );
1313 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1314 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1318 $this->mAffectedRows
= oci_num_rows( $stmt );
1321 $this->mAffectedRows
= oci_num_rows( $stmt );
1324 Wikimedia\restoreWarnings
();
1326 if ( isset( $lob ) ) {
1327 foreach ( $lob as $lob_v ) {
1332 if ( !$this->trxLevel
) {
1333 oci_commit( $this->conn
);
1336 return oci_free_statement( $stmt );
1339 function bitNot( $field ) {
1340 // expecting bit-fields smaller than 4bytes
1341 return 'BITNOT(' . $field . ')';
1344 function bitAnd( $fieldLeft, $fieldRight ) {
1345 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1348 function bitOr( $fieldLeft, $fieldRight ) {
1349 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1352 function getServer() {
1353 return $this->server
;
1356 public function buildGroupConcatField(
1357 $delim, $table, $field, $conds = '', $join_conds = []
1359 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1361 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1364 public function buildSubstring( $input, $startPosition, $length = null ) {
1365 $this->assertBuildSubstringParams( $startPosition, $length );
1366 $params = [ $input, $startPosition ];
1367 if ( $length !== null ) {
1368 $params[] = $length;
1370 return 'SUBSTR(' . implode( ',', $params ) . ')';
1374 * @param string $field Field or column to cast
1378 public function buildStringCast( $field ) {
1379 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1382 public function getInfinity() {
1383 return '31-12-2030 12:00:00.000000';