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 DatabaseBase $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];
135 class ORAField
implements Field
{
136 private $name, $tablename, $default, $max_length, $nullable,
137 $is_pk, $is_unique, $is_multiple, $is_key, $type;
139 function __construct( $info ) {
140 $this->name
= $info['column_name'];
141 $this->tablename
= $info['table_name'];
142 $this->default = $info['data_default'];
143 $this->max_length
= $info['data_length'];
144 $this->nullable
= $info['not_null'];
145 $this->is_pk
= isset( $info['prim'] ) && $info['prim'] == 1 ?
1 : 0;
146 $this->is_unique
= isset( $info['uniq'] ) && $info['uniq'] == 1 ?
1 : 0;
147 $this->is_multiple
= isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ?
1 : 0;
148 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
149 $this->type
= $info['data_type'];
156 function tableName() {
157 return $this->tablename
;
160 function defaultValue() {
161 return $this->default;
164 function maxLength() {
165 return $this->max_length
;
168 function isNullable() {
169 return $this->nullable
;
173 return $this->is_key
;
176 function isMultipleKey() {
177 return $this->is_multiple
;
188 class DatabaseOracle
extends Database
{
190 protected $mLastResult = null;
192 /** @var int The number of rows affected as an integer */
193 protected $mAffectedRows;
196 private $mInsertId = null;
199 private $ignoreDupValOnIndex = false;
201 /** @var bool|array */
202 private $sequenceData = null;
204 /** @var string Character set for Oracle database */
205 private $defaultCharset = 'AL32UTF8';
208 private $mFieldInfoCache = [];
210 function __construct( array $p ) {
213 if ( $p['tablePrefix'] == 'get from global' ) {
214 $p['tablePrefix'] = $wgDBprefix;
216 $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
217 parent
::__construct( $p );
218 Hooks
::run( 'DatabaseOraclePostInit', [ $this ] );
221 function __destruct() {
222 if ( $this->mOpened
) {
223 MediaWiki\
suppressWarnings();
225 MediaWiki\restoreWarnings
();
233 function cascadingDeletes() {
237 function cleanupTriggers() {
241 function strictIPs() {
245 function realTimestamps() {
249 function implicitGroupby() {
253 function implicitOrderby() {
257 function searchableIPs() {
262 * Usually aborts on failure
263 * @param string $server
264 * @param string $user
265 * @param string $password
266 * @param string $dbName
267 * @throws DBConnectionError
268 * @return DatabaseBase|null
270 function open( $server, $user, $password, $dbName ) {
271 global $wgDBOracleDRCP;
272 if ( !function_exists( 'oci_connect' ) ) {
273 throw new DBConnectionError(
275 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
276 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
281 $this->mUser
= $user;
282 $this->mPassword
= $password;
283 // changed internal variables functions
284 // mServer now holds the TNS endpoint
285 // mDBname is schema name if different from username
287 // backward compatibillity (server used to be null and TNS was supplied in dbname)
288 $this->mServer
= $dbName;
289 $this->mDBname
= $user;
291 $this->mServer
= $server;
293 $this->mDBname
= $user;
295 $this->mDBname
= $dbName;
299 if ( !strlen( $user ) ) { # e.g. the class is being loaded
303 if ( $wgDBOracleDRCP ) {
304 $this->setFlag( DBO_PERSISTENT
);
307 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
309 MediaWiki\
suppressWarnings();
310 if ( $this->mFlags
& DBO_PERSISTENT
) {
311 $this->mConn
= oci_pconnect(
315 $this->defaultCharset
,
318 } elseif ( $this->mFlags
& DBO_DEFAULT
) {
319 $this->mConn
= oci_new_connect(
323 $this->defaultCharset
,
327 $this->mConn
= oci_connect(
331 $this->defaultCharset
,
335 MediaWiki\restoreWarnings
();
337 if ( $this->mUser
!= $this->mDBname
) {
338 // change current schema in session
339 $this->selectDB( $this->mDBname
);
342 if ( !$this->mConn
) {
343 throw new DBConnectionError( $this, $this->lastError() );
346 $this->mOpened
= true;
348 # removed putenv calls because they interfere with the system globaly
349 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
350 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
351 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
357 * Closes a database connection, if it is open
358 * Returns success, true if already closed
361 protected function closeConnection() {
362 return oci_close( $this->mConn
);
365 function execFlags() {
366 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
369 protected function doQuery( $sql ) {
370 wfDebug( "SQL: [$sql]\n" );
371 if ( !StringUtils
::isUtf8( $sql ) ) {
372 throw new MWException( "SQL encoding is invalid\n$sql" );
375 // handle some oracle specifics
376 // remove AS column/table/subquery namings
377 if ( !$this->getFlag( DBO_DDLMODE
) ) {
378 $sql = preg_replace( '/ as /i', ' ', $sql );
381 // Oracle has issues with UNION clause if the statement includes LOB fields
382 // So we do a UNION ALL and then filter the results array with array_unique
383 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
384 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
385 // you have to select data from plan table after explain
386 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
390 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
396 MediaWiki\
suppressWarnings();
398 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
399 if ( $stmt === false ) {
400 $e = oci_error( $this->mConn
);
401 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
406 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
407 $e = oci_error( $stmt );
408 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
409 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
415 MediaWiki\restoreWarnings
();
417 if ( $explain_count > 0 ) {
418 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
419 'WHERE statement_id = \'' . $explain_id . '\'' );
420 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
421 return new ORAResult( $this, $stmt, $union_unique );
423 $this->mAffectedRows
= oci_num_rows( $stmt );
429 function queryIgnore( $sql, $fname = '' ) {
430 return $this->query( $sql, $fname, true );
434 * Frees resources associated with the LOB descriptor
435 * @param ResultWrapper|ORAResult $res
437 function freeResult( $res ) {
438 if ( $res instanceof ResultWrapper
) {
446 * @param ResultWrapper|ORAResult $res
449 function fetchObject( $res ) {
450 if ( $res instanceof ResultWrapper
) {
454 return $res->fetchObject();
458 * @param ResultWrapper|ORAResult $res
461 function fetchRow( $res ) {
462 if ( $res instanceof ResultWrapper
) {
466 return $res->fetchRow();
470 * @param ResultWrapper|ORAResult $res
473 function numRows( $res ) {
474 if ( $res instanceof ResultWrapper
) {
478 return $res->numRows();
482 * @param ResultWrapper|ORAResult $res
485 function numFields( $res ) {
486 if ( $res instanceof ResultWrapper
) {
490 return $res->numFields();
493 function fieldName( $stmt, $n ) {
494 return oci_field_name( $stmt, $n );
498 * This must be called after nextSequenceVal
501 function insertId() {
502 return $this->mInsertId
;
509 function dataSeek( $res, $row ) {
510 if ( $res instanceof ORAResult
) {
513 $res->result
->seek( $row );
517 function lastError() {
518 if ( $this->mConn
=== false ) {
521 $e = oci_error( $this->mConn
);
524 return $e['message'];
527 function lastErrno() {
528 if ( $this->mConn
=== false ) {
531 $e = oci_error( $this->mConn
);
537 function affectedRows() {
538 return $this->mAffectedRows
;
542 * Returns information about an index
543 * If errors are explicitly ignored, returns NULL on failure
544 * @param string $table
545 * @param string $index
546 * @param string $fname
549 function indexInfo( $table, $index, $fname = __METHOD__
) {
553 function indexUnique( $table, $index, $fname = __METHOD__
) {
557 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
558 if ( !count( $a ) ) {
562 if ( !is_array( $options ) ) {
563 $options = [ $options ];
566 if ( in_array( 'IGNORE', $options ) ) {
567 $this->ignoreDupValOnIndex
= true;
570 if ( !is_array( reset( $a ) ) ) {
574 foreach ( $a as &$row ) {
575 $this->insertOneRow( $table, $row, $fname );
579 if ( in_array( 'IGNORE', $options ) ) {
580 $this->ignoreDupValOnIndex
= false;
586 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
587 $col_info = $this->fieldInfoMulti( $table, $col );
588 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
591 if ( is_numeric( $col ) ) {
596 } elseif ( $includeCol ) {
600 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
604 if ( $val === 'NULL' ) {
608 if ( $val === null ) {
609 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
622 * @param string $table
624 * @param string $fname
626 * @throws DBUnexpectedError
628 private function insertOneRow( $table, $row, $fname ) {
631 $table = $this->tableName( $table );
632 // "INSERT INTO tables (a, b, c)"
633 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
636 // for each value, append ":key"
638 foreach ( $row as $col => &$val ) {
644 if ( $this->isQuotedIdentifier( $val ) ) {
645 $sql .= $this->removeIdentifierQuotes( $val );
648 $sql .= $this->fieldBindStatement( $table, $col, $val );
653 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
654 if ( $stmt === false ) {
655 $e = oci_error( $this->mConn
);
656 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
660 foreach ( $row as $col => &$val ) {
661 $col_info = $this->fieldInfoMulti( $table, $col );
662 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
664 if ( $val === null ) {
665 // do nothing ... null was inserted in statement creation
666 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
667 if ( is_object( $val ) ) {
668 $val = $val->fetch();
671 // backward compatibility
672 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
673 $val = $this->getInfinity();
676 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
677 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
678 $e = oci_error( $stmt );
679 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
684 /** @var OCI_Lob[] $lob */
685 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
686 if ( $lob[$col] === false ) {
687 $e = oci_error( $stmt );
688 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
691 if ( is_object( $val ) ) {
692 $val = $val->fetch();
695 if ( $col_type == 'BLOB' ) {
696 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
697 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
699 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
700 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
705 MediaWiki\
suppressWarnings();
707 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
708 $e = oci_error( $stmt );
709 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
710 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
714 $this->mAffectedRows
= oci_num_rows( $stmt );
717 $this->mAffectedRows
= oci_num_rows( $stmt );
720 MediaWiki\restoreWarnings
();
722 if ( isset( $lob ) ) {
723 foreach ( $lob as $lob_v ) {
728 if ( !$this->mTrxLevel
) {
729 oci_commit( $this->mConn
);
732 return oci_free_statement( $stmt );
735 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
736 $insertOptions = [], $selectOptions = []
738 $destTable = $this->tableName( $destTable );
739 if ( !is_array( $selectOptions ) ) {
740 $selectOptions = [ $selectOptions ];
742 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
743 if ( is_array( $srcTable ) ) {
744 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
746 $srcTable = $this->tableName( $srcTable );
749 $sequenceData = $this->getSequenceData( $destTable );
750 if ( $sequenceData !== false &&
751 !isset( $varMap[$sequenceData['column']] )
753 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
756 // count-alias subselect fields to avoid abigious definition errors
758 foreach ( $varMap as &$val ) {
759 $val = $val . ' field' . ( $i++
);
762 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
763 " SELECT $startOpts " . implode( ',', $varMap ) .
764 " FROM $srcTable $useIndex ";
765 if ( $conds != '*' ) {
766 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
768 $sql .= " $tailOpts";
770 if ( in_array( 'IGNORE', $insertOptions ) ) {
771 $this->ignoreDupValOnIndex
= true;
774 $retval = $this->query( $sql, $fname );
776 if ( in_array( 'IGNORE', $insertOptions ) ) {
777 $this->ignoreDupValOnIndex
= false;
783 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
786 if ( !count( $rows ) ) {
787 return true; // nothing to do
790 if ( !is_array( reset( $rows ) ) ) {
794 $sequenceData = $this->getSequenceData( $table );
795 if ( $sequenceData !== false ) {
796 // add sequence column to each list of columns, when not set
797 foreach ( $rows as &$row ) {
798 if ( !isset( $row[$sequenceData['column']] ) ) {
799 $row[$sequenceData['column']] =
800 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
801 $sequenceData['sequence'] . '\')' );
806 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
809 function tableName( $name, $format = 'quoted' ) {
811 Replace reserved words with better ones
812 Using uppercase because that's the only way Oracle can handle
820 $name = 'PAGECONTENT';
824 return strtoupper( parent
::tableName( $name, $format ) );
827 function tableNameInternal( $name ) {
828 $name = $this->tableName( $name );
830 return preg_replace( '/.*\.(.*)/', '$1', $name );
834 * Return the next in a sequence, save the value for retrieval via insertId()
836 * @param string $seqName
839 function nextSequenceValue( $seqName ) {
840 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
841 $row = $this->fetchRow( $res );
842 $this->mInsertId
= $row[0];
844 return $this->mInsertId
;
848 * Return sequence_name if table has a sequence
850 * @param string $table
853 private function getSequenceData( $table ) {
854 if ( $this->sequenceData
== null ) {
855 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
856 lower(atc.table_name),
857 lower(atc.column_name)
858 FROM all_sequences asq, all_tab_columns atc
861 '{$this->mTablePrefix}MWUSER',
862 '{$this->mTablePrefix}USER',
865 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
866 AND asq.sequence_owner = upper('{$this->mDBname}')
867 AND atc.owner = upper('{$this->mDBname}')" );
869 while ( ( $row = $result->fetchRow() ) !== false ) {
870 $this->sequenceData
[$row[1]] = [
871 'sequence' => $row[0],
876 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
878 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
882 * Returns the size of a text field, or -1 for "unlimited"
884 * @param string $table
885 * @param string $field
888 function textFieldSize( $table, $field ) {
889 $fieldInfoData = $this->fieldInfo( $table, $field );
891 return $fieldInfoData->maxLength();
894 function limitResult( $sql, $limit, $offset = false ) {
895 if ( $offset === false ) {
899 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
902 function encodeBlob( $b ) {
903 return new Blob( $b );
906 function decodeBlob( $b ) {
907 if ( $b instanceof Blob
) {
914 function unionQueries( $sqls, $all ) {
915 $glue = ' UNION ALL ';
917 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
918 'FROM (' . implode( $glue, $sqls ) . ')';
921 function wasDeadlock() {
922 return $this->lastErrno() == 'OCI-00060';
925 function duplicateTableStructure( $oldName, $newName, $temporary = false,
928 $temporary = $temporary ?
'TRUE' : 'FALSE';
930 $newName = strtoupper( $newName );
931 $oldName = strtoupper( $oldName );
933 $tabName = substr( $newName, strlen( $this->mTablePrefix
) );
934 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
935 $newPrefix = strtoupper( $this->mTablePrefix
);
937 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
938 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
941 function listTables( $prefix = null, $fname = __METHOD__
) {
943 if ( !empty( $prefix ) ) {
944 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
947 $owner = strtoupper( $this->mDBname
);
948 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
949 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
951 // dirty code ... i know
953 $endArray[] = strtoupper( $prefix . 'MWUSER' );
954 $endArray[] = strtoupper( $prefix . 'PAGE' );
955 $endArray[] = strtoupper( $prefix . 'IMAGE' );
956 $fixedOrderTabs = $endArray;
957 while ( ( $row = $result->fetchRow() ) !== false ) {
958 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
959 $endArray[] = $row['table_name'];
966 public function dropTable( $tableName, $fName = __METHOD__
) {
967 $tableName = $this->tableName( $tableName );
968 if ( !$this->tableExists( $tableName ) ) {
972 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
975 function timestamp( $ts = 0 ) {
976 return wfTimestamp( TS_ORACLE
, $ts );
980 * Return aggregated value function call
982 * @param array $valuedata
983 * @param string $valuename
986 public function aggregateValue( $valuedata, $valuename = 'value' ) {
991 * @return string Wikitext of a link to the server software's web site
993 public function getSoftwareLink() {
994 return '[{{int:version-db-oracle-url}} Oracle]';
998 * @return string Version information from the database
1000 function getServerVersion() {
1001 // better version number, fallback on driver
1002 $rset = $this->doQuery(
1003 'SELECT version FROM product_component_version ' .
1004 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
1006 $row = $rset->fetchRow();
1008 return oci_server_version( $this->mConn
);
1011 return $row['version'];
1015 * Query whether a given index exists
1016 * @param string $table
1017 * @param string $index
1018 * @param string $fname
1021 function indexExists( $table, $index, $fname = __METHOD__
) {
1022 $table = $this->tableName( $table );
1023 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
1024 $index = strtoupper( $index );
1025 $owner = strtoupper( $this->mDBname
);
1026 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
1027 $res = $this->doQuery( $sql );
1029 $count = $res->numRows();
1039 * Query whether a given table exists (in the given schema, or the default mw one if not given)
1040 * @param string $table
1041 * @param string $fname
1044 function tableExists( $table, $fname = __METHOD__
) {
1045 $table = $this->tableName( $table );
1046 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
1047 $owner = $this->addQuotes( strtoupper( $this->mDBname
) );
1048 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
1049 $res = $this->doQuery( $sql );
1050 if ( $res && $res->numRows() > 0 ) {
1062 * Function translates mysql_fetch_field() functionality on ORACLE.
1063 * Caching is present for reducing query time.
1064 * For internal calls. Use fieldInfo for normal usage.
1065 * Returns false if the field doesn't exist
1067 * @param array|string $table
1068 * @param string $field
1069 * @return ORAField|ORAResult
1071 private function fieldInfoMulti( $table, $field ) {
1072 $field = strtoupper( $field );
1073 if ( is_array( $table ) ) {
1074 $table = array_map( [ &$this, 'tableNameInternal' ], $table );
1075 $tableWhere = 'IN (';
1076 foreach ( $table as &$singleTable ) {
1077 $singleTable = $this->removeIdentifierQuotes( $singleTable );
1078 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
1079 return $this->mFieldInfoCache
["$singleTable.$field"];
1081 $tableWhere .= '\'' . $singleTable . '\',';
1083 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
1085 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
1086 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
1087 return $this->mFieldInfoCache
["$table.$field"];
1089 $tableWhere = '= \'' . $table . '\'';
1092 $fieldInfoStmt = oci_parse(
1094 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
1095 $tableWhere . ' and column_name = \'' . $field . '\''
1097 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
1098 $e = oci_error( $fieldInfoStmt );
1099 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
1103 $res = new ORAResult( $this, $fieldInfoStmt );
1104 if ( $res->numRows() == 0 ) {
1105 if ( is_array( $table ) ) {
1106 foreach ( $table as &$singleTable ) {
1107 $this->mFieldInfoCache
["$singleTable.$field"] = false;
1110 $this->mFieldInfoCache
["$table.$field"] = false;
1112 $fieldInfoTemp = null;
1114 $fieldInfoTemp = new ORAField( $res->fetchRow() );
1115 $table = $fieldInfoTemp->tableName();
1116 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
1120 return $fieldInfoTemp;
1124 * @throws DBUnexpectedError
1125 * @param string $table
1126 * @param string $field
1129 function fieldInfo( $table, $field ) {
1130 if ( is_array( $table ) ) {
1131 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
1134 return $this->fieldInfoMulti( $table, $field );
1137 protected function doBegin( $fname = __METHOD__
) {
1138 $this->mTrxLevel
= 1;
1139 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
1142 protected function doCommit( $fname = __METHOD__
) {
1143 if ( $this->mTrxLevel
) {
1144 $ret = oci_commit( $this->mConn
);
1146 throw new DBUnexpectedError( $this, $this->lastError() );
1148 $this->mTrxLevel
= 0;
1149 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1153 protected function doRollback( $fname = __METHOD__
) {
1154 if ( $this->mTrxLevel
) {
1155 oci_rollback( $this->mConn
);
1156 $this->mTrxLevel
= 0;
1157 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1162 * defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
1164 * @param resource $fp
1165 * @param bool|string $lineCallback
1166 * @param bool|callable $resultCallback
1167 * @param string $fname
1168 * @param bool|callable $inputCallback
1169 * @return bool|string
1171 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
1172 $fname = __METHOD__
, $inputCallback = false ) {
1175 $dollarquote = false;
1179 while ( !feof( $fp ) ) {
1180 if ( $lineCallback ) {
1181 call_user_func( $lineCallback );
1183 $line = trim( fgets( $fp, 1024 ) );
1184 $sl = strlen( $line ) - 1;
1189 if ( '-' == $line[0] && '-' == $line[1] ) {
1193 // Allow dollar quoting for function declarations
1194 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1195 if ( $dollarquote ) {
1196 $dollarquote = false;
1197 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1200 $dollarquote = true;
1202 } elseif ( !$dollarquote ) {
1203 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
1205 $line = substr( $line, 0, $sl );
1215 $cmd = str_replace( ';;', ";", $cmd );
1216 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1217 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1218 $replacements[$defines[2]] = $defines[1];
1221 foreach ( $replacements as $mwVar => $scVar ) {
1222 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1225 $cmd = $this->replaceVars( $cmd );
1226 if ( $inputCallback ) {
1227 call_user_func( $inputCallback, $cmd );
1229 $res = $this->doQuery( $cmd );
1230 if ( $resultCallback ) {
1231 call_user_func( $resultCallback, $res, $this );
1234 if ( false === $res ) {
1235 $err = $this->lastError();
1237 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1249 function selectDB( $db ) {
1250 $this->mDBname
= $db;
1251 if ( $db == null ||
$db == $this->mUser
) {
1254 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1255 $stmt = oci_parse( $this->mConn
, $sql );
1256 MediaWiki\
suppressWarnings();
1257 $success = oci_execute( $stmt );
1258 MediaWiki\restoreWarnings
();
1260 $e = oci_error( $stmt );
1261 if ( $e['code'] != '1435' ) {
1262 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1271 function strencode( $s ) {
1272 return str_replace( "'", "''", $s );
1275 function addQuotes( $s ) {
1277 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1278 $s = $wgContLang->checkTitleEncoding( $s );
1281 return "'" . $this->strencode( $s ) . "'";
1284 public function addIdentifierQuotes( $s ) {
1285 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1292 public function removeIdentifierQuotes( $s ) {
1293 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1296 public function isQuotedIdentifier( $s ) {
1297 return strpos( $s, '/*Q*/' ) !== false;
1300 private function wrapFieldForWhere( $table, &$col, &$val ) {
1303 $col_info = $this->fieldInfoMulti( $table, $col );
1304 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1305 if ( $col_type == 'CLOB' ) {
1306 $col = 'TO_CHAR(' . $col . ')';
1307 $val = $wgContLang->checkTitleEncoding( $val );
1308 } elseif ( $col_type == 'VARCHAR2' ) {
1309 $val = $wgContLang->checkTitleEncoding( $val );
1313 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1315 foreach ( $conds as $col => $val ) {
1316 if ( is_array( $val ) ) {
1317 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1319 if ( is_numeric( $col ) && $parentCol != null ) {
1320 $this->wrapFieldForWhere( $table, $parentCol, $val );
1322 $this->wrapFieldForWhere( $table, $col, $val );
1324 $conds2[$col] = $val;
1331 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1332 $options = [], $join_conds = []
1334 if ( is_array( $conds ) ) {
1335 $conds = $this->wrapConditionsForWhere( $table, $conds );
1338 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1342 * Returns an optional USE INDEX clause to go after the table, and a
1343 * string to go at the end of the query
1345 * @param array $options An associative array of options to be turned into
1346 * an SQL query, valid keys are listed in the function.
1349 function makeSelectOptions( $options ) {
1350 $preLimitTail = $postLimitTail = '';
1354 foreach ( $options as $key => $option ) {
1355 if ( is_numeric( $key ) ) {
1356 $noKeyOptions[$option] = true;
1360 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1362 $preLimitTail .= $this->makeOrderBy( $options );
1364 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1365 $postLimitTail .= ' FOR UPDATE';
1368 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1369 $startOpts .= 'DISTINCT';
1372 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1373 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1378 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail ];
1381 public function delete( $table, $conds, $fname = __METHOD__
) {
1382 if ( is_array( $conds ) ) {
1383 $conds = $this->wrapConditionsForWhere( $table, $conds );
1385 // a hack for deleting pages, users and images (which have non-nullable FKs)
1386 // all deletions on these tables have transactions so final failure rollbacks these updates
1387 $table = $this->tableName( $table );
1388 if ( $table == $this->tableName( 'user' ) ) {
1389 $this->update( 'archive', [ 'ar_user' => 0 ],
1390 [ 'ar_user' => $conds['user_id'] ], $fname );
1391 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1392 [ 'ipb_user' => $conds['user_id'] ], $fname );
1393 $this->update( 'image', [ 'img_user' => 0 ],
1394 [ 'img_user' => $conds['user_id'] ], $fname );
1395 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1396 [ 'oi_user' => $conds['user_id'] ], $fname );
1397 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1398 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1399 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1400 [ 'fa_user' => $conds['user_id'] ], $fname );
1401 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1402 [ 'us_user' => $conds['user_id'] ], $fname );
1403 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1404 [ 'rc_user' => $conds['user_id'] ], $fname );
1405 $this->update( 'logging', [ 'log_user' => 0 ],
1406 [ 'log_user' => $conds['user_id'] ], $fname );
1407 } elseif ( $table == $this->tableName( 'image' ) ) {
1408 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1409 [ 'oi_name' => $conds['img_name'] ], $fname );
1412 return parent
::delete( $table, $conds, $fname );
1416 * @param string $table
1417 * @param array $values
1418 * @param array $conds
1419 * @param string $fname
1420 * @param array $options
1422 * @throws DBUnexpectedError
1424 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1427 $table = $this->tableName( $table );
1428 $opts = $this->makeUpdateOptions( $options );
1429 $sql = "UPDATE $opts $table SET ";
1432 foreach ( $values as $col => &$val ) {
1433 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1436 $sqlSet = ', ' . $sqlSet;
1443 if ( $conds !== [] && $conds !== '*' ) {
1444 $conds = $this->wrapConditionsForWhere( $table, $conds );
1445 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1448 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
1449 if ( $stmt === false ) {
1450 $e = oci_error( $this->mConn
);
1451 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1455 foreach ( $values as $col => &$val ) {
1456 $col_info = $this->fieldInfoMulti( $table, $col );
1457 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1459 if ( $val === null ) {
1460 // do nothing ... null was inserted in statement creation
1461 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1462 if ( is_object( $val ) ) {
1463 $val = $val->getData();
1466 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1467 $val = '31-12-2030 12:00:00.000000';
1470 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1471 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1472 $e = oci_error( $stmt );
1473 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1478 /** @var OCI_Lob[] $lob */
1479 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
1480 if ( $lob[$col] === false ) {
1481 $e = oci_error( $stmt );
1482 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1485 if ( is_object( $val ) ) {
1486 $val = $val->getData();
1489 if ( $col_type == 'BLOB' ) {
1490 $lob[$col]->writeTemporary( $val );
1491 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1493 $lob[$col]->writeTemporary( $val );
1494 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1499 MediaWiki\
suppressWarnings();
1501 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1502 $e = oci_error( $stmt );
1503 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1504 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1508 $this->mAffectedRows
= oci_num_rows( $stmt );
1511 $this->mAffectedRows
= oci_num_rows( $stmt );
1514 MediaWiki\restoreWarnings
();
1516 if ( isset( $lob ) ) {
1517 foreach ( $lob as $lob_v ) {
1522 if ( !$this->mTrxLevel
) {
1523 oci_commit( $this->mConn
);
1526 return oci_free_statement( $stmt );
1529 function bitNot( $field ) {
1530 // expecting bit-fields smaller than 4bytes
1531 return 'BITNOT(' . $field . ')';
1534 function bitAnd( $fieldLeft, $fieldRight ) {
1535 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1538 function bitOr( $fieldLeft, $fieldRight ) {
1539 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1542 function getDBname() {
1543 return $this->mDBname
;
1546 function getServer() {
1547 return $this->mServer
;
1550 public function buildGroupConcatField(
1551 $delim, $table, $field, $conds = '', $join_conds = []
1553 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1555 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1558 public function getSearchEngine() {
1559 return 'SearchOracle';
1562 public function getInfinity() {
1563 return '31-12-2030 12:00:00.000000';