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
;
24 use Wikimedia\Rdbms\ResultWrapper
;
29 class DatabaseOracle
extends Database
{
31 protected $mLastResult = null;
33 /** @var int The number of rows affected as an integer */
34 protected $mAffectedRows;
37 private $mInsertId = null;
40 private $ignoreDupValOnIndex = false;
42 /** @var bool|array */
43 private $sequenceData = null;
45 /** @var string Character set for Oracle database */
46 private $defaultCharset = 'AL32UTF8';
49 private $mFieldInfoCache = [];
51 function __construct( array $p ) {
54 if ( $p['tablePrefix'] == 'get from global' ) {
55 $p['tablePrefix'] = $wgDBprefix;
57 $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
58 parent
::__construct( $p );
59 Hooks
::run( 'DatabaseOraclePostInit', [ $this ] );
62 function __destruct() {
63 if ( $this->mOpened
) {
64 MediaWiki\
suppressWarnings();
66 MediaWiki\restoreWarnings
();
74 function implicitGroupby() {
78 function implicitOrderby() {
83 * Usually aborts on failure
84 * @param string $server
86 * @param string $password
87 * @param string $dbName
88 * @throws DBConnectionError
89 * @return resource|null
91 function open( $server, $user, $password, $dbName ) {
92 global $wgDBOracleDRCP;
93 if ( !function_exists( 'oci_connect' ) ) {
94 throw new DBConnectionError(
96 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
97 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
102 $this->mUser
= $user;
103 $this->mPassword
= $password;
104 // changed internal variables functions
105 // mServer now holds the TNS endpoint
106 // mDBname is schema name if different from username
108 // backward compatibillity (server used to be null and TNS was supplied in dbname)
109 $this->mServer
= $dbName;
110 $this->mDBname
= $user;
112 $this->mServer
= $server;
114 $this->mDBname
= $user;
116 $this->mDBname
= $dbName;
120 if ( !strlen( $user ) ) { # e.g. the class is being loaded
124 if ( $wgDBOracleDRCP ) {
125 $this->setFlag( DBO_PERSISTENT
);
128 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
130 MediaWiki\
suppressWarnings();
131 if ( $this->mFlags
& DBO_PERSISTENT
) {
132 $this->mConn
= oci_pconnect(
136 $this->defaultCharset
,
139 } elseif ( $this->mFlags
& DBO_DEFAULT
) {
140 $this->mConn
= oci_new_connect(
144 $this->defaultCharset
,
148 $this->mConn
= oci_connect(
152 $this->defaultCharset
,
156 MediaWiki\restoreWarnings
();
158 if ( $this->mUser
!= $this->mDBname
) {
159 // change current schema in session
160 $this->selectDB( $this->mDBname
);
163 if ( !$this->mConn
) {
164 throw new DBConnectionError( $this, $this->lastError() );
167 $this->mOpened
= true;
169 # removed putenv calls because they interfere with the system globaly
170 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
171 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
172 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
178 * Closes a database connection, if it is open
179 * Returns success, true if already closed
182 protected function closeConnection() {
183 return oci_close( $this->mConn
);
186 function execFlags() {
187 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
190 protected function doQuery( $sql ) {
191 wfDebug( "SQL: [$sql]\n" );
192 if ( !StringUtils
::isUtf8( $sql ) ) {
193 throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
196 // handle some oracle specifics
197 // remove AS column/table/subquery namings
198 if ( !$this->getFlag( DBO_DDLMODE
) ) {
199 $sql = preg_replace( '/ as /i', ' ', $sql );
202 // Oracle has issues with UNION clause if the statement includes LOB fields
203 // So we do a UNION ALL and then filter the results array with array_unique
204 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
205 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
206 // you have to select data from plan table after explain
207 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
211 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
217 MediaWiki\
suppressWarnings();
219 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
220 if ( $stmt === false ) {
221 $e = oci_error( $this->mConn
);
222 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
227 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
228 $e = oci_error( $stmt );
229 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
230 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
236 MediaWiki\restoreWarnings
();
238 if ( $explain_count > 0 ) {
239 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
240 'WHERE statement_id = \'' . $explain_id . '\'' );
241 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
242 return new ORAResult( $this, $stmt, $union_unique );
244 $this->mAffectedRows
= oci_num_rows( $stmt );
250 function queryIgnore( $sql, $fname = '' ) {
251 return $this->query( $sql, $fname, true );
255 * Frees resources associated with the LOB descriptor
256 * @param ResultWrapper|ORAResult $res
258 function freeResult( $res ) {
259 if ( $res instanceof ResultWrapper
) {
267 * @param ResultWrapper|ORAResult $res
270 function fetchObject( $res ) {
271 if ( $res instanceof ResultWrapper
) {
275 return $res->fetchObject();
279 * @param ResultWrapper|ORAResult $res
282 function fetchRow( $res ) {
283 if ( $res instanceof ResultWrapper
) {
287 return $res->fetchRow();
291 * @param ResultWrapper|ORAResult $res
294 function numRows( $res ) {
295 if ( $res instanceof ResultWrapper
) {
299 return $res->numRows();
303 * @param ResultWrapper|ORAResult $res
306 function numFields( $res ) {
307 if ( $res instanceof ResultWrapper
) {
311 return $res->numFields();
314 function fieldName( $stmt, $n ) {
315 return oci_field_name( $stmt, $n );
319 * This must be called after nextSequenceVal
322 function insertId() {
323 return $this->mInsertId
;
330 function dataSeek( $res, $row ) {
331 if ( $res instanceof ORAResult
) {
334 $res->result
->seek( $row );
338 function lastError() {
339 if ( $this->mConn
=== false ) {
342 $e = oci_error( $this->mConn
);
345 return $e['message'];
348 function lastErrno() {
349 if ( $this->mConn
=== false ) {
352 $e = oci_error( $this->mConn
);
358 function affectedRows() {
359 return $this->mAffectedRows
;
363 * Returns information about an index
364 * If errors are explicitly ignored, returns NULL on failure
365 * @param string $table
366 * @param string $index
367 * @param string $fname
370 function indexInfo( $table, $index, $fname = __METHOD__
) {
374 function indexUnique( $table, $index, $fname = __METHOD__
) {
378 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
379 if ( !count( $a ) ) {
383 if ( !is_array( $options ) ) {
384 $options = [ $options ];
387 if ( in_array( 'IGNORE', $options ) ) {
388 $this->ignoreDupValOnIndex
= true;
391 if ( !is_array( reset( $a ) ) ) {
395 foreach ( $a as &$row ) {
396 $this->insertOneRow( $table, $row, $fname );
400 if ( in_array( 'IGNORE', $options ) ) {
401 $this->ignoreDupValOnIndex
= false;
407 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
408 $col_info = $this->fieldInfoMulti( $table, $col );
409 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
412 if ( is_numeric( $col ) ) {
417 } elseif ( $includeCol ) {
421 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
425 if ( $val === 'NULL' ) {
429 if ( $val === null ) {
430 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
443 * @param string $table
445 * @param string $fname
447 * @throws DBUnexpectedError
449 private function insertOneRow( $table, $row, $fname ) {
452 $table = $this->tableName( $table );
453 // "INSERT INTO tables (a, b, c)"
454 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
457 // for each value, append ":key"
459 foreach ( $row as $col => &$val ) {
465 if ( $this->isQuotedIdentifier( $val ) ) {
466 $sql .= $this->removeIdentifierQuotes( $val );
469 $sql .= $this->fieldBindStatement( $table, $col, $val );
474 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
475 if ( $stmt === false ) {
476 $e = oci_error( $this->mConn
);
477 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
481 foreach ( $row as $col => &$val ) {
482 $col_info = $this->fieldInfoMulti( $table, $col );
483 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
485 if ( $val === null ) {
486 // do nothing ... null was inserted in statement creation
487 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
488 if ( is_object( $val ) ) {
489 $val = $val->fetch();
492 // backward compatibility
493 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
494 $val = $this->getInfinity();
497 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
498 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
499 $e = oci_error( $stmt );
500 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
505 /** @var OCI_Lob[] $lob */
506 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
507 if ( $lob[$col] === false ) {
508 $e = oci_error( $stmt );
509 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
512 if ( is_object( $val ) ) {
513 $val = $val->fetch();
516 if ( $col_type == 'BLOB' ) {
517 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
518 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
520 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
521 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
526 MediaWiki\
suppressWarnings();
528 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
529 $e = oci_error( $stmt );
530 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
531 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
535 $this->mAffectedRows
= oci_num_rows( $stmt );
538 $this->mAffectedRows
= oci_num_rows( $stmt );
541 MediaWiki\restoreWarnings
();
543 if ( isset( $lob ) ) {
544 foreach ( $lob as $lob_v ) {
549 if ( !$this->mTrxLevel
) {
550 oci_commit( $this->mConn
);
553 return oci_free_statement( $stmt );
556 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
557 $insertOptions = [], $selectOptions = []
559 $destTable = $this->tableName( $destTable );
560 if ( !is_array( $selectOptions ) ) {
561 $selectOptions = [ $selectOptions ];
563 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) =
564 $this->makeSelectOptions( $selectOptions );
565 if ( is_array( $srcTable ) ) {
566 $srcTable = implode( ',', array_map( [ $this, 'tableName' ], $srcTable ) );
568 $srcTable = $this->tableName( $srcTable );
571 $sequenceData = $this->getSequenceData( $destTable );
572 if ( $sequenceData !== false &&
573 !isset( $varMap[$sequenceData['column']] )
575 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
578 // count-alias subselect fields to avoid abigious definition errors
580 foreach ( $varMap as &$val ) {
581 $val = $val . ' field' . ( $i++
);
584 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
585 " SELECT $startOpts " . implode( ',', $varMap ) .
586 " FROM $srcTable $useIndex $ignoreIndex ";
587 if ( $conds != '*' ) {
588 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
590 $sql .= " $tailOpts";
592 if ( in_array( 'IGNORE', $insertOptions ) ) {
593 $this->ignoreDupValOnIndex
= true;
596 $retval = $this->query( $sql, $fname );
598 if ( in_array( 'IGNORE', $insertOptions ) ) {
599 $this->ignoreDupValOnIndex
= false;
605 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
608 if ( !count( $rows ) ) {
609 return true; // nothing to do
612 if ( !is_array( reset( $rows ) ) ) {
616 $sequenceData = $this->getSequenceData( $table );
617 if ( $sequenceData !== false ) {
618 // add sequence column to each list of columns, when not set
619 foreach ( $rows as &$row ) {
620 if ( !isset( $row[$sequenceData['column']] ) ) {
621 $row[$sequenceData['column']] =
622 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
623 $sequenceData['sequence'] . '\')' );
628 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
631 function tableName( $name, $format = 'quoted' ) {
633 Replace reserved words with better ones
634 Using uppercase because that's the only way Oracle can handle
642 $name = 'PAGECONTENT';
646 return strtoupper( parent
::tableName( $name, $format ) );
649 function tableNameInternal( $name ) {
650 $name = $this->tableName( $name );
652 return preg_replace( '/.*\.(.*)/', '$1', $name );
656 * Return the next in a sequence, save the value for retrieval via insertId()
658 * @param string $seqName
661 function nextSequenceValue( $seqName ) {
662 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
663 $row = $this->fetchRow( $res );
664 $this->mInsertId
= $row[0];
666 return $this->mInsertId
;
670 * Return sequence_name if table has a sequence
672 * @param string $table
675 private function getSequenceData( $table ) {
676 if ( $this->sequenceData
== null ) {
677 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
678 lower(atc.table_name),
679 lower(atc.column_name)
680 FROM all_sequences asq, all_tab_columns atc
683 '{$this->mTablePrefix}MWUSER',
684 '{$this->mTablePrefix}USER',
687 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
688 AND asq.sequence_owner = upper('{$this->mDBname}')
689 AND atc.owner = upper('{$this->mDBname}')" );
691 while ( ( $row = $result->fetchRow() ) !== false ) {
692 $this->sequenceData
[$row[1]] = [
693 'sequence' => $row[0],
698 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
700 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
704 * Returns the size of a text field, or -1 for "unlimited"
706 * @param string $table
707 * @param string $field
710 function textFieldSize( $table, $field ) {
711 $fieldInfoData = $this->fieldInfo( $table, $field );
713 return $fieldInfoData->maxLength();
716 function limitResult( $sql, $limit, $offset = false ) {
717 if ( $offset === false ) {
721 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
724 function encodeBlob( $b ) {
725 return new Blob( $b );
728 function decodeBlob( $b ) {
729 if ( $b instanceof Blob
) {
736 function unionQueries( $sqls, $all ) {
737 $glue = ' UNION ALL ';
739 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
740 'FROM (' . implode( $glue, $sqls ) . ')';
743 function wasDeadlock() {
744 return $this->lastErrno() == 'OCI-00060';
747 function duplicateTableStructure( $oldName, $newName, $temporary = false,
750 $temporary = $temporary ?
'TRUE' : 'FALSE';
752 $newName = strtoupper( $newName );
753 $oldName = strtoupper( $oldName );
755 $tabName = substr( $newName, strlen( $this->mTablePrefix
) );
756 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
757 $newPrefix = strtoupper( $this->mTablePrefix
);
759 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
760 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
763 function listTables( $prefix = null, $fname = __METHOD__
) {
765 if ( !empty( $prefix ) ) {
766 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
769 $owner = strtoupper( $this->mDBname
);
770 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
771 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
773 // dirty code ... i know
775 $endArray[] = strtoupper( $prefix . 'MWUSER' );
776 $endArray[] = strtoupper( $prefix . 'PAGE' );
777 $endArray[] = strtoupper( $prefix . 'IMAGE' );
778 $fixedOrderTabs = $endArray;
779 while ( ( $row = $result->fetchRow() ) !== false ) {
780 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
781 $endArray[] = $row['table_name'];
788 public function dropTable( $tableName, $fName = __METHOD__
) {
789 $tableName = $this->tableName( $tableName );
790 if ( !$this->tableExists( $tableName ) ) {
794 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
797 function timestamp( $ts = 0 ) {
798 return wfTimestamp( TS_ORACLE
, $ts );
802 * Return aggregated value function call
804 * @param array $valuedata
805 * @param string $valuename
808 public function aggregateValue( $valuedata, $valuename = 'value' ) {
813 * @return string Wikitext of a link to the server software's web site
815 public function getSoftwareLink() {
816 return '[{{int:version-db-oracle-url}} Oracle]';
820 * @return string Version information from the database
822 function getServerVersion() {
823 // better version number, fallback on driver
824 $rset = $this->doQuery(
825 'SELECT version FROM product_component_version ' .
826 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
828 $row = $rset->fetchRow();
830 return oci_server_version( $this->mConn
);
833 return $row['version'];
837 * Query whether a given index exists
838 * @param string $table
839 * @param string $index
840 * @param string $fname
843 function indexExists( $table, $index, $fname = __METHOD__
) {
844 $table = $this->tableName( $table );
845 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
846 $index = strtoupper( $index );
847 $owner = strtoupper( $this->mDBname
);
848 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
849 $res = $this->doQuery( $sql );
851 $count = $res->numRows();
861 * Query whether a given table exists (in the given schema, or the default mw one if not given)
862 * @param string $table
863 * @param string $fname
866 function tableExists( $table, $fname = __METHOD__
) {
867 $table = $this->tableName( $table );
868 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
869 $owner = $this->addQuotes( strtoupper( $this->mDBname
) );
870 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
871 $res = $this->doQuery( $sql );
872 if ( $res && $res->numRows() > 0 ) {
884 * Function translates mysql_fetch_field() functionality on ORACLE.
885 * Caching is present for reducing query time.
886 * For internal calls. Use fieldInfo for normal usage.
887 * Returns false if the field doesn't exist
889 * @param array|string $table
890 * @param string $field
891 * @return ORAField|ORAResult|false
893 private function fieldInfoMulti( $table, $field ) {
894 $field = strtoupper( $field );
895 if ( is_array( $table ) ) {
896 $table = array_map( [ $this, 'tableNameInternal' ], $table );
897 $tableWhere = 'IN (';
898 foreach ( $table as &$singleTable ) {
899 $singleTable = $this->removeIdentifierQuotes( $singleTable );
900 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
901 return $this->mFieldInfoCache
["$singleTable.$field"];
903 $tableWhere .= '\'' . $singleTable . '\',';
905 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
907 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
908 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
909 return $this->mFieldInfoCache
["$table.$field"];
911 $tableWhere = '= \'' . $table . '\'';
914 $fieldInfoStmt = oci_parse(
916 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
917 $tableWhere . ' and column_name = \'' . $field . '\''
919 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
920 $e = oci_error( $fieldInfoStmt );
921 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
925 $res = new ORAResult( $this, $fieldInfoStmt );
926 if ( $res->numRows() == 0 ) {
927 if ( is_array( $table ) ) {
928 foreach ( $table as &$singleTable ) {
929 $this->mFieldInfoCache
["$singleTable.$field"] = false;
932 $this->mFieldInfoCache
["$table.$field"] = false;
934 $fieldInfoTemp = null;
936 $fieldInfoTemp = new ORAField( $res->fetchRow() );
937 $table = $fieldInfoTemp->tableName();
938 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
942 return $fieldInfoTemp;
946 * @throws DBUnexpectedError
947 * @param string $table
948 * @param string $field
951 function fieldInfo( $table, $field ) {
952 if ( is_array( $table ) ) {
953 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
956 return $this->fieldInfoMulti( $table, $field );
959 protected function doBegin( $fname = __METHOD__
) {
960 $this->mTrxLevel
= 1;
961 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
964 protected function doCommit( $fname = __METHOD__
) {
965 if ( $this->mTrxLevel
) {
966 $ret = oci_commit( $this->mConn
);
968 throw new DBUnexpectedError( $this, $this->lastError() );
970 $this->mTrxLevel
= 0;
971 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
975 protected function doRollback( $fname = __METHOD__
) {
976 if ( $this->mTrxLevel
) {
977 oci_rollback( $this->mConn
);
978 $this->mTrxLevel
= 0;
979 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
983 function sourceStream(
985 callable
$lineCallback = null,
986 callable
$resultCallback = null,
987 $fname = __METHOD__
, callable
$inputCallback = null
991 $dollarquote = false;
994 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
995 while ( !feof( $fp ) ) {
996 if ( $lineCallback ) {
997 call_user_func( $lineCallback );
999 $line = trim( fgets( $fp, 1024 ) );
1000 $sl = strlen( $line ) - 1;
1005 if ( '-' == $line[0] && '-' == $line[1] ) {
1009 // Allow dollar quoting for function declarations
1010 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1011 if ( $dollarquote ) {
1012 $dollarquote = false;
1013 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1016 $dollarquote = true;
1018 } elseif ( !$dollarquote ) {
1019 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
1021 $line = substr( $line, 0, $sl );
1031 $cmd = str_replace( ';;', ";", $cmd );
1032 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1033 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1034 $replacements[$defines[2]] = $defines[1];
1037 foreach ( $replacements as $mwVar => $scVar ) {
1038 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1041 $cmd = $this->replaceVars( $cmd );
1042 if ( $inputCallback ) {
1043 call_user_func( $inputCallback, $cmd );
1045 $res = $this->doQuery( $cmd );
1046 if ( $resultCallback ) {
1047 call_user_func( $resultCallback, $res, $this );
1050 if ( false === $res ) {
1051 $err = $this->lastError();
1053 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1065 function selectDB( $db ) {
1066 $this->mDBname
= $db;
1067 if ( $db == null ||
$db == $this->mUser
) {
1070 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1071 $stmt = oci_parse( $this->mConn
, $sql );
1072 MediaWiki\
suppressWarnings();
1073 $success = oci_execute( $stmt );
1074 MediaWiki\restoreWarnings
();
1076 $e = oci_error( $stmt );
1077 if ( $e['code'] != '1435' ) {
1078 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1087 function strencode( $s ) {
1088 return str_replace( "'", "''", $s );
1091 function addQuotes( $s ) {
1093 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1094 $s = $wgContLang->checkTitleEncoding( $s );
1097 return "'" . $this->strencode( $s ) . "'";
1100 public function addIdentifierQuotes( $s ) {
1101 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1108 public function removeIdentifierQuotes( $s ) {
1109 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1112 public function isQuotedIdentifier( $s ) {
1113 return strpos( $s, '/*Q*/' ) !== false;
1116 private function wrapFieldForWhere( $table, &$col, &$val ) {
1119 $col_info = $this->fieldInfoMulti( $table, $col );
1120 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1121 if ( $col_type == 'CLOB' ) {
1122 $col = 'TO_CHAR(' . $col . ')';
1123 $val = $wgContLang->checkTitleEncoding( $val );
1124 } elseif ( $col_type == 'VARCHAR2' ) {
1125 $val = $wgContLang->checkTitleEncoding( $val );
1129 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1131 foreach ( $conds as $col => $val ) {
1132 if ( is_array( $val ) ) {
1133 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1135 if ( is_numeric( $col ) && $parentCol != null ) {
1136 $this->wrapFieldForWhere( $table, $parentCol, $val );
1138 $this->wrapFieldForWhere( $table, $col, $val );
1140 $conds2[$col] = $val;
1147 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1148 $options = [], $join_conds = []
1150 if ( is_array( $conds ) ) {
1151 $conds = $this->wrapConditionsForWhere( $table, $conds );
1154 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1158 * Returns an optional USE INDEX clause to go after the table, and a
1159 * string to go at the end of the query
1161 * @param array $options An associative array of options to be turned into
1162 * an SQL query, valid keys are listed in the function.
1165 function makeSelectOptions( $options ) {
1166 $preLimitTail = $postLimitTail = '';
1170 foreach ( $options as $key => $option ) {
1171 if ( is_numeric( $key ) ) {
1172 $noKeyOptions[$option] = true;
1176 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1178 $preLimitTail .= $this->makeOrderBy( $options );
1180 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1181 $postLimitTail .= ' FOR UPDATE';
1184 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1185 $startOpts .= 'DISTINCT';
1188 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1189 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1194 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1195 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1200 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1203 public function delete( $table, $conds, $fname = __METHOD__
) {
1204 if ( is_array( $conds ) ) {
1205 $conds = $this->wrapConditionsForWhere( $table, $conds );
1207 // a hack for deleting pages, users and images (which have non-nullable FKs)
1208 // all deletions on these tables have transactions so final failure rollbacks these updates
1209 $table = $this->tableName( $table );
1210 if ( $table == $this->tableName( 'user' ) ) {
1211 $this->update( 'archive', [ 'ar_user' => 0 ],
1212 [ 'ar_user' => $conds['user_id'] ], $fname );
1213 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1214 [ 'ipb_user' => $conds['user_id'] ], $fname );
1215 $this->update( 'image', [ 'img_user' => 0 ],
1216 [ 'img_user' => $conds['user_id'] ], $fname );
1217 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1218 [ 'oi_user' => $conds['user_id'] ], $fname );
1219 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1220 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1221 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1222 [ 'fa_user' => $conds['user_id'] ], $fname );
1223 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1224 [ 'us_user' => $conds['user_id'] ], $fname );
1225 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1226 [ 'rc_user' => $conds['user_id'] ], $fname );
1227 $this->update( 'logging', [ 'log_user' => 0 ],
1228 [ 'log_user' => $conds['user_id'] ], $fname );
1229 } elseif ( $table == $this->tableName( 'image' ) ) {
1230 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1231 [ 'oi_name' => $conds['img_name'] ], $fname );
1234 return parent
::delete( $table, $conds, $fname );
1238 * @param string $table
1239 * @param array $values
1240 * @param array $conds
1241 * @param string $fname
1242 * @param array $options
1244 * @throws DBUnexpectedError
1246 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1249 $table = $this->tableName( $table );
1250 $opts = $this->makeUpdateOptions( $options );
1251 $sql = "UPDATE $opts $table SET ";
1254 foreach ( $values as $col => &$val ) {
1255 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1258 $sqlSet = ', ' . $sqlSet;
1265 if ( $conds !== [] && $conds !== '*' ) {
1266 $conds = $this->wrapConditionsForWhere( $table, $conds );
1267 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1270 $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql );
1271 if ( $stmt === false ) {
1272 $e = oci_error( $this->mConn
);
1273 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1277 foreach ( $values as $col => &$val ) {
1278 $col_info = $this->fieldInfoMulti( $table, $col );
1279 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1281 if ( $val === null ) {
1282 // do nothing ... null was inserted in statement creation
1283 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1284 if ( is_object( $val ) ) {
1285 $val = $val->getData();
1288 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1289 $val = '31-12-2030 12:00:00.000000';
1292 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1293 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1294 $e = oci_error( $stmt );
1295 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1300 /** @var OCI_Lob[] $lob */
1301 $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
);
1302 if ( $lob[$col] === false ) {
1303 $e = oci_error( $stmt );
1304 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1307 if ( is_object( $val ) ) {
1308 $val = $val->getData();
1311 if ( $col_type == 'BLOB' ) {
1312 $lob[$col]->writeTemporary( $val );
1313 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1315 $lob[$col]->writeTemporary( $val );
1316 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1321 MediaWiki\
suppressWarnings();
1323 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1324 $e = oci_error( $stmt );
1325 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1326 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1330 $this->mAffectedRows
= oci_num_rows( $stmt );
1333 $this->mAffectedRows
= oci_num_rows( $stmt );
1336 MediaWiki\restoreWarnings
();
1338 if ( isset( $lob ) ) {
1339 foreach ( $lob as $lob_v ) {
1344 if ( !$this->mTrxLevel
) {
1345 oci_commit( $this->mConn
);
1348 return oci_free_statement( $stmt );
1351 function bitNot( $field ) {
1352 // expecting bit-fields smaller than 4bytes
1353 return 'BITNOT(' . $field . ')';
1356 function bitAnd( $fieldLeft, $fieldRight ) {
1357 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1360 function bitOr( $fieldLeft, $fieldRight ) {
1361 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1364 function getDBname() {
1365 return $this->mDBname
;
1368 function getServer() {
1369 return $this->mServer
;
1372 public function buildGroupConcatField(
1373 $delim, $table, $field, $conds = '', $join_conds = []
1375 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1377 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1381 * @param string $field Field or column to cast
1385 public function buildStringCast( $field ) {
1386 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1389 public function getInfinity() {
1390 return '31-12-2030 12:00:00.000000';