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 ) {
56 $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
57 parent
::__construct( $p );
58 Hooks
::run( 'DatabaseOraclePostInit', [ $this ] );
61 function __destruct() {
62 if ( $this->opened
) {
63 Wikimedia\
suppressWarnings();
65 Wikimedia\restoreWarnings
();
73 function implicitGroupby() {
77 function implicitOrderby() {
81 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
82 global $wgDBOracleDRCP;
84 if ( !function_exists( 'oci_connect' ) ) {
85 throw new DBConnectionError(
87 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
88 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
94 $this->password
= $password;
96 // Backward compatibility (server used to be null and TNS was supplied in dbname)
97 $this->server
= $dbName;
98 $realDatabase = $user;
100 // $server now holds the TNS endpoint
101 $this->server
= $server;
102 // $dbName is schema name if different from username
103 $realDatabase = $dbName ?
: $user;
106 if ( !strlen( $user ) ) { # e.g. the class is being loaded
110 if ( $wgDBOracleDRCP ) {
111 $this->setFlag( DBO_PERSISTENT
);
114 $session_mode = ( $this->flags
& DBO_SYSDBA
) ? OCI_SYSDBA
: OCI_DEFAULT
;
116 Wikimedia\
suppressWarnings();
117 if ( $this->flags
& DBO_PERSISTENT
) {
118 $this->conn
= oci_pconnect(
122 $this->defaultCharset
,
125 } elseif ( $this->flags
& DBO_DEFAULT
) {
126 $this->conn
= oci_new_connect(
130 $this->defaultCharset
,
134 $this->conn
= oci_connect(
138 $this->defaultCharset
,
142 Wikimedia\restoreWarnings
();
144 if ( $this->user
!= $realDatabase ) {
145 // change current schema in session
146 $this->selectDB( $realDatabase );
148 $this->currentDomain
= new DatabaseDomain(
155 if ( !$this->conn
) {
156 throw new DBConnectionError( $this, $this->lastError() );
159 $this->opened
= true;
161 # removed putenv calls because they interfere with the system globaly
162 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
163 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
164 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
166 return (bool)$this->conn
;
170 * Closes a database connection, if it is open
171 * Returns success, true if already closed
174 protected function closeConnection() {
175 return oci_close( $this->conn
);
178 function execFlags() {
179 return $this->trxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
184 * @return bool|mixed|ORAResult
186 protected function doQuery( $sql ) {
187 wfDebug( "SQL: [$sql]\n" );
188 if ( !StringUtils
::isUtf8( $sql ) ) {
189 throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
192 // handle some oracle specifics
193 // remove AS column/table/subquery namings
194 if ( !$this->getFlag( DBO_DDLMODE
) ) {
195 $sql = preg_replace( '/ as /i', ' ', $sql );
198 // Oracle has issues with UNION clause if the statement includes LOB fields
199 // So we do a UNION ALL and then filter the results array with array_unique
200 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
201 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
202 // you have to select data from plan table after explain
203 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
207 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
213 Wikimedia\
suppressWarnings();
215 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
216 if ( $stmt === false ) {
217 $e = oci_error( $this->conn
);
218 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
223 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
224 $e = oci_error( $stmt );
225 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
226 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
232 Wikimedia\restoreWarnings
();
234 if ( $explain_count > 0 ) {
235 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
236 'WHERE statement_id = \'' . $explain_id . '\'' );
237 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
238 return new ORAResult( $this, $stmt, $union_unique );
240 $this->mAffectedRows
= oci_num_rows( $stmt );
246 function queryIgnore( $sql, $fname = '' ) {
247 return $this->query( $sql, $fname, true );
251 * Frees resources associated with the LOB descriptor
252 * @param ResultWrapper|ORAResult $res
254 function freeResult( $res ) {
255 if ( $res instanceof ResultWrapper
) {
263 * @param ResultWrapper|ORAResult $res
266 function fetchObject( $res ) {
267 if ( $res instanceof ResultWrapper
) {
271 return $res->fetchObject();
275 * @param ResultWrapper|ORAResult $res
278 function fetchRow( $res ) {
279 if ( $res instanceof ResultWrapper
) {
283 return $res->fetchRow();
287 * @param ResultWrapper|ORAResult $res
290 function numRows( $res ) {
291 if ( $res instanceof ResultWrapper
) {
295 return $res->numRows();
299 * @param ResultWrapper|ORAResult $res
302 function numFields( $res ) {
303 if ( $res instanceof ResultWrapper
) {
307 return $res->numFields();
310 function fieldName( $stmt, $n ) {
311 return oci_field_name( $stmt, $n );
314 function insertId() {
315 $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
316 $row = $this->fetchRow( $res );
317 return is_null( $row[0] ) ?
null : (int)$row[0];
324 function dataSeek( $res, $row ) {
325 if ( $res instanceof ORAResult
) {
328 $res->result
->seek( $row );
332 function lastError() {
333 if ( $this->conn
=== false ) {
336 $e = oci_error( $this->conn
);
339 return $e['message'];
342 function lastErrno() {
343 if ( $this->conn
=== false ) {
346 $e = oci_error( $this->conn
);
352 protected function fetchAffectedRowCount() {
353 return $this->mAffectedRows
;
357 * Returns information about an index
358 * If errors are explicitly ignored, returns NULL on failure
359 * @param string $table
360 * @param string $index
361 * @param string $fname
364 function indexInfo( $table, $index, $fname = __METHOD__
) {
368 function indexUnique( $table, $index, $fname = __METHOD__
) {
372 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
373 if ( !count( $a ) ) {
377 if ( !is_array( $options ) ) {
378 $options = [ $options ];
381 if ( in_array( 'IGNORE', $options ) ) {
382 $this->ignoreDupValOnIndex
= true;
385 if ( !is_array( reset( $a ) ) ) {
389 foreach ( $a as &$row ) {
390 $this->insertOneRow( $table, $row, $fname );
393 if ( in_array( 'IGNORE', $options ) ) {
394 $this->ignoreDupValOnIndex
= false;
400 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
401 $col_info = $this->fieldInfoMulti( $table, $col );
402 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
405 if ( is_numeric( $col ) ) {
410 } elseif ( $includeCol ) {
414 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
418 if ( $val === 'NULL' ) {
422 if ( $val === null ) {
423 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
436 * @param string $table
438 * @param string $fname
440 * @throws DBUnexpectedError
442 private function insertOneRow( $table, $row, $fname ) {
443 $table = $this->tableName( $table );
444 // "INSERT INTO tables (a, b, c)"
445 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
448 // for each value, append ":key"
450 foreach ( $row as $col => &$val ) {
456 if ( $this->isQuotedIdentifier( $val ) ) {
457 $sql .= $this->removeIdentifierQuotes( $val );
460 $sql .= $this->fieldBindStatement( $table, $col, $val );
465 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
466 if ( $stmt === false ) {
467 $e = oci_error( $this->conn
);
468 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
472 foreach ( $row as $col => &$val ) {
473 $col_info = $this->fieldInfoMulti( $table, $col );
474 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
476 if ( $val === null ) {
477 // do nothing ... null was inserted in statement creation
478 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
479 if ( is_object( $val ) ) {
480 $val = $val->fetch();
483 // backward compatibility
484 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
485 $val = $this->getInfinity();
488 $val = MediaWikiServices
::getInstance()->getContentLanguage()->
489 checkTitleEncoding( $val );
490 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
491 $e = oci_error( $stmt );
492 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
497 /** @var OCI_Lob[] $lob */
498 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
499 if ( $lob[$col] === false ) {
500 $e = oci_error( $stmt );
501 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
504 if ( is_object( $val ) ) {
505 $val = $val->fetch();
508 if ( $col_type == 'BLOB' ) {
509 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
510 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
512 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
513 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
518 Wikimedia\
suppressWarnings();
520 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
521 $e = oci_error( $stmt );
522 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
523 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
527 $this->mAffectedRows
= oci_num_rows( $stmt );
530 $this->mAffectedRows
= oci_num_rows( $stmt );
533 Wikimedia\restoreWarnings
();
535 if ( isset( $lob ) ) {
536 foreach ( $lob as $lob_v ) {
541 if ( !$this->trxLevel
) {
542 oci_commit( $this->conn
);
545 return oci_free_statement( $stmt );
548 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
549 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
551 $destTable = $this->tableName( $destTable );
553 $sequenceData = $this->getSequenceData( $destTable );
554 if ( $sequenceData !== false &&
555 !isset( $varMap[$sequenceData['column']] )
557 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
560 // count-alias subselect fields to avoid abigious definition errors
562 foreach ( $varMap as &$val ) {
563 $val .= ' field' . $i;
567 $selectSql = $this->selectSQLText(
569 array_values( $varMap ),
576 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
578 if ( in_array( 'IGNORE', $insertOptions ) ) {
579 $this->ignoreDupValOnIndex
= true;
582 $this->query( $sql, $fname );
584 if ( in_array( 'IGNORE', $insertOptions ) ) {
585 $this->ignoreDupValOnIndex
= false;
589 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
592 if ( $rows === [] ) {
593 return true; // nothing to do
596 if ( !is_array( reset( $rows ) ) ) {
600 $sequenceData = $this->getSequenceData( $table );
601 if ( $sequenceData !== false ) {
602 // add sequence column to each list of columns, when not set
603 foreach ( $rows as &$row ) {
604 if ( !isset( $row[$sequenceData['column']] ) ) {
605 $row[$sequenceData['column']] =
606 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
607 $sequenceData['sequence'] . '\')' );
612 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
615 function tableName( $name, $format = 'quoted' ) {
617 Replace reserved words with better ones
618 Using uppercase because that's the only way Oracle can handle
626 $name = 'PAGECONTENT';
630 return strtoupper( parent
::tableName( $name, $format ) );
633 function tableNameInternal( $name ) {
634 $name = $this->tableName( $name );
636 return preg_replace( '/.*\.(.*)/', '$1', $name );
640 * Return sequence_name if table has a sequence
642 * @param string $table
645 private function getSequenceData( $table ) {
646 if ( $this->sequenceData
== null ) {
647 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
648 lower(atc.table_name),
649 lower(atc.column_name)
650 FROM all_sequences asq, all_tab_columns atc
653 '{$this->tablePrefix}MWUSER',
654 '{$this->tablePrefix}USER',
657 atc.column_name || '_SEQ' = '{$this->tablePrefix}' || asq.sequence_name
658 AND asq.sequence_owner = upper('{$this->getDBname()}')
659 AND atc.owner = upper('{$this->getDBname()}')" );
661 while ( ( $row = $result->fetchRow() ) !== false ) {
662 $this->sequenceData
[$row[1]] = [
663 'sequence' => $row[0],
668 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
670 return $this->sequenceData
[$table] ??
false;
674 * Returns the size of a text field, or -1 for "unlimited"
676 * @param string $table
677 * @param string $field
680 function textFieldSize( $table, $field ) {
681 $fieldInfoData = $this->fieldInfo( $table, $field );
683 return $fieldInfoData->maxLength();
686 function limitResult( $sql, $limit, $offset = false ) {
687 if ( $offset === false ) {
691 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
694 function encodeBlob( $b ) {
695 return new Blob( $b );
698 function unionQueries( $sqls, $all ) {
699 $glue = ' UNION ALL ';
701 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
702 'FROM (' . implode( $glue, $sqls ) . ')';
705 function wasDeadlock() {
706 return $this->lastErrno() == 'OCI-00060';
709 function duplicateTableStructure( $oldName, $newName, $temporary = false,
712 $temporary = $temporary ?
'TRUE' : 'FALSE';
714 $newName = strtoupper( $newName );
715 $oldName = strtoupper( $oldName );
717 $tabName = substr( $newName, strlen( $this->tablePrefix
) );
718 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
719 $newPrefix = strtoupper( $this->tablePrefix
);
721 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
722 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
725 function listTables( $prefix = null, $fname = __METHOD__
) {
727 if ( !empty( $prefix ) ) {
728 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
731 $owner = strtoupper( $this->getDBname() );
732 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
733 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
735 // dirty code ... i know
737 $endArray[] = strtoupper( $prefix . 'MWUSER' );
738 $endArray[] = strtoupper( $prefix . 'PAGE' );
739 $endArray[] = strtoupper( $prefix . 'IMAGE' );
740 $fixedOrderTabs = $endArray;
741 while ( ( $row = $result->fetchRow() ) !== false ) {
742 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
743 $endArray[] = $row['table_name'];
750 public function dropTable( $tableName, $fName = __METHOD__
) {
751 $tableName = $this->tableName( $tableName );
752 if ( !$this->tableExists( $tableName ) ) {
756 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
759 function timestamp( $ts = 0 ) {
760 return wfTimestamp( TS_ORACLE
, $ts );
764 * Return aggregated value function call
766 * @param array $valuedata
767 * @param string $valuename
770 public function aggregateValue( $valuedata, $valuename = 'value' ) {
775 * @return string Wikitext of a link to the server software's web site
777 public function getSoftwareLink() {
778 return '[{{int:version-db-oracle-url}} Oracle]';
782 * @return string Version information from the database
784 function getServerVersion() {
785 // better version number, fallback on driver
786 $rset = $this->doQuery(
787 'SELECT version FROM product_component_version ' .
788 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
790 $row = $rset->fetchRow();
792 return oci_server_version( $this->conn
);
795 return $row['version'];
799 * Query whether a given index exists
800 * @param string $table
801 * @param string $index
802 * @param string $fname
805 function indexExists( $table, $index, $fname = __METHOD__
) {
806 $table = $this->tableName( $table );
807 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
808 $index = strtoupper( $index );
809 $owner = strtoupper( $this->getDBname() );
810 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
811 $res = $this->doQuery( $sql );
813 $count = $res->numRows();
823 * Query whether a given table exists (in the given schema, or the default mw one if not given)
824 * @param string $table
825 * @param string $fname
828 function tableExists( $table, $fname = __METHOD__
) {
829 $table = $this->tableName( $table );
830 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
831 $owner = $this->addQuotes( strtoupper( $this->getDBname() ) );
832 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
833 $res = $this->doQuery( $sql );
834 if ( $res && $res->numRows() > 0 ) {
846 * Function translates mysql_fetch_field() functionality on ORACLE.
847 * Caching is present for reducing query time.
848 * For internal calls. Use fieldInfo for normal usage.
849 * Returns false if the field doesn't exist
851 * @param array|string $table
852 * @param string $field
853 * @return ORAField|ORAResult|false
855 private function fieldInfoMulti( $table, $field ) {
856 $field = strtoupper( $field );
857 if ( is_array( $table ) ) {
858 $table = array_map( [ $this, 'tableNameInternal' ], $table );
859 $tableWhere = 'IN (';
860 foreach ( $table as &$singleTable ) {
861 $singleTable = $this->removeIdentifierQuotes( $singleTable );
862 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
863 return $this->mFieldInfoCache
["$singleTable.$field"];
865 $tableWhere .= '\'' . $singleTable . '\',';
867 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
869 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
870 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
871 return $this->mFieldInfoCache
["$table.$field"];
873 $tableWhere = '= \'' . $table . '\'';
876 $fieldInfoStmt = oci_parse(
878 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
879 $tableWhere . ' and column_name = \'' . $field . '\''
881 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
882 $e = oci_error( $fieldInfoStmt );
883 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
887 $res = new ORAResult( $this, $fieldInfoStmt );
888 if ( $res->numRows() == 0 ) {
889 if ( is_array( $table ) ) {
890 foreach ( $table as &$singleTable ) {
891 $this->mFieldInfoCache
["$singleTable.$field"] = false;
894 $this->mFieldInfoCache
["$table.$field"] = false;
896 $fieldInfoTemp = null;
898 $fieldInfoTemp = new ORAField( $res->fetchRow() );
899 $table = $fieldInfoTemp->tableName();
900 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
904 return $fieldInfoTemp;
908 * @throws DBUnexpectedError
909 * @param string $table
910 * @param string $field
913 function fieldInfo( $table, $field ) {
914 if ( is_array( $table ) ) {
915 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
918 return $this->fieldInfoMulti( $table, $field );
921 protected function doBegin( $fname = __METHOD__
) {
923 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
926 protected function doCommit( $fname = __METHOD__
) {
927 if ( $this->trxLevel
) {
928 $ret = oci_commit( $this->conn
);
930 throw new DBUnexpectedError( $this, $this->lastError() );
933 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
937 protected function doRollback( $fname = __METHOD__
) {
938 if ( $this->trxLevel
) {
939 oci_rollback( $this->conn
);
941 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
945 function sourceStream(
947 callable
$lineCallback = null,
948 callable
$resultCallback = null,
949 $fname = __METHOD__
, callable
$inputCallback = null
953 $dollarquote = false;
956 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
957 while ( !feof( $fp ) ) {
958 if ( $lineCallback ) {
961 $line = trim( fgets( $fp, 1024 ) );
962 $sl = strlen( $line ) - 1;
967 if ( $line[0] == '-' && $line[1] == '-' ) {
971 // Allow dollar quoting for function declarations
972 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
973 if ( $dollarquote ) {
974 $dollarquote = false;
975 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
980 } elseif ( !$dollarquote ) {
981 if ( $line[$sl] == ';' && ( $sl < 2 ||
$line[$sl - 1] != ';' ) ) {
983 $line = substr( $line, 0, $sl );
993 $cmd = str_replace( ';;', ";", $cmd );
994 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
995 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
996 $replacements[$defines[2]] = $defines[1];
999 foreach ( $replacements as $mwVar => $scVar ) {
1000 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1003 $cmd = $this->replaceVars( $cmd );
1004 if ( $inputCallback ) {
1005 $inputCallback( $cmd );
1007 $res = $this->doQuery( $cmd );
1008 if ( $resultCallback ) {
1009 call_user_func( $resultCallback, $res, $this );
1012 if ( $res === false ) {
1013 $err = $this->lastError();
1015 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1027 protected function doSelectDomain( DatabaseDomain
$domain ) {
1028 if ( $domain->getSchema() !== null ) {
1029 // We use the *database* aspect of $domain for schema, not the domain schema
1030 throw new DBExpectedError( $this, __CLASS__
. ": domain schemas are not supported." );
1033 $database = $domain->getDatabase();
1034 if ( $database === null ||
$database === $this->user
) {
1035 // Backward compatibility
1036 $this->currentDomain
= $domain;
1041 // https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj32268.html
1042 $encDatabase = $this->addIdentifierQuotes( strtoupper( $database ) );
1043 $sql = "ALTER SESSION SET CURRENT_SCHEMA=$encDatabase";
1044 $stmt = oci_parse( $this->conn
, $sql );
1045 Wikimedia\
suppressWarnings();
1046 $success = oci_execute( $stmt );
1047 Wikimedia\restoreWarnings
();
1049 // Update that domain fields on success (no exception thrown)
1050 $this->currentDomain
= $domain;
1052 $e = oci_error( $stmt );
1053 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1059 function strencode( $s ) {
1060 return str_replace( "'", "''", $s );
1063 function addQuotes( $s ) {
1064 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1065 if ( isset( $contLang->mLoaded
) && $contLang->mLoaded
) {
1066 $s = $contLang->checkTitleEncoding( $s );
1069 return "'" . $this->strencode( $s ) . "'";
1072 public function addIdentifierQuotes( $s ) {
1073 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1080 public function removeIdentifierQuotes( $s ) {
1081 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1084 public function isQuotedIdentifier( $s ) {
1085 return strpos( $s, '/*Q*/' ) !== false;
1088 private function wrapFieldForWhere( $table, &$col, &$val ) {
1089 $col_info = $this->fieldInfoMulti( $table, $col );
1090 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1091 if ( $col_type == 'CLOB' ) {
1092 $col = 'TO_CHAR(' . $col . ')';
1094 MediaWikiServices
::getInstance()->getContentLanguage()->checkTitleEncoding( $val );
1095 } elseif ( $col_type == 'VARCHAR2' ) {
1097 MediaWikiServices
::getInstance()->getContentLanguage()->checkTitleEncoding( $val );
1101 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1103 foreach ( $conds as $col => $val ) {
1104 if ( is_array( $val ) ) {
1105 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1107 if ( is_numeric( $col ) && $parentCol != null ) {
1108 $this->wrapFieldForWhere( $table, $parentCol, $val );
1110 $this->wrapFieldForWhere( $table, $col, $val );
1112 $conds2[$col] = $val;
1119 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1120 $options = [], $join_conds = []
1122 if ( is_array( $conds ) ) {
1123 $conds = $this->wrapConditionsForWhere( $table, $conds );
1126 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1130 * Returns an optional USE INDEX clause to go after the table, and a
1131 * string to go at the end of the query
1133 * @param array $options An associative array of options to be turned into
1134 * an SQL query, valid keys are listed in the function.
1137 function makeSelectOptions( $options ) {
1138 $preLimitTail = $postLimitTail = '';
1142 foreach ( $options as $key => $option ) {
1143 if ( is_numeric( $key ) ) {
1144 $noKeyOptions[$option] = true;
1148 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1150 $preLimitTail .= $this->makeOrderBy( $options );
1152 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1153 $postLimitTail .= ' FOR UPDATE';
1156 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1157 $startOpts .= 'DISTINCT';
1160 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1161 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1166 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1167 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1172 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1175 public function delete( $table, $conds, $fname = __METHOD__
) {
1176 global $wgActorTableSchemaMigrationStage;
1178 if ( is_array( $conds ) ) {
1179 $conds = $this->wrapConditionsForWhere( $table, $conds );
1181 // a hack for deleting pages, users and images (which have non-nullable FKs)
1182 // all deletions on these tables have transactions so final failure rollbacks these updates
1183 // @todo: Normalize the schema to match MySQL, no special FKs and such
1184 $table = $this->tableName( $table );
1185 if ( $table == $this->tableName( 'user' ) &&
1186 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
)
1188 $this->update( 'archive', [ 'ar_user' => 0 ],
1189 [ 'ar_user' => $conds['user_id'] ], $fname );
1190 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1191 [ 'ipb_user' => $conds['user_id'] ], $fname );
1192 $this->update( 'image', [ 'img_user' => 0 ],
1193 [ 'img_user' => $conds['user_id'] ], $fname );
1194 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1195 [ 'oi_user' => $conds['user_id'] ], $fname );
1196 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1197 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1198 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1199 [ 'fa_user' => $conds['user_id'] ], $fname );
1200 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1201 [ 'us_user' => $conds['user_id'] ], $fname );
1202 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1203 [ 'rc_user' => $conds['user_id'] ], $fname );
1204 $this->update( 'logging', [ 'log_user' => 0 ],
1205 [ 'log_user' => $conds['user_id'] ], $fname );
1206 } elseif ( $table == $this->tableName( 'image' ) ) {
1207 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1208 [ 'oi_name' => $conds['img_name'] ], $fname );
1211 return parent
::delete( $table, $conds, $fname );
1215 * @param string $table
1216 * @param array $values
1217 * @param array $conds
1218 * @param string $fname
1219 * @param array $options
1221 * @throws DBUnexpectedError
1223 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1224 $table = $this->tableName( $table );
1225 $opts = $this->makeUpdateOptions( $options );
1226 $sql = "UPDATE $opts $table SET ";
1229 foreach ( $values as $col => &$val ) {
1230 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1233 $sqlSet = ', ' . $sqlSet;
1240 if ( $conds !== [] && $conds !== '*' ) {
1241 $conds = $this->wrapConditionsForWhere( $table, $conds );
1242 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1245 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
1246 if ( $stmt === false ) {
1247 $e = oci_error( $this->conn
);
1248 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1252 foreach ( $values as $col => &$val ) {
1253 $col_info = $this->fieldInfoMulti( $table, $col );
1254 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1256 if ( $val === null ) {
1257 // do nothing ... null was inserted in statement creation
1258 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1259 if ( is_object( $val ) ) {
1260 $val = $val->getData();
1263 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1264 $val = '31-12-2030 12:00:00.000000';
1267 $val = MediaWikiServices
::getInstance()->getContentLanguage()->
1268 checkTitleEncoding( $val );
1269 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1270 $e = oci_error( $stmt );
1271 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1276 /** @var OCI_Lob[] $lob */
1277 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
1278 if ( $lob[$col] === false ) {
1279 $e = oci_error( $stmt );
1280 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1283 if ( is_object( $val ) ) {
1284 $val = $val->getData();
1287 if ( $col_type == 'BLOB' ) {
1288 $lob[$col]->writeTemporary( $val );
1289 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1291 $lob[$col]->writeTemporary( $val );
1292 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1297 Wikimedia\
suppressWarnings();
1299 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1300 $e = oci_error( $stmt );
1301 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1302 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1306 $this->mAffectedRows
= oci_num_rows( $stmt );
1309 $this->mAffectedRows
= oci_num_rows( $stmt );
1312 Wikimedia\restoreWarnings
();
1314 if ( isset( $lob ) ) {
1315 foreach ( $lob as $lob_v ) {
1320 if ( !$this->trxLevel
) {
1321 oci_commit( $this->conn
);
1324 return oci_free_statement( $stmt );
1327 function bitNot( $field ) {
1328 // expecting bit-fields smaller than 4bytes
1329 return 'BITNOT(' . $field . ')';
1332 function bitAnd( $fieldLeft, $fieldRight ) {
1333 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1336 function bitOr( $fieldLeft, $fieldRight ) {
1337 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1340 public function buildGroupConcatField(
1341 $delim, $table, $field, $conds = '', $join_conds = []
1343 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1345 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1348 public function buildSubstring( $input, $startPosition, $length = null ) {
1349 $this->assertBuildSubstringParams( $startPosition, $length );
1350 $params = [ $input, $startPosition ];
1351 if ( $length !== null ) {
1352 $params[] = $length;
1354 return 'SUBSTR(' . implode( ',', $params ) . ')';
1358 * @param string $field Field or column to cast
1362 public function buildStringCast( $field ) {
1363 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1366 public function getInfinity() {
1367 return '31-12-2030 12:00:00.000000';