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
23 use Wikimedia\Rdbms\Blob
;
26 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
27 * other things. We use a wrapper class to handle that and other
28 * Oracle-specific bits, like converting column names back to lowercase.
36 private $columns = [];
38 private function array_unique_md( $array_in ) {
42 foreach ( $array_in as $item ) {
43 $hash = md5( serialize( $item ) );
44 if ( !isset( $array_hashes[$hash] ) ) {
45 $array_hashes[$hash] = $hash;
54 * @param IDatabase $db
55 * @param resource $stmt A valid OCI statement identifier
58 function __construct( &$db, $stmt, $unique = false ) {
61 $this->nrows
= oci_fetch_all( $stmt, $this->rows
, 0, -1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM
);
62 if ( $this->nrows
=== false ) {
63 $e = oci_error( $stmt );
64 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__
);
71 $this->rows
= $this->array_unique_md( $this->rows
);
72 $this->nrows
= count( $this->rows
);
75 if ( $this->nrows
> 0 ) {
76 foreach ( $this->rows
[0] as $k => $v ) {
77 $this->columns
[$k] = strtolower( oci_field_name( $stmt, $k +
1 ) );
82 oci_free_statement( $stmt );
85 public function free() {
89 public function seek( $row ) {
90 $this->cursor
= min( $row, $this->nrows
);
93 public function numRows() {
97 public function numFields() {
98 return count( $this->columns
);
101 public function fetchObject() {
102 if ( $this->cursor
>= $this->nrows
) {
105 $row = $this->rows
[$this->cursor++
];
106 $ret = new stdClass();
107 foreach ( $row as $k => $v ) {
108 $lc = $this->columns
[$k];
115 public function fetchRow() {
116 if ( $this->cursor
>= $this->nrows
) {
120 $row = $this->rows
[$this->cursor++
];
122 foreach ( $row as $k => $v ) {
123 $lc = $this->columns
[$k];
135 class DatabaseOracle
extends Database
{
137 protected $mLastResult = null;
139 /** @var int The number of rows affected as an integer */
140 protected $mAffectedRows;
143 private $mInsertId = null;
146 private $ignoreDupValOnIndex = false;
148 /** @var bool|array */
149 private $sequenceData = null;
151 /** @var string Character set for Oracle database */
152 private $defaultCharset = 'AL32UTF8';
155 private $mFieldInfoCache = [];
157 function __construct( array $p ) {
160 if ( $p['tablePrefix'] == 'get from global' ) {
161 $p['tablePrefix'] = $wgDBprefix;
163 $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
164 parent
::__construct( $p );
165 Hooks
::run( 'DatabaseOraclePostInit', [ $this ] );
168 function __destruct() {
169 if ( $this->mOpened
) {
170 MediaWiki\
suppressWarnings();
172 MediaWiki\restoreWarnings
();
180 function implicitGroupby() {
184 function implicitOrderby() {
189 * Usually aborts on failure
190 * @param string $server
191 * @param string $user
192 * @param string $password
193 * @param string $dbName
194 * @throws DBConnectionError
195 * @return resource|null
197 function open( $server, $user, $password, $dbName ) {
198 global $wgDBOracleDRCP;
199 if ( !function_exists( 'oci_connect' ) ) {
200 throw new DBConnectionError(
202 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
203 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
208 $this->mUser
= $user;
209 $this->mPassword
= $password;
210 // changed internal variables functions
211 // mServer now holds the TNS endpoint
212 // mDBname is schema name if different from username
214 // backward compatibillity (server used to be null and TNS was supplied in dbname)
215 $this->mServer
= $dbName;
216 $this->mDBname
= $user;
218 $this->mServer
= $server;
220 $this->mDBname
= $user;
222 $this->mDBname
= $dbName;
226 if ( !strlen( $user ) ) { # e.g. the class is being loaded
230 if ( $wgDBOracleDRCP ) {
231 $this->setFlag( DBO_PERSISTENT
);
234 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
236 MediaWiki\
suppressWarnings();
237 if ( $this->mFlags
& DBO_PERSISTENT
) {
238 $this->mConn
= oci_pconnect(
242 $this->defaultCharset
,
245 } elseif ( $this->mFlags
& DBO_DEFAULT
) {
246 $this->mConn
= oci_new_connect(
250 $this->defaultCharset
,
254 $this->mConn
= oci_connect(
258 $this->defaultCharset
,
262 MediaWiki\restoreWarnings
();
264 if ( $this->mUser
!= $this->mDBname
) {
265 // change current schema in session
266 $this->selectDB( $this->mDBname
);
269 if ( !$this->mConn
) {
270 throw new DBConnectionError( $this, $this->lastError() );
273 $this->mOpened
= true;
275 # removed putenv calls because they interfere with the system globaly
276 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
277 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
278 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
284 * Closes a database connection, if it is open
285 * Returns success, true if already closed
288 protected function closeConnection() {
289 return oci_close( $this->mConn
);
292 function execFlags() {
293 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
296 protected function doQuery( $sql ) {
297 wfDebug( "SQL: [$sql]\n" );
298 if ( !StringUtils
::isUtf8( $sql ) ) {
299 throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
302 // handle some oracle specifics
303 // remove AS column/table/subquery namings
304 if ( !$this->getFlag( DBO_DDLMODE
) ) {
305 $sql = preg_replace( '/ as /i', ' ', $sql );
308 // Oracle has issues with UNION clause if the statement includes LOB fields
309 // So we do a UNION ALL and then filter the results array with array_unique
310 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
311 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
312 // you have to select data from plan table after explain
313 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
317 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
323 MediaWiki\
suppressWarnings();
325 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
326 if ( $stmt === false ) {
327 $e = oci_error( $this->mConn
);
328 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
333 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
334 $e = oci_error( $stmt );
335 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
336 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
342 MediaWiki\restoreWarnings
();
344 if ( $explain_count > 0 ) {
345 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
346 'WHERE statement_id = \'' . $explain_id . '\'' );
347 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
348 return new ORAResult( $this, $stmt, $union_unique );
350 $this->mAffectedRows
= oci_num_rows( $stmt );
356 function queryIgnore( $sql, $fname = '' ) {
357 return $this->query( $sql, $fname, true );
361 * Frees resources associated with the LOB descriptor
362 * @param ResultWrapper|ORAResult $res
364 function freeResult( $res ) {
365 if ( $res instanceof ResultWrapper
) {
373 * @param ResultWrapper|ORAResult $res
376 function fetchObject( $res ) {
377 if ( $res instanceof ResultWrapper
) {
381 return $res->fetchObject();
385 * @param ResultWrapper|ORAResult $res
388 function fetchRow( $res ) {
389 if ( $res instanceof ResultWrapper
) {
393 return $res->fetchRow();
397 * @param ResultWrapper|ORAResult $res
400 function numRows( $res ) {
401 if ( $res instanceof ResultWrapper
) {
405 return $res->numRows();
409 * @param ResultWrapper|ORAResult $res
412 function numFields( $res ) {
413 if ( $res instanceof ResultWrapper
) {
417 return $res->numFields();
420 function fieldName( $stmt, $n ) {
421 return oci_field_name( $stmt, $n );
425 * This must be called after nextSequenceVal
428 function insertId() {
429 return $this->mInsertId
;
436 function dataSeek( $res, $row ) {
437 if ( $res instanceof ORAResult
) {
440 $res->result
->seek( $row );
444 function lastError() {
445 if ( $this->mConn
=== false ) {
448 $e = oci_error( $this->mConn
);
451 return $e['message'];
454 function lastErrno() {
455 if ( $this->mConn
=== false ) {
458 $e = oci_error( $this->mConn
);
464 function affectedRows() {
465 return $this->mAffectedRows
;
469 * Returns information about an index
470 * If errors are explicitly ignored, returns NULL on failure
471 * @param string $table
472 * @param string $index
473 * @param string $fname
476 function indexInfo( $table, $index, $fname = __METHOD__
) {
480 function indexUnique( $table, $index, $fname = __METHOD__
) {
484 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
485 if ( !count( $a ) ) {
489 if ( !is_array( $options ) ) {
490 $options = [ $options ];
493 if ( in_array( 'IGNORE', $options ) ) {
494 $this->ignoreDupValOnIndex
= true;
497 if ( !is_array( reset( $a ) ) ) {
501 foreach ( $a as &$row ) {
502 $this->insertOneRow( $table, $row, $fname );
506 if ( in_array( 'IGNORE', $options ) ) {
507 $this->ignoreDupValOnIndex
= false;
513 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
514 $col_info = $this->fieldInfoMulti( $table, $col );
515 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
518 if ( is_numeric( $col ) ) {
523 } elseif ( $includeCol ) {
527 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
531 if ( $val === 'NULL' ) {
535 if ( $val === null ) {
536 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
549 * @param string $table
551 * @param string $fname
553 * @throws DBUnexpectedError
555 private function insertOneRow( $table, $row, $fname ) {
558 $table = $this->tableName( $table );
559 // "INSERT INTO tables (a, b, c)"
560 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
563 // for each value, append ":key"
565 foreach ( $row as $col => &$val ) {
571 if ( $this->isQuotedIdentifier( $val ) ) {
572 $sql .= $this->removeIdentifierQuotes( $val );
575 $sql .= $this->fieldBindStatement( $table, $col, $val );
580 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
581 if ( $stmt === false ) {
582 $e = oci_error( $this->mConn
);
583 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
587 foreach ( $row as $col => &$val ) {
588 $col_info = $this->fieldInfoMulti( $table, $col );
589 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
591 if ( $val === null ) {
592 // do nothing ... null was inserted in statement creation
593 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
594 if ( is_object( $val ) ) {
595 $val = $val->fetch();
598 // backward compatibility
599 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
600 $val = $this->getInfinity();
603 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
604 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
605 $e = oci_error( $stmt );
606 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
611 /** @var OCI_Lob[] $lob */
612 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
613 if ( $lob[$col] === false ) {
614 $e = oci_error( $stmt );
615 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
618 if ( is_object( $val ) ) {
619 $val = $val->fetch();
622 if ( $col_type == 'BLOB' ) {
623 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
624 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
626 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
627 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
632 MediaWiki\
suppressWarnings();
634 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
635 $e = oci_error( $stmt );
636 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
637 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
641 $this->mAffectedRows
= oci_num_rows( $stmt );
644 $this->mAffectedRows
= oci_num_rows( $stmt );
647 MediaWiki\restoreWarnings
();
649 if ( isset( $lob ) ) {
650 foreach ( $lob as $lob_v ) {
655 if ( !$this->mTrxLevel
) {
656 oci_commit( $this->mConn
);
659 return oci_free_statement( $stmt );
662 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
663 $insertOptions = [], $selectOptions = []
665 $destTable = $this->tableName( $destTable );
666 if ( !is_array( $selectOptions ) ) {
667 $selectOptions = [ $selectOptions ];
669 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) =
670 $this->makeSelectOptions( $selectOptions );
671 if ( is_array( $srcTable ) ) {
672 $srcTable = implode( ',', array_map( [ $this, 'tableName' ], $srcTable ) );
674 $srcTable = $this->tableName( $srcTable );
677 $sequenceData = $this->getSequenceData( $destTable );
678 if ( $sequenceData !== false &&
679 !isset( $varMap[$sequenceData['column']] )
681 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
684 // count-alias subselect fields to avoid abigious definition errors
686 foreach ( $varMap as &$val ) {
687 $val = $val . ' field' . ( $i++
);
690 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
691 " SELECT $startOpts " . implode( ',', $varMap ) .
692 " FROM $srcTable $useIndex $ignoreIndex ";
693 if ( $conds != '*' ) {
694 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
696 $sql .= " $tailOpts";
698 if ( in_array( 'IGNORE', $insertOptions ) ) {
699 $this->ignoreDupValOnIndex
= true;
702 $retval = $this->query( $sql, $fname );
704 if ( in_array( 'IGNORE', $insertOptions ) ) {
705 $this->ignoreDupValOnIndex
= false;
711 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
714 if ( !count( $rows ) ) {
715 return true; // nothing to do
718 if ( !is_array( reset( $rows ) ) ) {
722 $sequenceData = $this->getSequenceData( $table );
723 if ( $sequenceData !== false ) {
724 // add sequence column to each list of columns, when not set
725 foreach ( $rows as &$row ) {
726 if ( !isset( $row[$sequenceData['column']] ) ) {
727 $row[$sequenceData['column']] =
728 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
729 $sequenceData['sequence'] . '\')' );
734 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
737 function tableName( $name, $format = 'quoted' ) {
739 Replace reserved words with better ones
740 Using uppercase because that's the only way Oracle can handle
748 $name = 'PAGECONTENT';
752 return strtoupper( parent
::tableName( $name, $format ) );
755 function tableNameInternal( $name ) {
756 $name = $this->tableName( $name );
758 return preg_replace( '/.*\.(.*)/', '$1', $name );
762 * Return the next in a sequence, save the value for retrieval via insertId()
764 * @param string $seqName
767 function nextSequenceValue( $seqName ) {
768 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
769 $row = $this->fetchRow( $res );
770 $this->mInsertId
= $row[0];
772 return $this->mInsertId
;
776 * Return sequence_name if table has a sequence
778 * @param string $table
781 private function getSequenceData( $table ) {
782 if ( $this->sequenceData
== null ) {
783 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
784 lower(atc.table_name),
785 lower(atc.column_name)
786 FROM all_sequences asq, all_tab_columns atc
789 '{$this->mTablePrefix}MWUSER',
790 '{$this->mTablePrefix}USER',
793 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
794 AND asq.sequence_owner = upper('{$this->mDBname}')
795 AND atc.owner = upper('{$this->mDBname}')" );
797 while ( ( $row = $result->fetchRow() ) !== false ) {
798 $this->sequenceData
[$row[1]] = [
799 'sequence' => $row[0],
804 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
806 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
810 * Returns the size of a text field, or -1 for "unlimited"
812 * @param string $table
813 * @param string $field
816 function textFieldSize( $table, $field ) {
817 $fieldInfoData = $this->fieldInfo( $table, $field );
819 return $fieldInfoData->maxLength();
822 function limitResult( $sql, $limit, $offset = false ) {
823 if ( $offset === false ) {
827 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
830 function encodeBlob( $b ) {
831 return new Blob( $b );
834 function decodeBlob( $b ) {
835 if ( $b instanceof Blob
) {
842 function unionQueries( $sqls, $all ) {
843 $glue = ' UNION ALL ';
845 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
846 'FROM (' . implode( $glue, $sqls ) . ')';
849 function wasDeadlock() {
850 return $this->lastErrno() == 'OCI-00060';
853 function duplicateTableStructure( $oldName, $newName, $temporary = false,
856 $temporary = $temporary ?
'TRUE' : 'FALSE';
858 $newName = strtoupper( $newName );
859 $oldName = strtoupper( $oldName );
861 $tabName = substr( $newName, strlen( $this->mTablePrefix
) );
862 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
863 $newPrefix = strtoupper( $this->mTablePrefix
);
865 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
866 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
869 function listTables( $prefix = null, $fname = __METHOD__
) {
871 if ( !empty( $prefix ) ) {
872 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
875 $owner = strtoupper( $this->mDBname
);
876 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
877 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
879 // dirty code ... i know
881 $endArray[] = strtoupper( $prefix . 'MWUSER' );
882 $endArray[] = strtoupper( $prefix . 'PAGE' );
883 $endArray[] = strtoupper( $prefix . 'IMAGE' );
884 $fixedOrderTabs = $endArray;
885 while ( ( $row = $result->fetchRow() ) !== false ) {
886 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
887 $endArray[] = $row['table_name'];
894 public function dropTable( $tableName, $fName = __METHOD__
) {
895 $tableName = $this->tableName( $tableName );
896 if ( !$this->tableExists( $tableName ) ) {
900 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
903 function timestamp( $ts = 0 ) {
904 return wfTimestamp( TS_ORACLE
, $ts );
908 * Return aggregated value function call
910 * @param array $valuedata
911 * @param string $valuename
914 public function aggregateValue( $valuedata, $valuename = 'value' ) {
919 * @return string Wikitext of a link to the server software's web site
921 public function getSoftwareLink() {
922 return '[{{int:version-db-oracle-url}} Oracle]';
926 * @return string Version information from the database
928 function getServerVersion() {
929 // better version number, fallback on driver
930 $rset = $this->doQuery(
931 'SELECT version FROM product_component_version ' .
932 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
934 $row = $rset->fetchRow();
936 return oci_server_version( $this->mConn
);
939 return $row['version'];
943 * Query whether a given index exists
944 * @param string $table
945 * @param string $index
946 * @param string $fname
949 function indexExists( $table, $index, $fname = __METHOD__
) {
950 $table = $this->tableName( $table );
951 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
952 $index = strtoupper( $index );
953 $owner = strtoupper( $this->mDBname
);
954 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
955 $res = $this->doQuery( $sql );
957 $count = $res->numRows();
967 * Query whether a given table exists (in the given schema, or the default mw one if not given)
968 * @param string $table
969 * @param string $fname
972 function tableExists( $table, $fname = __METHOD__
) {
973 $table = $this->tableName( $table );
974 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
975 $owner = $this->addQuotes( strtoupper( $this->mDBname
) );
976 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
977 $res = $this->doQuery( $sql );
978 if ( $res && $res->numRows() > 0 ) {
990 * Function translates mysql_fetch_field() functionality on ORACLE.
991 * Caching is present for reducing query time.
992 * For internal calls. Use fieldInfo for normal usage.
993 * Returns false if the field doesn't exist
995 * @param array|string $table
996 * @param string $field
997 * @return ORAField|ORAResult|false
999 private function fieldInfoMulti( $table, $field ) {
1000 $field = strtoupper( $field );
1001 if ( is_array( $table ) ) {
1002 $table = array_map( [ $this, 'tableNameInternal' ], $table );
1003 $tableWhere = 'IN (';
1004 foreach ( $table as &$singleTable ) {
1005 $singleTable = $this->removeIdentifierQuotes( $singleTable );
1006 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
1007 return $this->mFieldInfoCache
["$singleTable.$field"];
1009 $tableWhere .= '\'' . $singleTable . '\',';
1011 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
1013 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
1014 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
1015 return $this->mFieldInfoCache
["$table.$field"];
1017 $tableWhere = '= \'' . $table . '\'';
1020 $fieldInfoStmt = oci_parse(
1022 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
1023 $tableWhere . ' and column_name = \'' . $field . '\''
1025 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
1026 $e = oci_error( $fieldInfoStmt );
1027 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
1031 $res = new ORAResult( $this, $fieldInfoStmt );
1032 if ( $res->numRows() == 0 ) {
1033 if ( is_array( $table ) ) {
1034 foreach ( $table as &$singleTable ) {
1035 $this->mFieldInfoCache
["$singleTable.$field"] = false;
1038 $this->mFieldInfoCache
["$table.$field"] = false;
1040 $fieldInfoTemp = null;
1042 $fieldInfoTemp = new ORAField( $res->fetchRow() );
1043 $table = $fieldInfoTemp->tableName();
1044 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
1048 return $fieldInfoTemp;
1052 * @throws DBUnexpectedError
1053 * @param string $table
1054 * @param string $field
1057 function fieldInfo( $table, $field ) {
1058 if ( is_array( $table ) ) {
1059 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
1062 return $this->fieldInfoMulti( $table, $field );
1065 protected function doBegin( $fname = __METHOD__
) {
1066 $this->mTrxLevel
= 1;
1067 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
1070 protected function doCommit( $fname = __METHOD__
) {
1071 if ( $this->mTrxLevel
) {
1072 $ret = oci_commit( $this->mConn
);
1074 throw new DBUnexpectedError( $this, $this->lastError() );
1076 $this->mTrxLevel
= 0;
1077 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1081 protected function doRollback( $fname = __METHOD__
) {
1082 if ( $this->mTrxLevel
) {
1083 oci_rollback( $this->mConn
);
1084 $this->mTrxLevel
= 0;
1085 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1089 function sourceStream(
1091 callable
$lineCallback = null,
1092 callable
$resultCallback = null,
1093 $fname = __METHOD__
, callable
$inputCallback = null
1097 $dollarquote = false;
1100 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
1101 while ( !feof( $fp ) ) {
1102 if ( $lineCallback ) {
1103 call_user_func( $lineCallback );
1105 $line = trim( fgets( $fp, 1024 ) );
1106 $sl = strlen( $line ) - 1;
1111 if ( '-' == $line[0] && '-' == $line[1] ) {
1115 // Allow dollar quoting for function declarations
1116 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1117 if ( $dollarquote ) {
1118 $dollarquote = false;
1119 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1122 $dollarquote = true;
1124 } elseif ( !$dollarquote ) {
1125 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
1127 $line = substr( $line, 0, $sl );
1137 $cmd = str_replace( ';;', ";", $cmd );
1138 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1139 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1140 $replacements[$defines[2]] = $defines[1];
1143 foreach ( $replacements as $mwVar => $scVar ) {
1144 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1147 $cmd = $this->replaceVars( $cmd );
1148 if ( $inputCallback ) {
1149 call_user_func( $inputCallback, $cmd );
1151 $res = $this->doQuery( $cmd );
1152 if ( $resultCallback ) {
1153 call_user_func( $resultCallback, $res, $this );
1156 if ( false === $res ) {
1157 $err = $this->lastError();
1159 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1171 function selectDB( $db ) {
1172 $this->mDBname
= $db;
1173 if ( $db == null ||
$db == $this->mUser
) {
1176 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1177 $stmt = oci_parse( $this->mConn
, $sql );
1178 MediaWiki\
suppressWarnings();
1179 $success = oci_execute( $stmt );
1180 MediaWiki\restoreWarnings
();
1182 $e = oci_error( $stmt );
1183 if ( $e['code'] != '1435' ) {
1184 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1193 function strencode( $s ) {
1194 return str_replace( "'", "''", $s );
1197 function addQuotes( $s ) {
1199 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1200 $s = $wgContLang->checkTitleEncoding( $s );
1203 return "'" . $this->strencode( $s ) . "'";
1206 public function addIdentifierQuotes( $s ) {
1207 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1214 public function removeIdentifierQuotes( $s ) {
1215 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1218 public function isQuotedIdentifier( $s ) {
1219 return strpos( $s, '/*Q*/' ) !== false;
1222 private function wrapFieldForWhere( $table, &$col, &$val ) {
1225 $col_info = $this->fieldInfoMulti( $table, $col );
1226 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1227 if ( $col_type == 'CLOB' ) {
1228 $col = 'TO_CHAR(' . $col . ')';
1229 $val = $wgContLang->checkTitleEncoding( $val );
1230 } elseif ( $col_type == 'VARCHAR2' ) {
1231 $val = $wgContLang->checkTitleEncoding( $val );
1235 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1237 foreach ( $conds as $col => $val ) {
1238 if ( is_array( $val ) ) {
1239 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1241 if ( is_numeric( $col ) && $parentCol != null ) {
1242 $this->wrapFieldForWhere( $table, $parentCol, $val );
1244 $this->wrapFieldForWhere( $table, $col, $val );
1246 $conds2[$col] = $val;
1253 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1254 $options = [], $join_conds = []
1256 if ( is_array( $conds ) ) {
1257 $conds = $this->wrapConditionsForWhere( $table, $conds );
1260 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1264 * Returns an optional USE INDEX clause to go after the table, and a
1265 * string to go at the end of the query
1267 * @param array $options An associative array of options to be turned into
1268 * an SQL query, valid keys are listed in the function.
1271 function makeSelectOptions( $options ) {
1272 $preLimitTail = $postLimitTail = '';
1276 foreach ( $options as $key => $option ) {
1277 if ( is_numeric( $key ) ) {
1278 $noKeyOptions[$option] = true;
1282 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1284 $preLimitTail .= $this->makeOrderBy( $options );
1286 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1287 $postLimitTail .= ' FOR UPDATE';
1290 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1291 $startOpts .= 'DISTINCT';
1294 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1295 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1300 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1301 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1306 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1309 public function delete( $table, $conds, $fname = __METHOD__
) {
1310 if ( is_array( $conds ) ) {
1311 $conds = $this->wrapConditionsForWhere( $table, $conds );
1313 // a hack for deleting pages, users and images (which have non-nullable FKs)
1314 // all deletions on these tables have transactions so final failure rollbacks these updates
1315 $table = $this->tableName( $table );
1316 if ( $table == $this->tableName( 'user' ) ) {
1317 $this->update( 'archive', [ 'ar_user' => 0 ],
1318 [ 'ar_user' => $conds['user_id'] ], $fname );
1319 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1320 [ 'ipb_user' => $conds['user_id'] ], $fname );
1321 $this->update( 'image', [ 'img_user' => 0 ],
1322 [ 'img_user' => $conds['user_id'] ], $fname );
1323 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1324 [ 'oi_user' => $conds['user_id'] ], $fname );
1325 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1326 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1327 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1328 [ 'fa_user' => $conds['user_id'] ], $fname );
1329 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1330 [ 'us_user' => $conds['user_id'] ], $fname );
1331 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1332 [ 'rc_user' => $conds['user_id'] ], $fname );
1333 $this->update( 'logging', [ 'log_user' => 0 ],
1334 [ 'log_user' => $conds['user_id'] ], $fname );
1335 } elseif ( $table == $this->tableName( 'image' ) ) {
1336 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1337 [ 'oi_name' => $conds['img_name'] ], $fname );
1340 return parent
::delete( $table, $conds, $fname );
1344 * @param string $table
1345 * @param array $values
1346 * @param array $conds
1347 * @param string $fname
1348 * @param array $options
1350 * @throws DBUnexpectedError
1352 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1355 $table = $this->tableName( $table );
1356 $opts = $this->makeUpdateOptions( $options );
1357 $sql = "UPDATE $opts $table SET ";
1360 foreach ( $values as $col => &$val ) {
1361 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1364 $sqlSet = ', ' . $sqlSet;
1371 if ( $conds !== [] && $conds !== '*' ) {
1372 $conds = $this->wrapConditionsForWhere( $table, $conds );
1373 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1376 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
1377 if ( $stmt === false ) {
1378 $e = oci_error( $this->mConn
);
1379 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1383 foreach ( $values as $col => &$val ) {
1384 $col_info = $this->fieldInfoMulti( $table, $col );
1385 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1387 if ( $val === null ) {
1388 // do nothing ... null was inserted in statement creation
1389 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1390 if ( is_object( $val ) ) {
1391 $val = $val->getData();
1394 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1395 $val = '31-12-2030 12:00:00.000000';
1398 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1399 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1400 $e = oci_error( $stmt );
1401 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1406 /** @var OCI_Lob[] $lob */
1407 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
1408 if ( $lob[$col] === false ) {
1409 $e = oci_error( $stmt );
1410 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1413 if ( is_object( $val ) ) {
1414 $val = $val->getData();
1417 if ( $col_type == 'BLOB' ) {
1418 $lob[$col]->writeTemporary( $val );
1419 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1421 $lob[$col]->writeTemporary( $val );
1422 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1427 MediaWiki\
suppressWarnings();
1429 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1430 $e = oci_error( $stmt );
1431 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1432 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1436 $this->mAffectedRows
= oci_num_rows( $stmt );
1439 $this->mAffectedRows
= oci_num_rows( $stmt );
1442 MediaWiki\restoreWarnings
();
1444 if ( isset( $lob ) ) {
1445 foreach ( $lob as $lob_v ) {
1450 if ( !$this->mTrxLevel
) {
1451 oci_commit( $this->mConn
);
1454 return oci_free_statement( $stmt );
1457 function bitNot( $field ) {
1458 // expecting bit-fields smaller than 4bytes
1459 return 'BITNOT(' . $field . ')';
1462 function bitAnd( $fieldLeft, $fieldRight ) {
1463 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1466 function bitOr( $fieldLeft, $fieldRight ) {
1467 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1470 function getDBname() {
1471 return $this->mDBname
;
1474 function getServer() {
1475 return $this->mServer
;
1478 public function buildGroupConcatField(
1479 $delim, $table, $field, $conds = '', $join_conds = []
1481 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1483 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1487 * @param string $field Field or column to cast
1491 public function buildStringCast( $field ) {
1492 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1495 public function getInfinity() {
1496 return '31-12-2030 12:00:00.000000';