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 $db DatabaseBase
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 );
445 function freeResult( $res ) {
446 if ( $res instanceof ResultWrapper
) {
453 function fetchObject( $res ) {
454 if ( $res instanceof ResultWrapper
) {
458 return $res->fetchObject();
461 function fetchRow( $res ) {
462 if ( $res instanceof ResultWrapper
) {
466 return $res->fetchRow();
469 function numRows( $res ) {
470 if ( $res instanceof ResultWrapper
) {
474 return $res->numRows();
477 function numFields( $res ) {
478 if ( $res instanceof ResultWrapper
) {
482 return $res->numFields();
485 function fieldName( $stmt, $n ) {
486 return oci_field_name( $stmt, $n );
490 * This must be called after nextSequenceVal
493 function insertId() {
494 return $this->mInsertId
;
497 function dataSeek( $res, $row ) {
498 if ( $res instanceof ORAResult
) {
501 $res->result
->seek( $row );
505 function lastError() {
506 if ( $this->mConn
=== false ) {
509 $e = oci_error( $this->mConn
);
512 return $e['message'];
515 function lastErrno() {
516 if ( $this->mConn
=== false ) {
519 $e = oci_error( $this->mConn
);
525 function affectedRows() {
526 return $this->mAffectedRows
;
530 * Returns information about an index
531 * If errors are explicitly ignored, returns NULL on failure
534 function indexInfo( $table, $index, $fname = __METHOD__
) {
538 function indexUnique( $table, $index, $fname = __METHOD__
) {
542 function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
543 if ( !count( $a ) ) {
547 if ( !is_array( $options ) ) {
548 $options = array( $options );
551 if ( in_array( 'IGNORE', $options ) ) {
552 $this->ignoreDupValOnIndex
= true;
555 if ( !is_array( reset( $a ) ) ) {
559 foreach ( $a as &$row ) {
560 $this->insertOneRow( $table, $row, $fname );
564 if ( in_array( 'IGNORE', $options ) ) {
565 $this->ignoreDupValOnIndex
= false;
571 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
572 $col_info = $this->fieldInfoMulti( $table, $col );
573 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
576 if ( is_numeric( $col ) ) {
581 } elseif ( $includeCol ) {
585 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
589 if ( $val === 'NULL' ) {
593 if ( $val === null ) {
594 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
606 private function insertOneRow( $table, $row, $fname ) {
609 $table = $this->tableName( $table );
610 // "INSERT INTO tables (a, b, c)"
611 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
614 // for each value, append ":key"
616 foreach ( $row as $col => &$val ) {
623 $sql .= $this->fieldBindStatement( $table, $col, $val );
627 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
628 $e = oci_error( $this->mConn
);
629 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
633 foreach ( $row as $col => &$val ) {
634 $col_info = $this->fieldInfoMulti( $table, $col );
635 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
637 if ( $val === null ) {
638 // do nothing ... null was inserted in statement creation
639 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
640 if ( is_object( $val ) ) {
641 $val = $val->fetch();
644 // backward compatibility
645 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
646 $val = $this->getInfinity();
649 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
650 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
651 $e = oci_error( $stmt );
652 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
657 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
658 $e = oci_error( $stmt );
659 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
662 if ( is_object( $val ) ) {
663 $val = $val->fetch();
666 if ( $col_type == 'BLOB' ) {
667 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
668 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
670 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
671 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
676 wfSuppressWarnings();
678 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
679 $e = oci_error( $stmt );
680 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
681 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
685 $this->mAffectedRows
= oci_num_rows( $stmt );
688 $this->mAffectedRows
= oci_num_rows( $stmt );
693 if ( isset( $lob ) ) {
694 foreach ( $lob as $lob_v ) {
699 if ( !$this->mTrxLevel
) {
700 oci_commit( $this->mConn
);
703 oci_free_statement( $stmt );
706 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
707 $insertOptions = array(), $selectOptions = array()
709 $destTable = $this->tableName( $destTable );
710 if ( !is_array( $selectOptions ) ) {
711 $selectOptions = array( $selectOptions );
713 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
714 if ( is_array( $srcTable ) ) {
715 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
717 $srcTable = $this->tableName( $srcTable );
720 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
721 !isset( $varMap[$sequenceData['column']] )
723 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
726 // count-alias subselect fields to avoid abigious definition errors
728 foreach ( $varMap as &$val ) {
729 $val = $val . ' field' . ( $i++
);
732 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
733 " SELECT $startOpts " . implode( ',', $varMap ) .
734 " FROM $srcTable $useIndex ";
735 if ( $conds != '*' ) {
736 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
738 $sql .= " $tailOpts";
740 if ( in_array( 'IGNORE', $insertOptions ) ) {
741 $this->ignoreDupValOnIndex
= true;
744 $retval = $this->query( $sql, $fname );
746 if ( in_array( 'IGNORE', $insertOptions ) ) {
747 $this->ignoreDupValOnIndex
= false;
753 function tableName( $name, $format = 'quoted' ) {
755 Replace reserved words with better ones
756 Using uppercase because that's the only way Oracle can handle
764 $name = 'PAGECONTENT';
768 return strtoupper( parent
::tableName( $name, $format ) );
771 function tableNameInternal( $name ) {
772 $name = $this->tableName( $name );
774 return preg_replace( '/.*\.(.*)/', '$1', $name );
778 * Return the next in a sequence, save the value for retrieval via insertId()
780 * @param string $seqName
783 function nextSequenceValue( $seqName ) {
784 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
785 $row = $this->fetchRow( $res );
786 $this->mInsertId
= $row[0];
788 return $this->mInsertId
;
792 * Return sequence_name if table has a sequence
794 * @param string $table
797 private function getSequenceData( $table ) {
798 if ( $this->sequenceData
== null ) {
799 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
800 lower(atc.table_name),
801 lower(atc.column_name)
802 FROM all_sequences asq, all_tab_columns atc
805 '{$this->mTablePrefix}MWUSER',
806 '{$this->mTablePrefix}USER',
809 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
810 AND asq.sequence_owner = upper('{$this->mDBname}')
811 AND atc.owner = upper('{$this->mDBname}')" );
813 while ( ( $row = $result->fetchRow() ) !== false ) {
814 $this->sequenceData
[$row[1]] = array(
815 'sequence' => $row[0],
820 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
822 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
825 # Returns the size of a text field, or -1 for "unlimited"
826 function textFieldSize( $table, $field ) {
827 $fieldInfoData = $this->fieldInfo( $table, $field );
829 return $fieldInfoData->maxLength();
832 function limitResult( $sql, $limit, $offset = false ) {
833 if ( $offset === false ) {
837 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
840 function encodeBlob( $b ) {
841 return new Blob( $b );
844 function decodeBlob( $b ) {
845 if ( $b instanceof Blob
) {
852 function unionQueries( $sqls, $all ) {
853 $glue = ' UNION ALL ';
855 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
856 'FROM (' . implode( $glue, $sqls ) . ')';
859 function wasDeadlock() {
860 return $this->lastErrno() == 'OCI-00060';
863 function duplicateTableStructure( $oldName, $newName, $temporary = false,
866 $temporary = $temporary ?
'TRUE' : 'FALSE';
868 $newName = strtoupper( $newName );
869 $oldName = strtoupper( $oldName );
871 $tabName = substr( $newName, strlen( $this->mTablePrefix
) );
872 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
873 $newPrefix = strtoupper( $this->mTablePrefix
);
875 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
876 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
879 function listTables( $prefix = null, $fname = __METHOD__
) {
881 if ( !empty( $prefix ) ) {
882 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
885 $owner = strtoupper( $this->mDBname
);
886 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
887 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
889 // dirty code ... i know
891 $endArray[] = strtoupper( $prefix . 'MWUSER' );
892 $endArray[] = strtoupper( $prefix . 'PAGE' );
893 $endArray[] = strtoupper( $prefix . 'IMAGE' );
894 $fixedOrderTabs = $endArray;
895 while ( ( $row = $result->fetchRow() ) !== false ) {
896 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
897 $endArray[] = $row['table_name'];
904 public function dropTable( $tableName, $fName = __METHOD__
) {
905 $tableName = $this->tableName( $tableName );
906 if ( !$this->tableExists( $tableName ) ) {
910 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
913 function timestamp( $ts = 0 ) {
914 return wfTimestamp( TS_ORACLE
, $ts );
918 * Return aggregated value function call
920 public function aggregateValue( $valuedata, $valuename = 'value' ) {
924 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
925 # Ignore errors during error handling to avoid infinite
927 $ignore = $this->ignoreErrors( true );
928 ++
$this->mErrorCount
;
930 if ( $ignore ||
$tempIgnore ) {
931 wfDebug( "SQL ERROR (ignored): $error\n" );
932 $this->ignoreErrors( $ignore );
934 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
939 * @return string wikitext of a link to the server software's web site
941 public function getSoftwareLink() {
942 return '[http://www.oracle.com/ Oracle]';
946 * @return string Version information from the database
948 function getServerVersion() {
949 //better version number, fallback on driver
950 $rset = $this->doQuery(
951 'SELECT version FROM product_component_version ' .
952 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
954 if ( !( $row = $rset->fetchRow() ) ) {
955 return oci_server_version( $this->mConn
);
958 return $row['version'];
962 * Query whether a given index exists
965 function indexExists( $table, $index, $fname = __METHOD__
) {
966 $table = $this->tableName( $table );
967 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
968 $index = strtoupper( $index );
969 $owner = strtoupper( $this->mDBname
);
970 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
971 $res = $this->doQuery( $SQL );
973 $count = $res->numRows();
983 * Query whether a given table exists (in the given schema, or the default mw one if not given)
986 function tableExists( $table, $fname = __METHOD__
) {
987 $table = $this->tableName( $table );
988 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
989 $owner = $this->addQuotes( strtoupper( $this->mDBname
) );
990 $SQL = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
991 $res = $this->doQuery( $SQL );
992 if ( $res && $res->numRows() > 0 ) {
1004 * Function translates mysql_fetch_field() functionality on ORACLE.
1005 * Caching is present for reducing query time.
1006 * For internal calls. Use fieldInfo for normal usage.
1007 * Returns false if the field doesn't exist
1009 * @param $table Array
1010 * @param $field String
1011 * @return ORAField|ORAResult
1013 private function fieldInfoMulti( $table, $field ) {
1014 $field = strtoupper( $field );
1015 if ( is_array( $table ) ) {
1016 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
1017 $tableWhere = 'IN (';
1018 foreach ( $table as &$singleTable ) {
1019 $singleTable = $this->removeIdentifierQuotes( $singleTable );
1020 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
1021 return $this->mFieldInfoCache
["$singleTable.$field"];
1023 $tableWhere .= '\'' . $singleTable . '\',';
1025 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
1027 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
1028 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
1029 return $this->mFieldInfoCache
["$table.$field"];
1031 $tableWhere = '= \'' . $table . '\'';
1034 $fieldInfoStmt = oci_parse(
1036 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
1037 $tableWhere . ' and column_name = \'' . $field . '\''
1039 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
1040 $e = oci_error( $fieldInfoStmt );
1041 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
1045 $res = new ORAResult( $this, $fieldInfoStmt );
1046 if ( $res->numRows() == 0 ) {
1047 if ( is_array( $table ) ) {
1048 foreach ( $table as &$singleTable ) {
1049 $this->mFieldInfoCache
["$singleTable.$field"] = false;
1052 $this->mFieldInfoCache
["$table.$field"] = false;
1054 $fieldInfoTemp = null;
1056 $fieldInfoTemp = new ORAField( $res->fetchRow() );
1057 $table = $fieldInfoTemp->tableName();
1058 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
1062 return $fieldInfoTemp;
1066 * @throws DBUnexpectedError
1071 function fieldInfo( $table, $field ) {
1072 if ( is_array( $table ) ) {
1073 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
1076 return $this->fieldInfoMulti( $table, $field );
1079 protected function doBegin( $fname = __METHOD__
) {
1080 $this->mTrxLevel
= 1;
1081 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
1084 protected function doCommit( $fname = __METHOD__
) {
1085 if ( $this->mTrxLevel
) {
1086 $ret = oci_commit( $this->mConn
);
1088 throw new DBUnexpectedError( $this, $this->lastError() );
1090 $this->mTrxLevel
= 0;
1091 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1095 protected function doRollback( $fname = __METHOD__
) {
1096 if ( $this->mTrxLevel
) {
1097 oci_rollback( $this->mConn
);
1098 $this->mTrxLevel
= 0;
1099 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1103 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
1104 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
1105 $fname = __METHOD__
, $inputCallback = false ) {
1108 $dollarquote = false;
1110 $replacements = array();
1112 while ( !feof( $fp ) ) {
1113 if ( $lineCallback ) {
1114 call_user_func( $lineCallback );
1116 $line = trim( fgets( $fp, 1024 ) );
1117 $sl = strlen( $line ) - 1;
1122 if ( '-' == $line[0] && '-' == $line[1] ) {
1126 // Allow dollar quoting for function declarations
1127 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1128 if ( $dollarquote ) {
1129 $dollarquote = false;
1130 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1133 $dollarquote = true;
1135 } elseif ( !$dollarquote ) {
1136 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
1138 $line = substr( $line, 0, $sl );
1148 $cmd = str_replace( ';;', ";", $cmd );
1149 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1150 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1151 $replacements[$defines[2]] = $defines[1];
1154 foreach ( $replacements as $mwVar => $scVar ) {
1155 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1158 $cmd = $this->replaceVars( $cmd );
1159 if ( $inputCallback ) {
1160 call_user_func( $inputCallback, $cmd );
1162 $res = $this->doQuery( $cmd );
1163 if ( $resultCallback ) {
1164 call_user_func( $resultCallback, $res, $this );
1167 if ( false === $res ) {
1168 $err = $this->lastError();
1170 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1182 function selectDB( $db ) {
1183 $this->mDBname
= $db;
1184 if ( $db == null ||
$db == $this->mUser
) {
1187 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1188 $stmt = oci_parse( $this->mConn
, $sql );
1189 wfSuppressWarnings();
1190 $success = oci_execute( $stmt );
1191 wfRestoreWarnings();
1193 $e = oci_error( $stmt );
1194 if ( $e['code'] != '1435' ) {
1195 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1204 function strencode( $s ) {
1205 return str_replace( "'", "''", $s );
1208 function addQuotes( $s ) {
1210 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1211 $s = $wgContLang->checkTitleEncoding( $s );
1214 return "'" . $this->strencode( $s ) . "'";
1217 public function addIdentifierQuotes( $s ) {
1218 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1225 public function removeIdentifierQuotes( $s ) {
1226 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1229 public function isQuotedIdentifier( $s ) {
1230 return strpos( $s, '/*Q*/' ) !== false;
1233 private function wrapFieldForWhere( $table, &$col, &$val ) {
1236 $col_info = $this->fieldInfoMulti( $table, $col );
1237 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1238 if ( $col_type == 'CLOB' ) {
1239 $col = 'TO_CHAR(' . $col . ')';
1240 $val = $wgContLang->checkTitleEncoding( $val );
1241 } elseif ( $col_type == 'VARCHAR2' ) {
1242 $val = $wgContLang->checkTitleEncoding( $val );
1246 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1248 foreach ( $conds as $col => $val ) {
1249 if ( is_array( $val ) ) {
1250 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1252 if ( is_numeric( $col ) && $parentCol != null ) {
1253 $this->wrapFieldForWhere( $table, $parentCol, $val );
1255 $this->wrapFieldForWhere( $table, $col, $val );
1257 $conds2[$col] = $val;
1264 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1265 $options = array(), $join_conds = array()
1267 if ( is_array( $conds ) ) {
1268 $conds = $this->wrapConditionsForWhere( $table, $conds );
1271 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1275 * Returns an optional USE INDEX clause to go after the table, and a
1276 * string to go at the end of the query
1280 * @param array $options an associative array of options to be turned into
1281 * an SQL query, valid keys are listed in the function.
1284 function makeSelectOptions( $options ) {
1285 $preLimitTail = $postLimitTail = '';
1288 $noKeyOptions = array();
1289 foreach ( $options as $key => $option ) {
1290 if ( is_numeric( $key ) ) {
1291 $noKeyOptions[$option] = true;
1295 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1297 $preLimitTail .= $this->makeOrderBy( $options );
1299 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1300 $postLimitTail .= ' FOR UPDATE';
1303 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1304 $startOpts .= 'DISTINCT';
1307 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1308 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1313 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1316 public function delete( $table, $conds, $fname = __METHOD__
) {
1317 if ( is_array( $conds ) ) {
1318 $conds = $this->wrapConditionsForWhere( $table, $conds );
1320 // a hack for deleting pages, users and images (which have non-nullable FKs)
1321 // all deletions on these tables have transactions so final failure rollbacks these updates
1322 $table = $this->tableName( $table );
1323 if ( $table == $this->tableName( 'user' ) ) {
1324 $this->update( 'archive', array( 'ar_user' => 0 ),
1325 array( 'ar_user' => $conds['user_id'] ), $fname );
1326 $this->update( 'ipblocks', array( 'ipb_user' => 0 ),
1327 array( 'ipb_user' => $conds['user_id'] ), $fname );
1328 $this->update( 'image', array( 'img_user' => 0 ),
1329 array( 'img_user' => $conds['user_id'] ), $fname );
1330 $this->update( 'oldimage', array( 'oi_user' => 0 ),
1331 array( 'oi_user' => $conds['user_id'] ), $fname );
1332 $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ),
1333 array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
1334 $this->update( 'filearchive', array( 'fa_user' => 0 ),
1335 array( 'fa_user' => $conds['user_id'] ), $fname );
1336 $this->update( 'uploadstash', array( 'us_user' => 0 ),
1337 array( 'us_user' => $conds['user_id'] ), $fname );
1338 $this->update( 'recentchanges', array( 'rc_user' => 0 ),
1339 array( 'rc_user' => $conds['user_id'] ), $fname );
1340 $this->update( 'logging', array( 'log_user' => 0 ),
1341 array( 'log_user' => $conds['user_id'] ), $fname );
1342 } elseif ( $table == $this->tableName( 'image' ) ) {
1343 $this->update( 'oldimage', array( 'oi_name' => 0 ),
1344 array( 'oi_name' => $conds['img_name'] ), $fname );
1347 return parent
::delete( $table, $conds, $fname );
1350 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1353 $table = $this->tableName( $table );
1354 $opts = $this->makeUpdateOptions( $options );
1355 $sql = "UPDATE $opts $table SET ";
1358 foreach ( $values as $col => &$val ) {
1359 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1362 $sqlSet = ', ' . $sqlSet;
1369 if ( $conds !== array() && $conds !== '*' ) {
1370 $conds = $this->wrapConditionsForWhere( $table, $conds );
1371 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1374 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1375 $e = oci_error( $this->mConn
);
1376 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1380 foreach ( $values as $col => &$val ) {
1381 $col_info = $this->fieldInfoMulti( $table, $col );
1382 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1384 if ( $val === null ) {
1385 // do nothing ... null was inserted in statement creation
1386 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1387 if ( is_object( $val ) ) {
1388 $val = $val->getData();
1391 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1392 $val = '31-12-2030 12:00:00.000000';
1395 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1396 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1397 $e = oci_error( $stmt );
1398 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1403 /** @var OCI_Lob[] $lob */
1404 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1405 $e = oci_error( $stmt );
1406 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1409 if ( $col_type == 'BLOB' ) {
1410 $lob[$col]->writeTemporary( $val );
1411 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1413 $lob[$col]->writeTemporary( $val );
1414 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1419 wfSuppressWarnings();
1421 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1422 $e = oci_error( $stmt );
1423 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1424 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1428 $this->mAffectedRows
= oci_num_rows( $stmt );
1431 $this->mAffectedRows
= oci_num_rows( $stmt );
1434 wfRestoreWarnings();
1436 if ( isset( $lob ) ) {
1437 foreach ( $lob as $lob_v ) {
1442 if ( !$this->mTrxLevel
) {
1443 oci_commit( $this->mConn
);
1446 oci_free_statement( $stmt );
1449 function bitNot( $field ) {
1450 // expecting bit-fields smaller than 4bytes
1451 return 'BITNOT(' . $field . ')';
1454 function bitAnd( $fieldLeft, $fieldRight ) {
1455 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1458 function bitOr( $fieldLeft, $fieldRight ) {
1459 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1462 function setFakeMaster( $enabled = true ) {
1465 function getDBname() {
1466 return $this->mDBname
;
1469 function getServer() {
1470 return $this->mServer
;
1473 public function buildGroupConcatField(
1474 $delim, $table, $field, $conds = '', $join_conds = array()
1476 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1478 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1481 public function getSearchEngine() {
1482 return 'SearchOracle';
1485 public function getInfinity() {
1486 return '31-12-2030 12:00:00.000000';
1488 } // end DatabaseOracle class