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\'' );
285 * Closes a database connection, if it is open
286 * Returns success, true if already closed
289 $this->mOpened
= false;
290 if ( $this->mConn
) {
291 if ( $this->mTrxLevel
) {
294 return oci_close( $this->mConn
);
300 function execFlags() {
301 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
304 function doQuery( $sql ) {
305 wfDebug( "SQL: [$sql]\n" );
306 if ( !mb_check_encoding( $sql ) ) {
307 throw new MWException( "SQL encoding is invalid\n$sql" );
310 // handle some oracle specifics
311 // remove AS column/table/subquery namings
312 if( !$this->getFlag( DBO_DDLMODE
) ) {
313 $sql = preg_replace( '/ as /i', ' ', $sql );
316 // Oracle has issues with UNION clause if the statement includes LOB fields
317 // So we do a UNION ALL and then filter the results array with array_unique
318 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
319 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
320 // you have to select data from plan table after explain
321 $explain_id = date( 'dmYHis' );
323 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
325 wfSuppressWarnings();
327 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
328 $e = oci_error( $this->mConn
);
329 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
333 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
334 $e = oci_error( $stmt );
335 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
336 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
343 if ( $explain_count > 0 ) {
344 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
345 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
346 return new ORAResult( $this, $stmt, $union_unique );
348 $this->mAffectedRows
= oci_num_rows( $stmt );
353 function queryIgnore( $sql, $fname = '' ) {
354 return $this->query( $sql, $fname, true );
357 function freeResult( $res ) {
358 if ( $res instanceof ResultWrapper
) {
365 function fetchObject( $res ) {
366 if ( $res instanceof ResultWrapper
) {
370 return $res->fetchObject();
373 function fetchRow( $res ) {
374 if ( $res instanceof ResultWrapper
) {
378 return $res->fetchRow();
381 function numRows( $res ) {
382 if ( $res instanceof ResultWrapper
) {
386 return $res->numRows();
389 function numFields( $res ) {
390 if ( $res instanceof ResultWrapper
) {
394 return $res->numFields();
397 function fieldName( $stmt, $n ) {
398 return oci_field_name( $stmt, $n );
402 * This must be called after nextSequenceVal
404 function insertId() {
405 return $this->mInsertId
;
408 function dataSeek( $res, $row ) {
409 if ( $res instanceof ORAResult
) {
412 $res->result
->seek( $row );
416 function lastError() {
417 if ( $this->mConn
=== false ) {
420 $e = oci_error( $this->mConn
);
422 return $e['message'];
425 function lastErrno() {
426 if ( $this->mConn
=== false ) {
429 $e = oci_error( $this->mConn
);
434 function affectedRows() {
435 return $this->mAffectedRows
;
439 * Returns information about an index
440 * If errors are explicitly ignored, returns NULL on failure
442 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
446 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
450 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
451 if ( !count( $a ) ) {
455 if ( !is_array( $options ) ) {
456 $options = array( $options );
459 if ( in_array( 'IGNORE', $options ) ) {
460 $this->ignore_DUP_VAL_ON_INDEX
= true;
463 if ( !is_array( reset( $a ) ) ) {
467 foreach ( $a as &$row ) {
468 $this->insertOneRow( $table, $row, $fname );
472 if ( in_array( 'IGNORE', $options ) ) {
473 $this->ignore_DUP_VAL_ON_INDEX
= false;
479 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
480 $col_info = $this->fieldInfoMulti( $table, $col );
481 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
484 if ( is_numeric( $col ) ) {
488 } else if ( $includeCol ) {
492 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
496 if ( $val === null ) {
497 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
509 private function insertOneRow( $table, $row, $fname ) {
512 $table = $this->tableName( $table );
513 // "INSERT INTO tables (a, b, c)"
514 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
517 // for each value, append ":key"
519 foreach ( $row as $col => &$val ) {
526 $sql .= $this->fieldBindStatement( $table, $col, $val );
530 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
531 $e = oci_error( $this->mConn
);
532 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
535 foreach ( $row as $col => &$val ) {
536 $col_info = $this->fieldInfoMulti( $table, $col );
537 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
539 if ( $val === null ) {
540 // do nothing ... null was inserted in statement creation
541 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
542 if ( is_object( $val ) ) {
543 $val = $val->fetch();
546 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
547 $val = '31-12-2030 12:00:00.000000';
550 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
551 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
552 $e = oci_error( $stmt );
553 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
557 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
558 $e = oci_error( $stmt );
559 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
562 if ( is_object( $val ) ) {
563 $val = $val->fetch();
566 if ( $col_type == 'BLOB' ) {
567 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
568 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB
);
570 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
571 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
576 wfSuppressWarnings();
578 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
579 $e = oci_error( $stmt );
580 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
581 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
584 $this->mAffectedRows
= oci_num_rows( $stmt );
587 $this->mAffectedRows
= oci_num_rows( $stmt );
592 if ( isset( $lob ) ) {
593 foreach ( $lob as $lob_v ) {
598 if ( !$this->mTrxLevel
) {
599 oci_commit( $this->mConn
);
602 oci_free_statement( $stmt );
605 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
606 $insertOptions = array(), $selectOptions = array() )
608 $destTable = $this->tableName( $destTable );
609 if ( !is_array( $selectOptions ) ) {
610 $selectOptions = array( $selectOptions );
612 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
613 if ( is_array( $srcTable ) ) {
614 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
616 $srcTable = $this->tableName( $srcTable );
619 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
620 !isset( $varMap[$sequenceData['column']] ) )
622 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
625 // count-alias subselect fields to avoid abigious definition errors
627 foreach ( $varMap as &$val ) {
628 $val = $val . ' field' . ( $i++
);
631 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
632 " SELECT $startOpts " . implode( ',', $varMap ) .
633 " FROM $srcTable $useIndex ";
634 if ( $conds != '*' ) {
635 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
637 $sql .= " $tailOpts";
639 if ( in_array( 'IGNORE', $insertOptions ) ) {
640 $this->ignore_DUP_VAL_ON_INDEX
= true;
643 $retval = $this->query( $sql, $fname );
645 if ( in_array( 'IGNORE', $insertOptions ) ) {
646 $this->ignore_DUP_VAL_ON_INDEX
= false;
652 function tableName( $name, $quoted = true ) {
654 Replace reserved words with better ones
655 Using uppercase because that's the only way Oracle can handle
663 $name = 'PAGECONTENT';
667 return parent
::tableName( strtoupper( $name ), $quoted );
670 function tableNameInternal( $name ) {
671 $name = $this->tableName( $name );
672 return preg_replace( '/.*\.(.*)/', '$1', $name);
675 * Return the next in a sequence, save the value for retrieval via insertId()
677 function nextSequenceValue( $seqName ) {
678 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
679 $row = $this->fetchRow( $res );
680 $this->mInsertId
= $row[0];
681 return $this->mInsertId
;
685 * Return sequence_name if table has a sequence
687 private function getSequenceData( $table ) {
688 if ( $this->sequenceData
== null ) {
689 $result = $this->doQuery( 'SELECT lower(us.sequence_name), lower(utc.table_name), lower(utc.column_name) from user_sequences us, user_tab_columns utc where us.sequence_name = utc.table_name||\'_\'||utc.column_name||\'_SEQ\'' );
691 while ( ( $row = $result->fetchRow() ) !== false ) {
692 $this->sequenceData
[$this->tableName( $row[1] )] = array(
693 'sequence' => $row[0],
699 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
703 * REPLACE query wrapper
704 * Oracle simulates this with a DELETE followed by INSERT
705 * $row is the row to insert, an associative array
706 * $uniqueIndexes is an array of indexes. Each element may be either a
707 * field name or an array of field names
709 * It may be more efficient to leave off unique indexes which are unlikely to collide.
710 * However if you do this, you run the risk of encountering errors which wouldn't have
713 * @param $table String: table name
714 * @param $uniqueIndexes Array: array of indexes. Each element may be
715 * either a field name or an array of field names
716 * @param $rows Array: rows to insert to $table
717 * @param $fname String: function name, you can use __METHOD__ here
719 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
720 $table = $this->tableName( $table );
722 if ( count( $rows ) == 0 ) {
727 if ( !is_array( reset( $rows ) ) ) {
728 $rows = array( $rows );
731 $sequenceData = $this->getSequenceData( $table );
733 foreach ( $rows as $row ) {
734 # Delete rows which collide
735 if ( $uniqueIndexes ) {
736 $condsDelete = array();
737 foreach ( $uniqueIndexes as $index ) {
738 $condsDelete[$index] = $row[$index];
740 if ( count( $condsDelete ) > 0 ) {
741 $this->delete( $table, $condsDelete, $fname );
745 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
746 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
750 $this->insert( $table, $row, $fname );
754 # DELETE where the condition is a join
755 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
757 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
760 $delTable = $this->tableName( $delTable );
761 $joinTable = $this->tableName( $joinTable );
762 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
763 if ( $conds != '*' ) {
764 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
768 $this->query( $sql, $fname );
771 # Returns the size of a text field, or -1 for "unlimited"
772 function textFieldSize( $table, $field ) {
773 $fieldInfoData = $this->fieldInfo( $table, $field );
774 return $fieldInfoData->maxLength();
777 function limitResult( $sql, $limit, $offset = false ) {
778 if ( $offset === false ) {
781 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
784 function encodeBlob( $b ) {
785 return new Blob( $b );
788 function decodeBlob( $b ) {
789 if ( $b instanceof Blob
) {
795 function unionQueries( $sqls, $all ) {
796 $glue = ' UNION ALL ';
797 return 'SELECT * ' . ( $all ?
'':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
800 function wasDeadlock() {
801 return $this->lastErrno() == 'OCI-00060';
804 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
806 $this->setFlag( DBO_DDLMODE
);
808 $temporary = $temporary ?
'TRUE' : 'FALSE';
810 $newName = strtoupper( $newName );
811 $oldName = strtoupper( $oldName );
813 $tabName = $this->addIdentifierQuotes( substr( $newName, strlen( $wgDBprefix ) ) );
814 $oldPrefix = $this->addIdentifierQuotes( substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) ) );
815 $newPrefix = $this->addIdentifierQuotes( $wgDBprefix );
817 $this->clearFlag( DBO_DDLMODE
);
818 return $this->doQuery( "BEGIN DUPLICATE_TABLE( $tabName, $oldPrefix, $newPrefix, $temporary ); END;" );
821 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
823 if (!empty($prefix)) {
824 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
827 $owner = strtoupper( $this->mDBname
);
828 $result = $this->doQuery( "SELECT table_name FROM all_tables WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX$_' ESCAPE '!' $listWhere" );
830 // dirty code ... i know
832 $endArray[] = $prefix.'MWUSER';
833 $endArray[] = $prefix.'PAGE';
834 $endArray[] = $prefix.'IMAGE';
835 $fixedOrderTabs = $endArray;
836 while (($row = $result->fetchRow()) !== false) {
837 if (!in_array($row['table_name'], $fixedOrderTabs))
838 $endArray[] = $row['table_name'];
844 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
845 $tableName = $this->tableName($tableName);
846 if( !$this->tableExists( $tableName ) ) {
850 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
853 function timestamp( $ts = 0 ) {
854 return wfTimestamp( TS_ORACLE
, $ts );
858 * Return aggregated value function call
860 function aggregateValue ( $valuedata, $valuename = 'value' ) {
864 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
865 # Ignore errors during error handling to avoid infinite
867 $ignore = $this->ignoreErrors( true );
868 ++
$this->mErrorCount
;
870 if ( $ignore ||
$tempIgnore ) {
871 wfDebug( "SQL ERROR (ignored): $error\n" );
872 $this->ignoreErrors( $ignore );
874 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
879 * @return string wikitext of a link to the server software's web site
881 public static function getSoftwareLink() {
882 return '[http://www.oracle.com/ Oracle]';
886 * @return string Version information from the database
888 function getServerVersion() {
889 //better version number, fallback on driver
890 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
891 if ( !( $row = $rset->fetchRow() ) ) {
892 return oci_server_version( $this->mConn
);
894 return $row['version'];
898 * Query whether a given index exists
900 function indexExists( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
901 $table = $this->tableName( $table );
902 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
903 $index = strtoupper( $index );
904 $owner = strtoupper( $this->mDBname
);
905 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
906 $res = $this->doQuery( $SQL );
908 $count = $res->numRows();
917 * Query whether a given table exists (in the given schema, or the default mw one if not given)
919 function tableExists( $table ) {
920 $table = $this->tableName( $table );
921 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
922 $owner = strtoupper( $this->mDBname
);
923 $SQL = "SELECT 1 FROM all_tables WHERE owner='$owner' AND table_name='$table'";
924 $res = $this->doQuery( $SQL );
926 $count = $res->numRows();
935 * Function translates mysql_fetch_field() functionality on ORACLE.
936 * Caching is present for reducing query time.
937 * For internal calls. Use fieldInfo for normal usage.
938 * Returns false if the field doesn't exist
940 * @param $table Array
941 * @param $field String
942 * @return ORAField|ORAResult
944 private function fieldInfoMulti( $table, $field ) {
945 $field = strtoupper( $field );
946 if ( is_array( $table ) ) {
947 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
948 $tableWhere = 'IN (';
949 foreach( $table as &$singleTable ) {
950 $singleTable = $this->removeIdentifierQuotes($singleTable);
951 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
952 return $this->mFieldInfoCache
["$singleTable.$field"];
954 $tableWhere .= '\'' . $singleTable . '\',';
956 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
958 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
959 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
960 return $this->mFieldInfoCache
["$table.$field"];
962 $tableWhere = '= \''.$table.'\'';
965 $fieldInfoStmt = oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
966 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
967 $e = oci_error( $fieldInfoStmt );
968 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
971 $res = new ORAResult( $this, $fieldInfoStmt );
972 if ( $res->numRows() == 0 ) {
973 if ( is_array( $table ) ) {
974 foreach( $table as &$singleTable ) {
975 $this->mFieldInfoCache
["$singleTable.$field"] = false;
978 $this->mFieldInfoCache
["$table.$field"] = false;
980 $fieldInfoTemp = null;
982 $fieldInfoTemp = new ORAField( $res->fetchRow() );
983 $table = $fieldInfoTemp->tableName();
984 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
987 return $fieldInfoTemp;
991 * @throws DBUnexpectedError
996 function fieldInfo( $table, $field ) {
997 if ( is_array( $table ) ) {
998 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
1000 return $this->fieldInfoMulti ($table, $field);
1003 function begin( $fname = 'DatabaseOracle::begin' ) {
1004 $this->mTrxLevel
= 1;
1007 function commit( $fname = 'DatabaseOracle::commit' ) {
1008 if ( $this->mTrxLevel
) {
1009 oci_commit( $this->mConn
);
1010 $this->mTrxLevel
= 0;
1014 function rollback( $fname = 'DatabaseOracle::rollback' ) {
1015 if ( $this->mTrxLevel
) {
1016 oci_rollback( $this->mConn
);
1017 $this->mTrxLevel
= 0;
1021 /* Not even sure why this is used in the main codebase... */
1022 function limitResultForUpdate( $sql, $num ) {
1026 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
1027 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
1030 $dollarquote = false;
1032 $replacements = array();
1034 while ( ! feof( $fp ) ) {
1035 if ( $lineCallback ) {
1036 call_user_func( $lineCallback );
1038 $line = trim( fgets( $fp, 1024 ) );
1039 $sl = strlen( $line ) - 1;
1044 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1048 // Allow dollar quoting for function declarations
1049 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1050 if ( $dollarquote ) {
1051 $dollarquote = false;
1052 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1055 $dollarquote = true;
1057 } elseif ( !$dollarquote ) {
1058 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
1060 $line = substr( $line, 0, $sl );
1070 $cmd = str_replace( ';;', ";", $cmd );
1071 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1072 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1073 $replacements[$defines[2]] = $defines[1];
1076 foreach ( $replacements as $mwVar => $scVar ) {
1077 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1080 $cmd = $this->replaceVars( $cmd );
1081 $res = $this->doQuery( $cmd );
1082 if ( $resultCallback ) {
1083 call_user_func( $resultCallback, $res, $this );
1086 if ( false === $res ) {
1087 $err = $this->lastError();
1088 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1099 function selectDB( $db ) {
1100 $this->mDBname
= $db;
1101 if ( $db == null ||
$db == $this->mUser
) {
1104 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1105 $stmt = oci_parse( $this->mConn
, $sql );
1106 wfSuppressWarnings();
1107 $success = oci_execute( $stmt );
1108 wfRestoreWarnings();
1110 $e = oci_error( $stmt );
1111 if ( $e['code'] != '1435' ) {
1112 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1119 function strencode( $s ) {
1120 return str_replace( "'", "''", $s );
1123 function addQuotes( $s ) {
1125 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1126 $s = $wgContLang->checkTitleEncoding( $s );
1128 return "'" . $this->strencode( $s ) . "'";
1131 public function addIdentifierQuotes( $s ) {
1132 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1138 public function removeIdentifierQuotes( $s ) {
1139 return strpos($s, '/*Q*/') === FALSE ?
$s : substr($s, 5);
1142 public function isQuotedIdentifier( $s ) {
1143 return strpos($s, '/*Q*/') !== FALSE;
1146 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1149 if ($conds != null) {
1151 $conds = ( !is_array( $conds ) ) ?
array( $conds ) : $conds;
1152 foreach ( $conds as $col => $val ) {
1153 $col_info = $this->fieldInfoMulti( $table, $col );
1154 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1155 if ( $col_type == 'CLOB' ) {
1156 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1157 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1158 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1160 $conds2[$col] = $val;
1164 return parent
::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1166 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1171 * Returns an optional USE INDEX clause to go after the table, and a
1172 * string to go at the end of the query
1176 * @param $options Array: an associative array of options to be turned into
1177 * an SQL query, valid keys are listed in the function.
1180 function makeSelectOptions( $options ) {
1181 $preLimitTail = $postLimitTail = '';
1184 $noKeyOptions = array();
1185 foreach ( $options as $key => $option ) {
1186 if ( is_numeric( $key ) ) {
1187 $noKeyOptions[$option] = true;
1191 if ( isset( $options['GROUP BY'] ) ) {
1192 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1194 if ( isset( $options['ORDER BY'] ) ) {
1195 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1198 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1199 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1200 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1201 $startOpts .= 'DISTINCT';
1204 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1205 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1210 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1213 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1216 if ( $wgContLang != null && $conds != null && $conds != '*' ) {
1218 $conds = ( !is_array( $conds ) ) ?
array( $conds ) : $conds;
1219 foreach ( $conds as $col => $val ) {
1220 $col_info = $this->fieldInfoMulti( $table, $col );
1221 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1222 if ( $col_type == 'CLOB' ) {
1223 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1225 if ( is_array( $val ) ) {
1226 $conds2[$col] = $val;
1227 foreach ( $conds2[$col] as &$val2 ) {
1228 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1231 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1236 return parent
::delete( $table, $conds2, $fname );
1238 return parent
::delete( $table, $conds, $fname );
1242 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1245 $table = $this->tableName( $table );
1246 $opts = $this->makeUpdateOptions( $options );
1247 $sql = "UPDATE $opts $table SET ";
1250 foreach ( $values as $col => &$val ) {
1251 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1254 $sqlSet = ', ' . $sqlSet;
1261 if ( $conds != '*' ) {
1262 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1265 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1266 $e = oci_error( $this->mConn
);
1267 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1270 foreach ( $values as $col => &$val ) {
1271 $col_info = $this->fieldInfoMulti( $table, $col );
1272 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1274 if ( $val === null ) {
1275 // do nothing ... null was inserted in statement creation
1276 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1277 if ( is_object( $val ) ) {
1278 $val = $val->getData();
1281 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1282 $val = '31-12-2030 12:00:00.000000';
1285 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1286 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1287 $e = oci_error( $stmt );
1288 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1292 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1293 $e = oci_error( $stmt );
1294 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1297 if ( $col_type == 'BLOB' ) {
1298 $lob[$col]->writeTemporary( $val );
1299 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
1301 $lob[$col]->writeTemporary( $val );
1302 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
1307 wfSuppressWarnings();
1309 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1310 $e = oci_error( $stmt );
1311 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
1312 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1315 $this->mAffectedRows
= oci_num_rows( $stmt );
1318 $this->mAffectedRows
= oci_num_rows( $stmt );
1321 wfRestoreWarnings();
1323 if ( isset( $lob ) ) {
1324 foreach ( $lob as $lob_v ) {
1329 if ( !$this->mTrxLevel
) {
1330 oci_commit( $this->mConn
);
1333 oci_free_statement( $stmt );
1336 function bitNot( $field ) {
1337 // expecting bit-fields smaller than 4bytes
1338 return 'BITNOT(' . $field . ')';
1341 function bitAnd( $fieldLeft, $fieldRight ) {
1342 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1345 function bitOr( $fieldLeft, $fieldRight ) {
1346 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1349 function setFakeMaster( $enabled = true ) { }
1351 function getDBname() {
1352 return $this->mDBname
;
1355 function getServer() {
1356 return $this->mServer
;
1359 public function getSearchEngine() {
1360 return 'SearchOracle';
1362 } // end DatabaseOracle class