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
;
31 class DatabaseOracle
extends Database
{
33 protected $mLastResult = null;
35 /** @var int The number of rows affected as an integer */
36 protected $mAffectedRows;
39 private $mInsertId = null;
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->mOpened
) {
66 MediaWiki\
suppressWarnings();
68 MediaWiki\restoreWarnings
();
76 function implicitGroupby() {
80 function implicitOrderby() {
85 * Usually aborts on failure
86 * @param string $server
88 * @param string $password
89 * @param string $dbName
90 * @throws DBConnectionError
91 * @return resource|null
93 function open( $server, $user, $password, $dbName ) {
94 global $wgDBOracleDRCP;
95 if ( !function_exists( 'oci_connect' ) ) {
96 throw new DBConnectionError(
98 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
99 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
104 $this->mUser
= $user;
105 $this->mPassword
= $password;
106 // changed internal variables functions
107 // mServer now holds the TNS endpoint
108 // mDBname is schema name if different from username
110 // backward compatibillity (server used to be null and TNS was supplied in dbname)
111 $this->mServer
= $dbName;
112 $this->mDBname
= $user;
114 $this->mServer
= $server;
116 $this->mDBname
= $user;
118 $this->mDBname
= $dbName;
122 if ( !strlen( $user ) ) { # e.g. the class is being loaded
126 if ( $wgDBOracleDRCP ) {
127 $this->setFlag( DBO_PERSISTENT
);
130 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
132 MediaWiki\
suppressWarnings();
133 if ( $this->mFlags
& DBO_PERSISTENT
) {
134 $this->mConn
= oci_pconnect(
138 $this->defaultCharset
,
141 } elseif ( $this->mFlags
& DBO_DEFAULT
) {
142 $this->mConn
= oci_new_connect(
146 $this->defaultCharset
,
150 $this->mConn
= oci_connect(
154 $this->defaultCharset
,
158 MediaWiki\restoreWarnings
();
160 if ( $this->mUser
!= $this->mDBname
) {
161 // change current schema in session
162 $this->selectDB( $this->mDBname
);
165 if ( !$this->mConn
) {
166 throw new DBConnectionError( $this, $this->lastError() );
169 $this->mOpened
= true;
171 # removed putenv calls because they interfere with the system globaly
172 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
173 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
174 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
180 * Closes a database connection, if it is open
181 * Returns success, true if already closed
184 protected function closeConnection() {
185 return oci_close( $this->mConn
);
188 function execFlags() {
189 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
192 protected function doQuery( $sql ) {
193 wfDebug( "SQL: [$sql]\n" );
194 if ( !StringUtils
::isUtf8( $sql ) ) {
195 throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
198 // handle some oracle specifics
199 // remove AS column/table/subquery namings
200 if ( !$this->getFlag( DBO_DDLMODE
) ) {
201 $sql = preg_replace( '/ as /i', ' ', $sql );
204 // Oracle has issues with UNION clause if the statement includes LOB fields
205 // So we do a UNION ALL and then filter the results array with array_unique
206 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
207 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
208 // you have to select data from plan table after explain
209 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
213 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
219 MediaWiki\
suppressWarnings();
221 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
222 if ( $stmt === false ) {
223 $e = oci_error( $this->mConn
);
224 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
229 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
230 $e = oci_error( $stmt );
231 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
232 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
238 MediaWiki\restoreWarnings
();
240 if ( $explain_count > 0 ) {
241 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
242 'WHERE statement_id = \'' . $explain_id . '\'' );
243 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
244 return new ORAResult( $this, $stmt, $union_unique );
246 $this->mAffectedRows
= oci_num_rows( $stmt );
252 function queryIgnore( $sql, $fname = '' ) {
253 return $this->query( $sql, $fname, true );
257 * Frees resources associated with the LOB descriptor
258 * @param ResultWrapper|ORAResult $res
260 function freeResult( $res ) {
261 if ( $res instanceof ResultWrapper
) {
269 * @param ResultWrapper|ORAResult $res
272 function fetchObject( $res ) {
273 if ( $res instanceof ResultWrapper
) {
277 return $res->fetchObject();
281 * @param ResultWrapper|ORAResult $res
284 function fetchRow( $res ) {
285 if ( $res instanceof ResultWrapper
) {
289 return $res->fetchRow();
293 * @param ResultWrapper|ORAResult $res
296 function numRows( $res ) {
297 if ( $res instanceof ResultWrapper
) {
301 return $res->numRows();
305 * @param ResultWrapper|ORAResult $res
308 function numFields( $res ) {
309 if ( $res instanceof ResultWrapper
) {
313 return $res->numFields();
316 function fieldName( $stmt, $n ) {
317 return oci_field_name( $stmt, $n );
321 * This must be called after nextSequenceVal
324 function insertId() {
325 return $this->mInsertId
;
332 function dataSeek( $res, $row ) {
333 if ( $res instanceof ORAResult
) {
336 $res->result
->seek( $row );
340 function lastError() {
341 if ( $this->mConn
=== false ) {
344 $e = oci_error( $this->mConn
);
347 return $e['message'];
350 function lastErrno() {
351 if ( $this->mConn
=== false ) {
354 $e = oci_error( $this->mConn
);
360 function affectedRows() {
361 return $this->mAffectedRows
;
365 * Returns information about an index
366 * If errors are explicitly ignored, returns NULL on failure
367 * @param string $table
368 * @param string $index
369 * @param string $fname
372 function indexInfo( $table, $index, $fname = __METHOD__
) {
376 function indexUnique( $table, $index, $fname = __METHOD__
) {
380 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
381 if ( !count( $a ) ) {
385 if ( !is_array( $options ) ) {
386 $options = [ $options ];
389 if ( in_array( 'IGNORE', $options ) ) {
390 $this->ignoreDupValOnIndex
= true;
393 if ( !is_array( reset( $a ) ) ) {
397 foreach ( $a as &$row ) {
398 $this->insertOneRow( $table, $row, $fname );
402 if ( in_array( 'IGNORE', $options ) ) {
403 $this->ignoreDupValOnIndex
= false;
409 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
410 $col_info = $this->fieldInfoMulti( $table, $col );
411 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
414 if ( is_numeric( $col ) ) {
419 } elseif ( $includeCol ) {
423 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
427 if ( $val === 'NULL' ) {
431 if ( $val === null ) {
432 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
445 * @param string $table
447 * @param string $fname
449 * @throws DBUnexpectedError
451 private function insertOneRow( $table, $row, $fname ) {
454 $table = $this->tableName( $table );
455 // "INSERT INTO tables (a, b, c)"
456 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
459 // for each value, append ":key"
461 foreach ( $row as $col => &$val ) {
467 if ( $this->isQuotedIdentifier( $val ) ) {
468 $sql .= $this->removeIdentifierQuotes( $val );
471 $sql .= $this->fieldBindStatement( $table, $col, $val );
476 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
477 if ( $stmt === false ) {
478 $e = oci_error( $this->mConn
);
479 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
483 foreach ( $row as $col => &$val ) {
484 $col_info = $this->fieldInfoMulti( $table, $col );
485 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
487 if ( $val === null ) {
488 // do nothing ... null was inserted in statement creation
489 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
490 if ( is_object( $val ) ) {
491 $val = $val->fetch();
494 // backward compatibility
495 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
496 $val = $this->getInfinity();
499 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
500 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
501 $e = oci_error( $stmt );
502 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
507 /** @var OCI_Lob[] $lob */
508 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
509 if ( $lob[$col] === false ) {
510 $e = oci_error( $stmt );
511 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
514 if ( is_object( $val ) ) {
515 $val = $val->fetch();
518 if ( $col_type == 'BLOB' ) {
519 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
520 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
522 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
523 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
528 MediaWiki\
suppressWarnings();
530 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
531 $e = oci_error( $stmt );
532 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
533 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
537 $this->mAffectedRows
= oci_num_rows( $stmt );
540 $this->mAffectedRows
= oci_num_rows( $stmt );
543 MediaWiki\restoreWarnings
();
545 if ( isset( $lob ) ) {
546 foreach ( $lob as $lob_v ) {
551 if ( !$this->mTrxLevel
) {
552 oci_commit( $this->mConn
);
555 return oci_free_statement( $stmt );
558 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
559 $insertOptions = [], $selectOptions = []
561 $destTable = $this->tableName( $destTable );
562 if ( !is_array( $selectOptions ) ) {
563 $selectOptions = [ $selectOptions ];
565 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) =
566 $this->makeSelectOptions( $selectOptions );
567 if ( is_array( $srcTable ) ) {
568 $srcTable = implode( ',', array_map( [ $this, 'tableName' ], $srcTable ) );
570 $srcTable = $this->tableName( $srcTable );
573 $sequenceData = $this->getSequenceData( $destTable );
574 if ( $sequenceData !== false &&
575 !isset( $varMap[$sequenceData['column']] )
577 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
580 // count-alias subselect fields to avoid abigious definition errors
582 foreach ( $varMap as &$val ) {
583 $val = $val . ' field' . ( $i++
);
586 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
587 " SELECT $startOpts " . implode( ',', $varMap ) .
588 " FROM $srcTable $useIndex $ignoreIndex ";
589 if ( $conds != '*' ) {
590 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
592 $sql .= " $tailOpts";
594 if ( in_array( 'IGNORE', $insertOptions ) ) {
595 $this->ignoreDupValOnIndex
= true;
598 $retval = $this->query( $sql, $fname );
600 if ( in_array( 'IGNORE', $insertOptions ) ) {
601 $this->ignoreDupValOnIndex
= false;
607 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
610 if ( !count( $rows ) ) {
611 return true; // nothing to do
614 if ( !is_array( reset( $rows ) ) ) {
618 $sequenceData = $this->getSequenceData( $table );
619 if ( $sequenceData !== false ) {
620 // add sequence column to each list of columns, when not set
621 foreach ( $rows as &$row ) {
622 if ( !isset( $row[$sequenceData['column']] ) ) {
623 $row[$sequenceData['column']] =
624 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
625 $sequenceData['sequence'] . '\')' );
630 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
633 function tableName( $name, $format = 'quoted' ) {
635 Replace reserved words with better ones
636 Using uppercase because that's the only way Oracle can handle
644 $name = 'PAGECONTENT';
648 return strtoupper( parent
::tableName( $name, $format ) );
651 function tableNameInternal( $name ) {
652 $name = $this->tableName( $name );
654 return preg_replace( '/.*\.(.*)/', '$1', $name );
658 * Return the next in a sequence, save the value for retrieval via insertId()
660 * @param string $seqName
663 function nextSequenceValue( $seqName ) {
664 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
665 $row = $this->fetchRow( $res );
666 $this->mInsertId
= $row[0];
668 return $this->mInsertId
;
672 * Return sequence_name if table has a sequence
674 * @param string $table
677 private function getSequenceData( $table ) {
678 if ( $this->sequenceData
== null ) {
679 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
680 lower(atc.table_name),
681 lower(atc.column_name)
682 FROM all_sequences asq, all_tab_columns atc
685 '{$this->mTablePrefix}MWUSER',
686 '{$this->mTablePrefix}USER',
689 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
690 AND asq.sequence_owner = upper('{$this->mDBname}')
691 AND atc.owner = upper('{$this->mDBname}')" );
693 while ( ( $row = $result->fetchRow() ) !== false ) {
694 $this->sequenceData
[$row[1]] = [
695 'sequence' => $row[0],
700 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
702 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
706 * Returns the size of a text field, or -1 for "unlimited"
708 * @param string $table
709 * @param string $field
712 function textFieldSize( $table, $field ) {
713 $fieldInfoData = $this->fieldInfo( $table, $field );
715 return $fieldInfoData->maxLength();
718 function limitResult( $sql, $limit, $offset = false ) {
719 if ( $offset === false ) {
723 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
726 function encodeBlob( $b ) {
727 return new Blob( $b );
730 function decodeBlob( $b ) {
731 if ( $b instanceof Blob
) {
738 function unionQueries( $sqls, $all ) {
739 $glue = ' UNION ALL ';
741 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
742 'FROM (' . implode( $glue, $sqls ) . ')';
745 function wasDeadlock() {
746 return $this->lastErrno() == 'OCI-00060';
749 function duplicateTableStructure( $oldName, $newName, $temporary = false,
752 $temporary = $temporary ?
'TRUE' : 'FALSE';
754 $newName = strtoupper( $newName );
755 $oldName = strtoupper( $oldName );
757 $tabName = substr( $newName, strlen( $this->mTablePrefix
) );
758 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
759 $newPrefix = strtoupper( $this->mTablePrefix
);
761 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
762 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
765 function listTables( $prefix = null, $fname = __METHOD__
) {
767 if ( !empty( $prefix ) ) {
768 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
771 $owner = strtoupper( $this->mDBname
);
772 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
773 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
775 // dirty code ... i know
777 $endArray[] = strtoupper( $prefix . 'MWUSER' );
778 $endArray[] = strtoupper( $prefix . 'PAGE' );
779 $endArray[] = strtoupper( $prefix . 'IMAGE' );
780 $fixedOrderTabs = $endArray;
781 while ( ( $row = $result->fetchRow() ) !== false ) {
782 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
783 $endArray[] = $row['table_name'];
790 public function dropTable( $tableName, $fName = __METHOD__
) {
791 $tableName = $this->tableName( $tableName );
792 if ( !$this->tableExists( $tableName ) ) {
796 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
799 function timestamp( $ts = 0 ) {
800 return wfTimestamp( TS_ORACLE
, $ts );
804 * Return aggregated value function call
806 * @param array $valuedata
807 * @param string $valuename
810 public function aggregateValue( $valuedata, $valuename = 'value' ) {
815 * @return string Wikitext of a link to the server software's web site
817 public function getSoftwareLink() {
818 return '[{{int:version-db-oracle-url}} Oracle]';
822 * @return string Version information from the database
824 function getServerVersion() {
825 // better version number, fallback on driver
826 $rset = $this->doQuery(
827 'SELECT version FROM product_component_version ' .
828 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
830 $row = $rset->fetchRow();
832 return oci_server_version( $this->mConn
);
835 return $row['version'];
839 * Query whether a given index exists
840 * @param string $table
841 * @param string $index
842 * @param string $fname
845 function indexExists( $table, $index, $fname = __METHOD__
) {
846 $table = $this->tableName( $table );
847 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
848 $index = strtoupper( $index );
849 $owner = strtoupper( $this->mDBname
);
850 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
851 $res = $this->doQuery( $sql );
853 $count = $res->numRows();
863 * Query whether a given table exists (in the given schema, or the default mw one if not given)
864 * @param string $table
865 * @param string $fname
868 function tableExists( $table, $fname = __METHOD__
) {
869 $table = $this->tableName( $table );
870 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
871 $owner = $this->addQuotes( strtoupper( $this->mDBname
) );
872 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
873 $res = $this->doQuery( $sql );
874 if ( $res && $res->numRows() > 0 ) {
886 * Function translates mysql_fetch_field() functionality on ORACLE.
887 * Caching is present for reducing query time.
888 * For internal calls. Use fieldInfo for normal usage.
889 * Returns false if the field doesn't exist
891 * @param array|string $table
892 * @param string $field
893 * @return ORAField|ORAResult|false
895 private function fieldInfoMulti( $table, $field ) {
896 $field = strtoupper( $field );
897 if ( is_array( $table ) ) {
898 $table = array_map( [ $this, 'tableNameInternal' ], $table );
899 $tableWhere = 'IN (';
900 foreach ( $table as &$singleTable ) {
901 $singleTable = $this->removeIdentifierQuotes( $singleTable );
902 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
903 return $this->mFieldInfoCache
["$singleTable.$field"];
905 $tableWhere .= '\'' . $singleTable . '\',';
907 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
909 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
910 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
911 return $this->mFieldInfoCache
["$table.$field"];
913 $tableWhere = '= \'' . $table . '\'';
916 $fieldInfoStmt = oci_parse(
918 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
919 $tableWhere . ' and column_name = \'' . $field . '\''
921 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
922 $e = oci_error( $fieldInfoStmt );
923 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
927 $res = new ORAResult( $this, $fieldInfoStmt );
928 if ( $res->numRows() == 0 ) {
929 if ( is_array( $table ) ) {
930 foreach ( $table as &$singleTable ) {
931 $this->mFieldInfoCache
["$singleTable.$field"] = false;
934 $this->mFieldInfoCache
["$table.$field"] = false;
936 $fieldInfoTemp = null;
938 $fieldInfoTemp = new ORAField( $res->fetchRow() );
939 $table = $fieldInfoTemp->tableName();
940 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
944 return $fieldInfoTemp;
948 * @throws DBUnexpectedError
949 * @param string $table
950 * @param string $field
953 function fieldInfo( $table, $field ) {
954 if ( is_array( $table ) ) {
955 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
958 return $this->fieldInfoMulti( $table, $field );
961 protected function doBegin( $fname = __METHOD__
) {
962 $this->mTrxLevel
= 1;
963 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
966 protected function doCommit( $fname = __METHOD__
) {
967 if ( $this->mTrxLevel
) {
968 $ret = oci_commit( $this->mConn
);
970 throw new DBUnexpectedError( $this, $this->lastError() );
972 $this->mTrxLevel
= 0;
973 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
977 protected function doRollback( $fname = __METHOD__
) {
978 if ( $this->mTrxLevel
) {
979 oci_rollback( $this->mConn
);
980 $this->mTrxLevel
= 0;
981 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
985 function sourceStream(
987 callable
$lineCallback = null,
988 callable
$resultCallback = null,
989 $fname = __METHOD__
, callable
$inputCallback = null
993 $dollarquote = false;
996 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
997 while ( !feof( $fp ) ) {
998 if ( $lineCallback ) {
999 call_user_func( $lineCallback );
1001 $line = trim( fgets( $fp, 1024 ) );
1002 $sl = strlen( $line ) - 1;
1007 if ( '-' == $line[0] && '-' == $line[1] ) {
1011 // Allow dollar quoting for function declarations
1012 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1013 if ( $dollarquote ) {
1014 $dollarquote = false;
1015 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1018 $dollarquote = true;
1020 } elseif ( !$dollarquote ) {
1021 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
1023 $line = substr( $line, 0, $sl );
1033 $cmd = str_replace( ';;', ";", $cmd );
1034 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1035 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1036 $replacements[$defines[2]] = $defines[1];
1039 foreach ( $replacements as $mwVar => $scVar ) {
1040 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1043 $cmd = $this->replaceVars( $cmd );
1044 if ( $inputCallback ) {
1045 call_user_func( $inputCallback, $cmd );
1047 $res = $this->doQuery( $cmd );
1048 if ( $resultCallback ) {
1049 call_user_func( $resultCallback, $res, $this );
1052 if ( false === $res ) {
1053 $err = $this->lastError();
1055 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1067 function selectDB( $db ) {
1068 $this->mDBname
= $db;
1069 if ( $db == null ||
$db == $this->mUser
) {
1072 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1073 $stmt = oci_parse( $this->mConn
, $sql );
1074 MediaWiki\
suppressWarnings();
1075 $success = oci_execute( $stmt );
1076 MediaWiki\restoreWarnings
();
1078 $e = oci_error( $stmt );
1079 if ( $e['code'] != '1435' ) {
1080 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1089 function strencode( $s ) {
1090 return str_replace( "'", "''", $s );
1093 function addQuotes( $s ) {
1095 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1096 $s = $wgContLang->checkTitleEncoding( $s );
1099 return "'" . $this->strencode( $s ) . "'";
1102 public function addIdentifierQuotes( $s ) {
1103 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1110 public function removeIdentifierQuotes( $s ) {
1111 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1114 public function isQuotedIdentifier( $s ) {
1115 return strpos( $s, '/*Q*/' ) !== false;
1118 private function wrapFieldForWhere( $table, &$col, &$val ) {
1121 $col_info = $this->fieldInfoMulti( $table, $col );
1122 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1123 if ( $col_type == 'CLOB' ) {
1124 $col = 'TO_CHAR(' . $col . ')';
1125 $val = $wgContLang->checkTitleEncoding( $val );
1126 } elseif ( $col_type == 'VARCHAR2' ) {
1127 $val = $wgContLang->checkTitleEncoding( $val );
1131 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1133 foreach ( $conds as $col => $val ) {
1134 if ( is_array( $val ) ) {
1135 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1137 if ( is_numeric( $col ) && $parentCol != null ) {
1138 $this->wrapFieldForWhere( $table, $parentCol, $val );
1140 $this->wrapFieldForWhere( $table, $col, $val );
1142 $conds2[$col] = $val;
1149 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1150 $options = [], $join_conds = []
1152 if ( is_array( $conds ) ) {
1153 $conds = $this->wrapConditionsForWhere( $table, $conds );
1156 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1160 * Returns an optional USE INDEX clause to go after the table, and a
1161 * string to go at the end of the query
1163 * @param array $options An associative array of options to be turned into
1164 * an SQL query, valid keys are listed in the function.
1167 function makeSelectOptions( $options ) {
1168 $preLimitTail = $postLimitTail = '';
1172 foreach ( $options as $key => $option ) {
1173 if ( is_numeric( $key ) ) {
1174 $noKeyOptions[$option] = true;
1178 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1180 $preLimitTail .= $this->makeOrderBy( $options );
1182 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1183 $postLimitTail .= ' FOR UPDATE';
1186 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1187 $startOpts .= 'DISTINCT';
1190 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1191 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1196 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1197 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1202 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1205 public function delete( $table, $conds, $fname = __METHOD__
) {
1206 if ( is_array( $conds ) ) {
1207 $conds = $this->wrapConditionsForWhere( $table, $conds );
1209 // a hack for deleting pages, users and images (which have non-nullable FKs)
1210 // all deletions on these tables have transactions so final failure rollbacks these updates
1211 $table = $this->tableName( $table );
1212 if ( $table == $this->tableName( 'user' ) ) {
1213 $this->update( 'archive', [ 'ar_user' => 0 ],
1214 [ 'ar_user' => $conds['user_id'] ], $fname );
1215 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1216 [ 'ipb_user' => $conds['user_id'] ], $fname );
1217 $this->update( 'image', [ 'img_user' => 0 ],
1218 [ 'img_user' => $conds['user_id'] ], $fname );
1219 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1220 [ 'oi_user' => $conds['user_id'] ], $fname );
1221 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1222 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1223 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1224 [ 'fa_user' => $conds['user_id'] ], $fname );
1225 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1226 [ 'us_user' => $conds['user_id'] ], $fname );
1227 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1228 [ 'rc_user' => $conds['user_id'] ], $fname );
1229 $this->update( 'logging', [ 'log_user' => 0 ],
1230 [ 'log_user' => $conds['user_id'] ], $fname );
1231 } elseif ( $table == $this->tableName( 'image' ) ) {
1232 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1233 [ 'oi_name' => $conds['img_name'] ], $fname );
1236 return parent
::delete( $table, $conds, $fname );
1240 * @param string $table
1241 * @param array $values
1242 * @param array $conds
1243 * @param string $fname
1244 * @param array $options
1246 * @throws DBUnexpectedError
1248 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1251 $table = $this->tableName( $table );
1252 $opts = $this->makeUpdateOptions( $options );
1253 $sql = "UPDATE $opts $table SET ";
1256 foreach ( $values as $col => &$val ) {
1257 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1260 $sqlSet = ', ' . $sqlSet;
1267 if ( $conds !== [] && $conds !== '*' ) {
1268 $conds = $this->wrapConditionsForWhere( $table, $conds );
1269 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1272 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
1273 if ( $stmt === false ) {
1274 $e = oci_error( $this->mConn
);
1275 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1279 foreach ( $values as $col => &$val ) {
1280 $col_info = $this->fieldInfoMulti( $table, $col );
1281 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1283 if ( $val === null ) {
1284 // do nothing ... null was inserted in statement creation
1285 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1286 if ( is_object( $val ) ) {
1287 $val = $val->getData();
1290 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1291 $val = '31-12-2030 12:00:00.000000';
1294 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1295 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1296 $e = oci_error( $stmt );
1297 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1302 /** @var OCI_Lob[] $lob */
1303 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
1304 if ( $lob[$col] === false ) {
1305 $e = oci_error( $stmt );
1306 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1309 if ( is_object( $val ) ) {
1310 $val = $val->getData();
1313 if ( $col_type == 'BLOB' ) {
1314 $lob[$col]->writeTemporary( $val );
1315 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1317 $lob[$col]->writeTemporary( $val );
1318 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1323 MediaWiki\
suppressWarnings();
1325 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1326 $e = oci_error( $stmt );
1327 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1328 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1332 $this->mAffectedRows
= oci_num_rows( $stmt );
1335 $this->mAffectedRows
= oci_num_rows( $stmt );
1338 MediaWiki\restoreWarnings
();
1340 if ( isset( $lob ) ) {
1341 foreach ( $lob as $lob_v ) {
1346 if ( !$this->mTrxLevel
) {
1347 oci_commit( $this->mConn
);
1350 return oci_free_statement( $stmt );
1353 function bitNot( $field ) {
1354 // expecting bit-fields smaller than 4bytes
1355 return 'BITNOT(' . $field . ')';
1358 function bitAnd( $fieldLeft, $fieldRight ) {
1359 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1362 function bitOr( $fieldLeft, $fieldRight ) {
1363 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1366 function getDBname() {
1367 return $this->mDBname
;
1370 function getServer() {
1371 return $this->mServer
;
1374 public function buildGroupConcatField(
1375 $delim, $table, $field, $conds = '', $join_conds = []
1377 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1379 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1383 * @param string $field Field or column to cast
1387 public function buildStringCast( $field ) {
1388 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1391 public function getInfinity() {
1392 return '31-12-2030 12:00:00.000000';