3 * This is the Oracle database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use Wikimedia\Rdbms\Database
;
25 use Wikimedia\Rdbms\Blob
;
26 use Wikimedia\Rdbms\ResultWrapper
;
27 use Wikimedia\Rdbms\DBConnectionError
;
28 use Wikimedia\Rdbms\DBUnexpectedError
;
33 class DatabaseOracle
extends Database
{
35 protected $mLastResult = null;
37 /** @var int The number of rows affected as an integer */
38 protected $mAffectedRows;
41 private $mInsertId = null;
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->mOpened
) {
68 MediaWiki\
suppressWarnings();
70 MediaWiki\restoreWarnings
();
78 function implicitGroupby() {
82 function implicitOrderby() {
87 * Usually aborts on failure
88 * @param string $server
90 * @param string $password
91 * @param string $dbName
92 * @throws DBConnectionError
93 * @return resource|null
95 function open( $server, $user, $password, $dbName ) {
96 global $wgDBOracleDRCP;
97 if ( !function_exists( 'oci_connect' ) ) {
98 throw new DBConnectionError(
100 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
101 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
106 $this->mUser
= $user;
107 $this->mPassword
= $password;
108 // changed internal variables functions
109 // mServer now holds the TNS endpoint
110 // mDBname is schema name if different from username
112 // backward compatibillity (server used to be null and TNS was supplied in dbname)
113 $this->mServer
= $dbName;
114 $this->mDBname
= $user;
116 $this->mServer
= $server;
118 $this->mDBname
= $user;
120 $this->mDBname
= $dbName;
124 if ( !strlen( $user ) ) { # e.g. the class is being loaded
128 if ( $wgDBOracleDRCP ) {
129 $this->setFlag( DBO_PERSISTENT
);
132 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
134 MediaWiki\
suppressWarnings();
135 if ( $this->mFlags
& DBO_PERSISTENT
) {
136 $this->mConn
= oci_pconnect(
140 $this->defaultCharset
,
143 } elseif ( $this->mFlags
& DBO_DEFAULT
) {
144 $this->mConn
= oci_new_connect(
148 $this->defaultCharset
,
152 $this->mConn
= oci_connect(
156 $this->defaultCharset
,
160 MediaWiki\restoreWarnings
();
162 if ( $this->mUser
!= $this->mDBname
) {
163 // change current schema in session
164 $this->selectDB( $this->mDBname
);
167 if ( !$this->mConn
) {
168 throw new DBConnectionError( $this, $this->lastError() );
171 $this->mOpened
= true;
173 # removed putenv calls because they interfere with the system globaly
174 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
175 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
176 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
182 * Closes a database connection, if it is open
183 * Returns success, true if already closed
186 protected function closeConnection() {
187 return oci_close( $this->mConn
);
190 function execFlags() {
191 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
194 protected function doQuery( $sql ) {
195 wfDebug( "SQL: [$sql]\n" );
196 if ( !StringUtils
::isUtf8( $sql ) ) {
197 throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
200 // handle some oracle specifics
201 // remove AS column/table/subquery namings
202 if ( !$this->getFlag( DBO_DDLMODE
) ) {
203 $sql = preg_replace( '/ as /i', ' ', $sql );
206 // Oracle has issues with UNION clause if the statement includes LOB fields
207 // So we do a UNION ALL and then filter the results array with array_unique
208 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
209 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
210 // you have to select data from plan table after explain
211 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
215 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
221 MediaWiki\
suppressWarnings();
223 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
224 if ( $stmt === false ) {
225 $e = oci_error( $this->mConn
);
226 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
231 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
232 $e = oci_error( $stmt );
233 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
234 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
240 MediaWiki\restoreWarnings
();
242 if ( $explain_count > 0 ) {
243 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
244 'WHERE statement_id = \'' . $explain_id . '\'' );
245 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
246 return new ORAResult( $this, $stmt, $union_unique );
248 $this->mAffectedRows
= oci_num_rows( $stmt );
254 function queryIgnore( $sql, $fname = '' ) {
255 return $this->query( $sql, $fname, true );
259 * Frees resources associated with the LOB descriptor
260 * @param ResultWrapper|ORAResult $res
262 function freeResult( $res ) {
263 if ( $res instanceof ResultWrapper
) {
271 * @param ResultWrapper|ORAResult $res
274 function fetchObject( $res ) {
275 if ( $res instanceof ResultWrapper
) {
279 return $res->fetchObject();
283 * @param ResultWrapper|ORAResult $res
286 function fetchRow( $res ) {
287 if ( $res instanceof ResultWrapper
) {
291 return $res->fetchRow();
295 * @param ResultWrapper|ORAResult $res
298 function numRows( $res ) {
299 if ( $res instanceof ResultWrapper
) {
303 return $res->numRows();
307 * @param ResultWrapper|ORAResult $res
310 function numFields( $res ) {
311 if ( $res instanceof ResultWrapper
) {
315 return $res->numFields();
318 function fieldName( $stmt, $n ) {
319 return oci_field_name( $stmt, $n );
323 * This must be called after nextSequenceVal
326 function insertId() {
327 return $this->mInsertId
;
334 function dataSeek( $res, $row ) {
335 if ( $res instanceof ORAResult
) {
338 $res->result
->seek( $row );
342 function lastError() {
343 if ( $this->mConn
=== false ) {
346 $e = oci_error( $this->mConn
);
349 return $e['message'];
352 function lastErrno() {
353 if ( $this->mConn
=== false ) {
356 $e = oci_error( $this->mConn
);
362 function affectedRows() {
363 return $this->mAffectedRows
;
367 * Returns information about an index
368 * If errors are explicitly ignored, returns NULL on failure
369 * @param string $table
370 * @param string $index
371 * @param string $fname
374 function indexInfo( $table, $index, $fname = __METHOD__
) {
378 function indexUnique( $table, $index, $fname = __METHOD__
) {
382 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
383 if ( !count( $a ) ) {
387 if ( !is_array( $options ) ) {
388 $options = [ $options ];
391 if ( in_array( 'IGNORE', $options ) ) {
392 $this->ignoreDupValOnIndex
= true;
395 if ( !is_array( reset( $a ) ) ) {
399 foreach ( $a as &$row ) {
400 $this->insertOneRow( $table, $row, $fname );
404 if ( in_array( 'IGNORE', $options ) ) {
405 $this->ignoreDupValOnIndex
= false;
411 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
412 $col_info = $this->fieldInfoMulti( $table, $col );
413 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
416 if ( is_numeric( $col ) ) {
421 } elseif ( $includeCol ) {
425 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
429 if ( $val === 'NULL' ) {
433 if ( $val === null ) {
434 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
447 * @param string $table
449 * @param string $fname
451 * @throws DBUnexpectedError
453 private function insertOneRow( $table, $row, $fname ) {
456 $table = $this->tableName( $table );
457 // "INSERT INTO tables (a, b, c)"
458 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
461 // for each value, append ":key"
463 foreach ( $row as $col => &$val ) {
469 if ( $this->isQuotedIdentifier( $val ) ) {
470 $sql .= $this->removeIdentifierQuotes( $val );
473 $sql .= $this->fieldBindStatement( $table, $col, $val );
478 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
479 if ( $stmt === false ) {
480 $e = oci_error( $this->mConn
);
481 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
485 foreach ( $row as $col => &$val ) {
486 $col_info = $this->fieldInfoMulti( $table, $col );
487 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
489 if ( $val === null ) {
490 // do nothing ... null was inserted in statement creation
491 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
492 if ( is_object( $val ) ) {
493 $val = $val->fetch();
496 // backward compatibility
497 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
498 $val = $this->getInfinity();
501 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
502 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
503 $e = oci_error( $stmt );
504 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
509 /** @var OCI_Lob[] $lob */
510 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
511 if ( $lob[$col] === false ) {
512 $e = oci_error( $stmt );
513 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
516 if ( is_object( $val ) ) {
517 $val = $val->fetch();
520 if ( $col_type == 'BLOB' ) {
521 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
522 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
524 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
525 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
530 MediaWiki\
suppressWarnings();
532 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
533 $e = oci_error( $stmt );
534 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
535 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
539 $this->mAffectedRows
= oci_num_rows( $stmt );
542 $this->mAffectedRows
= oci_num_rows( $stmt );
545 MediaWiki\restoreWarnings
();
547 if ( isset( $lob ) ) {
548 foreach ( $lob as $lob_v ) {
553 if ( !$this->mTrxLevel
) {
554 oci_commit( $this->mConn
);
557 return oci_free_statement( $stmt );
560 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
561 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
563 $destTable = $this->tableName( $destTable );
565 $sequenceData = $this->getSequenceData( $destTable );
566 if ( $sequenceData !== false &&
567 !isset( $varMap[$sequenceData['column']] )
569 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
572 // count-alias subselect fields to avoid abigious definition errors
574 foreach ( $varMap as &$val ) {
575 $val = $val . ' field' . ( $i++
);
578 $selectSql = $this->selectSQLText(
580 array_values( $varMap ),
587 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
589 if ( in_array( 'IGNORE', $insertOptions ) ) {
590 $this->ignoreDupValOnIndex
= true;
593 $retval = $this->query( $sql, $fname );
595 if ( in_array( 'IGNORE', $insertOptions ) ) {
596 $this->ignoreDupValOnIndex
= false;
602 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
605 if ( !count( $rows ) ) {
606 return true; // nothing to do
609 if ( !is_array( reset( $rows ) ) ) {
613 $sequenceData = $this->getSequenceData( $table );
614 if ( $sequenceData !== false ) {
615 // add sequence column to each list of columns, when not set
616 foreach ( $rows as &$row ) {
617 if ( !isset( $row[$sequenceData['column']] ) ) {
618 $row[$sequenceData['column']] =
619 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
620 $sequenceData['sequence'] . '\')' );
625 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
628 function tableName( $name, $format = 'quoted' ) {
630 Replace reserved words with better ones
631 Using uppercase because that's the only way Oracle can handle
639 $name = 'PAGECONTENT';
643 return strtoupper( parent
::tableName( $name, $format ) );
646 function tableNameInternal( $name ) {
647 $name = $this->tableName( $name );
649 return preg_replace( '/.*\.(.*)/', '$1', $name );
653 * Return the next in a sequence, save the value for retrieval via insertId()
655 * @param string $seqName
658 function nextSequenceValue( $seqName ) {
659 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
660 $row = $this->fetchRow( $res );
661 $this->mInsertId
= $row[0];
663 return $this->mInsertId
;
667 * Return sequence_name if table has a sequence
669 * @param string $table
672 private function getSequenceData( $table ) {
673 if ( $this->sequenceData
== null ) {
674 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
675 lower(atc.table_name),
676 lower(atc.column_name)
677 FROM all_sequences asq, all_tab_columns atc
680 '{$this->mTablePrefix}MWUSER',
681 '{$this->mTablePrefix}USER',
684 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
685 AND asq.sequence_owner = upper('{$this->mDBname}')
686 AND atc.owner = upper('{$this->mDBname}')" );
688 while ( ( $row = $result->fetchRow() ) !== false ) {
689 $this->sequenceData
[$row[1]] = [
690 'sequence' => $row[0],
695 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
697 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
701 * Returns the size of a text field, or -1 for "unlimited"
703 * @param string $table
704 * @param string $field
707 function textFieldSize( $table, $field ) {
708 $fieldInfoData = $this->fieldInfo( $table, $field );
710 return $fieldInfoData->maxLength();
713 function limitResult( $sql, $limit, $offset = false ) {
714 if ( $offset === false ) {
718 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
721 function encodeBlob( $b ) {
722 return new Blob( $b );
725 function decodeBlob( $b ) {
726 if ( $b instanceof Blob
) {
733 function unionQueries( $sqls, $all ) {
734 $glue = ' UNION ALL ';
736 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
737 'FROM (' . implode( $glue, $sqls ) . ')';
740 function wasDeadlock() {
741 return $this->lastErrno() == 'OCI-00060';
744 function duplicateTableStructure( $oldName, $newName, $temporary = false,
747 $temporary = $temporary ?
'TRUE' : 'FALSE';
749 $newName = strtoupper( $newName );
750 $oldName = strtoupper( $oldName );
752 $tabName = substr( $newName, strlen( $this->mTablePrefix
) );
753 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
754 $newPrefix = strtoupper( $this->mTablePrefix
);
756 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
757 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
760 function listTables( $prefix = null, $fname = __METHOD__
) {
762 if ( !empty( $prefix ) ) {
763 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
766 $owner = strtoupper( $this->mDBname
);
767 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
768 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
770 // dirty code ... i know
772 $endArray[] = strtoupper( $prefix . 'MWUSER' );
773 $endArray[] = strtoupper( $prefix . 'PAGE' );
774 $endArray[] = strtoupper( $prefix . 'IMAGE' );
775 $fixedOrderTabs = $endArray;
776 while ( ( $row = $result->fetchRow() ) !== false ) {
777 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
778 $endArray[] = $row['table_name'];
785 public function dropTable( $tableName, $fName = __METHOD__
) {
786 $tableName = $this->tableName( $tableName );
787 if ( !$this->tableExists( $tableName ) ) {
791 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
794 function timestamp( $ts = 0 ) {
795 return wfTimestamp( TS_ORACLE
, $ts );
799 * Return aggregated value function call
801 * @param array $valuedata
802 * @param string $valuename
805 public function aggregateValue( $valuedata, $valuename = 'value' ) {
810 * @return string Wikitext of a link to the server software's web site
812 public function getSoftwareLink() {
813 return '[{{int:version-db-oracle-url}} Oracle]';
817 * @return string Version information from the database
819 function getServerVersion() {
820 // better version number, fallback on driver
821 $rset = $this->doQuery(
822 'SELECT version FROM product_component_version ' .
823 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
825 $row = $rset->fetchRow();
827 return oci_server_version( $this->mConn
);
830 return $row['version'];
834 * Query whether a given index exists
835 * @param string $table
836 * @param string $index
837 * @param string $fname
840 function indexExists( $table, $index, $fname = __METHOD__
) {
841 $table = $this->tableName( $table );
842 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
843 $index = strtoupper( $index );
844 $owner = strtoupper( $this->mDBname
);
845 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
846 $res = $this->doQuery( $sql );
848 $count = $res->numRows();
858 * Query whether a given table exists (in the given schema, or the default mw one if not given)
859 * @param string $table
860 * @param string $fname
863 function tableExists( $table, $fname = __METHOD__
) {
864 $table = $this->tableName( $table );
865 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
866 $owner = $this->addQuotes( strtoupper( $this->mDBname
) );
867 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
868 $res = $this->doQuery( $sql );
869 if ( $res && $res->numRows() > 0 ) {
881 * Function translates mysql_fetch_field() functionality on ORACLE.
882 * Caching is present for reducing query time.
883 * For internal calls. Use fieldInfo for normal usage.
884 * Returns false if the field doesn't exist
886 * @param array|string $table
887 * @param string $field
888 * @return ORAField|ORAResult|false
890 private function fieldInfoMulti( $table, $field ) {
891 $field = strtoupper( $field );
892 if ( is_array( $table ) ) {
893 $table = array_map( [ $this, 'tableNameInternal' ], $table );
894 $tableWhere = 'IN (';
895 foreach ( $table as &$singleTable ) {
896 $singleTable = $this->removeIdentifierQuotes( $singleTable );
897 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
898 return $this->mFieldInfoCache
["$singleTable.$field"];
900 $tableWhere .= '\'' . $singleTable . '\',';
902 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
904 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
905 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
906 return $this->mFieldInfoCache
["$table.$field"];
908 $tableWhere = '= \'' . $table . '\'';
911 $fieldInfoStmt = oci_parse(
913 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
914 $tableWhere . ' and column_name = \'' . $field . '\''
916 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
917 $e = oci_error( $fieldInfoStmt );
918 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
922 $res = new ORAResult( $this, $fieldInfoStmt );
923 if ( $res->numRows() == 0 ) {
924 if ( is_array( $table ) ) {
925 foreach ( $table as &$singleTable ) {
926 $this->mFieldInfoCache
["$singleTable.$field"] = false;
929 $this->mFieldInfoCache
["$table.$field"] = false;
931 $fieldInfoTemp = null;
933 $fieldInfoTemp = new ORAField( $res->fetchRow() );
934 $table = $fieldInfoTemp->tableName();
935 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
939 return $fieldInfoTemp;
943 * @throws DBUnexpectedError
944 * @param string $table
945 * @param string $field
948 function fieldInfo( $table, $field ) {
949 if ( is_array( $table ) ) {
950 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
953 return $this->fieldInfoMulti( $table, $field );
956 protected function doBegin( $fname = __METHOD__
) {
957 $this->mTrxLevel
= 1;
958 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
961 protected function doCommit( $fname = __METHOD__
) {
962 if ( $this->mTrxLevel
) {
963 $ret = oci_commit( $this->mConn
);
965 throw new DBUnexpectedError( $this, $this->lastError() );
967 $this->mTrxLevel
= 0;
968 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
972 protected function doRollback( $fname = __METHOD__
) {
973 if ( $this->mTrxLevel
) {
974 oci_rollback( $this->mConn
);
975 $this->mTrxLevel
= 0;
976 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
980 function sourceStream(
982 callable
$lineCallback = null,
983 callable
$resultCallback = null,
984 $fname = __METHOD__
, callable
$inputCallback = null
988 $dollarquote = false;
991 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
992 while ( !feof( $fp ) ) {
993 if ( $lineCallback ) {
994 call_user_func( $lineCallback );
996 $line = trim( fgets( $fp, 1024 ) );
997 $sl = strlen( $line ) - 1;
1002 if ( '-' == $line[0] && '-' == $line[1] ) {
1006 // Allow dollar quoting for function declarations
1007 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1008 if ( $dollarquote ) {
1009 $dollarquote = false;
1010 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1013 $dollarquote = true;
1015 } elseif ( !$dollarquote ) {
1016 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
1018 $line = substr( $line, 0, $sl );
1028 $cmd = str_replace( ';;', ";", $cmd );
1029 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1030 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1031 $replacements[$defines[2]] = $defines[1];
1034 foreach ( $replacements as $mwVar => $scVar ) {
1035 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1038 $cmd = $this->replaceVars( $cmd );
1039 if ( $inputCallback ) {
1040 call_user_func( $inputCallback, $cmd );
1042 $res = $this->doQuery( $cmd );
1043 if ( $resultCallback ) {
1044 call_user_func( $resultCallback, $res, $this );
1047 if ( false === $res ) {
1048 $err = $this->lastError();
1050 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1062 function selectDB( $db ) {
1063 $this->mDBname
= $db;
1064 if ( $db == null ||
$db == $this->mUser
) {
1067 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1068 $stmt = oci_parse( $this->mConn
, $sql );
1069 MediaWiki\
suppressWarnings();
1070 $success = oci_execute( $stmt );
1071 MediaWiki\restoreWarnings
();
1073 $e = oci_error( $stmt );
1074 if ( $e['code'] != '1435' ) {
1075 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1084 function strencode( $s ) {
1085 return str_replace( "'", "''", $s );
1088 function addQuotes( $s ) {
1090 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1091 $s = $wgContLang->checkTitleEncoding( $s );
1094 return "'" . $this->strencode( $s ) . "'";
1097 public function addIdentifierQuotes( $s ) {
1098 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1105 public function removeIdentifierQuotes( $s ) {
1106 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1109 public function isQuotedIdentifier( $s ) {
1110 return strpos( $s, '/*Q*/' ) !== false;
1113 private function wrapFieldForWhere( $table, &$col, &$val ) {
1116 $col_info = $this->fieldInfoMulti( $table, $col );
1117 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1118 if ( $col_type == 'CLOB' ) {
1119 $col = 'TO_CHAR(' . $col . ')';
1120 $val = $wgContLang->checkTitleEncoding( $val );
1121 } elseif ( $col_type == 'VARCHAR2' ) {
1122 $val = $wgContLang->checkTitleEncoding( $val );
1126 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1128 foreach ( $conds as $col => $val ) {
1129 if ( is_array( $val ) ) {
1130 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1132 if ( is_numeric( $col ) && $parentCol != null ) {
1133 $this->wrapFieldForWhere( $table, $parentCol, $val );
1135 $this->wrapFieldForWhere( $table, $col, $val );
1137 $conds2[$col] = $val;
1144 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1145 $options = [], $join_conds = []
1147 if ( is_array( $conds ) ) {
1148 $conds = $this->wrapConditionsForWhere( $table, $conds );
1151 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1155 * Returns an optional USE INDEX clause to go after the table, and a
1156 * string to go at the end of the query
1158 * @param array $options An associative array of options to be turned into
1159 * an SQL query, valid keys are listed in the function.
1162 function makeSelectOptions( $options ) {
1163 $preLimitTail = $postLimitTail = '';
1167 foreach ( $options as $key => $option ) {
1168 if ( is_numeric( $key ) ) {
1169 $noKeyOptions[$option] = true;
1173 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1175 $preLimitTail .= $this->makeOrderBy( $options );
1177 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1178 $postLimitTail .= ' FOR UPDATE';
1181 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1182 $startOpts .= 'DISTINCT';
1185 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1186 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1191 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1192 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1197 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1200 public function delete( $table, $conds, $fname = __METHOD__
) {
1201 if ( is_array( $conds ) ) {
1202 $conds = $this->wrapConditionsForWhere( $table, $conds );
1204 // a hack for deleting pages, users and images (which have non-nullable FKs)
1205 // all deletions on these tables have transactions so final failure rollbacks these updates
1206 $table = $this->tableName( $table );
1207 if ( $table == $this->tableName( 'user' ) ) {
1208 $this->update( 'archive', [ 'ar_user' => 0 ],
1209 [ 'ar_user' => $conds['user_id'] ], $fname );
1210 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1211 [ 'ipb_user' => $conds['user_id'] ], $fname );
1212 $this->update( 'image', [ 'img_user' => 0 ],
1213 [ 'img_user' => $conds['user_id'] ], $fname );
1214 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1215 [ 'oi_user' => $conds['user_id'] ], $fname );
1216 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1217 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1218 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1219 [ 'fa_user' => $conds['user_id'] ], $fname );
1220 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1221 [ 'us_user' => $conds['user_id'] ], $fname );
1222 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1223 [ 'rc_user' => $conds['user_id'] ], $fname );
1224 $this->update( 'logging', [ 'log_user' => 0 ],
1225 [ 'log_user' => $conds['user_id'] ], $fname );
1226 } elseif ( $table == $this->tableName( 'image' ) ) {
1227 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1228 [ 'oi_name' => $conds['img_name'] ], $fname );
1231 return parent
::delete( $table, $conds, $fname );
1235 * @param string $table
1236 * @param array $values
1237 * @param array $conds
1238 * @param string $fname
1239 * @param array $options
1241 * @throws DBUnexpectedError
1243 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1246 $table = $this->tableName( $table );
1247 $opts = $this->makeUpdateOptions( $options );
1248 $sql = "UPDATE $opts $table SET ";
1251 foreach ( $values as $col => &$val ) {
1252 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1255 $sqlSet = ', ' . $sqlSet;
1262 if ( $conds !== [] && $conds !== '*' ) {
1263 $conds = $this->wrapConditionsForWhere( $table, $conds );
1264 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1267 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
1268 if ( $stmt === false ) {
1269 $e = oci_error( $this->mConn
);
1270 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1274 foreach ( $values as $col => &$val ) {
1275 $col_info = $this->fieldInfoMulti( $table, $col );
1276 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1278 if ( $val === null ) {
1279 // do nothing ... null was inserted in statement creation
1280 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1281 if ( is_object( $val ) ) {
1282 $val = $val->getData();
1285 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1286 $val = '31-12-2030 12:00:00.000000';
1289 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1290 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1291 $e = oci_error( $stmt );
1292 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1297 /** @var OCI_Lob[] $lob */
1298 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
1299 if ( $lob[$col] === false ) {
1300 $e = oci_error( $stmt );
1301 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1304 if ( is_object( $val ) ) {
1305 $val = $val->getData();
1308 if ( $col_type == 'BLOB' ) {
1309 $lob[$col]->writeTemporary( $val );
1310 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1312 $lob[$col]->writeTemporary( $val );
1313 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1318 MediaWiki\
suppressWarnings();
1320 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1321 $e = oci_error( $stmt );
1322 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1323 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1327 $this->mAffectedRows
= oci_num_rows( $stmt );
1330 $this->mAffectedRows
= oci_num_rows( $stmt );
1333 MediaWiki\restoreWarnings
();
1335 if ( isset( $lob ) ) {
1336 foreach ( $lob as $lob_v ) {
1341 if ( !$this->mTrxLevel
) {
1342 oci_commit( $this->mConn
);
1345 return oci_free_statement( $stmt );
1348 function bitNot( $field ) {
1349 // expecting bit-fields smaller than 4bytes
1350 return 'BITNOT(' . $field . ')';
1353 function bitAnd( $fieldLeft, $fieldRight ) {
1354 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1357 function bitOr( $fieldLeft, $fieldRight ) {
1358 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1361 function getDBname() {
1362 return $this->mDBname
;
1365 function getServer() {
1366 return $this->mServer
;
1369 public function buildGroupConcatField(
1370 $delim, $table, $field, $conds = '', $join_conds = []
1372 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1374 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1378 * @param string $field Field or column to cast
1382 public function buildStringCast( $field ) {
1383 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1386 public function getInfinity() {
1387 return '31-12-2030 12:00:00.000000';