3 * This is the Oracle database abstraction layer.
10 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
11 * other things. We use a wrapper class to handle that and other
12 * Oracle-specific bits, like converting column names back to lowercase.
20 private $columns = array();
22 private function array_unique_md( $array_in ) {
24 $array_hashes = array();
26 foreach ( $array_in as $item ) {
27 $hash = md5( serialize( $item ) );
28 if ( !isset( $array_hashes[$hash] ) ) {
29 $array_hashes[$hash] = $hash;
38 * @param $db DatabaseBase
42 function __construct( &$db, $stmt, $unique = false ) {
45 if ( ( $this->nrows
= oci_fetch_all( $stmt, $this->rows
, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM
) ) === false ) {
46 $e = oci_error( $stmt );
47 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__
);
53 $this->rows
= $this->array_unique_md( $this->rows
);
54 $this->nrows
= count( $this->rows
);
57 if ($this->nrows
> 0) {
58 foreach ( $this->rows
[0] as $k => $v ) {
59 $this->columns
[$k] = strtolower( oci_field_name( $stmt, $k +
1 ) );
64 oci_free_statement( $stmt );
67 public function free() {
71 public function seek( $row ) {
72 $this->cursor
= min( $row, $this->nrows
);
75 public function numRows() {
79 public function numFields() {
80 return count($this->columns
);
83 public function fetchObject() {
84 if ( $this->cursor
>= $this->nrows
) {
87 $row = $this->rows
[$this->cursor++
];
88 $ret = new stdClass();
89 foreach ( $row as $k => $v ) {
90 $lc = $this->columns
[$k];
97 public function fetchRow() {
98 if ( $this->cursor
>= $this->nrows
) {
102 $row = $this->rows
[$this->cursor++
];
104 foreach ( $row as $k => $v ) {
105 $lc = $this->columns
[$k];
117 class ORAField
implements Field
{
118 private $name, $tablename, $default, $max_length, $nullable,
119 $is_pk, $is_unique, $is_multiple, $is_key, $type;
121 function __construct( $info ) {
122 $this->name
= $info['column_name'];
123 $this->tablename
= $info['table_name'];
124 $this->default = $info['data_default'];
125 $this->max_length
= $info['data_length'];
126 $this->nullable
= $info['not_null'];
127 $this->is_pk
= isset( $info['prim'] ) && $info['prim'] == 1 ?
1 : 0;
128 $this->is_unique
= isset( $info['uniq'] ) && $info['uniq'] == 1 ?
1 : 0;
129 $this->is_multiple
= isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ?
1 : 0;
130 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
131 $this->type
= $info['data_type'];
138 function tableName() {
139 return $this->tablename
;
142 function defaultValue() {
143 return $this->default;
146 function maxLength() {
147 return $this->max_length
;
150 function isNullable() {
151 return $this->nullable
;
155 return $this->is_key
;
158 function isMultipleKey() {
159 return $this->is_multiple
;
170 class DatabaseOracle
extends DatabaseBase
{
171 var $mInsertId = null;
172 var $mLastResult = null;
173 var $lastResult = null;
177 var $ignore_DUP_VAL_ON_INDEX = false;
178 var $sequenceData = null;
180 var $defaultCharset = 'AL32UTF8';
182 var $mFieldInfoCache = array();
184 function __construct( $server = false, $user = false, $password = false, $dbName = false,
185 $flags = 0, $tablePrefix = 'get from global' )
188 $tablePrefix = $tablePrefix == 'get from global' ?
strtoupper( $wgDBprefix ) : strtoupper( $tablePrefix );
189 parent
::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
190 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
193 function __destruct() {
194 if ($this->mOpened
) {
195 wfSuppressWarnings();
205 function cascadingDeletes() {
208 function cleanupTriggers() {
211 function strictIPs() {
214 function realTimestamps() {
217 function implicitGroupby() {
220 function implicitOrderby() {
223 function searchableIPs() {
228 * Usually aborts on failure
230 function open( $server, $user, $password, $dbName ) {
231 if ( !function_exists( 'oci_connect' ) ) {
232 throw new DBConnectionError( $this, "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n (Note: if you recently installed PHP, you may need to restart your webserver and database)\n" );
236 $this->mUser
= $user;
237 $this->mPassword
= $password;
238 // changed internal variables functions
239 // mServer now holds the TNS endpoint
240 // mDBname is schema name if different from username
242 // backward compatibillity (server used to be null and TNS was supplied in dbname)
243 $this->mServer
= $dbName;
244 $this->mDBname
= $user;
246 $this->mServer
= $server;
248 $this->mDBname
= $user;
250 $this->mDBname
= $dbName;
254 if ( !strlen( $user ) ) { # e.g. the class is being loaded
258 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
259 wfSuppressWarnings();
260 if ( $this->mFlags
& DBO_DEFAULT
) {
261 $this->mConn
= oci_new_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
263 $this->mConn
= oci_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
267 if ( $this->mUser
!= $this->mDBname
) {
268 //change current schema in session
269 $this->selectDB( $this->mDBname
);
272 if ( !$this->mConn
) {
273 throw new DBConnectionError( $this, $this->lastError() );
276 $this->mOpened
= true;
278 # removed putenv calls because they interfere with the system globaly
279 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
280 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
281 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
286 * Closes a database connection, if it is open
287 * Returns success, true if already closed
290 $this->mOpened
= false;
291 if ( $this->mConn
) {
292 if ( $this->mTrxLevel
) {
295 return oci_close( $this->mConn
);
301 function execFlags() {
302 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
305 function doQuery( $sql ) {
306 wfDebug( "SQL: [$sql]\n" );
307 if ( !mb_check_encoding( $sql ) ) {
308 throw new MWException( "SQL encoding is invalid\n$sql" );
311 // handle some oracle specifics
312 // remove AS column/table/subquery namings
313 if( !$this->getFlag( DBO_DDLMODE
) ) {
314 $sql = preg_replace( '/ as /i', ' ', $sql );
317 // Oracle has issues with UNION clause if the statement includes LOB fields
318 // So we do a UNION ALL and then filter the results array with array_unique
319 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
320 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
321 // you have to select data from plan table after explain
322 $explain_id = date( 'dmYHis' );
324 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
326 wfSuppressWarnings();
328 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
329 $e = oci_error( $this->mConn
);
330 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
334 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
335 $e = oci_error( $stmt );
336 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
337 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
344 if ( $explain_count > 0 ) {
345 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
346 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
347 return new ORAResult( $this, $stmt, $union_unique );
349 $this->mAffectedRows
= oci_num_rows( $stmt );
354 function queryIgnore( $sql, $fname = '' ) {
355 return $this->query( $sql, $fname, true );
358 function freeResult( $res ) {
359 if ( $res instanceof ResultWrapper
) {
366 function fetchObject( $res ) {
367 if ( $res instanceof ResultWrapper
) {
371 return $res->fetchObject();
374 function fetchRow( $res ) {
375 if ( $res instanceof ResultWrapper
) {
379 return $res->fetchRow();
382 function numRows( $res ) {
383 if ( $res instanceof ResultWrapper
) {
387 return $res->numRows();
390 function numFields( $res ) {
391 if ( $res instanceof ResultWrapper
) {
395 return $res->numFields();
398 function fieldName( $stmt, $n ) {
399 return oci_field_name( $stmt, $n );
403 * This must be called after nextSequenceVal
405 function insertId() {
406 return $this->mInsertId
;
409 function dataSeek( $res, $row ) {
410 if ( $res instanceof ORAResult
) {
413 $res->result
->seek( $row );
417 function lastError() {
418 if ( $this->mConn
=== false ) {
421 $e = oci_error( $this->mConn
);
423 return $e['message'];
426 function lastErrno() {
427 if ( $this->mConn
=== false ) {
430 $e = oci_error( $this->mConn
);
435 function affectedRows() {
436 return $this->mAffectedRows
;
440 * Returns information about an index
441 * If errors are explicitly ignored, returns NULL on failure
443 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
447 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
451 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
452 if ( !count( $a ) ) {
456 if ( !is_array( $options ) ) {
457 $options = array( $options );
460 if ( in_array( 'IGNORE', $options ) ) {
461 $this->ignore_DUP_VAL_ON_INDEX
= true;
464 if ( !is_array( reset( $a ) ) ) {
468 foreach ( $a as &$row ) {
469 $this->insertOneRow( $table, $row, $fname );
473 if ( in_array( 'IGNORE', $options ) ) {
474 $this->ignore_DUP_VAL_ON_INDEX
= false;
480 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
481 $col_info = $this->fieldInfoMulti( $table, $col );
482 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
485 if ( is_numeric( $col ) ) {
489 } elseif ( $includeCol ) {
493 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
497 if ( $val === null ) {
498 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
510 private function insertOneRow( $table, $row, $fname ) {
513 $table = $this->tableName( $table );
514 // "INSERT INTO tables (a, b, c)"
515 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
518 // for each value, append ":key"
520 foreach ( $row as $col => &$val ) {
527 $sql .= $this->fieldBindStatement( $table, $col, $val );
531 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
532 $e = oci_error( $this->mConn
);
533 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
536 foreach ( $row as $col => &$val ) {
537 $col_info = $this->fieldInfoMulti( $table, $col );
538 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
540 if ( $val === null ) {
541 // do nothing ... null was inserted in statement creation
542 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
543 if ( is_object( $val ) ) {
544 $val = $val->fetch();
547 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
548 $val = '31-12-2030 12:00:00.000000';
551 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
552 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
553 $e = oci_error( $stmt );
554 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
558 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
559 $e = oci_error( $stmt );
560 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
563 if ( is_object( $val ) ) {
564 $val = $val->fetch();
567 if ( $col_type == 'BLOB' ) {
568 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
569 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB
);
571 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
572 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
577 wfSuppressWarnings();
579 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
580 $e = oci_error( $stmt );
581 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
582 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
585 $this->mAffectedRows
= oci_num_rows( $stmt );
588 $this->mAffectedRows
= oci_num_rows( $stmt );
593 if ( isset( $lob ) ) {
594 foreach ( $lob as $lob_v ) {
599 if ( !$this->mTrxLevel
) {
600 oci_commit( $this->mConn
);
603 oci_free_statement( $stmt );
606 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
607 $insertOptions = array(), $selectOptions = array() )
609 $destTable = $this->tableName( $destTable );
610 if ( !is_array( $selectOptions ) ) {
611 $selectOptions = array( $selectOptions );
613 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
614 if ( is_array( $srcTable ) ) {
615 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
617 $srcTable = $this->tableName( $srcTable );
620 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
621 !isset( $varMap[$sequenceData['column']] ) )
623 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
626 // count-alias subselect fields to avoid abigious definition errors
628 foreach ( $varMap as &$val ) {
629 $val = $val . ' field' . ( $i++
);
632 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
633 " SELECT $startOpts " . implode( ',', $varMap ) .
634 " FROM $srcTable $useIndex ";
635 if ( $conds != '*' ) {
636 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
638 $sql .= " $tailOpts";
640 if ( in_array( 'IGNORE', $insertOptions ) ) {
641 $this->ignore_DUP_VAL_ON_INDEX
= true;
644 $retval = $this->query( $sql, $fname );
646 if ( in_array( 'IGNORE', $insertOptions ) ) {
647 $this->ignore_DUP_VAL_ON_INDEX
= false;
653 function tableName( $name, $quoted = true ) {
655 Replace reserved words with better ones
656 Using uppercase because that's the only way Oracle can handle
664 $name = 'PAGECONTENT';
668 return parent
::tableName( strtoupper( $name ), $quoted );
671 function tableNameInternal( $name ) {
672 $name = $this->tableName( $name );
673 return preg_replace( '/.*\.(.*)/', '$1', $name);
676 * Return the next in a sequence, save the value for retrieval via insertId()
678 function nextSequenceValue( $seqName ) {
679 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
680 $row = $this->fetchRow( $res );
681 $this->mInsertId
= $row[0];
682 return $this->mInsertId
;
686 * Return sequence_name if table has a sequence
688 private function getSequenceData( $table ) {
689 if ( $this->sequenceData
== null ) {
690 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
691 lower(atc.table_name),
692 lower(atc.column_name)
693 FROM all_sequences asq, all_tab_columns atc
694 WHERE decode(atc.table_name, '{$this->mTablePrefix}MWUSER', '{$this->mTablePrefix}USER', atc.table_name) || '_' ||
695 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
696 AND asq.sequence_owner = '{$this->mDBname}'
697 AND atc.owner = '{$this->mDBname}'" );
699 while ( ( $row = $result->fetchRow() ) !== false ) {
700 $this->sequenceData
[$this->tableName( $row[1] )] = array(
701 'sequence' => $row[0],
706 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
707 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
711 * REPLACE query wrapper
712 * Oracle simulates this with a DELETE followed by INSERT
713 * $row is the row to insert, an associative array
714 * $uniqueIndexes is an array of indexes. Each element may be either a
715 * field name or an array of field names
717 * It may be more efficient to leave off unique indexes which are unlikely to collide.
718 * However if you do this, you run the risk of encountering errors which wouldn't have
721 * @param $table String: table name
722 * @param $uniqueIndexes Array: array of indexes. Each element may be
723 * either a field name or an array of field names
724 * @param $rows Array: rows to insert to $table
725 * @param $fname String: function name, you can use __METHOD__ here
727 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
728 $table = $this->tableName( $table );
730 if ( count( $rows ) == 0 ) {
735 if ( !is_array( reset( $rows ) ) ) {
736 $rows = array( $rows );
739 $sequenceData = $this->getSequenceData( $table );
741 foreach ( $rows as $row ) {
742 # Delete rows which collide
743 if ( $uniqueIndexes ) {
744 $deleteConds = array();
745 foreach ( $uniqueIndexes as $key=>$index ) {
746 if ( is_array( $index ) ) {
747 $deleteConds2 = array();
748 foreach ( $index as $col ) {
749 $deleteConds2[$col] = $row[$col];
751 $deleteConds[$key] = $this->makeList( $deleteConds2, LIST_AND
);
753 $deleteConds[$index] = $row[$index];
756 $deleteConds = array( $this->makeList( $deleteConds, LIST_OR
) );
757 $this->delete( $table, $deleteConds, $fname );
761 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
762 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
766 $this->insert( $table, $row, $fname );
770 # DELETE where the condition is a join
771 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
773 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
776 $delTable = $this->tableName( $delTable );
777 $joinTable = $this->tableName( $joinTable );
778 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
779 if ( $conds != '*' ) {
780 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
784 $this->query( $sql, $fname );
787 # Returns the size of a text field, or -1 for "unlimited"
788 function textFieldSize( $table, $field ) {
789 $fieldInfoData = $this->fieldInfo( $table, $field );
790 return $fieldInfoData->maxLength();
793 function limitResult( $sql, $limit, $offset = false ) {
794 if ( $offset === false ) {
797 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
800 function encodeBlob( $b ) {
801 return new Blob( $b );
804 function decodeBlob( $b ) {
805 if ( $b instanceof Blob
) {
811 function unionQueries( $sqls, $all ) {
812 $glue = ' UNION ALL ';
813 return 'SELECT * ' . ( $all ?
'':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
816 function wasDeadlock() {
817 return $this->lastErrno() == 'OCI-00060';
820 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
821 $temporary = $temporary ?
'TRUE' : 'FALSE';
823 $newName = strtoupper( $newName );
824 $oldName = strtoupper( $oldName );
826 $tabName = substr( $newName, strlen( $this->mTablePrefix
) );
827 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
828 $newPrefix = strtoupper( $this->mTablePrefix
);
830 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', '$oldPrefix', '$newPrefix', $temporary ); END;" );
833 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
835 if (!empty($prefix)) {
836 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
839 $owner = strtoupper( $this->mDBname
);
840 $result = $this->doQuery( "SELECT table_name FROM all_tables WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
842 // dirty code ... i know
844 $endArray[] = $prefix.'MWUSER';
845 $endArray[] = $prefix.'PAGE';
846 $endArray[] = $prefix.'IMAGE';
847 $fixedOrderTabs = $endArray;
848 while (($row = $result->fetchRow()) !== false) {
849 if (!in_array($row['table_name'], $fixedOrderTabs))
850 $endArray[] = $row['table_name'];
856 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
857 $tableName = $this->tableName($tableName);
858 if( !$this->tableExists( $tableName ) ) {
862 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
865 function timestamp( $ts = 0 ) {
866 return wfTimestamp( TS_ORACLE
, $ts );
870 * Return aggregated value function call
872 function aggregateValue ( $valuedata, $valuename = 'value' ) {
876 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
877 # Ignore errors during error handling to avoid infinite
879 $ignore = $this->ignoreErrors( true );
880 ++
$this->mErrorCount
;
882 if ( $ignore ||
$tempIgnore ) {
883 wfDebug( "SQL ERROR (ignored): $error\n" );
884 $this->ignoreErrors( $ignore );
886 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
891 * @return string wikitext of a link to the server software's web site
893 public static function getSoftwareLink() {
894 return '[http://www.oracle.com/ Oracle]';
898 * @return string Version information from the database
900 function getServerVersion() {
901 //better version number, fallback on driver
902 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
903 if ( !( $row = $rset->fetchRow() ) ) {
904 return oci_server_version( $this->mConn
);
906 return $row['version'];
910 * Query whether a given index exists
912 function indexExists( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
913 $table = $this->tableName( $table );
914 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
915 $index = strtoupper( $index );
916 $owner = strtoupper( $this->mDBname
);
917 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
918 $res = $this->doQuery( $SQL );
920 $count = $res->numRows();
929 * Query whether a given table exists (in the given schema, or the default mw one if not given)
931 function tableExists( $table ) {
932 $table = $this->tableName( $table );
933 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
934 $owner = $this->addQuotes( strtoupper( $this->mDBname
) );
935 $SQL = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
936 $res = $this->doQuery( $SQL );
938 $count = $res->numRows();
947 * Function translates mysql_fetch_field() functionality on ORACLE.
948 * Caching is present for reducing query time.
949 * For internal calls. Use fieldInfo for normal usage.
950 * Returns false if the field doesn't exist
952 * @param $table Array
953 * @param $field String
954 * @return ORAField|ORAResult
956 private function fieldInfoMulti( $table, $field ) {
957 $field = strtoupper( $field );
958 if ( is_array( $table ) ) {
959 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
960 $tableWhere = 'IN (';
961 foreach( $table as &$singleTable ) {
962 $singleTable = $this->removeIdentifierQuotes($singleTable);
963 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
964 return $this->mFieldInfoCache
["$singleTable.$field"];
966 $tableWhere .= '\'' . $singleTable . '\',';
968 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
970 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
971 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
972 return $this->mFieldInfoCache
["$table.$field"];
974 $tableWhere = '= \''.$table.'\'';
977 $fieldInfoStmt = oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
978 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
979 $e = oci_error( $fieldInfoStmt );
980 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
983 $res = new ORAResult( $this, $fieldInfoStmt );
984 if ( $res->numRows() == 0 ) {
985 if ( is_array( $table ) ) {
986 foreach( $table as &$singleTable ) {
987 $this->mFieldInfoCache
["$singleTable.$field"] = false;
990 $this->mFieldInfoCache
["$table.$field"] = false;
992 $fieldInfoTemp = null;
994 $fieldInfoTemp = new ORAField( $res->fetchRow() );
995 $table = $fieldInfoTemp->tableName();
996 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
999 return $fieldInfoTemp;
1003 * @throws DBUnexpectedError
1008 function fieldInfo( $table, $field ) {
1009 if ( is_array( $table ) ) {
1010 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
1012 return $this->fieldInfoMulti ($table, $field);
1015 function begin( $fname = 'DatabaseOracle::begin' ) {
1016 $this->mTrxLevel
= 1;
1017 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
1020 function commit( $fname = 'DatabaseOracle::commit' ) {
1021 if ( $this->mTrxLevel
) {
1022 $ret = oci_commit( $this->mConn
);
1024 throw new DBUnexpectedError( $this, $this->lastError() );
1026 $this->mTrxLevel
= 0;
1027 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1031 function rollback( $fname = 'DatabaseOracle::rollback' ) {
1032 if ( $this->mTrxLevel
) {
1033 oci_rollback( $this->mConn
);
1034 $this->mTrxLevel
= 0;
1035 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1039 /* Not even sure why this is used in the main codebase... */
1040 function limitResultForUpdate( $sql, $num ) {
1044 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
1045 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
1048 $dollarquote = false;
1050 $replacements = array();
1052 while ( ! feof( $fp ) ) {
1053 if ( $lineCallback ) {
1054 call_user_func( $lineCallback );
1056 $line = trim( fgets( $fp, 1024 ) );
1057 $sl = strlen( $line ) - 1;
1062 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1066 // Allow dollar quoting for function declarations
1067 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1068 if ( $dollarquote ) {
1069 $dollarquote = false;
1070 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1073 $dollarquote = true;
1075 } elseif ( !$dollarquote ) {
1076 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
1078 $line = substr( $line, 0, $sl );
1088 $cmd = str_replace( ';;', ";", $cmd );
1089 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1090 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1091 $replacements[$defines[2]] = $defines[1];
1094 foreach ( $replacements as $mwVar => $scVar ) {
1095 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1098 $cmd = $this->replaceVars( $cmd );
1099 $res = $this->doQuery( $cmd );
1100 if ( $resultCallback ) {
1101 call_user_func( $resultCallback, $res, $this );
1104 if ( false === $res ) {
1105 $err = $this->lastError();
1106 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1117 function selectDB( $db ) {
1118 $this->mDBname
= $db;
1119 if ( $db == null ||
$db == $this->mUser
) {
1122 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1123 $stmt = oci_parse( $this->mConn
, $sql );
1124 wfSuppressWarnings();
1125 $success = oci_execute( $stmt );
1126 wfRestoreWarnings();
1128 $e = oci_error( $stmt );
1129 if ( $e['code'] != '1435' ) {
1130 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1137 function strencode( $s ) {
1138 return str_replace( "'", "''", $s );
1141 function addQuotes( $s ) {
1143 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1144 $s = $wgContLang->checkTitleEncoding( $s );
1146 return "'" . $this->strencode( $s ) . "'";
1149 public function addIdentifierQuotes( $s ) {
1150 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1156 public function removeIdentifierQuotes( $s ) {
1157 return strpos($s, '/*Q*/') === FALSE ?
$s : substr($s, 5);
1160 public function isQuotedIdentifier( $s ) {
1161 return strpos($s, '/*Q*/') !== FALSE;
1164 private function wrapFieldForWhere( $table, &$col, &$val ) {
1167 $col_info = $this->fieldInfoMulti( $table, $col );
1168 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1169 if ( $col_type == 'CLOB' ) {
1170 $col = 'TO_CHAR(' . $col . ')';
1171 $val = $wgContLang->checkTitleEncoding( $val );
1172 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1173 $val = $wgContLang->checkTitleEncoding( $val );
1177 private function wrapConditionsForWhere ( $table, $conds, $parentCol = null ) {
1179 foreach ( $conds as $col => $val ) {
1180 if ( is_array( $val ) ) {
1181 $conds2[$col] = $this->wrapConditionsForWhere ( $table, $val, $col );
1183 if ( is_numeric( $col ) && $parentCol != null ) {
1184 $this->wrapFieldForWhere ( $table, $parentCol, $val );
1186 $this->wrapFieldForWhere ( $table, $col, $val );
1188 $conds2[$col] = $val;
1194 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1195 if ( is_array($conds) ) {
1196 $conds = $this->wrapConditionsForWhere( $table, $conds );
1198 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1202 * Returns an optional USE INDEX clause to go after the table, and a
1203 * string to go at the end of the query
1207 * @param $options Array: an associative array of options to be turned into
1208 * an SQL query, valid keys are listed in the function.
1211 function makeSelectOptions( $options ) {
1212 $preLimitTail = $postLimitTail = '';
1215 $noKeyOptions = array();
1216 foreach ( $options as $key => $option ) {
1217 if ( is_numeric( $key ) ) {
1218 $noKeyOptions[$option] = true;
1222 if ( isset( $options['GROUP BY'] ) ) {
1223 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1225 if ( isset( $options['ORDER BY'] ) ) {
1226 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1229 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1230 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1231 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1232 $startOpts .= 'DISTINCT';
1235 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1236 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1241 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1244 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1245 if ( is_array($conds) ) {
1246 $conds = $this->wrapConditionsForWhere( $table, $conds );
1248 return parent
::delete( $table, $conds, $fname );
1251 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1254 $table = $this->tableName( $table );
1255 $opts = $this->makeUpdateOptions( $options );
1256 $sql = "UPDATE $opts $table SET ";
1259 foreach ( $values as $col => &$val ) {
1260 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1263 $sqlSet = ', ' . $sqlSet;
1270 if ( $conds != '*' ) {
1271 $conds = $this->wrapConditionsForWhere( $table, $conds );
1272 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1275 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1276 $e = oci_error( $this->mConn
);
1277 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1280 foreach ( $values as $col => &$val ) {
1281 $col_info = $this->fieldInfoMulti( $table, $col );
1282 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1284 if ( $val === null ) {
1285 // do nothing ... null was inserted in statement creation
1286 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1287 if ( is_object( $val ) ) {
1288 $val = $val->getData();
1291 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1292 $val = '31-12-2030 12:00:00.000000';
1295 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1296 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1297 $e = oci_error( $stmt );
1298 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1302 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1303 $e = oci_error( $stmt );
1304 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1307 if ( $col_type == 'BLOB' ) {
1308 $lob[$col]->writeTemporary( $val );
1309 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
1311 $lob[$col]->writeTemporary( $val );
1312 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
1317 wfSuppressWarnings();
1319 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1320 $e = oci_error( $stmt );
1321 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
1322 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1325 $this->mAffectedRows
= oci_num_rows( $stmt );
1328 $this->mAffectedRows
= oci_num_rows( $stmt );
1331 wfRestoreWarnings();
1333 if ( isset( $lob ) ) {
1334 foreach ( $lob as $lob_v ) {
1339 if ( !$this->mTrxLevel
) {
1340 oci_commit( $this->mConn
);
1343 oci_free_statement( $stmt );
1346 function bitNot( $field ) {
1347 // expecting bit-fields smaller than 4bytes
1348 return 'BITNOT(' . $field . ')';
1351 function bitAnd( $fieldLeft, $fieldRight ) {
1352 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1355 function bitOr( $fieldLeft, $fieldRight ) {
1356 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1359 function setFakeMaster( $enabled = true ) { }
1361 function getDBname() {
1362 return $this->mDBname
;
1365 function getServer() {
1366 return $this->mServer
;
1369 public function getSearchEngine() {
1370 return 'SearchOracle';
1372 } // end DatabaseOracle class