3 * This is the Oracle database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use Wikimedia\Rdbms\Database
;
25 use Wikimedia\Rdbms\Blob
;
26 use Wikimedia\Rdbms\ResultWrapper
;
27 use Wikimedia\Rdbms\DBConnectionError
;
28 use Wikimedia\Rdbms\DBUnexpectedError
;
33 class DatabaseOracle
extends Database
{
35 protected $mLastResult = null;
37 /** @var int The number of rows affected as an integer */
38 protected $mAffectedRows;
41 private $mInsertId = null;
44 private $ignoreDupValOnIndex = false;
46 /** @var bool|array */
47 private $sequenceData = null;
49 /** @var string Character set for Oracle database */
50 private $defaultCharset = 'AL32UTF8';
53 private $mFieldInfoCache = [];
55 function __construct( array $p ) {
58 if ( $p['tablePrefix'] == 'get from global' ) {
59 $p['tablePrefix'] = $wgDBprefix;
61 $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
62 parent
::__construct( $p );
63 Hooks
::run( 'DatabaseOraclePostInit', [ $this ] );
66 function __destruct() {
67 if ( $this->mOpened
) {
68 MediaWiki\
suppressWarnings();
70 MediaWiki\restoreWarnings
();
78 function implicitGroupby() {
82 function implicitOrderby() {
87 * Usually aborts on failure
88 * @param string $server
90 * @param string $password
91 * @param string $dbName
92 * @throws DBConnectionError
93 * @return resource|null
95 function open( $server, $user, $password, $dbName ) {
96 global $wgDBOracleDRCP;
97 if ( !function_exists( 'oci_connect' ) ) {
98 throw new DBConnectionError(
100 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
101 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
106 $this->mUser
= $user;
107 $this->mPassword
= $password;
108 // changed internal variables functions
109 // mServer now holds the TNS endpoint
110 // mDBname is schema name if different from username
112 // backward compatibillity (server used to be null and TNS was supplied in dbname)
113 $this->mServer
= $dbName;
114 $this->mDBname
= $user;
116 $this->mServer
= $server;
118 $this->mDBname
= $user;
120 $this->mDBname
= $dbName;
124 if ( !strlen( $user ) ) { # e.g. the class is being loaded
128 if ( $wgDBOracleDRCP ) {
129 $this->setFlag( DBO_PERSISTENT
);
132 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
134 MediaWiki\
suppressWarnings();
135 if ( $this->mFlags
& DBO_PERSISTENT
) {
136 $this->mConn
= oci_pconnect(
140 $this->defaultCharset
,
143 } elseif ( $this->mFlags
& DBO_DEFAULT
) {
144 $this->mConn
= oci_new_connect(
148 $this->defaultCharset
,
152 $this->mConn
= oci_connect(
156 $this->defaultCharset
,
160 MediaWiki\restoreWarnings
();
162 if ( $this->mUser
!= $this->mDBname
) {
163 // change current schema in session
164 $this->selectDB( $this->mDBname
);
167 if ( !$this->mConn
) {
168 throw new DBConnectionError( $this, $this->lastError() );
171 $this->mOpened
= true;
173 # removed putenv calls because they interfere with the system globaly
174 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
175 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
176 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
182 * Closes a database connection, if it is open
183 * Returns success, true if already closed
186 protected function closeConnection() {
187 return oci_close( $this->mConn
);
190 function execFlags() {
191 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
194 protected function doQuery( $sql ) {
195 wfDebug( "SQL: [$sql]\n" );
196 if ( !StringUtils
::isUtf8( $sql ) ) {
197 throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
200 // handle some oracle specifics
201 // remove AS column/table/subquery namings
202 if ( !$this->getFlag( DBO_DDLMODE
) ) {
203 $sql = preg_replace( '/ as /i', ' ', $sql );
206 // Oracle has issues with UNION clause if the statement includes LOB fields
207 // So we do a UNION ALL and then filter the results array with array_unique
208 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
209 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
210 // you have to select data from plan table after explain
211 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
215 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
221 MediaWiki\
suppressWarnings();
223 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
224 if ( $stmt === false ) {
225 $e = oci_error( $this->mConn
);
226 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
231 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
232 $e = oci_error( $stmt );
233 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
234 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
240 MediaWiki\restoreWarnings
();
242 if ( $explain_count > 0 ) {
243 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
244 'WHERE statement_id = \'' . $explain_id . '\'' );
245 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
246 return new ORAResult( $this, $stmt, $union_unique );
248 $this->mAffectedRows
= oci_num_rows( $stmt );
254 function queryIgnore( $sql, $fname = '' ) {
255 return $this->query( $sql, $fname, true );
259 * Frees resources associated with the LOB descriptor
260 * @param ResultWrapper|ORAResult $res
262 function freeResult( $res ) {
263 if ( $res instanceof ResultWrapper
) {
271 * @param ResultWrapper|ORAResult $res
274 function fetchObject( $res ) {
275 if ( $res instanceof ResultWrapper
) {
279 return $res->fetchObject();
283 * @param ResultWrapper|ORAResult $res
286 function fetchRow( $res ) {
287 if ( $res instanceof ResultWrapper
) {
291 return $res->fetchRow();
295 * @param ResultWrapper|ORAResult $res
298 function numRows( $res ) {
299 if ( $res instanceof ResultWrapper
) {
303 return $res->numRows();
307 * @param ResultWrapper|ORAResult $res
310 function numFields( $res ) {
311 if ( $res instanceof ResultWrapper
) {
315 return $res->numFields();
318 function fieldName( $stmt, $n ) {
319 return oci_field_name( $stmt, $n );
323 * This must be called after nextSequenceVal
326 function insertId() {
327 return $this->mInsertId
;
334 function dataSeek( $res, $row ) {
335 if ( $res instanceof ORAResult
) {
338 $res->result
->seek( $row );
342 function lastError() {
343 if ( $this->mConn
=== false ) {
346 $e = oci_error( $this->mConn
);
349 return $e['message'];
352 function lastErrno() {
353 if ( $this->mConn
=== false ) {
356 $e = oci_error( $this->mConn
);
362 function affectedRows() {
363 return $this->mAffectedRows
;
367 * Returns information about an index
368 * If errors are explicitly ignored, returns NULL on failure
369 * @param string $table
370 * @param string $index
371 * @param string $fname
374 function indexInfo( $table, $index, $fname = __METHOD__
) {
378 function indexUnique( $table, $index, $fname = __METHOD__
) {
382 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
383 if ( !count( $a ) ) {
387 if ( !is_array( $options ) ) {
388 $options = [ $options ];
391 if ( in_array( 'IGNORE', $options ) ) {
392 $this->ignoreDupValOnIndex
= true;
395 if ( !is_array( reset( $a ) ) ) {
399 foreach ( $a as &$row ) {
400 $this->insertOneRow( $table, $row, $fname );
404 if ( in_array( 'IGNORE', $options ) ) {
405 $this->ignoreDupValOnIndex
= false;
411 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
412 $col_info = $this->fieldInfoMulti( $table, $col );
413 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
416 if ( is_numeric( $col ) ) {
421 } elseif ( $includeCol ) {
425 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
429 if ( $val === 'NULL' ) {
433 if ( $val === null ) {
434 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
447 * @param string $table
449 * @param string $fname
451 * @throws DBUnexpectedError
453 private function insertOneRow( $table, $row, $fname ) {
456 $table = $this->tableName( $table );
457 // "INSERT INTO tables (a, b, c)"
458 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
461 // for each value, append ":key"
463 foreach ( $row as $col => &$val ) {
469 if ( $this->isQuotedIdentifier( $val ) ) {
470 $sql .= $this->removeIdentifierQuotes( $val );
473 $sql .= $this->fieldBindStatement( $table, $col, $val );
478 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
479 if ( $stmt === false ) {
480 $e = oci_error( $this->mConn
);
481 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
485 foreach ( $row as $col => &$val ) {
486 $col_info = $this->fieldInfoMulti( $table, $col );
487 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
489 if ( $val === null ) {
490 // do nothing ... null was inserted in statement creation
491 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
492 if ( is_object( $val ) ) {
493 $val = $val->fetch();
496 // backward compatibility
497 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
498 $val = $this->getInfinity();
501 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
502 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
503 $e = oci_error( $stmt );
504 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
509 /** @var OCI_Lob[] $lob */
510 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
511 if ( $lob[$col] === false ) {
512 $e = oci_error( $stmt );
513 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
516 if ( is_object( $val ) ) {
517 $val = $val->fetch();
520 if ( $col_type == 'BLOB' ) {
521 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
522 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
524 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
525 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
530 MediaWiki\
suppressWarnings();
532 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
533 $e = oci_error( $stmt );
534 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
535 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
539 $this->mAffectedRows
= oci_num_rows( $stmt );
542 $this->mAffectedRows
= oci_num_rows( $stmt );
545 MediaWiki\restoreWarnings
();
547 if ( isset( $lob ) ) {
548 foreach ( $lob as $lob_v ) {
553 if ( !$this->mTrxLevel
) {
554 oci_commit( $this->mConn
);
557 return oci_free_statement( $stmt );
560 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
561 $insertOptions = [], $selectOptions = []
563 $destTable = $this->tableName( $destTable );
564 if ( !is_array( $selectOptions ) ) {
565 $selectOptions = [ $selectOptions ];
567 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) =
568 $this->makeSelectOptions( $selectOptions );
569 if ( is_array( $srcTable ) ) {
570 $srcTable = implode( ',', array_map( [ $this, 'tableName' ], $srcTable ) );
572 $srcTable = $this->tableName( $srcTable );
575 $sequenceData = $this->getSequenceData( $destTable );
576 if ( $sequenceData !== false &&
577 !isset( $varMap[$sequenceData['column']] )
579 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
582 // count-alias subselect fields to avoid abigious definition errors
584 foreach ( $varMap as &$val ) {
585 $val = $val . ' field' . ( $i++
);
588 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
589 " SELECT $startOpts " . implode( ',', $varMap ) .
590 " FROM $srcTable $useIndex $ignoreIndex ";
591 if ( $conds != '*' ) {
592 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
594 $sql .= " $tailOpts";
596 if ( in_array( 'IGNORE', $insertOptions ) ) {
597 $this->ignoreDupValOnIndex
= true;
600 $retval = $this->query( $sql, $fname );
602 if ( in_array( 'IGNORE', $insertOptions ) ) {
603 $this->ignoreDupValOnIndex
= false;
609 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
612 if ( !count( $rows ) ) {
613 return true; // nothing to do
616 if ( !is_array( reset( $rows ) ) ) {
620 $sequenceData = $this->getSequenceData( $table );
621 if ( $sequenceData !== false ) {
622 // add sequence column to each list of columns, when not set
623 foreach ( $rows as &$row ) {
624 if ( !isset( $row[$sequenceData['column']] ) ) {
625 $row[$sequenceData['column']] =
626 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
627 $sequenceData['sequence'] . '\')' );
632 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
635 function tableName( $name, $format = 'quoted' ) {
637 Replace reserved words with better ones
638 Using uppercase because that's the only way Oracle can handle
646 $name = 'PAGECONTENT';
650 return strtoupper( parent
::tableName( $name, $format ) );
653 function tableNameInternal( $name ) {
654 $name = $this->tableName( $name );
656 return preg_replace( '/.*\.(.*)/', '$1', $name );
660 * Return the next in a sequence, save the value for retrieval via insertId()
662 * @param string $seqName
665 function nextSequenceValue( $seqName ) {
666 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
667 $row = $this->fetchRow( $res );
668 $this->mInsertId
= $row[0];
670 return $this->mInsertId
;
674 * Return sequence_name if table has a sequence
676 * @param string $table
679 private function getSequenceData( $table ) {
680 if ( $this->sequenceData
== null ) {
681 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
682 lower(atc.table_name),
683 lower(atc.column_name)
684 FROM all_sequences asq, all_tab_columns atc
687 '{$this->mTablePrefix}MWUSER',
688 '{$this->mTablePrefix}USER',
691 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
692 AND asq.sequence_owner = upper('{$this->mDBname}')
693 AND atc.owner = upper('{$this->mDBname}')" );
695 while ( ( $row = $result->fetchRow() ) !== false ) {
696 $this->sequenceData
[$row[1]] = [
697 'sequence' => $row[0],
702 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
704 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
708 * Returns the size of a text field, or -1 for "unlimited"
710 * @param string $table
711 * @param string $field
714 function textFieldSize( $table, $field ) {
715 $fieldInfoData = $this->fieldInfo( $table, $field );
717 return $fieldInfoData->maxLength();
720 function limitResult( $sql, $limit, $offset = false ) {
721 if ( $offset === false ) {
725 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
728 function encodeBlob( $b ) {
729 return new Blob( $b );
732 function decodeBlob( $b ) {
733 if ( $b instanceof Blob
) {
740 function unionQueries( $sqls, $all ) {
741 $glue = ' UNION ALL ';
743 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
744 'FROM (' . implode( $glue, $sqls ) . ')';
747 function wasDeadlock() {
748 return $this->lastErrno() == 'OCI-00060';
751 function duplicateTableStructure( $oldName, $newName, $temporary = false,
754 $temporary = $temporary ?
'TRUE' : 'FALSE';
756 $newName = strtoupper( $newName );
757 $oldName = strtoupper( $oldName );
759 $tabName = substr( $newName, strlen( $this->mTablePrefix
) );
760 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
761 $newPrefix = strtoupper( $this->mTablePrefix
);
763 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
764 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
767 function listTables( $prefix = null, $fname = __METHOD__
) {
769 if ( !empty( $prefix ) ) {
770 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
773 $owner = strtoupper( $this->mDBname
);
774 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
775 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
777 // dirty code ... i know
779 $endArray[] = strtoupper( $prefix . 'MWUSER' );
780 $endArray[] = strtoupper( $prefix . 'PAGE' );
781 $endArray[] = strtoupper( $prefix . 'IMAGE' );
782 $fixedOrderTabs = $endArray;
783 while ( ( $row = $result->fetchRow() ) !== false ) {
784 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
785 $endArray[] = $row['table_name'];
792 public function dropTable( $tableName, $fName = __METHOD__
) {
793 $tableName = $this->tableName( $tableName );
794 if ( !$this->tableExists( $tableName ) ) {
798 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
801 function timestamp( $ts = 0 ) {
802 return wfTimestamp( TS_ORACLE
, $ts );
806 * Return aggregated value function call
808 * @param array $valuedata
809 * @param string $valuename
812 public function aggregateValue( $valuedata, $valuename = 'value' ) {
817 * @return string Wikitext of a link to the server software's web site
819 public function getSoftwareLink() {
820 return '[{{int:version-db-oracle-url}} Oracle]';
824 * @return string Version information from the database
826 function getServerVersion() {
827 // better version number, fallback on driver
828 $rset = $this->doQuery(
829 'SELECT version FROM product_component_version ' .
830 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
832 $row = $rset->fetchRow();
834 return oci_server_version( $this->mConn
);
837 return $row['version'];
841 * Query whether a given index exists
842 * @param string $table
843 * @param string $index
844 * @param string $fname
847 function indexExists( $table, $index, $fname = __METHOD__
) {
848 $table = $this->tableName( $table );
849 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
850 $index = strtoupper( $index );
851 $owner = strtoupper( $this->mDBname
);
852 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
853 $res = $this->doQuery( $sql );
855 $count = $res->numRows();
865 * Query whether a given table exists (in the given schema, or the default mw one if not given)
866 * @param string $table
867 * @param string $fname
870 function tableExists( $table, $fname = __METHOD__
) {
871 $table = $this->tableName( $table );
872 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
873 $owner = $this->addQuotes( strtoupper( $this->mDBname
) );
874 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
875 $res = $this->doQuery( $sql );
876 if ( $res && $res->numRows() > 0 ) {
888 * Function translates mysql_fetch_field() functionality on ORACLE.
889 * Caching is present for reducing query time.
890 * For internal calls. Use fieldInfo for normal usage.
891 * Returns false if the field doesn't exist
893 * @param array|string $table
894 * @param string $field
895 * @return ORAField|ORAResult|false
897 private function fieldInfoMulti( $table, $field ) {
898 $field = strtoupper( $field );
899 if ( is_array( $table ) ) {
900 $table = array_map( [ $this, 'tableNameInternal' ], $table );
901 $tableWhere = 'IN (';
902 foreach ( $table as &$singleTable ) {
903 $singleTable = $this->removeIdentifierQuotes( $singleTable );
904 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
905 return $this->mFieldInfoCache
["$singleTable.$field"];
907 $tableWhere .= '\'' . $singleTable . '\',';
909 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
911 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
912 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
913 return $this->mFieldInfoCache
["$table.$field"];
915 $tableWhere = '= \'' . $table . '\'';
918 $fieldInfoStmt = oci_parse(
920 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
921 $tableWhere . ' and column_name = \'' . $field . '\''
923 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
924 $e = oci_error( $fieldInfoStmt );
925 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
929 $res = new ORAResult( $this, $fieldInfoStmt );
930 if ( $res->numRows() == 0 ) {
931 if ( is_array( $table ) ) {
932 foreach ( $table as &$singleTable ) {
933 $this->mFieldInfoCache
["$singleTable.$field"] = false;
936 $this->mFieldInfoCache
["$table.$field"] = false;
938 $fieldInfoTemp = null;
940 $fieldInfoTemp = new ORAField( $res->fetchRow() );
941 $table = $fieldInfoTemp->tableName();
942 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
946 return $fieldInfoTemp;
950 * @throws DBUnexpectedError
951 * @param string $table
952 * @param string $field
955 function fieldInfo( $table, $field ) {
956 if ( is_array( $table ) ) {
957 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
960 return $this->fieldInfoMulti( $table, $field );
963 protected function doBegin( $fname = __METHOD__
) {
964 $this->mTrxLevel
= 1;
965 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
968 protected function doCommit( $fname = __METHOD__
) {
969 if ( $this->mTrxLevel
) {
970 $ret = oci_commit( $this->mConn
);
972 throw new DBUnexpectedError( $this, $this->lastError() );
974 $this->mTrxLevel
= 0;
975 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
979 protected function doRollback( $fname = __METHOD__
) {
980 if ( $this->mTrxLevel
) {
981 oci_rollback( $this->mConn
);
982 $this->mTrxLevel
= 0;
983 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
987 function sourceStream(
989 callable
$lineCallback = null,
990 callable
$resultCallback = null,
991 $fname = __METHOD__
, callable
$inputCallback = null
995 $dollarquote = false;
998 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
999 while ( !feof( $fp ) ) {
1000 if ( $lineCallback ) {
1001 call_user_func( $lineCallback );
1003 $line = trim( fgets( $fp, 1024 ) );
1004 $sl = strlen( $line ) - 1;
1009 if ( '-' == $line[0] && '-' == $line[1] ) {
1013 // Allow dollar quoting for function declarations
1014 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1015 if ( $dollarquote ) {
1016 $dollarquote = false;
1017 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1020 $dollarquote = true;
1022 } elseif ( !$dollarquote ) {
1023 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
1025 $line = substr( $line, 0, $sl );
1035 $cmd = str_replace( ';;', ";", $cmd );
1036 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1037 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1038 $replacements[$defines[2]] = $defines[1];
1041 foreach ( $replacements as $mwVar => $scVar ) {
1042 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1045 $cmd = $this->replaceVars( $cmd );
1046 if ( $inputCallback ) {
1047 call_user_func( $inputCallback, $cmd );
1049 $res = $this->doQuery( $cmd );
1050 if ( $resultCallback ) {
1051 call_user_func( $resultCallback, $res, $this );
1054 if ( false === $res ) {
1055 $err = $this->lastError();
1057 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1069 function selectDB( $db ) {
1070 $this->mDBname
= $db;
1071 if ( $db == null ||
$db == $this->mUser
) {
1074 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1075 $stmt = oci_parse( $this->mConn
, $sql );
1076 MediaWiki\
suppressWarnings();
1077 $success = oci_execute( $stmt );
1078 MediaWiki\restoreWarnings
();
1080 $e = oci_error( $stmt );
1081 if ( $e['code'] != '1435' ) {
1082 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1091 function strencode( $s ) {
1092 return str_replace( "'", "''", $s );
1095 function addQuotes( $s ) {
1097 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1098 $s = $wgContLang->checkTitleEncoding( $s );
1101 return "'" . $this->strencode( $s ) . "'";
1104 public function addIdentifierQuotes( $s ) {
1105 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1112 public function removeIdentifierQuotes( $s ) {
1113 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1116 public function isQuotedIdentifier( $s ) {
1117 return strpos( $s, '/*Q*/' ) !== false;
1120 private function wrapFieldForWhere( $table, &$col, &$val ) {
1123 $col_info = $this->fieldInfoMulti( $table, $col );
1124 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1125 if ( $col_type == 'CLOB' ) {
1126 $col = 'TO_CHAR(' . $col . ')';
1127 $val = $wgContLang->checkTitleEncoding( $val );
1128 } elseif ( $col_type == 'VARCHAR2' ) {
1129 $val = $wgContLang->checkTitleEncoding( $val );
1133 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1135 foreach ( $conds as $col => $val ) {
1136 if ( is_array( $val ) ) {
1137 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1139 if ( is_numeric( $col ) && $parentCol != null ) {
1140 $this->wrapFieldForWhere( $table, $parentCol, $val );
1142 $this->wrapFieldForWhere( $table, $col, $val );
1144 $conds2[$col] = $val;
1151 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1152 $options = [], $join_conds = []
1154 if ( is_array( $conds ) ) {
1155 $conds = $this->wrapConditionsForWhere( $table, $conds );
1158 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1162 * Returns an optional USE INDEX clause to go after the table, and a
1163 * string to go at the end of the query
1165 * @param array $options An associative array of options to be turned into
1166 * an SQL query, valid keys are listed in the function.
1169 function makeSelectOptions( $options ) {
1170 $preLimitTail = $postLimitTail = '';
1174 foreach ( $options as $key => $option ) {
1175 if ( is_numeric( $key ) ) {
1176 $noKeyOptions[$option] = true;
1180 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1182 $preLimitTail .= $this->makeOrderBy( $options );
1184 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1185 $postLimitTail .= ' FOR UPDATE';
1188 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1189 $startOpts .= 'DISTINCT';
1192 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1193 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1198 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1199 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1204 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1207 public function delete( $table, $conds, $fname = __METHOD__
) {
1208 if ( is_array( $conds ) ) {
1209 $conds = $this->wrapConditionsForWhere( $table, $conds );
1211 // a hack for deleting pages, users and images (which have non-nullable FKs)
1212 // all deletions on these tables have transactions so final failure rollbacks these updates
1213 $table = $this->tableName( $table );
1214 if ( $table == $this->tableName( 'user' ) ) {
1215 $this->update( 'archive', [ 'ar_user' => 0 ],
1216 [ 'ar_user' => $conds['user_id'] ], $fname );
1217 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1218 [ 'ipb_user' => $conds['user_id'] ], $fname );
1219 $this->update( 'image', [ 'img_user' => 0 ],
1220 [ 'img_user' => $conds['user_id'] ], $fname );
1221 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1222 [ 'oi_user' => $conds['user_id'] ], $fname );
1223 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1224 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1225 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1226 [ 'fa_user' => $conds['user_id'] ], $fname );
1227 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1228 [ 'us_user' => $conds['user_id'] ], $fname );
1229 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1230 [ 'rc_user' => $conds['user_id'] ], $fname );
1231 $this->update( 'logging', [ 'log_user' => 0 ],
1232 [ 'log_user' => $conds['user_id'] ], $fname );
1233 } elseif ( $table == $this->tableName( 'image' ) ) {
1234 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1235 [ 'oi_name' => $conds['img_name'] ], $fname );
1238 return parent
::delete( $table, $conds, $fname );
1242 * @param string $table
1243 * @param array $values
1244 * @param array $conds
1245 * @param string $fname
1246 * @param array $options
1248 * @throws DBUnexpectedError
1250 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1253 $table = $this->tableName( $table );
1254 $opts = $this->makeUpdateOptions( $options );
1255 $sql = "UPDATE $opts $table SET ";
1258 foreach ( $values as $col => &$val ) {
1259 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1262 $sqlSet = ', ' . $sqlSet;
1269 if ( $conds !== [] && $conds !== '*' ) {
1270 $conds = $this->wrapConditionsForWhere( $table, $conds );
1271 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1274 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
1275 if ( $stmt === false ) {
1276 $e = oci_error( $this->mConn
);
1277 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1281 foreach ( $values as $col => &$val ) {
1282 $col_info = $this->fieldInfoMulti( $table, $col );
1283 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1285 if ( $val === null ) {
1286 // do nothing ... null was inserted in statement creation
1287 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1288 if ( is_object( $val ) ) {
1289 $val = $val->getData();
1292 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1293 $val = '31-12-2030 12:00:00.000000';
1296 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1297 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1298 $e = oci_error( $stmt );
1299 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1304 /** @var OCI_Lob[] $lob */
1305 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
1306 if ( $lob[$col] === false ) {
1307 $e = oci_error( $stmt );
1308 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1311 if ( is_object( $val ) ) {
1312 $val = $val->getData();
1315 if ( $col_type == 'BLOB' ) {
1316 $lob[$col]->writeTemporary( $val );
1317 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1319 $lob[$col]->writeTemporary( $val );
1320 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1325 MediaWiki\
suppressWarnings();
1327 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1328 $e = oci_error( $stmt );
1329 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1330 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1334 $this->mAffectedRows
= oci_num_rows( $stmt );
1337 $this->mAffectedRows
= oci_num_rows( $stmt );
1340 MediaWiki\restoreWarnings
();
1342 if ( isset( $lob ) ) {
1343 foreach ( $lob as $lob_v ) {
1348 if ( !$this->mTrxLevel
) {
1349 oci_commit( $this->mConn
);
1352 return oci_free_statement( $stmt );
1355 function bitNot( $field ) {
1356 // expecting bit-fields smaller than 4bytes
1357 return 'BITNOT(' . $field . ')';
1360 function bitAnd( $fieldLeft, $fieldRight ) {
1361 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1364 function bitOr( $fieldLeft, $fieldRight ) {
1365 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1368 function getDBname() {
1369 return $this->mDBname
;
1372 function getServer() {
1373 return $this->mServer
;
1376 public function buildGroupConcatField(
1377 $delim, $table, $field, $conds = '', $join_conds = []
1379 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1381 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1385 * @param string $field Field or column to cast
1389 public function buildStringCast( $field ) {
1390 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1393 public function getInfinity() {
1394 return '31-12-2030 12:00:00.000000';