* close connection in class destructor (unlike MySql, Oracle does not commit on close)
[mediawiki.git] / includes / db / DatabaseOracle.php
blob32ffcc90985a7ec43c2b56d1f103703222853e87
1 <?php
2 /**
3 * This is the Oracle database abstraction layer.
5 * @file
6 * @ingroup Database
7 */
9 /**
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.
13 * @ingroup Database
15 class ORAResult {
16 private $rows;
17 private $cursor;
18 private $nrows;
20 private $columns = array();
22 private function array_unique_md( $array_in ) {
23 $array_out = array();
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;
30 $array_out[] = $item;
34 return $array_out;
37 function __construct( &$db, $stmt, $unique = false ) {
38 $this->db =& $db;
40 if ( ( $this->nrows = oci_fetch_all( $stmt, $this->rows, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM ) ) === false ) {
41 $e = oci_error( $stmt );
42 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__ );
43 $this->free();
44 return;
47 if ( $unique ) {
48 $this->rows = $this->array_unique_md( $this->rows );
49 $this->nrows = count( $this->rows );
52 if ($this->nrows > 0) {
53 foreach ( $this->rows[0] as $k => $v ) {
54 $this->columns[$k] = strtolower( oci_field_name( $stmt, $k + 1 ) );
58 $this->cursor = 0;
59 oci_free_statement( $stmt );
62 public function free() {
63 unset($this->db);
66 public function seek( $row ) {
67 $this->cursor = min( $row, $this->nrows );
70 public function numRows() {
71 return $this->nrows;
74 public function numFields() {
75 return count($this->columns);
78 public function fetchObject() {
79 if ( $this->cursor >= $this->nrows ) {
80 return false;
82 $row = $this->rows[$this->cursor++];
83 $ret = new stdClass();
84 foreach ( $row as $k => $v ) {
85 $lc = $this->columns[$k];
86 $ret->$lc = $v;
89 return $ret;
92 public function fetchRow() {
93 if ( $this->cursor >= $this->nrows ) {
94 return false;
97 $row = $this->rows[$this->cursor++];
98 $ret = array();
99 foreach ( $row as $k => $v ) {
100 $lc = $this->columns[$k];
101 $ret[$lc] = $v;
102 $ret[$k] = $v;
104 return $ret;
109 * Utility class.
110 * @ingroup Database
112 class ORAField implements Field {
113 private $name, $tablename, $default, $max_length, $nullable,
114 $is_pk, $is_unique, $is_multiple, $is_key, $type;
116 function __construct( $info ) {
117 $this->name = $info['column_name'];
118 $this->tablename = $info['table_name'];
119 $this->default = $info['data_default'];
120 $this->max_length = $info['data_length'];
121 $this->nullable = $info['not_null'];
122 $this->is_pk = isset( $info['prim'] ) && $info['prim'] == 1 ? 1 : 0;
123 $this->is_unique = isset( $info['uniq'] ) && $info['uniq'] == 1 ? 1 : 0;
124 $this->is_multiple = isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ? 1 : 0;
125 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
126 $this->type = $info['data_type'];
129 function name() {
130 return $this->name;
133 function tableName() {
134 return $this->tablename;
137 function defaultValue() {
138 return $this->default;
141 function maxLength() {
142 return $this->max_length;
145 function isNullable() {
146 return $this->nullable;
149 function isKey() {
150 return $this->is_key;
153 function isMultipleKey() {
154 return $this->is_multiple;
157 function type() {
158 return $this->type;
163 * @ingroup Database
165 class DatabaseOracle extends DatabaseBase {
166 var $mInsertId = null;
167 var $mLastResult = null;
168 var $lastResult = null;
169 var $cursor = 0;
170 var $mAffectedRows;
172 var $ignore_DUP_VAL_ON_INDEX = false;
173 var $sequenceData = null;
175 var $defaultCharset = 'AL32UTF8';
177 var $mFieldInfoCache = array();
179 function __construct( $server = false, $user = false, $password = false, $dbName = false,
180 $flags = 0, $tablePrefix = 'get from global' )
182 global $wgDBprefix;
183 $tablePrefix = $tablePrefix == 'get from global' ? strtoupper( $wgDBprefix ) : strtoupper( $tablePrefix );
184 parent::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
185 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
188 function __destruct() {
189 if ($this->mOpened) {
190 wfSuppressWarnings();
191 $this->close();
192 wfRestoreWarnings();
196 function getType() {
197 return 'oracle';
200 function cascadingDeletes() {
201 return true;
203 function cleanupTriggers() {
204 return true;
206 function strictIPs() {
207 return true;
209 function realTimestamps() {
210 return true;
212 function implicitGroupby() {
213 return false;
215 function implicitOrderby() {
216 return false;
218 function searchableIPs() {
219 return true;
223 * Usually aborts on failure
225 function open( $server, $user, $password, $dbName ) {
226 if ( !function_exists( 'oci_connect' ) ) {
227 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" );
230 $this->close();
231 $this->mUser = $user;
232 $this->mPassword = $password;
233 // changed internal variables functions
234 // mServer now holds the TNS endpoint
235 // mDBname is schema name if different from username
236 if ( !$server ) {
237 // backward compatibillity (server used to be null and TNS was supplied in dbname)
238 $this->mServer = $dbName;
239 $this->mDBname = $user;
240 } else {
241 $this->mServer = $server;
242 if ( !$dbName ) {
243 $this->mDBname = $user;
244 } else {
245 $this->mDBname = $dbName;
249 if ( !strlen( $user ) ) { # e.g. the class is being loaded
250 return;
253 $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
254 wfSuppressWarnings();
255 if ( $this->mFlags & DBO_DEFAULT ) {
256 $this->mConn = oci_new_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
257 } else {
258 $this->mConn = oci_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
260 wfRestoreWarnings();
262 if ( $this->mUser != $this->mDBname ) {
263 //change current schema in session
264 $this->selectDB( $this->mDBname );
267 if ( !$this->mConn ) {
268 throw new DBConnectionError( $this, $this->lastError() );
271 $this->mOpened = true;
273 # removed putenv calls because they interfere with the system globaly
274 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
275 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
276 return $this->mConn;
280 * Closes a database connection, if it is open
281 * Returns success, true if already closed
283 function close() {
284 $this->mOpened = false;
285 if ( $this->mConn ) {
286 if ( $this->mTrxLevel ) {
287 $this->commit();
289 return oci_close( $this->mConn );
290 } else {
291 return true;
295 function execFlags() {
296 return $this->mTrxLevel ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
299 function doQuery( $sql ) {
300 wfDebug( "SQL: [$sql]\n" );
301 if ( !mb_check_encoding( $sql ) ) {
302 throw new MWException( "SQL encoding is invalid\n$sql" );
305 // handle some oracle specifics
306 // remove AS column/table/subquery namings
307 if( !$this->getFlag( DBO_DDLMODE ) ) {
308 $sql = preg_replace( '/ as /i', ' ', $sql );
311 // Oracle has issues with UNION clause if the statement includes LOB fields
312 // So we do a UNION ALL and then filter the results array with array_unique
313 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
314 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
315 // you have to select data from plan table after explain
316 $explain_id = date( 'dmYHis' );
318 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
320 wfSuppressWarnings();
322 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
323 $e = oci_error( $this->mConn );
324 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
325 return false;
328 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
329 $e = oci_error( $stmt );
330 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
331 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
332 return false;
336 wfRestoreWarnings();
338 if ( $explain_count > 0 ) {
339 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
340 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
341 return new ORAResult( $this, $stmt, $union_unique );
342 } else {
343 $this->mAffectedRows = oci_num_rows( $stmt );
344 return true;
348 function queryIgnore( $sql, $fname = '' ) {
349 return $this->query( $sql, $fname, true );
352 function freeResult( $res ) {
353 if ( $res instanceof ResultWrapper ) {
354 $res = $res->result;
357 $res->free();
360 function fetchObject( $res ) {
361 if ( $res instanceof ResultWrapper ) {
362 $res = $res->result;
365 return $res->fetchObject();
368 function fetchRow( $res ) {
369 if ( $res instanceof ResultWrapper ) {
370 $res = $res->result;
373 return $res->fetchRow();
376 function numRows( $res ) {
377 if ( $res instanceof ResultWrapper ) {
378 $res = $res->result;
381 return $res->numRows();
384 function numFields( $res ) {
385 if ( $res instanceof ResultWrapper ) {
386 $res = $res->result;
389 return $res->numFields();
392 function fieldName( $stmt, $n ) {
393 return oci_field_name( $stmt, $n );
397 * This must be called after nextSequenceVal
399 function insertId() {
400 return $this->mInsertId;
403 function dataSeek( $res, $row ) {
404 if ( $res instanceof ORAResult ) {
405 $res->seek( $row );
406 } else {
407 $res->result->seek( $row );
411 function lastError() {
412 if ( $this->mConn === false ) {
413 $e = oci_error();
414 } else {
415 $e = oci_error( $this->mConn );
417 return $e['message'];
420 function lastErrno() {
421 if ( $this->mConn === false ) {
422 $e = oci_error();
423 } else {
424 $e = oci_error( $this->mConn );
426 return $e['code'];
429 function affectedRows() {
430 return $this->mAffectedRows;
434 * Returns information about an index
435 * If errors are explicitly ignored, returns NULL on failure
437 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
438 return false;
441 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
442 return false;
445 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
446 if ( !count( $a ) ) {
447 return true;
450 if ( !is_array( $options ) ) {
451 $options = array( $options );
454 if ( in_array( 'IGNORE', $options ) ) {
455 $this->ignore_DUP_VAL_ON_INDEX = true;
458 if ( !is_array( reset( $a ) ) ) {
459 $a = array( $a );
462 foreach ( $a as &$row ) {
463 $this->insertOneRow( $table, $row, $fname );
465 $retVal = true;
467 if ( in_array( 'IGNORE', $options ) ) {
468 $this->ignore_DUP_VAL_ON_INDEX = false;
471 return $retVal;
474 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
475 $col_info = $this->fieldInfoMulti( $table, $col );
476 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
478 $bind = '';
479 if ( is_numeric( $col ) ) {
480 $bind = $val;
481 $val = null;
482 return $bind;
483 } else if ( $includeCol ) {
484 $bind = "$col = ";
487 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
488 $val = null;
491 if ( $val === null ) {
492 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
493 $bind .= 'DEFAULT';
494 } else {
495 $bind .= 'NULL';
497 } else {
498 $bind .= ':' . $col;
501 return $bind;
504 private function insertOneRow( $table, $row, $fname ) {
505 global $wgContLang;
507 $table = $this->tableName( $table );
508 // "INSERT INTO tables (a, b, c)"
509 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
510 $sql .= " VALUES (";
512 // for each value, append ":key"
513 $first = true;
514 foreach ( $row as $col => &$val ) {
515 if ( !$first ) {
516 $sql .= ', ';
517 } else {
518 $first = false;
521 $sql .= $this->fieldBindStatement( $table, $col, $val );
523 $sql .= ')';
525 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
526 $e = oci_error( $this->mConn );
527 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
528 return false;
530 foreach ( $row as $col => &$val ) {
531 $col_info = $this->fieldInfoMulti( $table, $col );
532 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
534 if ( $val === null ) {
535 // do nothing ... null was inserted in statement creation
536 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
537 if ( is_object( $val ) ) {
538 $val = $val->fetch();
541 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
542 $val = '31-12-2030 12:00:00.000000';
545 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
546 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
547 $e = oci_error( $stmt );
548 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
549 return false;
551 } else {
552 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
553 $e = oci_error( $stmt );
554 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
557 if ( is_object( $val ) ) {
558 $val = $val->fetch();
561 if ( $col_type == 'BLOB' ) {
562 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
563 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB );
564 } else {
565 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
566 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
571 wfSuppressWarnings();
573 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
574 $e = oci_error( $stmt );
575 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
576 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
577 return false;
578 } else {
579 $this->mAffectedRows = oci_num_rows( $stmt );
581 } else {
582 $this->mAffectedRows = oci_num_rows( $stmt );
585 wfRestoreWarnings();
587 if ( isset( $lob ) ) {
588 foreach ( $lob as $lob_v ) {
589 $lob_v->free();
593 if ( !$this->mTrxLevel ) {
594 oci_commit( $this->mConn );
597 oci_free_statement( $stmt );
600 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
601 $insertOptions = array(), $selectOptions = array() )
603 $destTable = $this->tableName( $destTable );
604 if ( !is_array( $selectOptions ) ) {
605 $selectOptions = array( $selectOptions );
607 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
608 if ( is_array( $srcTable ) ) {
609 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
610 } else {
611 $srcTable = $this->tableName( $srcTable );
614 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
615 !isset( $varMap[$sequenceData['column']] ) )
617 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
620 // count-alias subselect fields to avoid abigious definition errors
621 $i = 0;
622 foreach ( $varMap as &$val ) {
623 $val = $val . ' field' . ( $i++ );
626 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
627 " SELECT $startOpts " . implode( ',', $varMap ) .
628 " FROM $srcTable $useIndex ";
629 if ( $conds != '*' ) {
630 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
632 $sql .= " $tailOpts";
634 if ( in_array( 'IGNORE', $insertOptions ) ) {
635 $this->ignore_DUP_VAL_ON_INDEX = true;
638 $retval = $this->query( $sql, $fname );
640 if ( in_array( 'IGNORE', $insertOptions ) ) {
641 $this->ignore_DUP_VAL_ON_INDEX = false;
644 return $retval;
647 function tableName( $name, $quoted = true ) {
649 Replace reserved words with better ones
650 Using uppercase because that's the only way Oracle can handle
651 quoted tablenames
653 switch( $name ) {
654 case 'user':
655 $name = 'MWUSER';
656 break;
657 case 'text':
658 $name = 'PAGECONTENT';
659 break;
662 return parent::tableName( strtoupper( $name ), $quoted );
666 * Return the next in a sequence, save the value for retrieval via insertId()
668 function nextSequenceValue( $seqName ) {
669 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
670 $row = $this->fetchRow( $res );
671 $this->mInsertId = $row[0];
672 return $this->mInsertId;
676 * Return sequence_name if table has a sequence
678 private function getSequenceData( $table ) {
679 if ( $this->sequenceData == null ) {
680 $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\'' );
682 while ( ( $row = $result->fetchRow() ) !== false ) {
683 $this->sequenceData[$this->tableName( $row[1] )] = array(
684 'sequence' => $row[0],
685 'column' => $row[2]
690 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
694 * REPLACE query wrapper
695 * Oracle simulates this with a DELETE followed by INSERT
696 * $row is the row to insert, an associative array
697 * $uniqueIndexes is an array of indexes. Each element may be either a
698 * field name or an array of field names
700 * It may be more efficient to leave off unique indexes which are unlikely to collide.
701 * However if you do this, you run the risk of encountering errors which wouldn't have
702 * occurred in MySQL.
704 * @param $table String: table name
705 * @param $uniqueIndexes Array: array of indexes. Each element may be
706 * either a field name or an array of field names
707 * @param $rows Array: rows to insert to $table
708 * @param $fname String: function name, you can use __METHOD__ here
710 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
711 $table = $this->tableName( $table );
713 if ( count( $rows ) == 0 ) {
714 return;
717 # Single row case
718 if ( !is_array( reset( $rows ) ) ) {
719 $rows = array( $rows );
722 $sequenceData = $this->getSequenceData( $table );
724 foreach ( $rows as $row ) {
725 # Delete rows which collide
726 if ( $uniqueIndexes ) {
727 $condsDelete = array();
728 foreach ( $uniqueIndexes as $index ) {
729 $condsDelete[$index] = $row[$index];
731 if ( count( $condsDelete ) > 0 ) {
732 $this->delete( $table, $condsDelete, $fname );
736 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
737 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
740 # Now insert the row
741 $this->insert( $table, $row, $fname );
745 # DELETE where the condition is a join
746 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
747 if ( !$conds ) {
748 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
751 $delTable = $this->tableName( $delTable );
752 $joinTable = $this->tableName( $joinTable );
753 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
754 if ( $conds != '*' ) {
755 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
757 $sql .= ')';
759 $this->query( $sql, $fname );
762 # Returns the size of a text field, or -1 for "unlimited"
763 function textFieldSize( $table, $field ) {
764 $fieldInfoData = $this->fieldInfo( $table, $field );
765 return $fieldInfoData->maxLength();
768 function limitResult( $sql, $limit, $offset = false ) {
769 if ( $offset === false ) {
770 $offset = 0;
772 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
775 function encodeBlob( $b ) {
776 return new Blob( $b );
779 function decodeBlob( $b ) {
780 if ( $b instanceof Blob ) {
781 $b = $b->fetch();
783 return $b;
786 function unionQueries( $sqls, $all ) {
787 $glue = ' UNION ALL ';
788 return 'SELECT * ' . ( $all ? '':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
791 function wasDeadlock() {
792 return $this->lastErrno() == 'OCI-00060';
795 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
796 global $wgDBprefix;
797 $this->setFlag( DBO_DDLMODE );
799 $temporary = $temporary ? 'TRUE' : 'FALSE';
801 $newName = strtoupper( $newName );
802 $oldName = strtoupper( $oldName );
804 $tabName = $this->addIdentifierQuotes( substr( $newName, strlen( $wgDBprefix ) ) );
805 $oldPrefix = $this->addIdentifierQuotes( substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) ) );
806 $newPrefix = $this->addIdentifierQuotes( $wgDBprefix );
808 $this->clearFlag( DBO_DDLMODE );
809 return $this->doQuery( "BEGIN DUPLICATE_TABLE( $tabName, $oldPrefix, $newPrefix, $temporary ); END;" );
812 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
813 $listWhere = '';
814 if (!empty($prefix)) {
815 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
818 $result = $this->doQuery( "SELECT table_name FROM user_tables WHERE table_name NOT LIKE '%!_IDX$_' ESCAPE '!' $listWhere" );
820 // dirty code ... i know
821 $endArray = array();
822 $endArray[] = $prefix.'MWUSER';
823 $endArray[] = $prefix.'PAGE';
824 $endArray[] = $prefix.'IMAGE';
825 $fixedOrderTabs = $endArray;
826 while (($row = $result->fetchRow()) !== false) {
827 if (!in_array($row['table_name'], $fixedOrderTabs))
828 $endArray[] = $row['table_name'];
831 return $endArray;
834 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
835 $tableName = $this->tableName($tableName);
836 if( !$this->tableExists( $tableName ) ) {
837 return false;
840 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
843 function timestamp( $ts = 0 ) {
844 return wfTimestamp( TS_ORACLE, $ts );
848 * Return aggregated value function call
850 function aggregateValue ( $valuedata, $valuename = 'value' ) {
851 return $valuedata;
854 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
855 # Ignore errors during error handling to avoid infinite
856 # recursion
857 $ignore = $this->ignoreErrors( true );
858 ++$this->mErrorCount;
860 if ( $ignore || $tempIgnore ) {
861 wfDebug( "SQL ERROR (ignored): $error\n" );
862 $this->ignoreErrors( $ignore );
863 } else {
864 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
869 * @return string wikitext of a link to the server software's web site
871 public static function getSoftwareLink() {
872 return '[http://www.oracle.com/ Oracle]';
876 * @return string Version information from the database
878 function getServerVersion() {
879 //better version number, fallback on driver
880 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
881 if ( !( $row = $rset->fetchRow() ) ) {
882 return oci_server_version( $this->mConn );
884 return $row['version'];
888 * Query whether a given table exists (in the given schema, or the default mw one if not given)
890 function tableExists( $table ) {
891 $table = $this->removeIdentifierQuotes($table);
892 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
893 $res = $this->doQuery( $SQL );
894 if ( $res ) {
895 $count = $res->numRows();
896 $res->free();
897 } else {
898 $count = 0;
900 return $count;
904 * Function translates mysql_fetch_field() functionality on ORACLE.
905 * Caching is present for reducing query time.
906 * For internal calls. Use fieldInfo for normal usage.
907 * Returns false if the field doesn't exist
909 * @param $table Array
910 * @param $field String
911 * @return ORAField
913 private function fieldInfoMulti( $table, $field ) {
914 $field = strtoupper( $field );
915 if ( is_array( $table ) ) {
916 $table = array_map( array( &$this, 'tableName' ), $table );
917 $tableWhere = 'IN (';
918 foreach( $table as &$singleTable ) {
919 $singleTable = $this->removeIdentifierQuotes($singleTable);
920 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
921 return $this->mFieldInfoCache["$singleTable.$field"];
923 $tableWhere .= '\'' . $singleTable . '\',';
925 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
926 } else {
927 $table = $this->removeIdentifierQuotes($table);
928 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
929 return $this->mFieldInfoCache["$table.$field"];
931 $tableWhere = '= \''.$table.'\'';
934 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
935 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
936 $e = oci_error( $fieldInfoStmt );
937 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
938 return false;
940 $res = new ORAResult( $this, $fieldInfoStmt );
941 if ( $res->numRows() == 0 ) {
942 if ( is_array( $table ) ) {
943 foreach( $table as &$singleTable ) {
944 $this->mFieldInfoCache["$singleTable.$field"] = false;
946 } else {
947 $this->mFieldInfoCache["$table.$field"] = false;
949 $fieldInfoTemp = null;
950 } else {
951 $fieldInfoTemp = new ORAField( $res->fetchRow() );
952 $table = $fieldInfoTemp->tableName();
953 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
955 $res->free();
956 return $fieldInfoTemp;
960 * @throws DBUnexpectedError
961 * @param $table
962 * @param $field
963 * @return ORAField
965 function fieldInfo( $table, $field ) {
966 if ( is_array( $table ) ) {
967 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
969 return $this->fieldInfoMulti ($table, $field);
972 function begin( $fname = 'DatabaseOracle::begin' ) {
973 $this->mTrxLevel = 1;
976 function commit( $fname = 'DatabaseOracle::commit' ) {
977 if ( $this->mTrxLevel ) {
978 oci_commit( $this->mConn );
979 $this->mTrxLevel = 0;
983 function rollback( $fname = 'DatabaseOracle::rollback' ) {
984 if ( $this->mTrxLevel ) {
985 oci_rollback( $this->mConn );
986 $this->mTrxLevel = 0;
990 /* Not even sure why this is used in the main codebase... */
991 function limitResultForUpdate( $sql, $num ) {
992 return $sql;
995 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
996 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
997 $cmd = '';
998 $done = false;
999 $dollarquote = false;
1001 $replacements = array();
1003 while ( ! feof( $fp ) ) {
1004 if ( $lineCallback ) {
1005 call_user_func( $lineCallback );
1007 $line = trim( fgets( $fp, 1024 ) );
1008 $sl = strlen( $line ) - 1;
1010 if ( $sl < 0 ) {
1011 continue;
1013 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1014 continue;
1017 // Allow dollar quoting for function declarations
1018 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1019 if ( $dollarquote ) {
1020 $dollarquote = false;
1021 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1022 $done = true;
1023 } else {
1024 $dollarquote = true;
1026 } elseif ( !$dollarquote ) {
1027 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1028 $done = true;
1029 $line = substr( $line, 0, $sl );
1033 if ( $cmd != '' ) {
1034 $cmd .= ' ';
1036 $cmd .= "$line\n";
1038 if ( $done ) {
1039 $cmd = str_replace( ';;', ";", $cmd );
1040 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1041 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1042 $replacements[$defines[2]] = $defines[1];
1044 } else {
1045 foreach ( $replacements as $mwVar => $scVar ) {
1046 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1049 $cmd = $this->replaceVars( $cmd );
1050 $res = $this->doQuery( $cmd );
1051 if ( $resultCallback ) {
1052 call_user_func( $resultCallback, $res, $this );
1055 if ( false === $res ) {
1056 $err = $this->lastError();
1057 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1061 $cmd = '';
1062 $done = false;
1065 return true;
1068 function selectDB( $db ) {
1069 $this->mDBname = $db;
1070 if ( $db == null || $db == $this->mUser ) {
1071 return true;
1073 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1074 $stmt = oci_parse( $this->mConn, $sql );
1075 wfSuppressWarnings();
1076 $success = oci_execute( $stmt );
1077 wfRestoreWarnings();
1078 if ( !$success ) {
1079 $e = oci_error( $stmt );
1080 if ( $e['code'] != '1435' ) {
1081 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1083 return false;
1085 return true;
1088 function strencode( $s ) {
1089 return str_replace( "'", "''", $s );
1092 function addQuotes( $s ) {
1093 global $wgContLang;
1094 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1095 $s = $wgContLang->checkTitleEncoding( $s );
1097 return "'" . $this->strencode( $s ) . "'";
1100 public function addIdentifierQuotes( $s ) {
1101 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1102 $s = '/*Q*/' . $s;
1104 return $s;
1107 public function removeIdentifierQuotes( $s ) {
1108 return strpos($s, '/*Q*/') === FALSE ? $s : substr($s, 5);
1111 public function isQuotedIdentifier( $s ) {
1112 return strpos($s, '/*Q*/') !== FALSE;
1115 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1116 global $wgContLang;
1118 if ($conds != null) {
1119 $conds2 = array();
1120 $conds = ( !is_array( $conds ) ) ? array( $conds ) : $conds;
1121 foreach ( $conds as $col => $val ) {
1122 $col_info = $this->fieldInfoMulti( $table, $col );
1123 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1124 if ( $col_type == 'CLOB' ) {
1125 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1126 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1127 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1128 } else {
1129 $conds2[$col] = $val;
1133 return parent::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1134 } else {
1135 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1140 * Returns an optional USE INDEX clause to go after the table, and a
1141 * string to go at the end of the query
1143 * @private
1145 * @param $options Array: an associative array of options to be turned into
1146 * an SQL query, valid keys are listed in the function.
1147 * @return array
1149 function makeSelectOptions( $options ) {
1150 $preLimitTail = $postLimitTail = '';
1151 $startOpts = '';
1153 $noKeyOptions = array();
1154 foreach ( $options as $key => $option ) {
1155 if ( is_numeric( $key ) ) {
1156 $noKeyOptions[$option] = true;
1160 if ( isset( $options['GROUP BY'] ) ) {
1161 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1163 if ( isset( $options['ORDER BY'] ) ) {
1164 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1167 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1168 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1169 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1170 $startOpts .= 'DISTINCT';
1173 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1174 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1175 } else {
1176 $useIndex = '';
1179 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1182 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1183 global $wgContLang;
1185 if ( $wgContLang != null && $conds != null && $conds != '*' ) {
1186 $conds2 = array();
1187 $conds = ( !is_array( $conds ) ) ? array( $conds ) : $conds;
1188 foreach ( $conds as $col => $val ) {
1189 $col_info = $this->fieldInfoMulti( $table, $col );
1190 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1191 if ( $col_type == 'CLOB' ) {
1192 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1193 } else {
1194 if ( is_array( $val ) ) {
1195 $conds2[$col] = $val;
1196 foreach ( $conds2[$col] as &$val2 ) {
1197 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1199 } else {
1200 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1205 return parent::delete( $table, $conds2, $fname );
1206 } else {
1207 return parent::delete( $table, $conds, $fname );
1211 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1212 global $wgContLang;
1214 $table = $this->tableName( $table );
1215 $opts = $this->makeUpdateOptions( $options );
1216 $sql = "UPDATE $opts $table SET ";
1218 $first = true;
1219 foreach ( $values as $col => &$val ) {
1220 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1222 if ( !$first ) {
1223 $sqlSet = ', ' . $sqlSet;
1224 } else {
1225 $first = false;
1227 $sql .= $sqlSet;
1230 if ( $conds != '*' ) {
1231 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1234 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1235 $e = oci_error( $this->mConn );
1236 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1237 return false;
1239 foreach ( $values as $col => &$val ) {
1240 $col_info = $this->fieldInfoMulti( $table, $col );
1241 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1243 if ( $val === null ) {
1244 // do nothing ... null was inserted in statement creation
1245 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1246 if ( is_object( $val ) ) {
1247 $val = $val->getData();
1250 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1251 $val = '31-12-2030 12:00:00.000000';
1254 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1255 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1256 $e = oci_error( $stmt );
1257 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1258 return false;
1260 } else {
1261 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1262 $e = oci_error( $stmt );
1263 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1266 if ( $col_type == 'BLOB' ) {
1267 $lob[$col]->writeTemporary( $val );
1268 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1269 } else {
1270 $lob[$col]->writeTemporary( $val );
1271 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1276 wfSuppressWarnings();
1278 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1279 $e = oci_error( $stmt );
1280 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1281 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1282 return false;
1283 } else {
1284 $this->mAffectedRows = oci_num_rows( $stmt );
1286 } else {
1287 $this->mAffectedRows = oci_num_rows( $stmt );
1290 wfRestoreWarnings();
1292 if ( isset( $lob ) ) {
1293 foreach ( $lob as $lob_v ) {
1294 $lob_v->free();
1298 if ( !$this->mTrxLevel ) {
1299 oci_commit( $this->mConn );
1302 oci_free_statement( $stmt );
1305 function bitNot( $field ) {
1306 // expecting bit-fields smaller than 4bytes
1307 return 'BITNOT(' . $field . ')';
1310 function bitAnd( $fieldLeft, $fieldRight ) {
1311 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1314 function bitOr( $fieldLeft, $fieldRight ) {
1315 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1318 function setFakeMaster( $enabled = true ) { }
1320 function getDBname() {
1321 return $this->mDBname;
1324 function getServer() {
1325 return $this->mServer;
1328 public function getSearchEngine() {
1329 return 'SearchOracle';
1331 } // end DatabaseOracle class