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 = array();
37 private function array_unique_md( $array_in ) {
39 $array_hashes = array();
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 DatabaseBase
{
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 = array();
210 function __construct( $p = null ) {
213 if ( !is_array( $p ) ) { // legacy calling pattern
214 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.22" );
215 $args = func_get_args();
217 'host' => isset( $args[0] ) ?
$args[0] : false,
218 'user' => isset( $args[1] ) ?
$args[1] : false,
219 'password' => isset( $args[2] ) ?
$args[2] : false,
220 'dbname' => isset( $args[3] ) ?
$args[3] : false,
221 'flags' => isset( $args[4] ) ?
$args[4] : 0,
222 'tablePrefix' => isset( $args[5] ) ?
$args[5] : 'get from global',
223 'foreign' => isset( $args[6] ) ?
$args[6] : false
226 if ( $p['tablePrefix'] == 'get from global' ) {
227 $p['tablePrefix'] = $wgDBprefix;
229 $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
230 parent
::__construct( $p );
231 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
234 function __destruct() {
235 if ( $this->mOpened
) {
236 wfSuppressWarnings();
246 function cascadingDeletes() {
250 function cleanupTriggers() {
254 function strictIPs() {
258 function realTimestamps() {
262 function implicitGroupby() {
266 function implicitOrderby() {
270 function searchableIPs() {
275 * Usually aborts on failure
276 * @param string $server
277 * @param string $user
278 * @param string $password
279 * @param string $dbName
280 * @throws DBConnectionError
281 * @return DatabaseBase|null
283 function open( $server, $user, $password, $dbName ) {
284 global $wgDBOracleDRCP;
285 if ( !function_exists( 'oci_connect' ) ) {
286 throw new DBConnectionError(
288 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
289 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
294 $this->mUser
= $user;
295 $this->mPassword
= $password;
296 // changed internal variables functions
297 // mServer now holds the TNS endpoint
298 // mDBname is schema name if different from username
300 // backward compatibillity (server used to be null and TNS was supplied in dbname)
301 $this->mServer
= $dbName;
302 $this->mDBname
= $user;
304 $this->mServer
= $server;
306 $this->mDBname
= $user;
308 $this->mDBname
= $dbName;
312 if ( !strlen( $user ) ) { # e.g. the class is being loaded
316 if ( $wgDBOracleDRCP ) {
317 $this->setFlag( DBO_PERSISTENT
);
320 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
322 wfSuppressWarnings();
323 if ( $this->mFlags
& DBO_PERSISTENT
) {
324 $this->mConn
= oci_pconnect(
328 $this->defaultCharset
,
331 } elseif ( $this->mFlags
& DBO_DEFAULT
) {
332 $this->mConn
= oci_new_connect(
336 $this->defaultCharset
,
340 $this->mConn
= oci_connect(
344 $this->defaultCharset
,
350 if ( $this->mUser
!= $this->mDBname
) {
351 //change current schema in session
352 $this->selectDB( $this->mDBname
);
355 if ( !$this->mConn
) {
356 throw new DBConnectionError( $this, $this->lastError() );
359 $this->mOpened
= true;
361 # removed putenv calls because they interfere with the system globaly
362 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
363 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
364 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
370 * Closes a database connection, if it is open
371 * Returns success, true if already closed
374 protected function closeConnection() {
375 return oci_close( $this->mConn
);
378 function execFlags() {
379 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
382 protected function doQuery( $sql ) {
383 wfDebug( "SQL: [$sql]\n" );
384 if ( !StringUtils
::isUtf8( $sql ) ) {
385 throw new MWException( "SQL encoding is invalid\n$sql" );
388 // handle some oracle specifics
389 // remove AS column/table/subquery namings
390 if ( !$this->getFlag( DBO_DDLMODE
) ) {
391 $sql = preg_replace( '/ as /i', ' ', $sql );
394 // Oracle has issues with UNION clause if the statement includes LOB fields
395 // So we do a UNION ALL and then filter the results array with array_unique
396 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
397 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
398 // you have to select data from plan table after explain
399 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
403 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
409 wfSuppressWarnings();
411 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
412 $e = oci_error( $this->mConn
);
413 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
418 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
419 $e = oci_error( $stmt );
420 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
421 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
429 if ( $explain_count > 0 ) {
430 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
431 'WHERE statement_id = \'' . $explain_id . '\'' );
432 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
433 return new ORAResult( $this, $stmt, $union_unique );
435 $this->mAffectedRows
= oci_num_rows( $stmt );
441 function queryIgnore( $sql, $fname = '' ) {
442 return $this->query( $sql, $fname, true );
446 * Frees resources associated with the LOB descriptor
447 * @param ResultWrapper|resource $res
449 function freeResult( $res ) {
450 if ( $res instanceof ResultWrapper
) {
458 * @param ResultWrapper|stdClass $res
461 function fetchObject( $res ) {
462 if ( $res instanceof ResultWrapper
) {
466 return $res->fetchObject();
469 function fetchRow( $res ) {
470 if ( $res instanceof ResultWrapper
) {
474 return $res->fetchRow();
477 function numRows( $res ) {
478 if ( $res instanceof ResultWrapper
) {
482 return $res->numRows();
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 = array() ) {
558 if ( !count( $a ) ) {
562 if ( !is_array( $options ) ) {
563 $options = array( $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 . " (" . join( ',', array_keys( $row ) ) . ')';
636 // for each value, append ":key"
638 foreach ( $row as $col => &$val ) {
645 $sql .= $this->fieldBindStatement( $table, $col, $val );
649 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
650 $e = oci_error( $this->mConn
);
651 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
655 foreach ( $row as $col => &$val ) {
656 $col_info = $this->fieldInfoMulti( $table, $col );
657 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
659 if ( $val === null ) {
660 // do nothing ... null was inserted in statement creation
661 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
662 if ( is_object( $val ) ) {
663 $val = $val->fetch();
666 // backward compatibility
667 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
668 $val = $this->getInfinity();
671 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
672 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
673 $e = oci_error( $stmt );
674 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
679 /** @var OCI_Lob[] $lob */
680 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
681 $e = oci_error( $stmt );
682 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
685 if ( is_object( $val ) ) {
686 $val = $val->fetch();
689 if ( $col_type == 'BLOB' ) {
690 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
691 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
693 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
694 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
699 wfSuppressWarnings();
701 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
702 $e = oci_error( $stmt );
703 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
704 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
708 $this->mAffectedRows
= oci_num_rows( $stmt );
711 $this->mAffectedRows
= oci_num_rows( $stmt );
716 if ( isset( $lob ) ) {
717 foreach ( $lob as $lob_v ) {
722 if ( !$this->mTrxLevel
) {
723 oci_commit( $this->mConn
);
726 oci_free_statement( $stmt );
729 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
730 $insertOptions = array(), $selectOptions = array()
732 $destTable = $this->tableName( $destTable );
733 if ( !is_array( $selectOptions ) ) {
734 $selectOptions = array( $selectOptions );
736 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
737 if ( is_array( $srcTable ) ) {
738 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
740 $srcTable = $this->tableName( $srcTable );
743 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
744 !isset( $varMap[$sequenceData['column']] )
746 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
749 // count-alias subselect fields to avoid abigious definition errors
751 foreach ( $varMap as &$val ) {
752 $val = $val . ' field' . ( $i++
);
755 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
756 " SELECT $startOpts " . implode( ',', $varMap ) .
757 " FROM $srcTable $useIndex ";
758 if ( $conds != '*' ) {
759 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
761 $sql .= " $tailOpts";
763 if ( in_array( 'IGNORE', $insertOptions ) ) {
764 $this->ignoreDupValOnIndex
= true;
767 $retval = $this->query( $sql, $fname );
769 if ( in_array( 'IGNORE', $insertOptions ) ) {
770 $this->ignoreDupValOnIndex
= false;
776 function tableName( $name, $format = 'quoted' ) {
778 Replace reserved words with better ones
779 Using uppercase because that's the only way Oracle can handle
787 $name = 'PAGECONTENT';
791 return strtoupper( parent
::tableName( $name, $format ) );
794 function tableNameInternal( $name ) {
795 $name = $this->tableName( $name );
797 return preg_replace( '/.*\.(.*)/', '$1', $name );
801 * Return the next in a sequence, save the value for retrieval via insertId()
803 * @param string $seqName
806 function nextSequenceValue( $seqName ) {
807 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
808 $row = $this->fetchRow( $res );
809 $this->mInsertId
= $row[0];
811 return $this->mInsertId
;
815 * Return sequence_name if table has a sequence
817 * @param string $table
820 private function getSequenceData( $table ) {
821 if ( $this->sequenceData
== null ) {
822 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
823 lower(atc.table_name),
824 lower(atc.column_name)
825 FROM all_sequences asq, all_tab_columns atc
828 '{$this->mTablePrefix}MWUSER',
829 '{$this->mTablePrefix}USER',
832 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
833 AND asq.sequence_owner = upper('{$this->mDBname}')
834 AND atc.owner = upper('{$this->mDBname}')" );
836 while ( ( $row = $result->fetchRow() ) !== false ) {
837 $this->sequenceData
[$row[1]] = array(
838 'sequence' => $row[0],
843 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
845 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
849 * Returns the size of a text field, or -1 for "unlimited"
851 * @param string $table
852 * @param string $field
855 function textFieldSize( $table, $field ) {
856 $fieldInfoData = $this->fieldInfo( $table, $field );
858 return $fieldInfoData->maxLength();
861 function limitResult( $sql, $limit, $offset = false ) {
862 if ( $offset === false ) {
866 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
869 function encodeBlob( $b ) {
870 return new Blob( $b );
873 function decodeBlob( $b ) {
874 if ( $b instanceof Blob
) {
881 function unionQueries( $sqls, $all ) {
882 $glue = ' UNION ALL ';
884 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
885 'FROM (' . implode( $glue, $sqls ) . ')';
888 function wasDeadlock() {
889 return $this->lastErrno() == 'OCI-00060';
892 function duplicateTableStructure( $oldName, $newName, $temporary = false,
895 $temporary = $temporary ?
'TRUE' : 'FALSE';
897 $newName = strtoupper( $newName );
898 $oldName = strtoupper( $oldName );
900 $tabName = substr( $newName, strlen( $this->mTablePrefix
) );
901 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
902 $newPrefix = strtoupper( $this->mTablePrefix
);
904 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
905 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
908 function listTables( $prefix = null, $fname = __METHOD__
) {
910 if ( !empty( $prefix ) ) {
911 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
914 $owner = strtoupper( $this->mDBname
);
915 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
916 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
918 // dirty code ... i know
920 $endArray[] = strtoupper( $prefix . 'MWUSER' );
921 $endArray[] = strtoupper( $prefix . 'PAGE' );
922 $endArray[] = strtoupper( $prefix . 'IMAGE' );
923 $fixedOrderTabs = $endArray;
924 while ( ( $row = $result->fetchRow() ) !== false ) {
925 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
926 $endArray[] = $row['table_name'];
933 public function dropTable( $tableName, $fName = __METHOD__
) {
934 $tableName = $this->tableName( $tableName );
935 if ( !$this->tableExists( $tableName ) ) {
939 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
942 function timestamp( $ts = 0 ) {
943 return wfTimestamp( TS_ORACLE
, $ts );
947 * Return aggregated value function call
950 * @param string $valuename
953 public function aggregateValue( $valuedata, $valuename = 'value' ) {
957 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
958 # Ignore errors during error handling to avoid infinite
960 $ignore = $this->ignoreErrors( true );
961 ++
$this->mErrorCount
;
963 if ( $ignore ||
$tempIgnore ) {
964 wfDebug( "SQL ERROR (ignored): $error\n" );
965 $this->ignoreErrors( $ignore );
967 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
972 * @return string wikitext of a link to the server software's web site
974 public function getSoftwareLink() {
975 return '[http://www.oracle.com/ Oracle]';
979 * @return string Version information from the database
981 function getServerVersion() {
982 //better version number, fallback on driver
983 $rset = $this->doQuery(
984 'SELECT version FROM product_component_version ' .
985 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
987 if ( !( $row = $rset->fetchRow() ) ) {
988 return oci_server_version( $this->mConn
);
991 return $row['version'];
995 * Query whether a given index exists
996 * @param string $table
997 * @param string $index
998 * @param string $fname
1001 function indexExists( $table, $index, $fname = __METHOD__
) {
1002 $table = $this->tableName( $table );
1003 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
1004 $index = strtoupper( $index );
1005 $owner = strtoupper( $this->mDBname
);
1006 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
1007 $res = $this->doQuery( $SQL );
1009 $count = $res->numRows();
1019 * Query whether a given table exists (in the given schema, or the default mw one if not given)
1020 * @param string $table
1021 * @param string $fname
1024 function tableExists( $table, $fname = __METHOD__
) {
1025 $table = $this->tableName( $table );
1026 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
1027 $owner = $this->addQuotes( strtoupper( $this->mDBname
) );
1028 $SQL = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
1029 $res = $this->doQuery( $SQL );
1030 if ( $res && $res->numRows() > 0 ) {
1042 * Function translates mysql_fetch_field() functionality on ORACLE.
1043 * Caching is present for reducing query time.
1044 * For internal calls. Use fieldInfo for normal usage.
1045 * Returns false if the field doesn't exist
1047 * @param array|string $table
1048 * @param string $field
1049 * @return ORAField|ORAResult
1051 private function fieldInfoMulti( $table, $field ) {
1052 $field = strtoupper( $field );
1053 if ( is_array( $table ) ) {
1054 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
1055 $tableWhere = 'IN (';
1056 foreach ( $table as &$singleTable ) {
1057 $singleTable = $this->removeIdentifierQuotes( $singleTable );
1058 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
1059 return $this->mFieldInfoCache
["$singleTable.$field"];
1061 $tableWhere .= '\'' . $singleTable . '\',';
1063 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
1065 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
1066 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
1067 return $this->mFieldInfoCache
["$table.$field"];
1069 $tableWhere = '= \'' . $table . '\'';
1072 $fieldInfoStmt = oci_parse(
1074 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
1075 $tableWhere . ' and column_name = \'' . $field . '\''
1077 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
1078 $e = oci_error( $fieldInfoStmt );
1079 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
1083 $res = new ORAResult( $this, $fieldInfoStmt );
1084 if ( $res->numRows() == 0 ) {
1085 if ( is_array( $table ) ) {
1086 foreach ( $table as &$singleTable ) {
1087 $this->mFieldInfoCache
["$singleTable.$field"] = false;
1090 $this->mFieldInfoCache
["$table.$field"] = false;
1092 $fieldInfoTemp = null;
1094 $fieldInfoTemp = new ORAField( $res->fetchRow() );
1095 $table = $fieldInfoTemp->tableName();
1096 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
1100 return $fieldInfoTemp;
1104 * @throws DBUnexpectedError
1105 * @param string $table
1106 * @param string $field
1109 function fieldInfo( $table, $field ) {
1110 if ( is_array( $table ) ) {
1111 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
1114 return $this->fieldInfoMulti( $table, $field );
1117 protected function doBegin( $fname = __METHOD__
) {
1118 $this->mTrxLevel
= 1;
1119 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
1122 protected function doCommit( $fname = __METHOD__
) {
1123 if ( $this->mTrxLevel
) {
1124 $ret = oci_commit( $this->mConn
);
1126 throw new DBUnexpectedError( $this, $this->lastError() );
1128 $this->mTrxLevel
= 0;
1129 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1133 protected function doRollback( $fname = __METHOD__
) {
1134 if ( $this->mTrxLevel
) {
1135 oci_rollback( $this->mConn
);
1136 $this->mTrxLevel
= 0;
1137 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1142 * defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
1144 * @param resource $fp
1145 * @param bool|string $lineCallback
1146 * @param bool|callable $resultCallback
1147 * @param string $fname
1148 * @param bool|callable $inputCallback
1149 * @return bool|string
1151 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
1152 $fname = __METHOD__
, $inputCallback = false ) {
1155 $dollarquote = false;
1157 $replacements = array();
1159 while ( !feof( $fp ) ) {
1160 if ( $lineCallback ) {
1161 call_user_func( $lineCallback );
1163 $line = trim( fgets( $fp, 1024 ) );
1164 $sl = strlen( $line ) - 1;
1169 if ( '-' == $line[0] && '-' == $line[1] ) {
1173 // Allow dollar quoting for function declarations
1174 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1175 if ( $dollarquote ) {
1176 $dollarquote = false;
1177 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1180 $dollarquote = true;
1182 } elseif ( !$dollarquote ) {
1183 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
1185 $line = substr( $line, 0, $sl );
1195 $cmd = str_replace( ';;', ";", $cmd );
1196 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1197 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1198 $replacements[$defines[2]] = $defines[1];
1201 foreach ( $replacements as $mwVar => $scVar ) {
1202 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1205 $cmd = $this->replaceVars( $cmd );
1206 if ( $inputCallback ) {
1207 call_user_func( $inputCallback, $cmd );
1209 $res = $this->doQuery( $cmd );
1210 if ( $resultCallback ) {
1211 call_user_func( $resultCallback, $res, $this );
1214 if ( false === $res ) {
1215 $err = $this->lastError();
1217 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1229 function selectDB( $db ) {
1230 $this->mDBname
= $db;
1231 if ( $db == null ||
$db == $this->mUser
) {
1234 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1235 $stmt = oci_parse( $this->mConn
, $sql );
1236 wfSuppressWarnings();
1237 $success = oci_execute( $stmt );
1238 wfRestoreWarnings();
1240 $e = oci_error( $stmt );
1241 if ( $e['code'] != '1435' ) {
1242 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1251 function strencode( $s ) {
1252 return str_replace( "'", "''", $s );
1255 function addQuotes( $s ) {
1257 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1258 $s = $wgContLang->checkTitleEncoding( $s );
1261 return "'" . $this->strencode( $s ) . "'";
1264 public function addIdentifierQuotes( $s ) {
1265 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1272 public function removeIdentifierQuotes( $s ) {
1273 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1276 public function isQuotedIdentifier( $s ) {
1277 return strpos( $s, '/*Q*/' ) !== false;
1280 private function wrapFieldForWhere( $table, &$col, &$val ) {
1283 $col_info = $this->fieldInfoMulti( $table, $col );
1284 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1285 if ( $col_type == 'CLOB' ) {
1286 $col = 'TO_CHAR(' . $col . ')';
1287 $val = $wgContLang->checkTitleEncoding( $val );
1288 } elseif ( $col_type == 'VARCHAR2' ) {
1289 $val = $wgContLang->checkTitleEncoding( $val );
1293 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1295 foreach ( $conds as $col => $val ) {
1296 if ( is_array( $val ) ) {
1297 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1299 if ( is_numeric( $col ) && $parentCol != null ) {
1300 $this->wrapFieldForWhere( $table, $parentCol, $val );
1302 $this->wrapFieldForWhere( $table, $col, $val );
1304 $conds2[$col] = $val;
1311 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1312 $options = array(), $join_conds = array()
1314 if ( is_array( $conds ) ) {
1315 $conds = $this->wrapConditionsForWhere( $table, $conds );
1318 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1322 * Returns an optional USE INDEX clause to go after the table, and a
1323 * string to go at the end of the query
1325 * @param array $options An associative array of options to be turned into
1326 * an SQL query, valid keys are listed in the function.
1329 function makeSelectOptions( $options ) {
1330 $preLimitTail = $postLimitTail = '';
1333 $noKeyOptions = array();
1334 foreach ( $options as $key => $option ) {
1335 if ( is_numeric( $key ) ) {
1336 $noKeyOptions[$option] = true;
1340 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1342 $preLimitTail .= $this->makeOrderBy( $options );
1344 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1345 $postLimitTail .= ' FOR UPDATE';
1348 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1349 $startOpts .= 'DISTINCT';
1352 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1353 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1358 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1361 public function delete( $table, $conds, $fname = __METHOD__
) {
1362 if ( is_array( $conds ) ) {
1363 $conds = $this->wrapConditionsForWhere( $table, $conds );
1365 // a hack for deleting pages, users and images (which have non-nullable FKs)
1366 // all deletions on these tables have transactions so final failure rollbacks these updates
1367 $table = $this->tableName( $table );
1368 if ( $table == $this->tableName( 'user' ) ) {
1369 $this->update( 'archive', array( 'ar_user' => 0 ),
1370 array( 'ar_user' => $conds['user_id'] ), $fname );
1371 $this->update( 'ipblocks', array( 'ipb_user' => 0 ),
1372 array( 'ipb_user' => $conds['user_id'] ), $fname );
1373 $this->update( 'image', array( 'img_user' => 0 ),
1374 array( 'img_user' => $conds['user_id'] ), $fname );
1375 $this->update( 'oldimage', array( 'oi_user' => 0 ),
1376 array( 'oi_user' => $conds['user_id'] ), $fname );
1377 $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ),
1378 array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
1379 $this->update( 'filearchive', array( 'fa_user' => 0 ),
1380 array( 'fa_user' => $conds['user_id'] ), $fname );
1381 $this->update( 'uploadstash', array( 'us_user' => 0 ),
1382 array( 'us_user' => $conds['user_id'] ), $fname );
1383 $this->update( 'recentchanges', array( 'rc_user' => 0 ),
1384 array( 'rc_user' => $conds['user_id'] ), $fname );
1385 $this->update( 'logging', array( 'log_user' => 0 ),
1386 array( 'log_user' => $conds['user_id'] ), $fname );
1387 } elseif ( $table == $this->tableName( 'image' ) ) {
1388 $this->update( 'oldimage', array( 'oi_name' => 0 ),
1389 array( 'oi_name' => $conds['img_name'] ), $fname );
1392 return parent
::delete( $table, $conds, $fname );
1396 * @param string $table
1397 * @param array $values
1398 * @param array $conds
1399 * @param string $fname
1400 * @param array $options
1402 * @throws DBUnexpectedError
1404 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1407 $table = $this->tableName( $table );
1408 $opts = $this->makeUpdateOptions( $options );
1409 $sql = "UPDATE $opts $table SET ";
1412 foreach ( $values as $col => &$val ) {
1413 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1416 $sqlSet = ', ' . $sqlSet;
1423 if ( $conds !== array() && $conds !== '*' ) {
1424 $conds = $this->wrapConditionsForWhere( $table, $conds );
1425 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1428 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1429 $e = oci_error( $this->mConn
);
1430 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1434 foreach ( $values as $col => &$val ) {
1435 $col_info = $this->fieldInfoMulti( $table, $col );
1436 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1438 if ( $val === null ) {
1439 // do nothing ... null was inserted in statement creation
1440 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1441 if ( is_object( $val ) ) {
1442 $val = $val->getData();
1445 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1446 $val = '31-12-2030 12:00:00.000000';
1449 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1450 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1451 $e = oci_error( $stmt );
1452 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1457 /** @var OCI_Lob[] $lob */
1458 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1459 $e = oci_error( $stmt );
1460 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1463 if ( $col_type == 'BLOB' ) {
1464 $lob[$col]->writeTemporary( $val );
1465 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1467 $lob[$col]->writeTemporary( $val );
1468 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1473 wfSuppressWarnings();
1475 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1476 $e = oci_error( $stmt );
1477 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1478 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1482 $this->mAffectedRows
= oci_num_rows( $stmt );
1485 $this->mAffectedRows
= oci_num_rows( $stmt );
1488 wfRestoreWarnings();
1490 if ( isset( $lob ) ) {
1491 foreach ( $lob as $lob_v ) {
1496 if ( !$this->mTrxLevel
) {
1497 oci_commit( $this->mConn
);
1500 oci_free_statement( $stmt );
1503 function bitNot( $field ) {
1504 // expecting bit-fields smaller than 4bytes
1505 return 'BITNOT(' . $field . ')';
1508 function bitAnd( $fieldLeft, $fieldRight ) {
1509 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1512 function bitOr( $fieldLeft, $fieldRight ) {
1513 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1516 function setFakeMaster( $enabled = true ) {
1519 function getDBname() {
1520 return $this->mDBname
;
1523 function getServer() {
1524 return $this->mServer
;
1527 public function buildGroupConcatField(
1528 $delim, $table, $field, $conds = '', $join_conds = array()
1530 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1532 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1535 public function getSearchEngine() {
1536 return 'SearchOracle';
1539 public function getInfinity() {
1540 return '31-12-2030 12:00:00.000000';