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
25 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
26 * other things. We use a wrapper class to handle that and other
27 * Oracle-specific bits, like converting column names back to lowercase.
35 private $columns = [];
37 private function array_unique_md( $array_in ) {
41 foreach ( $array_in as $item ) {
42 $hash = md5( serialize( $item ) );
43 if ( !isset( $array_hashes[$hash] ) ) {
44 $array_hashes[$hash] = $hash;
53 * @param IDatabase $db
54 * @param resource $stmt A valid OCI statement identifier
57 function __construct( &$db, $stmt, $unique = false ) {
60 $this->nrows
= oci_fetch_all( $stmt, $this->rows
, 0, -1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM
);
61 if ( $this->nrows
=== false ) {
62 $e = oci_error( $stmt );
63 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__
);
70 $this->rows
= $this->array_unique_md( $this->rows
);
71 $this->nrows
= count( $this->rows
);
74 if ( $this->nrows
> 0 ) {
75 foreach ( $this->rows
[0] as $k => $v ) {
76 $this->columns
[$k] = strtolower( oci_field_name( $stmt, $k +
1 ) );
81 oci_free_statement( $stmt );
84 public function free() {
88 public function seek( $row ) {
89 $this->cursor
= min( $row, $this->nrows
);
92 public function numRows() {
96 public function numFields() {
97 return count( $this->columns
);
100 public function fetchObject() {
101 if ( $this->cursor
>= $this->nrows
) {
104 $row = $this->rows
[$this->cursor++
];
105 $ret = new stdClass();
106 foreach ( $row as $k => $v ) {
107 $lc = $this->columns
[$k];
114 public function fetchRow() {
115 if ( $this->cursor
>= $this->nrows
) {
119 $row = $this->rows
[$this->cursor++
];
121 foreach ( $row as $k => $v ) {
122 $lc = $this->columns
[$k];
134 class DatabaseOracle
extends DatabaseBase
{
136 protected $mLastResult = null;
138 /** @var int The number of rows affected as an integer */
139 protected $mAffectedRows;
142 private $mInsertId = null;
145 private $ignoreDupValOnIndex = false;
147 /** @var bool|array */
148 private $sequenceData = null;
150 /** @var string Character set for Oracle database */
151 private $defaultCharset = 'AL32UTF8';
154 private $mFieldInfoCache = [];
156 function __construct( array $p ) {
159 if ( $p['tablePrefix'] == 'get from global' ) {
160 $p['tablePrefix'] = $wgDBprefix;
162 $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
163 parent
::__construct( $p );
164 Hooks
::run( 'DatabaseOraclePostInit', [ $this ] );
167 function __destruct() {
168 if ( $this->mOpened
) {
169 MediaWiki\
suppressWarnings();
171 MediaWiki\restoreWarnings
();
179 function cascadingDeletes() {
183 function cleanupTriggers() {
187 function strictIPs() {
191 function realTimestamps() {
195 function implicitGroupby() {
199 function implicitOrderby() {
203 function searchableIPs() {
208 * Usually aborts on failure
209 * @param string $server
210 * @param string $user
211 * @param string $password
212 * @param string $dbName
213 * @throws DBConnectionError
214 * @return resource|null
216 function open( $server, $user, $password, $dbName ) {
217 global $wgDBOracleDRCP;
218 if ( !function_exists( 'oci_connect' ) ) {
219 throw new DBConnectionError(
221 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
222 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
227 $this->mUser
= $user;
228 $this->mPassword
= $password;
229 // changed internal variables functions
230 // mServer now holds the TNS endpoint
231 // mDBname is schema name if different from username
233 // backward compatibillity (server used to be null and TNS was supplied in dbname)
234 $this->mServer
= $dbName;
235 $this->mDBname
= $user;
237 $this->mServer
= $server;
239 $this->mDBname
= $user;
241 $this->mDBname
= $dbName;
245 if ( !strlen( $user ) ) { # e.g. the class is being loaded
249 if ( $wgDBOracleDRCP ) {
250 $this->setFlag( DBO_PERSISTENT
);
253 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
255 MediaWiki\
suppressWarnings();
256 if ( $this->mFlags
& DBO_PERSISTENT
) {
257 $this->mConn
= oci_pconnect(
261 $this->defaultCharset
,
264 } elseif ( $this->mFlags
& DBO_DEFAULT
) {
265 $this->mConn
= oci_new_connect(
269 $this->defaultCharset
,
273 $this->mConn
= oci_connect(
277 $this->defaultCharset
,
281 MediaWiki\restoreWarnings
();
283 if ( $this->mUser
!= $this->mDBname
) {
284 // change current schema in session
285 $this->selectDB( $this->mDBname
);
288 if ( !$this->mConn
) {
289 throw new DBConnectionError( $this, $this->lastError() );
292 $this->mOpened
= true;
294 # removed putenv calls because they interfere with the system globaly
295 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
296 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
297 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
303 * Closes a database connection, if it is open
304 * Returns success, true if already closed
307 protected function closeConnection() {
308 return oci_close( $this->mConn
);
311 function execFlags() {
312 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
315 protected function doQuery( $sql ) {
316 wfDebug( "SQL: [$sql]\n" );
317 if ( !StringUtils
::isUtf8( $sql ) ) {
318 throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
321 // handle some oracle specifics
322 // remove AS column/table/subquery namings
323 if ( !$this->getFlag( DBO_DDLMODE
) ) {
324 $sql = preg_replace( '/ as /i', ' ', $sql );
327 // Oracle has issues with UNION clause if the statement includes LOB fields
328 // So we do a UNION ALL and then filter the results array with array_unique
329 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
330 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
331 // you have to select data from plan table after explain
332 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
336 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
342 MediaWiki\
suppressWarnings();
344 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
345 if ( $stmt === false ) {
346 $e = oci_error( $this->mConn
);
347 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
352 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
353 $e = oci_error( $stmt );
354 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
355 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
361 MediaWiki\restoreWarnings
();
363 if ( $explain_count > 0 ) {
364 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
365 'WHERE statement_id = \'' . $explain_id . '\'' );
366 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
367 return new ORAResult( $this, $stmt, $union_unique );
369 $this->mAffectedRows
= oci_num_rows( $stmt );
375 function queryIgnore( $sql, $fname = '' ) {
376 return $this->query( $sql, $fname, true );
380 * Frees resources associated with the LOB descriptor
381 * @param ResultWrapper|ORAResult $res
383 function freeResult( $res ) {
384 if ( $res instanceof ResultWrapper
) {
392 * @param ResultWrapper|ORAResult $res
395 function fetchObject( $res ) {
396 if ( $res instanceof ResultWrapper
) {
400 return $res->fetchObject();
404 * @param ResultWrapper|ORAResult $res
407 function fetchRow( $res ) {
408 if ( $res instanceof ResultWrapper
) {
412 return $res->fetchRow();
416 * @param ResultWrapper|ORAResult $res
419 function numRows( $res ) {
420 if ( $res instanceof ResultWrapper
) {
424 return $res->numRows();
428 * @param ResultWrapper|ORAResult $res
431 function numFields( $res ) {
432 if ( $res instanceof ResultWrapper
) {
436 return $res->numFields();
439 function fieldName( $stmt, $n ) {
440 return oci_field_name( $stmt, $n );
444 * This must be called after nextSequenceVal
447 function insertId() {
448 return $this->mInsertId
;
455 function dataSeek( $res, $row ) {
456 if ( $res instanceof ORAResult
) {
459 $res->result
->seek( $row );
463 function lastError() {
464 if ( $this->mConn
=== false ) {
467 $e = oci_error( $this->mConn
);
470 return $e['message'];
473 function lastErrno() {
474 if ( $this->mConn
=== false ) {
477 $e = oci_error( $this->mConn
);
483 function affectedRows() {
484 return $this->mAffectedRows
;
488 * Returns information about an index
489 * If errors are explicitly ignored, returns NULL on failure
490 * @param string $table
491 * @param string $index
492 * @param string $fname
495 function indexInfo( $table, $index, $fname = __METHOD__
) {
499 function indexUnique( $table, $index, $fname = __METHOD__
) {
503 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
504 if ( !count( $a ) ) {
508 if ( !is_array( $options ) ) {
509 $options = [ $options ];
512 if ( in_array( 'IGNORE', $options ) ) {
513 $this->ignoreDupValOnIndex
= true;
516 if ( !is_array( reset( $a ) ) ) {
520 foreach ( $a as &$row ) {
521 $this->insertOneRow( $table, $row, $fname );
525 if ( in_array( 'IGNORE', $options ) ) {
526 $this->ignoreDupValOnIndex
= false;
532 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
533 $col_info = $this->fieldInfoMulti( $table, $col );
534 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
537 if ( is_numeric( $col ) ) {
542 } elseif ( $includeCol ) {
546 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
550 if ( $val === 'NULL' ) {
554 if ( $val === null ) {
555 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
568 * @param string $table
570 * @param string $fname
572 * @throws DBUnexpectedError
574 private function insertOneRow( $table, $row, $fname ) {
577 $table = $this->tableName( $table );
578 // "INSERT INTO tables (a, b, c)"
579 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
582 // for each value, append ":key"
584 foreach ( $row as $col => &$val ) {
590 if ( $this->isQuotedIdentifier( $val ) ) {
591 $sql .= $this->removeIdentifierQuotes( $val );
594 $sql .= $this->fieldBindStatement( $table, $col, $val );
599 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
600 if ( $stmt === false ) {
601 $e = oci_error( $this->mConn
);
602 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
606 foreach ( $row as $col => &$val ) {
607 $col_info = $this->fieldInfoMulti( $table, $col );
608 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
610 if ( $val === null ) {
611 // do nothing ... null was inserted in statement creation
612 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
613 if ( is_object( $val ) ) {
614 $val = $val->fetch();
617 // backward compatibility
618 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
619 $val = $this->getInfinity();
622 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
623 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
624 $e = oci_error( $stmt );
625 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
630 /** @var OCI_Lob[] $lob */
631 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
632 if ( $lob[$col] === false ) {
633 $e = oci_error( $stmt );
634 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
637 if ( is_object( $val ) ) {
638 $val = $val->fetch();
641 if ( $col_type == 'BLOB' ) {
642 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
643 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
645 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
646 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
651 MediaWiki\
suppressWarnings();
653 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
654 $e = oci_error( $stmt );
655 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
656 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
660 $this->mAffectedRows
= oci_num_rows( $stmt );
663 $this->mAffectedRows
= oci_num_rows( $stmt );
666 MediaWiki\restoreWarnings
();
668 if ( isset( $lob ) ) {
669 foreach ( $lob as $lob_v ) {
674 if ( !$this->mTrxLevel
) {
675 oci_commit( $this->mConn
);
678 return oci_free_statement( $stmt );
681 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
682 $insertOptions = [], $selectOptions = []
684 $destTable = $this->tableName( $destTable );
685 if ( !is_array( $selectOptions ) ) {
686 $selectOptions = [ $selectOptions ];
688 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) =
689 $this->makeSelectOptions( $selectOptions );
690 if ( is_array( $srcTable ) ) {
691 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
693 $srcTable = $this->tableName( $srcTable );
696 $sequenceData = $this->getSequenceData( $destTable );
697 if ( $sequenceData !== false &&
698 !isset( $varMap[$sequenceData['column']] )
700 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
703 // count-alias subselect fields to avoid abigious definition errors
705 foreach ( $varMap as &$val ) {
706 $val = $val . ' field' . ( $i++
);
709 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
710 " SELECT $startOpts " . implode( ',', $varMap ) .
711 " FROM $srcTable $useIndex $ignoreIndex ";
712 if ( $conds != '*' ) {
713 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
715 $sql .= " $tailOpts";
717 if ( in_array( 'IGNORE', $insertOptions ) ) {
718 $this->ignoreDupValOnIndex
= true;
721 $retval = $this->query( $sql, $fname );
723 if ( in_array( 'IGNORE', $insertOptions ) ) {
724 $this->ignoreDupValOnIndex
= false;
730 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
733 if ( !count( $rows ) ) {
734 return true; // nothing to do
737 if ( !is_array( reset( $rows ) ) ) {
741 $sequenceData = $this->getSequenceData( $table );
742 if ( $sequenceData !== false ) {
743 // add sequence column to each list of columns, when not set
744 foreach ( $rows as &$row ) {
745 if ( !isset( $row[$sequenceData['column']] ) ) {
746 $row[$sequenceData['column']] =
747 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
748 $sequenceData['sequence'] . '\')' );
753 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
756 function tableName( $name, $format = 'quoted' ) {
758 Replace reserved words with better ones
759 Using uppercase because that's the only way Oracle can handle
767 $name = 'PAGECONTENT';
771 return strtoupper( parent
::tableName( $name, $format ) );
774 function tableNameInternal( $name ) {
775 $name = $this->tableName( $name );
777 return preg_replace( '/.*\.(.*)/', '$1', $name );
781 * Return the next in a sequence, save the value for retrieval via insertId()
783 * @param string $seqName
786 function nextSequenceValue( $seqName ) {
787 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
788 $row = $this->fetchRow( $res );
789 $this->mInsertId
= $row[0];
791 return $this->mInsertId
;
795 * Return sequence_name if table has a sequence
797 * @param string $table
800 private function getSequenceData( $table ) {
801 if ( $this->sequenceData
== null ) {
802 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
803 lower(atc.table_name),
804 lower(atc.column_name)
805 FROM all_sequences asq, all_tab_columns atc
808 '{$this->mTablePrefix}MWUSER',
809 '{$this->mTablePrefix}USER',
812 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
813 AND asq.sequence_owner = upper('{$this->mDBname}')
814 AND atc.owner = upper('{$this->mDBname}')" );
816 while ( ( $row = $result->fetchRow() ) !== false ) {
817 $this->sequenceData
[$row[1]] = [
818 'sequence' => $row[0],
823 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
825 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
829 * Returns the size of a text field, or -1 for "unlimited"
831 * @param string $table
832 * @param string $field
835 function textFieldSize( $table, $field ) {
836 $fieldInfoData = $this->fieldInfo( $table, $field );
838 return $fieldInfoData->maxLength();
841 function limitResult( $sql, $limit, $offset = false ) {
842 if ( $offset === false ) {
846 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
849 function encodeBlob( $b ) {
850 return new Blob( $b );
853 function decodeBlob( $b ) {
854 if ( $b instanceof Blob
) {
861 function unionQueries( $sqls, $all ) {
862 $glue = ' UNION ALL ';
864 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
865 'FROM (' . implode( $glue, $sqls ) . ')';
868 function wasDeadlock() {
869 return $this->lastErrno() == 'OCI-00060';
872 function duplicateTableStructure( $oldName, $newName, $temporary = false,
875 $temporary = $temporary ?
'TRUE' : 'FALSE';
877 $newName = strtoupper( $newName );
878 $oldName = strtoupper( $oldName );
880 $tabName = substr( $newName, strlen( $this->mTablePrefix
) );
881 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
882 $newPrefix = strtoupper( $this->mTablePrefix
);
884 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
885 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
888 function listTables( $prefix = null, $fname = __METHOD__
) {
890 if ( !empty( $prefix ) ) {
891 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
894 $owner = strtoupper( $this->mDBname
);
895 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
896 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
898 // dirty code ... i know
900 $endArray[] = strtoupper( $prefix . 'MWUSER' );
901 $endArray[] = strtoupper( $prefix . 'PAGE' );
902 $endArray[] = strtoupper( $prefix . 'IMAGE' );
903 $fixedOrderTabs = $endArray;
904 while ( ( $row = $result->fetchRow() ) !== false ) {
905 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
906 $endArray[] = $row['table_name'];
913 public function dropTable( $tableName, $fName = __METHOD__
) {
914 $tableName = $this->tableName( $tableName );
915 if ( !$this->tableExists( $tableName ) ) {
919 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
922 function timestamp( $ts = 0 ) {
923 return wfTimestamp( TS_ORACLE
, $ts );
927 * Return aggregated value function call
929 * @param array $valuedata
930 * @param string $valuename
933 public function aggregateValue( $valuedata, $valuename = 'value' ) {
938 * @return string Wikitext of a link to the server software's web site
940 public function getSoftwareLink() {
941 return '[{{int:version-db-oracle-url}} Oracle]';
945 * @return string Version information from the database
947 function getServerVersion() {
948 // better version number, fallback on driver
949 $rset = $this->doQuery(
950 'SELECT version FROM product_component_version ' .
951 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
953 $row = $rset->fetchRow();
955 return oci_server_version( $this->mConn
);
958 return $row['version'];
962 * Query whether a given index exists
963 * @param string $table
964 * @param string $index
965 * @param string $fname
968 function indexExists( $table, $index, $fname = __METHOD__
) {
969 $table = $this->tableName( $table );
970 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
971 $index = strtoupper( $index );
972 $owner = strtoupper( $this->mDBname
);
973 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
974 $res = $this->doQuery( $sql );
976 $count = $res->numRows();
986 * Query whether a given table exists (in the given schema, or the default mw one if not given)
987 * @param string $table
988 * @param string $fname
991 function tableExists( $table, $fname = __METHOD__
) {
992 $table = $this->tableName( $table );
993 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
994 $owner = $this->addQuotes( strtoupper( $this->mDBname
) );
995 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
996 $res = $this->doQuery( $sql );
997 if ( $res && $res->numRows() > 0 ) {
1009 * Function translates mysql_fetch_field() functionality on ORACLE.
1010 * Caching is present for reducing query time.
1011 * For internal calls. Use fieldInfo for normal usage.
1012 * Returns false if the field doesn't exist
1014 * @param array|string $table
1015 * @param string $field
1016 * @return ORAField|ORAResult
1018 private function fieldInfoMulti( $table, $field ) {
1019 $field = strtoupper( $field );
1020 if ( is_array( $table ) ) {
1021 $table = array_map( [ &$this, 'tableNameInternal' ], $table );
1022 $tableWhere = 'IN (';
1023 foreach ( $table as &$singleTable ) {
1024 $singleTable = $this->removeIdentifierQuotes( $singleTable );
1025 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
1026 return $this->mFieldInfoCache
["$singleTable.$field"];
1028 $tableWhere .= '\'' . $singleTable . '\',';
1030 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
1032 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
1033 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
1034 return $this->mFieldInfoCache
["$table.$field"];
1036 $tableWhere = '= \'' . $table . '\'';
1039 $fieldInfoStmt = oci_parse(
1041 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
1042 $tableWhere . ' and column_name = \'' . $field . '\''
1044 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
1045 $e = oci_error( $fieldInfoStmt );
1046 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
1050 $res = new ORAResult( $this, $fieldInfoStmt );
1051 if ( $res->numRows() == 0 ) {
1052 if ( is_array( $table ) ) {
1053 foreach ( $table as &$singleTable ) {
1054 $this->mFieldInfoCache
["$singleTable.$field"] = false;
1057 $this->mFieldInfoCache
["$table.$field"] = false;
1059 $fieldInfoTemp = null;
1061 $fieldInfoTemp = new ORAField( $res->fetchRow() );
1062 $table = $fieldInfoTemp->tableName();
1063 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
1067 return $fieldInfoTemp;
1071 * @throws DBUnexpectedError
1072 * @param string $table
1073 * @param string $field
1076 function fieldInfo( $table, $field ) {
1077 if ( is_array( $table ) ) {
1078 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
1081 return $this->fieldInfoMulti( $table, $field );
1084 protected function doBegin( $fname = __METHOD__
) {
1085 $this->mTrxLevel
= 1;
1086 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
1089 protected function doCommit( $fname = __METHOD__
) {
1090 if ( $this->mTrxLevel
) {
1091 $ret = oci_commit( $this->mConn
);
1093 throw new DBUnexpectedError( $this, $this->lastError() );
1095 $this->mTrxLevel
= 0;
1096 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1100 protected function doRollback( $fname = __METHOD__
) {
1101 if ( $this->mTrxLevel
) {
1102 oci_rollback( $this->mConn
);
1103 $this->mTrxLevel
= 0;
1104 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1109 * defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
1111 * @param resource $fp
1112 * @param bool|string $lineCallback
1113 * @param bool|callable $resultCallback
1114 * @param string $fname
1115 * @param bool|callable $inputCallback
1116 * @return bool|string
1118 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
1119 $fname = __METHOD__
, $inputCallback = false ) {
1122 $dollarquote = false;
1126 while ( !feof( $fp ) ) {
1127 if ( $lineCallback ) {
1128 call_user_func( $lineCallback );
1130 $line = trim( fgets( $fp, 1024 ) );
1131 $sl = strlen( $line ) - 1;
1136 if ( '-' == $line[0] && '-' == $line[1] ) {
1140 // Allow dollar quoting for function declarations
1141 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1142 if ( $dollarquote ) {
1143 $dollarquote = false;
1144 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1147 $dollarquote = true;
1149 } elseif ( !$dollarquote ) {
1150 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
1152 $line = substr( $line, 0, $sl );
1162 $cmd = str_replace( ';;', ";", $cmd );
1163 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1164 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1165 $replacements[$defines[2]] = $defines[1];
1168 foreach ( $replacements as $mwVar => $scVar ) {
1169 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1172 $cmd = $this->replaceVars( $cmd );
1173 if ( $inputCallback ) {
1174 call_user_func( $inputCallback, $cmd );
1176 $res = $this->doQuery( $cmd );
1177 if ( $resultCallback ) {
1178 call_user_func( $resultCallback, $res, $this );
1181 if ( false === $res ) {
1182 $err = $this->lastError();
1184 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1196 function selectDB( $db ) {
1197 $this->mDBname
= $db;
1198 if ( $db == null ||
$db == $this->mUser
) {
1201 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1202 $stmt = oci_parse( $this->mConn
, $sql );
1203 MediaWiki\
suppressWarnings();
1204 $success = oci_execute( $stmt );
1205 MediaWiki\restoreWarnings
();
1207 $e = oci_error( $stmt );
1208 if ( $e['code'] != '1435' ) {
1209 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1218 function strencode( $s ) {
1219 return str_replace( "'", "''", $s );
1222 function addQuotes( $s ) {
1224 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1225 $s = $wgContLang->checkTitleEncoding( $s );
1228 return "'" . $this->strencode( $s ) . "'";
1231 public function addIdentifierQuotes( $s ) {
1232 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1239 public function removeIdentifierQuotes( $s ) {
1240 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1243 public function isQuotedIdentifier( $s ) {
1244 return strpos( $s, '/*Q*/' ) !== false;
1247 private function wrapFieldForWhere( $table, &$col, &$val ) {
1250 $col_info = $this->fieldInfoMulti( $table, $col );
1251 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1252 if ( $col_type == 'CLOB' ) {
1253 $col = 'TO_CHAR(' . $col . ')';
1254 $val = $wgContLang->checkTitleEncoding( $val );
1255 } elseif ( $col_type == 'VARCHAR2' ) {
1256 $val = $wgContLang->checkTitleEncoding( $val );
1260 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1262 foreach ( $conds as $col => $val ) {
1263 if ( is_array( $val ) ) {
1264 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1266 if ( is_numeric( $col ) && $parentCol != null ) {
1267 $this->wrapFieldForWhere( $table, $parentCol, $val );
1269 $this->wrapFieldForWhere( $table, $col, $val );
1271 $conds2[$col] = $val;
1278 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1279 $options = [], $join_conds = []
1281 if ( is_array( $conds ) ) {
1282 $conds = $this->wrapConditionsForWhere( $table, $conds );
1285 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1289 * Returns an optional USE INDEX clause to go after the table, and a
1290 * string to go at the end of the query
1292 * @param array $options An associative array of options to be turned into
1293 * an SQL query, valid keys are listed in the function.
1296 function makeSelectOptions( $options ) {
1297 $preLimitTail = $postLimitTail = '';
1301 foreach ( $options as $key => $option ) {
1302 if ( is_numeric( $key ) ) {
1303 $noKeyOptions[$option] = true;
1307 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1309 $preLimitTail .= $this->makeOrderBy( $options );
1311 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1312 $postLimitTail .= ' FOR UPDATE';
1315 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1316 $startOpts .= 'DISTINCT';
1319 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1320 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1325 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1326 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1331 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1334 public function delete( $table, $conds, $fname = __METHOD__
) {
1335 if ( is_array( $conds ) ) {
1336 $conds = $this->wrapConditionsForWhere( $table, $conds );
1338 // a hack for deleting pages, users and images (which have non-nullable FKs)
1339 // all deletions on these tables have transactions so final failure rollbacks these updates
1340 $table = $this->tableName( $table );
1341 if ( $table == $this->tableName( 'user' ) ) {
1342 $this->update( 'archive', [ 'ar_user' => 0 ],
1343 [ 'ar_user' => $conds['user_id'] ], $fname );
1344 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1345 [ 'ipb_user' => $conds['user_id'] ], $fname );
1346 $this->update( 'image', [ 'img_user' => 0 ],
1347 [ 'img_user' => $conds['user_id'] ], $fname );
1348 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1349 [ 'oi_user' => $conds['user_id'] ], $fname );
1350 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1351 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1352 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1353 [ 'fa_user' => $conds['user_id'] ], $fname );
1354 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1355 [ 'us_user' => $conds['user_id'] ], $fname );
1356 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1357 [ 'rc_user' => $conds['user_id'] ], $fname );
1358 $this->update( 'logging', [ 'log_user' => 0 ],
1359 [ 'log_user' => $conds['user_id'] ], $fname );
1360 } elseif ( $table == $this->tableName( 'image' ) ) {
1361 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1362 [ 'oi_name' => $conds['img_name'] ], $fname );
1365 return parent
::delete( $table, $conds, $fname );
1369 * @param string $table
1370 * @param array $values
1371 * @param array $conds
1372 * @param string $fname
1373 * @param array $options
1375 * @throws DBUnexpectedError
1377 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1380 $table = $this->tableName( $table );
1381 $opts = $this->makeUpdateOptions( $options );
1382 $sql = "UPDATE $opts $table SET ";
1385 foreach ( $values as $col => &$val ) {
1386 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1389 $sqlSet = ', ' . $sqlSet;
1396 if ( $conds !== [] && $conds !== '*' ) {
1397 $conds = $this->wrapConditionsForWhere( $table, $conds );
1398 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1401 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
1402 if ( $stmt === false ) {
1403 $e = oci_error( $this->mConn
);
1404 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1408 foreach ( $values as $col => &$val ) {
1409 $col_info = $this->fieldInfoMulti( $table, $col );
1410 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1412 if ( $val === null ) {
1413 // do nothing ... null was inserted in statement creation
1414 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1415 if ( is_object( $val ) ) {
1416 $val = $val->getData();
1419 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1420 $val = '31-12-2030 12:00:00.000000';
1423 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1424 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1425 $e = oci_error( $stmt );
1426 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1431 /** @var OCI_Lob[] $lob */
1432 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
1433 if ( $lob[$col] === false ) {
1434 $e = oci_error( $stmt );
1435 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1438 if ( is_object( $val ) ) {
1439 $val = $val->getData();
1442 if ( $col_type == 'BLOB' ) {
1443 $lob[$col]->writeTemporary( $val );
1444 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1446 $lob[$col]->writeTemporary( $val );
1447 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1452 MediaWiki\
suppressWarnings();
1454 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1455 $e = oci_error( $stmt );
1456 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1457 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1461 $this->mAffectedRows
= oci_num_rows( $stmt );
1464 $this->mAffectedRows
= oci_num_rows( $stmt );
1467 MediaWiki\restoreWarnings
();
1469 if ( isset( $lob ) ) {
1470 foreach ( $lob as $lob_v ) {
1475 if ( !$this->mTrxLevel
) {
1476 oci_commit( $this->mConn
);
1479 return oci_free_statement( $stmt );
1482 function bitNot( $field ) {
1483 // expecting bit-fields smaller than 4bytes
1484 return 'BITNOT(' . $field . ')';
1487 function bitAnd( $fieldLeft, $fieldRight ) {
1488 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1491 function bitOr( $fieldLeft, $fieldRight ) {
1492 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1495 function getDBname() {
1496 return $this->mDBname
;
1499 function getServer() {
1500 return $this->mServer
;
1503 public function buildGroupConcatField(
1504 $delim, $table, $field, $conds = '', $join_conds = []
1506 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1508 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1512 * @param string $field Field or column to cast
1516 public function buildStringCast( $field ) {
1517 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1520 public function getSearchEngine() {
1521 return 'SearchOracle';
1524 public function getInfinity() {
1525 return '31-12-2030 12:00:00.000000';