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\Blob
;
27 use Wikimedia\Rdbms\ResultWrapper
;
28 use Wikimedia\Rdbms\DBConnectionError
;
29 use Wikimedia\Rdbms\DBUnexpectedError
;
34 class DatabaseOracle
extends Database
{
36 protected $mLastResult = null;
38 /** @var int The number of rows affected as an integer */
39 protected $mAffectedRows;
42 private $ignoreDupValOnIndex = false;
44 /** @var bool|array */
45 private $sequenceData = null;
47 /** @var string Character set for Oracle database */
48 private $defaultCharset = 'AL32UTF8';
51 private $mFieldInfoCache = [];
53 function __construct( array $p ) {
56 if ( $p['tablePrefix'] == 'get from global' ) {
57 $p['tablePrefix'] = $wgDBprefix;
59 $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
60 parent
::__construct( $p );
61 Hooks
::run( 'DatabaseOraclePostInit', [ $this ] );
64 function __destruct() {
65 if ( $this->opened
) {
66 Wikimedia\
suppressWarnings();
68 Wikimedia\restoreWarnings
();
76 function implicitGroupby() {
80 function implicitOrderby() {
84 function open( $server, $user, $password, $dbName ) {
85 global $wgDBOracleDRCP;
86 if ( !function_exists( 'oci_connect' ) ) {
87 throw new DBConnectionError(
89 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
90 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
96 $this->password
= $password;
97 // changed internal variables functions
98 // mServer now holds the TNS endpoint
99 // mDBname is schema name if different from username
101 // backward compatibillity (server used to be null and TNS was supplied in dbname)
102 $this->server
= $dbName;
103 $this->dbName
= $user;
105 $this->server
= $server;
107 $this->dbName
= $user;
109 $this->dbName
= $dbName;
113 if ( !strlen( $user ) ) { # e.g. the class is being loaded
117 if ( $wgDBOracleDRCP ) {
118 $this->setFlag( DBO_PERSISTENT
);
121 $session_mode = $this->flags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
123 Wikimedia\
suppressWarnings();
124 if ( $this->flags
& DBO_PERSISTENT
) {
125 $this->conn
= oci_pconnect(
129 $this->defaultCharset
,
132 } elseif ( $this->flags
& DBO_DEFAULT
) {
133 $this->conn
= oci_new_connect(
137 $this->defaultCharset
,
141 $this->conn
= oci_connect(
145 $this->defaultCharset
,
149 Wikimedia\restoreWarnings
();
151 if ( $this->user
!= $this->dbName
) {
152 // change current schema in session
153 $this->selectDB( $this->dbName
);
156 if ( !$this->conn
) {
157 throw new DBConnectionError( $this, $this->lastError() );
160 $this->opened
= true;
162 # removed putenv calls because they interfere with the system globaly
163 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
164 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
165 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
167 return (bool)$this->conn
;
171 * Closes a database connection, if it is open
172 * Returns success, true if already closed
175 protected function closeConnection() {
176 return oci_close( $this->conn
);
179 function execFlags() {
180 return $this->trxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
183 protected function doQuery( $sql ) {
184 wfDebug( "SQL: [$sql]\n" );
185 if ( !StringUtils
::isUtf8( $sql ) ) {
186 throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
189 // handle some oracle specifics
190 // remove AS column/table/subquery namings
191 if ( !$this->getFlag( DBO_DDLMODE
) ) {
192 $sql = preg_replace( '/ as /i', ' ', $sql );
195 // Oracle has issues with UNION clause if the statement includes LOB fields
196 // So we do a UNION ALL and then filter the results array with array_unique
197 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
198 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
199 // you have to select data from plan table after explain
200 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
204 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
210 Wikimedia\
suppressWarnings();
212 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
213 if ( $stmt === false ) {
214 $e = oci_error( $this->conn
);
215 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
220 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
221 $e = oci_error( $stmt );
222 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
223 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
229 Wikimedia\restoreWarnings
();
231 if ( $explain_count > 0 ) {
232 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
233 'WHERE statement_id = \'' . $explain_id . '\'' );
234 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
235 return new ORAResult( $this, $stmt, $union_unique );
237 $this->mAffectedRows
= oci_num_rows( $stmt );
243 function queryIgnore( $sql, $fname = '' ) {
244 return $this->query( $sql, $fname, true );
248 * Frees resources associated with the LOB descriptor
249 * @param ResultWrapper|ORAResult $res
251 function freeResult( $res ) {
252 if ( $res instanceof ResultWrapper
) {
260 * @param ResultWrapper|ORAResult $res
263 function fetchObject( $res ) {
264 if ( $res instanceof ResultWrapper
) {
268 return $res->fetchObject();
272 * @param ResultWrapper|ORAResult $res
275 function fetchRow( $res ) {
276 if ( $res instanceof ResultWrapper
) {
280 return $res->fetchRow();
284 * @param ResultWrapper|ORAResult $res
287 function numRows( $res ) {
288 if ( $res instanceof ResultWrapper
) {
292 return $res->numRows();
296 * @param ResultWrapper|ORAResult $res
299 function numFields( $res ) {
300 if ( $res instanceof ResultWrapper
) {
304 return $res->numFields();
307 function fieldName( $stmt, $n ) {
308 return oci_field_name( $stmt, $n );
311 function insertId() {
312 $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
313 $row = $this->fetchRow( $res );
314 return is_null( $row[0] ) ?
null : (int)$row[0];
321 function dataSeek( $res, $row ) {
322 if ( $res instanceof ORAResult
) {
325 $res->result
->seek( $row );
329 function lastError() {
330 if ( $this->conn
=== false ) {
333 $e = oci_error( $this->conn
);
336 return $e['message'];
339 function lastErrno() {
340 if ( $this->conn
=== false ) {
343 $e = oci_error( $this->conn
);
349 protected function fetchAffectedRowCount() {
350 return $this->mAffectedRows
;
354 * Returns information about an index
355 * If errors are explicitly ignored, returns NULL on failure
356 * @param string $table
357 * @param string $index
358 * @param string $fname
361 function indexInfo( $table, $index, $fname = __METHOD__
) {
365 function indexUnique( $table, $index, $fname = __METHOD__
) {
369 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
370 if ( !count( $a ) ) {
374 if ( !is_array( $options ) ) {
375 $options = [ $options ];
378 if ( in_array( 'IGNORE', $options ) ) {
379 $this->ignoreDupValOnIndex
= true;
382 if ( !is_array( reset( $a ) ) ) {
386 foreach ( $a as &$row ) {
387 $this->insertOneRow( $table, $row, $fname );
391 if ( in_array( 'IGNORE', $options ) ) {
392 $this->ignoreDupValOnIndex
= false;
398 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
399 $col_info = $this->fieldInfoMulti( $table, $col );
400 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
403 if ( is_numeric( $col ) ) {
408 } elseif ( $includeCol ) {
412 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
416 if ( $val === 'NULL' ) {
420 if ( $val === null ) {
421 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
434 * @param string $table
436 * @param string $fname
438 * @throws DBUnexpectedError
440 private function insertOneRow( $table, $row, $fname ) {
441 $table = $this->tableName( $table );
442 // "INSERT INTO tables (a, b, c)"
443 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
446 // for each value, append ":key"
448 foreach ( $row as $col => &$val ) {
454 if ( $this->isQuotedIdentifier( $val ) ) {
455 $sql .= $this->removeIdentifierQuotes( $val );
458 $sql .= $this->fieldBindStatement( $table, $col, $val );
463 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
464 if ( $stmt === false ) {
465 $e = oci_error( $this->conn
);
466 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
470 foreach ( $row as $col => &$val ) {
471 $col_info = $this->fieldInfoMulti( $table, $col );
472 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
474 if ( $val === null ) {
475 // do nothing ... null was inserted in statement creation
476 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
477 if ( is_object( $val ) ) {
478 $val = $val->fetch();
481 // backward compatibility
482 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
483 $val = $this->getInfinity();
486 $val = MediaWikiServices
::getInstance()->getContentLanguage()->
487 checkTitleEncoding( $val );
488 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
489 $e = oci_error( $stmt );
490 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
495 /** @var OCI_Lob[] $lob */
496 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
497 if ( $lob[$col] === false ) {
498 $e = oci_error( $stmt );
499 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
502 if ( is_object( $val ) ) {
503 $val = $val->fetch();
506 if ( $col_type == 'BLOB' ) {
507 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
508 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
510 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
511 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
516 Wikimedia\
suppressWarnings();
518 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
519 $e = oci_error( $stmt );
520 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
521 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
525 $this->mAffectedRows
= oci_num_rows( $stmt );
528 $this->mAffectedRows
= oci_num_rows( $stmt );
531 Wikimedia\restoreWarnings
();
533 if ( isset( $lob ) ) {
534 foreach ( $lob as $lob_v ) {
539 if ( !$this->trxLevel
) {
540 oci_commit( $this->conn
);
543 return oci_free_statement( $stmt );
546 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
547 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
549 $destTable = $this->tableName( $destTable );
551 $sequenceData = $this->getSequenceData( $destTable );
552 if ( $sequenceData !== false &&
553 !isset( $varMap[$sequenceData['column']] )
555 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
558 // count-alias subselect fields to avoid abigious definition errors
560 foreach ( $varMap as &$val ) {
561 $val = $val . ' field' . ( $i++
);
564 $selectSql = $this->selectSQLText(
566 array_values( $varMap ),
573 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
575 if ( in_array( 'IGNORE', $insertOptions ) ) {
576 $this->ignoreDupValOnIndex
= true;
579 $retval = $this->query( $sql, $fname );
581 if ( in_array( 'IGNORE', $insertOptions ) ) {
582 $this->ignoreDupValOnIndex
= false;
588 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
591 if ( !count( $rows ) ) {
592 return true; // nothing to do
595 if ( !is_array( reset( $rows ) ) ) {
599 $sequenceData = $this->getSequenceData( $table );
600 if ( $sequenceData !== false ) {
601 // add sequence column to each list of columns, when not set
602 foreach ( $rows as &$row ) {
603 if ( !isset( $row[$sequenceData['column']] ) ) {
604 $row[$sequenceData['column']] =
605 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
606 $sequenceData['sequence'] . '\')' );
611 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
614 function tableName( $name, $format = 'quoted' ) {
616 Replace reserved words with better ones
617 Using uppercase because that's the only way Oracle can handle
625 $name = 'PAGECONTENT';
629 return strtoupper( parent
::tableName( $name, $format ) );
632 function tableNameInternal( $name ) {
633 $name = $this->tableName( $name );
635 return preg_replace( '/.*\.(.*)/', '$1', $name );
639 * Return sequence_name if table has a sequence
641 * @param string $table
644 private function getSequenceData( $table ) {
645 if ( $this->sequenceData
== null ) {
646 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
647 lower(atc.table_name),
648 lower(atc.column_name)
649 FROM all_sequences asq, all_tab_columns atc
652 '{$this->tablePrefix}MWUSER',
653 '{$this->tablePrefix}USER',
656 atc.column_name || '_SEQ' = '{$this->tablePrefix}' || asq.sequence_name
657 AND asq.sequence_owner = upper('{$this->dbName}')
658 AND atc.owner = upper('{$this->dbName}')" );
660 while ( ( $row = $result->fetchRow() ) !== false ) {
661 $this->sequenceData
[$row[1]] = [
662 'sequence' => $row[0],
667 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
669 return $this->sequenceData
[$table] ??
false;
673 * Returns the size of a text field, or -1 for "unlimited"
675 * @param string $table
676 * @param string $field
679 function textFieldSize( $table, $field ) {
680 $fieldInfoData = $this->fieldInfo( $table, $field );
682 return $fieldInfoData->maxLength();
685 function limitResult( $sql, $limit, $offset = false ) {
686 if ( $offset === false ) {
690 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
693 function encodeBlob( $b ) {
694 return new Blob( $b );
697 function decodeBlob( $b ) {
698 if ( $b instanceof Blob
) {
705 function unionQueries( $sqls, $all ) {
706 $glue = ' UNION ALL ';
708 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
709 'FROM (' . implode( $glue, $sqls ) . ')';
712 function wasDeadlock() {
713 return $this->lastErrno() == 'OCI-00060';
716 function duplicateTableStructure( $oldName, $newName, $temporary = false,
719 $temporary = $temporary ?
'TRUE' : 'FALSE';
721 $newName = strtoupper( $newName );
722 $oldName = strtoupper( $oldName );
724 $tabName = substr( $newName, strlen( $this->tablePrefix
) );
725 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
726 $newPrefix = strtoupper( $this->tablePrefix
);
728 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
729 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
732 function listTables( $prefix = null, $fname = __METHOD__
) {
734 if ( !empty( $prefix ) ) {
735 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
738 $owner = strtoupper( $this->dbName
);
739 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
740 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
742 // dirty code ... i know
744 $endArray[] = strtoupper( $prefix . 'MWUSER' );
745 $endArray[] = strtoupper( $prefix . 'PAGE' );
746 $endArray[] = strtoupper( $prefix . 'IMAGE' );
747 $fixedOrderTabs = $endArray;
748 while ( ( $row = $result->fetchRow() ) !== false ) {
749 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
750 $endArray[] = $row['table_name'];
757 public function dropTable( $tableName, $fName = __METHOD__
) {
758 $tableName = $this->tableName( $tableName );
759 if ( !$this->tableExists( $tableName ) ) {
763 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
766 function timestamp( $ts = 0 ) {
767 return wfTimestamp( TS_ORACLE
, $ts );
771 * Return aggregated value function call
773 * @param array $valuedata
774 * @param string $valuename
777 public function aggregateValue( $valuedata, $valuename = 'value' ) {
782 * @return string Wikitext of a link to the server software's web site
784 public function getSoftwareLink() {
785 return '[{{int:version-db-oracle-url}} Oracle]';
789 * @return string Version information from the database
791 function getServerVersion() {
792 // better version number, fallback on driver
793 $rset = $this->doQuery(
794 'SELECT version FROM product_component_version ' .
795 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
797 $row = $rset->fetchRow();
799 return oci_server_version( $this->conn
);
802 return $row['version'];
806 * Query whether a given index exists
807 * @param string $table
808 * @param string $index
809 * @param string $fname
812 function indexExists( $table, $index, $fname = __METHOD__
) {
813 $table = $this->tableName( $table );
814 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
815 $index = strtoupper( $index );
816 $owner = strtoupper( $this->dbName
);
817 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
818 $res = $this->doQuery( $sql );
820 $count = $res->numRows();
830 * Query whether a given table exists (in the given schema, or the default mw one if not given)
831 * @param string $table
832 * @param string $fname
835 function tableExists( $table, $fname = __METHOD__
) {
836 $table = $this->tableName( $table );
837 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
838 $owner = $this->addQuotes( strtoupper( $this->dbName
) );
839 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
840 $res = $this->doQuery( $sql );
841 if ( $res && $res->numRows() > 0 ) {
853 * Function translates mysql_fetch_field() functionality on ORACLE.
854 * Caching is present for reducing query time.
855 * For internal calls. Use fieldInfo for normal usage.
856 * Returns false if the field doesn't exist
858 * @param array|string $table
859 * @param string $field
860 * @return ORAField|ORAResult|false
862 private function fieldInfoMulti( $table, $field ) {
863 $field = strtoupper( $field );
864 if ( is_array( $table ) ) {
865 $table = array_map( [ $this, 'tableNameInternal' ], $table );
866 $tableWhere = 'IN (';
867 foreach ( $table as &$singleTable ) {
868 $singleTable = $this->removeIdentifierQuotes( $singleTable );
869 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
870 return $this->mFieldInfoCache
["$singleTable.$field"];
872 $tableWhere .= '\'' . $singleTable . '\',';
874 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
876 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
877 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
878 return $this->mFieldInfoCache
["$table.$field"];
880 $tableWhere = '= \'' . $table . '\'';
883 $fieldInfoStmt = oci_parse(
885 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
886 $tableWhere . ' and column_name = \'' . $field . '\''
888 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
889 $e = oci_error( $fieldInfoStmt );
890 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
894 $res = new ORAResult( $this, $fieldInfoStmt );
895 if ( $res->numRows() == 0 ) {
896 if ( is_array( $table ) ) {
897 foreach ( $table as &$singleTable ) {
898 $this->mFieldInfoCache
["$singleTable.$field"] = false;
901 $this->mFieldInfoCache
["$table.$field"] = false;
903 $fieldInfoTemp = null;
905 $fieldInfoTemp = new ORAField( $res->fetchRow() );
906 $table = $fieldInfoTemp->tableName();
907 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
911 return $fieldInfoTemp;
915 * @throws DBUnexpectedError
916 * @param string $table
917 * @param string $field
920 function fieldInfo( $table, $field ) {
921 if ( is_array( $table ) ) {
922 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
925 return $this->fieldInfoMulti( $table, $field );
928 protected function doBegin( $fname = __METHOD__
) {
930 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
933 protected function doCommit( $fname = __METHOD__
) {
934 if ( $this->trxLevel
) {
935 $ret = oci_commit( $this->conn
);
937 throw new DBUnexpectedError( $this, $this->lastError() );
940 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
944 protected function doRollback( $fname = __METHOD__
) {
945 if ( $this->trxLevel
) {
946 oci_rollback( $this->conn
);
948 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
952 function sourceStream(
954 callable
$lineCallback = null,
955 callable
$resultCallback = null,
956 $fname = __METHOD__
, callable
$inputCallback = null
960 $dollarquote = false;
963 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
964 while ( !feof( $fp ) ) {
965 if ( $lineCallback ) {
966 call_user_func( $lineCallback );
968 $line = trim( fgets( $fp, 1024 ) );
969 $sl = strlen( $line ) - 1;
974 if ( '-' == $line[0] && '-' == $line[1] ) {
978 // Allow dollar quoting for function declarations
979 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
980 if ( $dollarquote ) {
981 $dollarquote = false;
982 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
987 } elseif ( !$dollarquote ) {
988 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
990 $line = substr( $line, 0, $sl );
1000 $cmd = str_replace( ';;', ";", $cmd );
1001 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1002 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1003 $replacements[$defines[2]] = $defines[1];
1006 foreach ( $replacements as $mwVar => $scVar ) {
1007 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1010 $cmd = $this->replaceVars( $cmd );
1011 if ( $inputCallback ) {
1012 call_user_func( $inputCallback, $cmd );
1014 $res = $this->doQuery( $cmd );
1015 if ( $resultCallback ) {
1016 call_user_func( $resultCallback, $res, $this );
1019 if ( false === $res ) {
1020 $err = $this->lastError();
1022 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1034 function selectDB( $db ) {
1035 $this->dbName
= $db;
1036 if ( $db == null ||
$db == $this->user
) {
1039 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1040 $stmt = oci_parse( $this->conn
, $sql );
1041 Wikimedia\
suppressWarnings();
1042 $success = oci_execute( $stmt );
1043 Wikimedia\restoreWarnings
();
1045 $e = oci_error( $stmt );
1046 if ( $e['code'] != '1435' ) {
1047 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1056 function strencode( $s ) {
1057 return str_replace( "'", "''", $s );
1060 function addQuotes( $s ) {
1061 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1062 if ( isset( $contLang->mLoaded
) && $contLang->mLoaded
) {
1063 $s = $contLang->checkTitleEncoding( $s );
1066 return "'" . $this->strencode( $s ) . "'";
1069 public function addIdentifierQuotes( $s ) {
1070 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1077 public function removeIdentifierQuotes( $s ) {
1078 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1081 public function isQuotedIdentifier( $s ) {
1082 return strpos( $s, '/*Q*/' ) !== false;
1085 private function wrapFieldForWhere( $table, &$col, &$val ) {
1086 $col_info = $this->fieldInfoMulti( $table, $col );
1087 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1088 if ( $col_type == 'CLOB' ) {
1089 $col = 'TO_CHAR(' . $col . ')';
1091 MediaWikiServices
::getInstance()->getContentLanguage()->checkTitleEncoding( $val );
1092 } elseif ( $col_type == 'VARCHAR2' ) {
1094 MediaWikiServices
::getInstance()->getContentLanguage()->checkTitleEncoding( $val );
1098 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1100 foreach ( $conds as $col => $val ) {
1101 if ( is_array( $val ) ) {
1102 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1104 if ( is_numeric( $col ) && $parentCol != null ) {
1105 $this->wrapFieldForWhere( $table, $parentCol, $val );
1107 $this->wrapFieldForWhere( $table, $col, $val );
1109 $conds2[$col] = $val;
1116 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1117 $options = [], $join_conds = []
1119 if ( is_array( $conds ) ) {
1120 $conds = $this->wrapConditionsForWhere( $table, $conds );
1123 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1127 * Returns an optional USE INDEX clause to go after the table, and a
1128 * string to go at the end of the query
1130 * @param array $options An associative array of options to be turned into
1131 * an SQL query, valid keys are listed in the function.
1134 function makeSelectOptions( $options ) {
1135 $preLimitTail = $postLimitTail = '';
1139 foreach ( $options as $key => $option ) {
1140 if ( is_numeric( $key ) ) {
1141 $noKeyOptions[$option] = true;
1145 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1147 $preLimitTail .= $this->makeOrderBy( $options );
1149 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1150 $postLimitTail .= ' FOR UPDATE';
1153 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1154 $startOpts .= 'DISTINCT';
1157 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1158 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1163 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1164 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1169 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1172 public function delete( $table, $conds, $fname = __METHOD__
) {
1173 global $wgActorTableSchemaMigrationStage;
1175 if ( is_array( $conds ) ) {
1176 $conds = $this->wrapConditionsForWhere( $table, $conds );
1178 // a hack for deleting pages, users and images (which have non-nullable FKs)
1179 // all deletions on these tables have transactions so final failure rollbacks these updates
1180 // @todo: Normalize the schema to match MySQL, no special FKs and such
1181 $table = $this->tableName( $table );
1182 if ( $table == $this->tableName( 'user' ) && $wgActorTableSchemaMigrationStage < MIGRATION_NEW
) {
1183 $this->update( 'archive', [ 'ar_user' => 0 ],
1184 [ 'ar_user' => $conds['user_id'] ], $fname );
1185 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1186 [ 'ipb_user' => $conds['user_id'] ], $fname );
1187 $this->update( 'image', [ 'img_user' => 0 ],
1188 [ 'img_user' => $conds['user_id'] ], $fname );
1189 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1190 [ 'oi_user' => $conds['user_id'] ], $fname );
1191 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1192 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1193 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1194 [ 'fa_user' => $conds['user_id'] ], $fname );
1195 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1196 [ 'us_user' => $conds['user_id'] ], $fname );
1197 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1198 [ 'rc_user' => $conds['user_id'] ], $fname );
1199 $this->update( 'logging', [ 'log_user' => 0 ],
1200 [ 'log_user' => $conds['user_id'] ], $fname );
1201 } elseif ( $table == $this->tableName( 'image' ) ) {
1202 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1203 [ 'oi_name' => $conds['img_name'] ], $fname );
1206 return parent
::delete( $table, $conds, $fname );
1210 * @param string $table
1211 * @param array $values
1212 * @param array $conds
1213 * @param string $fname
1214 * @param array $options
1216 * @throws DBUnexpectedError
1218 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1219 $table = $this->tableName( $table );
1220 $opts = $this->makeUpdateOptions( $options );
1221 $sql = "UPDATE $opts $table SET ";
1224 foreach ( $values as $col => &$val ) {
1225 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1228 $sqlSet = ', ' . $sqlSet;
1235 if ( $conds !== [] && $conds !== '*' ) {
1236 $conds = $this->wrapConditionsForWhere( $table, $conds );
1237 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1240 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
1241 if ( $stmt === false ) {
1242 $e = oci_error( $this->conn
);
1243 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1247 foreach ( $values as $col => &$val ) {
1248 $col_info = $this->fieldInfoMulti( $table, $col );
1249 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1251 if ( $val === null ) {
1252 // do nothing ... null was inserted in statement creation
1253 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1254 if ( is_object( $val ) ) {
1255 $val = $val->getData();
1258 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1259 $val = '31-12-2030 12:00:00.000000';
1262 $val = MediaWikiServices
::getInstance()->getContentLanguage()->
1263 checkTitleEncoding( $val );
1264 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1265 $e = oci_error( $stmt );
1266 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1271 /** @var OCI_Lob[] $lob */
1272 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
1273 if ( $lob[$col] === false ) {
1274 $e = oci_error( $stmt );
1275 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1278 if ( is_object( $val ) ) {
1279 $val = $val->getData();
1282 if ( $col_type == 'BLOB' ) {
1283 $lob[$col]->writeTemporary( $val );
1284 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1286 $lob[$col]->writeTemporary( $val );
1287 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1292 Wikimedia\
suppressWarnings();
1294 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1295 $e = oci_error( $stmt );
1296 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1297 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1301 $this->mAffectedRows
= oci_num_rows( $stmt );
1304 $this->mAffectedRows
= oci_num_rows( $stmt );
1307 Wikimedia\restoreWarnings
();
1309 if ( isset( $lob ) ) {
1310 foreach ( $lob as $lob_v ) {
1315 if ( !$this->trxLevel
) {
1316 oci_commit( $this->conn
);
1319 return oci_free_statement( $stmt );
1322 function bitNot( $field ) {
1323 // expecting bit-fields smaller than 4bytes
1324 return 'BITNOT(' . $field . ')';
1327 function bitAnd( $fieldLeft, $fieldRight ) {
1328 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1331 function bitOr( $fieldLeft, $fieldRight ) {
1332 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1335 function getDBname() {
1336 return $this->dbName
;
1339 function getServer() {
1340 return $this->server
;
1343 public function buildGroupConcatField(
1344 $delim, $table, $field, $conds = '', $join_conds = []
1346 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1348 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1351 public function buildSubstring( $input, $startPosition, $length = null ) {
1352 $this->assertBuildSubstringParams( $startPosition, $length );
1353 $params = [ $input, $startPosition ];
1354 if ( $length !== null ) {
1355 $params[] = $length;
1357 return 'SUBSTR(' . implode( ',', $params ) . ')';
1361 * @param string $field Field or column to cast
1365 public function buildStringCast( $field ) {
1366 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1369 public function getInfinity() {
1370 return '31-12-2030 12:00:00.000000';