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
;
187 protected function doQuery( $sql ) {
188 wfDebug( "SQL: [$sql]\n" );
189 if ( !StringUtils
::isUtf8( $sql ) ) {
190 throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
193 // handle some oracle specifics
194 // remove AS column/table/subquery namings
195 if ( !$this->getFlag( DBO_DDLMODE
) ) {
196 $sql = preg_replace( '/ as /i', ' ', $sql );
199 // Oracle has issues with UNION clause if the statement includes LOB fields
200 // So we do a UNION ALL and then filter the results array with array_unique
201 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
202 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
203 // you have to select data from plan table after explain
204 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
208 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
214 Wikimedia\
suppressWarnings();
216 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
217 if ( $stmt === false ) {
218 $e = oci_error( $this->conn
);
219 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
224 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
225 $e = oci_error( $stmt );
226 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
227 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
233 Wikimedia\restoreWarnings
();
235 if ( $explain_count > 0 ) {
236 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
237 'WHERE statement_id = \'' . $explain_id . '\'' );
238 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
239 return new ORAResult( $this, $stmt, $union_unique );
241 $this->mAffectedRows
= oci_num_rows( $stmt );
247 function queryIgnore( $sql, $fname = '' ) {
248 return $this->query( $sql, $fname, true );
252 * Frees resources associated with the LOB descriptor
253 * @param ResultWrapper|ORAResult $res
255 function freeResult( $res ) {
256 if ( $res instanceof ResultWrapper
) {
264 * @param ResultWrapper|ORAResult $res
267 function fetchObject( $res ) {
268 if ( $res instanceof ResultWrapper
) {
272 return $res->fetchObject();
276 * @param ResultWrapper|ORAResult $res
279 function fetchRow( $res ) {
280 if ( $res instanceof ResultWrapper
) {
284 return $res->fetchRow();
288 * @param ResultWrapper|ORAResult $res
291 function numRows( $res ) {
292 if ( $res instanceof ResultWrapper
) {
296 return $res->numRows();
300 * @param ResultWrapper|ORAResult $res
303 function numFields( $res ) {
304 if ( $res instanceof ResultWrapper
) {
308 return $res->numFields();
311 function fieldName( $stmt, $n ) {
312 return oci_field_name( $stmt, $n );
315 function insertId() {
316 $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
317 $row = $this->fetchRow( $res );
318 return is_null( $row[0] ) ?
null : (int)$row[0];
325 function dataSeek( $res, $row ) {
326 if ( $res instanceof ORAResult
) {
329 $res->result
->seek( $row );
333 function lastError() {
334 if ( $this->conn
=== false ) {
337 $e = oci_error( $this->conn
);
340 return $e['message'];
343 function lastErrno() {
344 if ( $this->conn
=== false ) {
347 $e = oci_error( $this->conn
);
353 protected function fetchAffectedRowCount() {
354 return $this->mAffectedRows
;
358 * Returns information about an index
359 * If errors are explicitly ignored, returns NULL on failure
360 * @param string $table
361 * @param string $index
362 * @param string $fname
365 function indexInfo( $table, $index, $fname = __METHOD__
) {
369 function indexUnique( $table, $index, $fname = __METHOD__
) {
373 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
374 if ( !count( $a ) ) {
378 if ( !is_array( $options ) ) {
379 $options = [ $options ];
382 if ( in_array( 'IGNORE', $options ) ) {
383 $this->ignoreDupValOnIndex
= true;
386 if ( !is_array( reset( $a ) ) ) {
390 foreach ( $a as &$row ) {
391 $this->insertOneRow( $table, $row, $fname );
394 if ( in_array( 'IGNORE', $options ) ) {
395 $this->ignoreDupValOnIndex
= false;
401 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
402 $col_info = $this->fieldInfoMulti( $table, $col );
403 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
406 if ( is_numeric( $col ) ) {
411 } elseif ( $includeCol ) {
415 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
419 if ( $val === 'NULL' ) {
423 if ( $val === null ) {
424 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
437 * @param string $table
439 * @param string $fname
441 * @throws DBUnexpectedError
443 private function insertOneRow( $table, $row, $fname ) {
444 $table = $this->tableName( $table );
445 // "INSERT INTO tables (a, b, c)"
446 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
449 // for each value, append ":key"
451 foreach ( $row as $col => &$val ) {
457 if ( $this->isQuotedIdentifier( $val ) ) {
458 $sql .= $this->removeIdentifierQuotes( $val );
461 $sql .= $this->fieldBindStatement( $table, $col, $val );
466 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
467 if ( $stmt === false ) {
468 $e = oci_error( $this->conn
);
469 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
473 foreach ( $row as $col => &$val ) {
474 $col_info = $this->fieldInfoMulti( $table, $col );
475 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
477 if ( $val === null ) {
478 // do nothing ... null was inserted in statement creation
479 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
480 if ( is_object( $val ) ) {
481 $val = $val->fetch();
484 // backward compatibility
485 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
486 $val = $this->getInfinity();
489 $val = MediaWikiServices
::getInstance()->getContentLanguage()->
490 checkTitleEncoding( $val );
491 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
492 $e = oci_error( $stmt );
493 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
498 /** @var OCI_Lob[] $lob */
499 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
500 if ( $lob[$col] === false ) {
501 $e = oci_error( $stmt );
502 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
505 if ( is_object( $val ) ) {
506 $val = $val->fetch();
509 if ( $col_type == 'BLOB' ) {
510 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
511 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
513 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
514 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
519 Wikimedia\
suppressWarnings();
521 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
522 $e = oci_error( $stmt );
523 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
524 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
528 $this->mAffectedRows
= oci_num_rows( $stmt );
531 $this->mAffectedRows
= oci_num_rows( $stmt );
534 Wikimedia\restoreWarnings
();
536 if ( isset( $lob ) ) {
537 foreach ( $lob as $lob_v ) {
542 if ( !$this->trxLevel
) {
543 oci_commit( $this->conn
);
546 return oci_free_statement( $stmt );
549 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
550 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
552 $destTable = $this->tableName( $destTable );
554 $sequenceData = $this->getSequenceData( $destTable );
555 if ( $sequenceData !== false &&
556 !isset( $varMap[$sequenceData['column']] )
558 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
561 // count-alias subselect fields to avoid abigious definition errors
563 foreach ( $varMap as &$val ) {
564 $val = $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, array $uniqueIndexes, array $set,
592 if ( !count( $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 decodeBlob( $b ) {
699 if ( $b instanceof Blob
) {
706 function unionQueries( $sqls, $all ) {
707 $glue = ' UNION ALL ';
709 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
710 'FROM (' . implode( $glue, $sqls ) . ')';
713 function wasDeadlock() {
714 return $this->lastErrno() == 'OCI-00060';
717 function duplicateTableStructure( $oldName, $newName, $temporary = false,
720 $temporary = $temporary ?
'TRUE' : 'FALSE';
722 $newName = strtoupper( $newName );
723 $oldName = strtoupper( $oldName );
725 $tabName = substr( $newName, strlen( $this->tablePrefix
) );
726 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
727 $newPrefix = strtoupper( $this->tablePrefix
);
729 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
730 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
733 function listTables( $prefix = null, $fname = __METHOD__
) {
735 if ( !empty( $prefix ) ) {
736 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
739 $owner = strtoupper( $this->getDBname() );
740 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
741 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
743 // dirty code ... i know
745 $endArray[] = strtoupper( $prefix . 'MWUSER' );
746 $endArray[] = strtoupper( $prefix . 'PAGE' );
747 $endArray[] = strtoupper( $prefix . 'IMAGE' );
748 $fixedOrderTabs = $endArray;
749 while ( ( $row = $result->fetchRow() ) !== false ) {
750 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
751 $endArray[] = $row['table_name'];
758 public function dropTable( $tableName, $fName = __METHOD__
) {
759 $tableName = $this->tableName( $tableName );
760 if ( !$this->tableExists( $tableName ) ) {
764 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
767 function timestamp( $ts = 0 ) {
768 return wfTimestamp( TS_ORACLE
, $ts );
772 * Return aggregated value function call
774 * @param array $valuedata
775 * @param string $valuename
778 public function aggregateValue( $valuedata, $valuename = 'value' ) {
783 * @return string Wikitext of a link to the server software's web site
785 public function getSoftwareLink() {
786 return '[{{int:version-db-oracle-url}} Oracle]';
790 * @return string Version information from the database
792 function getServerVersion() {
793 // better version number, fallback on driver
794 $rset = $this->doQuery(
795 'SELECT version FROM product_component_version ' .
796 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
798 $row = $rset->fetchRow();
800 return oci_server_version( $this->conn
);
803 return $row['version'];
807 * Query whether a given index exists
808 * @param string $table
809 * @param string $index
810 * @param string $fname
813 function indexExists( $table, $index, $fname = __METHOD__
) {
814 $table = $this->tableName( $table );
815 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
816 $index = strtoupper( $index );
817 $owner = strtoupper( $this->getDBname() );
818 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
819 $res = $this->doQuery( $sql );
821 $count = $res->numRows();
831 * Query whether a given table exists (in the given schema, or the default mw one if not given)
832 * @param string $table
833 * @param string $fname
836 function tableExists( $table, $fname = __METHOD__
) {
837 $table = $this->tableName( $table );
838 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
839 $owner = $this->addQuotes( strtoupper( $this->getDBname() ) );
840 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
841 $res = $this->doQuery( $sql );
842 if ( $res && $res->numRows() > 0 ) {
854 * Function translates mysql_fetch_field() functionality on ORACLE.
855 * Caching is present for reducing query time.
856 * For internal calls. Use fieldInfo for normal usage.
857 * Returns false if the field doesn't exist
859 * @param array|string $table
860 * @param string $field
861 * @return ORAField|ORAResult|false
863 private function fieldInfoMulti( $table, $field ) {
864 $field = strtoupper( $field );
865 if ( is_array( $table ) ) {
866 $table = array_map( [ $this, 'tableNameInternal' ], $table );
867 $tableWhere = 'IN (';
868 foreach ( $table as &$singleTable ) {
869 $singleTable = $this->removeIdentifierQuotes( $singleTable );
870 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
871 return $this->mFieldInfoCache
["$singleTable.$field"];
873 $tableWhere .= '\'' . $singleTable . '\',';
875 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
877 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
878 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
879 return $this->mFieldInfoCache
["$table.$field"];
881 $tableWhere = '= \'' . $table . '\'';
884 $fieldInfoStmt = oci_parse(
886 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
887 $tableWhere . ' and column_name = \'' . $field . '\''
889 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
890 $e = oci_error( $fieldInfoStmt );
891 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
895 $res = new ORAResult( $this, $fieldInfoStmt );
896 if ( $res->numRows() == 0 ) {
897 if ( is_array( $table ) ) {
898 foreach ( $table as &$singleTable ) {
899 $this->mFieldInfoCache
["$singleTable.$field"] = false;
902 $this->mFieldInfoCache
["$table.$field"] = false;
904 $fieldInfoTemp = null;
906 $fieldInfoTemp = new ORAField( $res->fetchRow() );
907 $table = $fieldInfoTemp->tableName();
908 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
912 return $fieldInfoTemp;
916 * @throws DBUnexpectedError
917 * @param string $table
918 * @param string $field
921 function fieldInfo( $table, $field ) {
922 if ( is_array( $table ) ) {
923 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
926 return $this->fieldInfoMulti( $table, $field );
929 protected function doBegin( $fname = __METHOD__
) {
931 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
934 protected function doCommit( $fname = __METHOD__
) {
935 if ( $this->trxLevel
) {
936 $ret = oci_commit( $this->conn
);
938 throw new DBUnexpectedError( $this, $this->lastError() );
941 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
945 protected function doRollback( $fname = __METHOD__
) {
946 if ( $this->trxLevel
) {
947 oci_rollback( $this->conn
);
949 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
953 function sourceStream(
955 callable
$lineCallback = null,
956 callable
$resultCallback = null,
957 $fname = __METHOD__
, callable
$inputCallback = null
961 $dollarquote = false;
964 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
965 while ( !feof( $fp ) ) {
966 if ( $lineCallback ) {
967 call_user_func( $lineCallback );
969 $line = trim( fgets( $fp, 1024 ) );
970 $sl = strlen( $line ) - 1;
975 if ( $line[0] == '-' && $line[1] == '-' ) {
979 // Allow dollar quoting for function declarations
980 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
981 if ( $dollarquote ) {
982 $dollarquote = false;
983 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
988 } elseif ( !$dollarquote ) {
989 if ( $line[$sl] == ';' && ( $sl < 2 ||
$line[$sl - 1] != ';' ) ) {
991 $line = substr( $line, 0, $sl );
1001 $cmd = str_replace( ';;', ";", $cmd );
1002 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1003 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1004 $replacements[$defines[2]] = $defines[1];
1007 foreach ( $replacements as $mwVar => $scVar ) {
1008 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1011 $cmd = $this->replaceVars( $cmd );
1012 if ( $inputCallback ) {
1013 call_user_func( $inputCallback, $cmd );
1015 $res = $this->doQuery( $cmd );
1016 if ( $resultCallback ) {
1017 call_user_func( $resultCallback, $res, $this );
1020 if ( $res === false ) {
1021 $err = $this->lastError();
1023 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1035 protected function doSelectDomain( DatabaseDomain
$domain ) {
1036 if ( $domain->getSchema() !== null ) {
1037 // We use the *database* aspect of $domain for schema, not the domain schema
1038 throw new DBExpectedError( $this, __CLASS__
. ": domain schemas are not supported." );
1041 $database = $domain->getDatabase();
1042 if ( $database === null ||
$database === $this->user
) {
1043 // Backward compatibility
1044 $this->currentDomain
= $domain;
1049 // https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj32268.html
1050 $encDatabase = $this->addIdentifierQuotes( strtoupper( $database ) );
1051 $sql = "ALTER SESSION SET CURRENT_SCHEMA=$encDatabase";
1052 $stmt = oci_parse( $this->conn
, $sql );
1053 Wikimedia\
suppressWarnings();
1054 $success = oci_execute( $stmt );
1055 Wikimedia\restoreWarnings
();
1057 // Update that domain fields on success (no exception thrown)
1058 $this->currentDomain
= $domain;
1060 $e = oci_error( $stmt );
1061 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1067 function strencode( $s ) {
1068 return str_replace( "'", "''", $s );
1071 function addQuotes( $s ) {
1072 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1073 if ( isset( $contLang->mLoaded
) && $contLang->mLoaded
) {
1074 $s = $contLang->checkTitleEncoding( $s );
1077 return "'" . $this->strencode( $s ) . "'";
1080 public function addIdentifierQuotes( $s ) {
1081 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1088 public function removeIdentifierQuotes( $s ) {
1089 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1092 public function isQuotedIdentifier( $s ) {
1093 return strpos( $s, '/*Q*/' ) !== false;
1096 private function wrapFieldForWhere( $table, &$col, &$val ) {
1097 $col_info = $this->fieldInfoMulti( $table, $col );
1098 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1099 if ( $col_type == 'CLOB' ) {
1100 $col = 'TO_CHAR(' . $col . ')';
1102 MediaWikiServices
::getInstance()->getContentLanguage()->checkTitleEncoding( $val );
1103 } elseif ( $col_type == 'VARCHAR2' ) {
1105 MediaWikiServices
::getInstance()->getContentLanguage()->checkTitleEncoding( $val );
1109 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1111 foreach ( $conds as $col => $val ) {
1112 if ( is_array( $val ) ) {
1113 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1115 if ( is_numeric( $col ) && $parentCol != null ) {
1116 $this->wrapFieldForWhere( $table, $parentCol, $val );
1118 $this->wrapFieldForWhere( $table, $col, $val );
1120 $conds2[$col] = $val;
1127 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1128 $options = [], $join_conds = []
1130 if ( is_array( $conds ) ) {
1131 $conds = $this->wrapConditionsForWhere( $table, $conds );
1134 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1138 * Returns an optional USE INDEX clause to go after the table, and a
1139 * string to go at the end of the query
1141 * @param array $options An associative array of options to be turned into
1142 * an SQL query, valid keys are listed in the function.
1145 function makeSelectOptions( $options ) {
1146 $preLimitTail = $postLimitTail = '';
1150 foreach ( $options as $key => $option ) {
1151 if ( is_numeric( $key ) ) {
1152 $noKeyOptions[$option] = true;
1156 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1158 $preLimitTail .= $this->makeOrderBy( $options );
1160 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1161 $postLimitTail .= ' FOR UPDATE';
1164 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1165 $startOpts .= 'DISTINCT';
1168 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1169 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1174 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1175 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1180 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1183 public function delete( $table, $conds, $fname = __METHOD__
) {
1184 global $wgActorTableSchemaMigrationStage;
1186 if ( is_array( $conds ) ) {
1187 $conds = $this->wrapConditionsForWhere( $table, $conds );
1189 // a hack for deleting pages, users and images (which have non-nullable FKs)
1190 // all deletions on these tables have transactions so final failure rollbacks these updates
1191 // @todo: Normalize the schema to match MySQL, no special FKs and such
1192 $table = $this->tableName( $table );
1193 if ( $table == $this->tableName( 'user' ) &&
1194 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD
)
1196 $this->update( 'archive', [ 'ar_user' => 0 ],
1197 [ 'ar_user' => $conds['user_id'] ], $fname );
1198 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1199 [ 'ipb_user' => $conds['user_id'] ], $fname );
1200 $this->update( 'image', [ 'img_user' => 0 ],
1201 [ 'img_user' => $conds['user_id'] ], $fname );
1202 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1203 [ 'oi_user' => $conds['user_id'] ], $fname );
1204 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1205 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1206 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1207 [ 'fa_user' => $conds['user_id'] ], $fname );
1208 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1209 [ 'us_user' => $conds['user_id'] ], $fname );
1210 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1211 [ 'rc_user' => $conds['user_id'] ], $fname );
1212 $this->update( 'logging', [ 'log_user' => 0 ],
1213 [ 'log_user' => $conds['user_id'] ], $fname );
1214 } elseif ( $table == $this->tableName( 'image' ) ) {
1215 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1216 [ 'oi_name' => $conds['img_name'] ], $fname );
1219 return parent
::delete( $table, $conds, $fname );
1223 * @param string $table
1224 * @param array $values
1225 * @param array $conds
1226 * @param string $fname
1227 * @param array $options
1229 * @throws DBUnexpectedError
1231 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1232 $table = $this->tableName( $table );
1233 $opts = $this->makeUpdateOptions( $options );
1234 $sql = "UPDATE $opts $table SET ";
1237 foreach ( $values as $col => &$val ) {
1238 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1241 $sqlSet = ', ' . $sqlSet;
1248 if ( $conds !== [] && $conds !== '*' ) {
1249 $conds = $this->wrapConditionsForWhere( $table, $conds );
1250 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1253 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
1254 if ( $stmt === false ) {
1255 $e = oci_error( $this->conn
);
1256 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1260 foreach ( $values as $col => &$val ) {
1261 $col_info = $this->fieldInfoMulti( $table, $col );
1262 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1264 if ( $val === null ) {
1265 // do nothing ... null was inserted in statement creation
1266 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1267 if ( is_object( $val ) ) {
1268 $val = $val->getData();
1271 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1272 $val = '31-12-2030 12:00:00.000000';
1275 $val = MediaWikiServices
::getInstance()->getContentLanguage()->
1276 checkTitleEncoding( $val );
1277 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1278 $e = oci_error( $stmt );
1279 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1284 /** @var OCI_Lob[] $lob */
1285 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
1286 if ( $lob[$col] === false ) {
1287 $e = oci_error( $stmt );
1288 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1291 if ( is_object( $val ) ) {
1292 $val = $val->getData();
1295 if ( $col_type == 'BLOB' ) {
1296 $lob[$col]->writeTemporary( $val );
1297 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1299 $lob[$col]->writeTemporary( $val );
1300 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1305 Wikimedia\
suppressWarnings();
1307 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1308 $e = oci_error( $stmt );
1309 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1310 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1314 $this->mAffectedRows
= oci_num_rows( $stmt );
1317 $this->mAffectedRows
= oci_num_rows( $stmt );
1320 Wikimedia\restoreWarnings
();
1322 if ( isset( $lob ) ) {
1323 foreach ( $lob as $lob_v ) {
1328 if ( !$this->trxLevel
) {
1329 oci_commit( $this->conn
);
1332 return oci_free_statement( $stmt );
1335 function bitNot( $field ) {
1336 // expecting bit-fields smaller than 4bytes
1337 return 'BITNOT(' . $field . ')';
1340 function bitAnd( $fieldLeft, $fieldRight ) {
1341 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1344 function bitOr( $fieldLeft, $fieldRight ) {
1345 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1348 function getServer() {
1349 return $this->server
;
1352 public function buildGroupConcatField(
1353 $delim, $table, $field, $conds = '', $join_conds = []
1355 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1357 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1360 public function buildSubstring( $input, $startPosition, $length = null ) {
1361 $this->assertBuildSubstringParams( $startPosition, $length );
1362 $params = [ $input, $startPosition ];
1363 if ( $length !== null ) {
1364 $params[] = $length;
1366 return 'SUBSTR(' . implode( ',', $params ) . ')';
1370 * @param string $field Field or column to cast
1374 public function buildStringCast( $field ) {
1375 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1378 public function getInfinity() {
1379 return '31-12-2030 12:00:00.000000';