* OracleInstaller now also supports installation with (requested by Tim):
[mediawiki.git] / includes / db / DatabaseOracle.php
blob6c07a3a2f7b8a74d252b05d82a3e8183643f0915
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 $numeric_version = null;
169 var $lastResult = null;
170 var $cursor = 0;
171 var $mAffectedRows;
173 var $ignore_DUP_VAL_ON_INDEX = false;
174 var $sequenceData = null;
176 var $defaultCharset = 'AL32UTF8';
178 var $mFieldInfoCache = array();
180 function __construct( $server = false, $user = false, $password = false, $dbName = false,
181 $flags = 0, $tablePrefix = 'get from global' )
183 $tablePrefix = $tablePrefix == 'get from global' ? $tablePrefix : strtoupper( $tablePrefix );
184 parent::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
185 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
188 function getType() {
189 return 'oracle';
192 function cascadingDeletes() {
193 return true;
195 function cleanupTriggers() {
196 return true;
198 function strictIPs() {
199 return true;
201 function realTimestamps() {
202 return true;
204 function implicitGroupby() {
205 return false;
207 function implicitOrderby() {
208 return false;
210 function searchableIPs() {
211 return true;
215 * Usually aborts on failure
217 function open( $server, $user, $password, $dbName ) {
218 if ( !function_exists( 'oci_connect' ) ) {
219 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" );
222 $this->close();
223 $this->mUser = $user;
224 $this->mPassword = $password;
225 // changed internal variables functions
226 // mServer now holds the TNS endpoint
227 // mDBname is schema name if different from username
228 if ( !$server ) {
229 // backward compatibillity (server used to be null and TNS was supplied in dbname)
230 $this->mServer = $dbName;
231 $this->mDBname = $user;
232 } else {
233 $this->mServer = $server;
234 if ( !$dbName ) {
235 $this->mDBname = $user;
236 } else {
237 $this->mDBname = $dbName;
241 if ( !strlen( $user ) ) { # e.g. the class is being loaded
242 return;
245 $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
246 if ( $this->mFlags & DBO_DEFAULT ) {
247 $this->mConn = @oci_new_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
248 } else {
249 $this->mConn = @oci_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
252 if ( $this->mUser != $this->mDBname ) {
253 //change current schema in session
254 $this->selectDB( $this->mDBname );
257 if ( !$this->mConn ) {
258 throw new DBConnectionError( $this, $this->lastError() );
261 $this->mOpened = true;
263 # removed putenv calls because they interfere with the system globaly
264 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
265 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
266 return $this->mConn;
270 * Closes a database connection, if it is open
271 * Returns success, true if already closed
273 function close() {
274 $this->mOpened = false;
275 if ( $this->mConn ) {
276 return oci_close( $this->mConn );
277 } else {
278 return true;
282 function execFlags() {
283 return $this->mTrxLevel ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
286 function doQuery( $sql ) {
287 wfDebug( "SQL: [$sql]\n" );
288 if ( !mb_check_encoding( $sql ) ) {
289 throw new MWException( "SQL encoding is invalid\n$sql" );
292 // handle some oracle specifics
293 // remove AS column/table/subquery namings
294 if( !$this->getFlag( DBO_DDLMODE ) ) {
295 $sql = preg_replace( '/ as /i', ' ', $sql );
298 // Oracle has issues with UNION clause if the statement includes LOB fields
299 // So we do a UNION ALL and then filter the results array with array_unique
300 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
301 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
302 // you have to select data from plan table after explain
303 $explain_id = date( 'dmYHis' );
305 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
307 wfSuppressWarnings();
309 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
310 $e = oci_error( $this->mConn );
311 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
312 return false;
315 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
316 $e = oci_error( $stmt );
317 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
318 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
319 return false;
323 wfRestoreWarnings();
325 if ( $explain_count > 0 ) {
326 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
327 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
328 return new ORAResult( $this, $stmt, $union_unique );
329 } else {
330 $this->mAffectedRows = oci_num_rows( $stmt );
331 return true;
335 function queryIgnore( $sql, $fname = '' ) {
336 return $this->query( $sql, $fname, true );
339 function freeResult( $res ) {
340 if ( $res instanceof ResultWrapper ) {
341 $res = $res->result;
344 $res->free();
347 function fetchObject( $res ) {
348 if ( $res instanceof ResultWrapper ) {
349 $res = $res->result;
352 return $res->fetchObject();
355 function fetchRow( $res ) {
356 if ( $res instanceof ResultWrapper ) {
357 $res = $res->result;
360 return $res->fetchRow();
363 function numRows( $res ) {
364 if ( $res instanceof ResultWrapper ) {
365 $res = $res->result;
368 return $res->numRows();
371 function numFields( $res ) {
372 if ( $res instanceof ResultWrapper ) {
373 $res = $res->result;
376 return $res->numFields();
379 function fieldName( $stmt, $n ) {
380 return oci_field_name( $stmt, $n );
384 * This must be called after nextSequenceVal
386 function insertId() {
387 return $this->mInsertId;
390 function dataSeek( $res, $row ) {
391 if ( $res instanceof ORAResult ) {
392 $res->seek( $row );
393 } else {
394 $res->result->seek( $row );
398 function lastError() {
399 if ( $this->mConn === false ) {
400 $e = oci_error();
401 } else {
402 $e = oci_error( $this->mConn );
404 return $e['message'];
407 function lastErrno() {
408 if ( $this->mConn === false ) {
409 $e = oci_error();
410 } else {
411 $e = oci_error( $this->mConn );
413 return $e['code'];
416 function affectedRows() {
417 return $this->mAffectedRows;
421 * Returns information about an index
422 * If errors are explicitly ignored, returns NULL on failure
424 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
425 return false;
428 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
429 return false;
432 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
433 if ( !count( $a ) ) {
434 return true;
437 if ( !is_array( $options ) ) {
438 $options = array( $options );
441 if ( in_array( 'IGNORE', $options ) ) {
442 $this->ignore_DUP_VAL_ON_INDEX = true;
445 if ( !is_array( reset( $a ) ) ) {
446 $a = array( $a );
449 foreach ( $a as &$row ) {
450 $this->insertOneRow( $table, $row, $fname );
452 $retVal = true;
454 if ( in_array( 'IGNORE', $options ) ) {
455 $this->ignore_DUP_VAL_ON_INDEX = false;
458 return $retVal;
461 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
462 $col_info = $this->fieldInfoMulti( $table, $col );
463 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
465 $bind = '';
466 if ( is_numeric( $col ) ) {
467 $bind = $val;
468 $val = null;
469 return $bind;
470 } else if ( $includeCol ) {
471 $bind = "$col = ";
474 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
475 $val = null;
478 if ( $val === null ) {
479 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
480 $bind .= 'DEFAULT';
481 } else {
482 $bind .= 'NULL';
484 } else {
485 $bind .= ':' . $col;
488 return $bind;
491 private function insertOneRow( $table, $row, $fname ) {
492 global $wgContLang;
494 $table = $this->tableName( $table );
495 // "INSERT INTO tables (a, b, c)"
496 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
497 $sql .= " VALUES (";
499 // for each value, append ":key"
500 $first = true;
501 foreach ( $row as $col => &$val ) {
502 if ( !$first ) {
503 $sql .= ', ';
504 } else {
505 $first = false;
508 $sql .= $this->fieldBindStatement( $table, $col, $val );
510 $sql .= ')';
512 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
513 $e = oci_error( $this->mConn );
514 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
515 return false;
517 foreach ( $row as $col => &$val ) {
518 $col_info = $this->fieldInfoMulti( $table, $col );
519 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
521 if ( $val === null ) {
522 // do nothing ... null was inserted in statement creation
523 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
524 if ( is_object( $val ) ) {
525 $val = $val->fetch();
528 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
529 $val = '31-12-2030 12:00:00.000000';
532 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
533 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
534 $e = oci_error( $stmt );
535 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
536 return false;
538 } else {
539 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
540 $e = oci_error( $stmt );
541 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
544 if ( is_object( $val ) ) {
545 $val = $val->fetch();
548 if ( $col_type == 'BLOB' ) {
549 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
550 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB );
551 } else {
552 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
553 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
558 wfSuppressWarnings();
560 if ( oci_execute( $stmt, OCI_DEFAULT ) === false ) {
561 $e = oci_error( $stmt );
562 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
563 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
564 return false;
565 } else {
566 $this->mAffectedRows = oci_num_rows( $stmt );
568 } else {
569 $this->mAffectedRows = oci_num_rows( $stmt );
572 wfRestoreWarnings();
574 if ( isset( $lob ) ) {
575 foreach ( $lob as $lob_v ) {
576 $lob_v->free();
580 if ( !$this->mTrxLevel ) {
581 oci_commit( $this->mConn );
584 oci_free_statement( $stmt );
587 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
588 $insertOptions = array(), $selectOptions = array() )
590 $destTable = $this->tableName( $destTable );
591 if ( !is_array( $selectOptions ) ) {
592 $selectOptions = array( $selectOptions );
594 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
595 if ( is_array( $srcTable ) ) {
596 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
597 } else {
598 $srcTable = $this->tableName( $srcTable );
601 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
602 !isset( $varMap[$sequenceData['column']] ) )
604 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
607 // count-alias subselect fields to avoid abigious definition errors
608 $i = 0;
609 foreach ( $varMap as &$val ) {
610 $val = $val . ' field' . ( $i++ );
613 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
614 " SELECT $startOpts " . implode( ',', $varMap ) .
615 " FROM $srcTable $useIndex ";
616 if ( $conds != '*' ) {
617 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
619 $sql .= " $tailOpts";
621 if ( in_array( 'IGNORE', $insertOptions ) ) {
622 $this->ignore_DUP_VAL_ON_INDEX = true;
625 $retval = $this->query( $sql, $fname );
627 if ( in_array( 'IGNORE', $insertOptions ) ) {
628 $this->ignore_DUP_VAL_ON_INDEX = false;
631 return $retval;
634 function tableName( $name ) {
635 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
637 Replace reserved words with better ones
638 Using uppercase because that's the only way Oracle can handle
639 quoted tablenames
641 switch( $name ) {
642 case 'user':
643 $name = 'MWUSER';
644 break;
645 case 'text':
646 $name = 'PAGECONTENT';
647 break;
651 The rest of procedure is equal to generic Databse class
652 except for the quoting style
654 if ( $name[0] == '"' && substr( $name, - 1, 1 ) == '"' ) {
655 return $name;
657 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
658 return $name;
660 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
661 if ( isset( $dbDetails[1] ) ) {
662 @list( $table, $database ) = $dbDetails;
663 } else {
664 @list( $table ) = $dbDetails;
667 $prefix = $this->mTablePrefix;
669 if ( isset( $database ) ) {
670 $table = ( $table[0] == '`' ? $table : "`{$table}`" );
673 if ( !isset( $database ) && isset( $wgSharedDB ) && $table[0] != '"'
674 && isset( $wgSharedTables )
675 && is_array( $wgSharedTables )
676 && in_array( $table, $wgSharedTables )
678 $database = $wgSharedDB;
679 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
682 if ( isset( $database ) ) {
683 $database = ( $database[0] == '"' ? $database : "\"{$database}\"" );
685 $table = ( $table[0] == '"') ? $table : "\"{$prefix}{$table}\"" ;
687 $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
689 return strtoupper( $tableName );
693 * Return the next in a sequence, save the value for retrieval via insertId()
695 function nextSequenceValue( $seqName ) {
696 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
697 $row = $this->fetchRow( $res );
698 $this->mInsertId = $row[0];
699 return $this->mInsertId;
703 * Return sequence_name if table has a sequence
705 private function getSequenceData( $table ) {
706 if ( $this->sequenceData == null ) {
707 $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\'' );
709 while ( ( $row = $result->fetchRow() ) !== false ) {
710 $this->sequenceData[$this->tableName( $row[1] )] = array(
711 'sequence' => $row[0],
712 'column' => $row[2]
717 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
721 * REPLACE query wrapper
722 * Oracle simulates this with a DELETE followed by INSERT
723 * $row is the row to insert, an associative array
724 * $uniqueIndexes is an array of indexes. Each element may be either a
725 * field name or an array of field names
727 * It may be more efficient to leave off unique indexes which are unlikely to collide.
728 * However if you do this, you run the risk of encountering errors which wouldn't have
729 * occurred in MySQL.
731 * @param $table String: table name
732 * @param $uniqueIndexes Array: array of indexes. Each element may be
733 * either a field name or an array of field names
734 * @param $rows Array: rows to insert to $table
735 * @param $fname String: function name, you can use __METHOD__ here
737 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
738 $table = $this->tableName( $table );
740 if ( count( $rows ) == 0 ) {
741 return;
744 # Single row case
745 if ( !is_array( reset( $rows ) ) ) {
746 $rows = array( $rows );
749 $sequenceData = $this->getSequenceData( $table );
751 foreach ( $rows as $row ) {
752 # Delete rows which collide
753 if ( $uniqueIndexes ) {
754 $condsDelete = array();
755 foreach ( $uniqueIndexes as $index ) {
756 $condsDelete[$index] = $row[$index];
758 if ( count( $condsDelete ) > 0 ) {
759 $this->delete( $table, $condsDelete, $fname );
763 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
764 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
767 # Now insert the row
768 $this->insert( $table, $row, $fname );
772 # DELETE where the condition is a join
773 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
774 if ( !$conds ) {
775 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
778 $delTable = $this->tableName( $delTable );
779 $joinTable = $this->tableName( $joinTable );
780 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
781 if ( $conds != '*' ) {
782 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
784 $sql .= ')';
786 $this->query( $sql, $fname );
789 # Returns the size of a text field, or -1 for "unlimited"
790 function textFieldSize( $table, $field ) {
791 $fieldInfoData = $this->fieldInfo( $table, $field );
792 return $fieldInfoData->maxLength();
795 function limitResult( $sql, $limit, $offset = false ) {
796 if ( $offset === false ) {
797 $offset = 0;
799 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
802 function encodeBlob( $b ) {
803 return new Blob( $b );
806 function decodeBlob( $b ) {
807 if ( $b instanceof Blob ) {
808 $b = $b->fetch();
810 return $b;
813 function unionQueries( $sqls, $all ) {
814 $glue = ' UNION ALL ';
815 return 'SELECT * ' . ( $all ? '':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
818 function wasDeadlock() {
819 return $this->lastErrno() == 'OCI-00060';
822 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
823 global $wgDBprefix;
825 $temporary = $temporary ? 'TRUE' : 'FALSE';
827 $newName = trim( strtoupper( $newName ), '"');
828 $oldName = trim( strtoupper( $oldName ), '"');
830 $tabName = substr( $newName, strlen( $wgDBprefix ) );
831 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
833 return $this->doQuery( 'BEGIN DUPLICATE_TABLE(\'' . $tabName . '\', \'' . $oldPrefix . '\', \'' . strtoupper( $wgDBprefix ) . '\', ' . $temporary . '); END;' );
836 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
837 $listWhere = '';
838 if (!empty($prefix)) {
839 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
842 $result = $this->doQuery( "SELECT table_name FROM user_tables WHERE table_name NOT LIKE '%!_IDX$_' ESCAPE '!' $listWhere" );
844 // dirty code ... i know
845 $endArray = array();
846 $endArray[] = $prefix.'MWUSER';
847 $endArray[] = $prefix.'PAGE';
848 $endArray[] = $prefix.'IMAGE';
849 $fixedOrderTabs = $endArray;
850 while (($row = $result->fetchRow()) !== false) {
851 if (!in_array($row['table_name'], $fixedOrderTabs))
852 $endArray[] = $row['table_name'];
855 return $endArray;
858 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
859 $tableName = $this->tableName($tableName);
860 if( !$this->tableExists( $tableName ) ) {
861 return false;
864 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
867 function timestamp( $ts = 0 ) {
868 return wfTimestamp( TS_ORACLE, $ts );
872 * Return aggregated value function call
874 function aggregateValue ( $valuedata, $valuename = 'value' ) {
875 return $valuedata;
878 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
879 # Ignore errors during error handling to avoid infinite
880 # recursion
881 $ignore = $this->ignoreErrors( true );
882 ++$this->mErrorCount;
884 if ( $ignore || $tempIgnore ) {
885 wfDebug( "SQL ERROR (ignored): $error\n" );
886 $this->ignoreErrors( $ignore );
887 } else {
888 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
893 * @return string wikitext of a link to the server software's web site
895 public static function getSoftwareLink() {
896 return '[http://www.oracle.com/ Oracle]';
900 * @return string Version information from the database
902 function getServerVersion() {
903 //better version number, fallback on driver
904 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
905 if ( !( $row = $rset->fetchRow() ) ) {
906 return oci_server_version( $this->mConn );
908 return $row['version'];
912 * Query whether a given table exists (in the given schema, or the default mw one if not given)
914 function tableExists( $table ) {
915 $table = trim($this->tableName($table), '"');
916 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
917 $res = $this->doQuery( $SQL );
918 if ( $res ) {
919 $count = $res->numRows();
920 $res->free();
921 } else {
922 $count = 0;
924 return $count;
928 * Function translates mysql_fetch_field() functionality on ORACLE.
929 * Caching is present for reducing query time.
930 * For internal calls. Use fieldInfo for normal usage.
931 * Returns false if the field doesn't exist
933 * @param $table Array
934 * @param $field String
935 * @return ORAField
937 private function fieldInfoMulti( $table, $field ) {
938 $field = strtoupper( $field );
939 if ( is_array( $table ) ) {
940 $table = array_map( array( &$this, 'tableName' ), $table );
941 $tableWhere = 'IN (';
942 foreach( $table as &$singleTable ) {
943 $singleTable = strtoupper( trim( $singleTable, '"' ) );
944 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
945 return $this->mFieldInfoCache["$singleTable.$field"];
947 $tableWhere .= '\'' . $singleTable . '\',';
949 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
950 } else {
951 $table = strtoupper( trim( $this->tableName( $table ), '"' ) );
952 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
953 return $this->mFieldInfoCache["$table.$field"];
955 $tableWhere = '= \''.$table.'\'';
958 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
959 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT ) === false ) {
960 $e = oci_error( $fieldInfoStmt );
961 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
962 return false;
964 $res = new ORAResult( $this, $fieldInfoStmt );
965 if ( $res->numRows() == 0 ) {
966 if ( is_array( $table ) ) {
967 foreach( $table as &$singleTable ) {
968 $this->mFieldInfoCache["$singleTable.$field"] = false;
970 } else {
971 $this->mFieldInfoCache["$table.$field"] = false;
973 $fieldInfoTemp = null;
974 } else {
975 $fieldInfoTemp = new ORAField( $res->fetchRow() );
976 $table = $fieldInfoTemp->tableName();
977 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
979 $res->free();
980 return $fieldInfoTemp;
984 * @throws DBUnexpectedError
985 * @param $table
986 * @param $field
987 * @return ORAField
989 function fieldInfo( $table, $field ) {
990 if ( is_array( $table ) ) {
991 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
993 return $this->fieldInfoMulti ($table, $field);
996 function begin( $fname = '' ) {
997 $this->mTrxLevel = 1;
1000 function commit( $fname = '' ) {
1001 oci_commit( $this->mConn );
1002 $this->mTrxLevel = 0;
1005 /* Not even sure why this is used in the main codebase... */
1006 function limitResultForUpdate( $sql, $num ) {
1007 return $sql;
1010 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
1011 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
1012 $cmd = '';
1013 $done = false;
1014 $dollarquote = false;
1016 $replacements = array();
1018 while ( ! feof( $fp ) ) {
1019 if ( $lineCallback ) {
1020 call_user_func( $lineCallback );
1022 $line = trim( fgets( $fp, 1024 ) );
1023 $sl = strlen( $line ) - 1;
1025 if ( $sl < 0 ) {
1026 continue;
1028 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1029 continue;
1032 // Allow dollar quoting for function declarations
1033 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1034 if ( $dollarquote ) {
1035 $dollarquote = false;
1036 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1037 $done = true;
1038 } else {
1039 $dollarquote = true;
1041 } elseif ( !$dollarquote ) {
1042 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1043 $done = true;
1044 $line = substr( $line, 0, $sl );
1048 if ( $cmd != '' ) {
1049 $cmd .= ' ';
1051 $cmd .= "$line\n";
1053 if ( $done ) {
1054 $cmd = str_replace( ';;', ";", $cmd );
1055 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1056 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1057 $replacements[$defines[2]] = $defines[1];
1059 } else {
1060 foreach ( $replacements as $mwVar => $scVar ) {
1061 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1064 $cmd = $this->replaceVars( $cmd );
1065 $res = $this->doQuery( $cmd );
1066 if ( $resultCallback ) {
1067 call_user_func( $resultCallback, $res, $this );
1070 if ( false === $res ) {
1071 $err = $this->lastError();
1072 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1076 $cmd = '';
1077 $done = false;
1080 return true;
1083 function selectDB( $db ) {
1084 $this->mDBname = $db;
1085 if ( $db == null || $db == $this->mUser ) {
1086 return true;
1088 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1089 $stmt = oci_parse( $this->mConn, $sql );
1090 wfSuppressWarnings();
1091 $success = oci_execute( $stmt );
1092 wfRestoreWarnings();
1093 if ( !$success ) {
1094 $e = oci_error( $stmt );
1095 if ( $e['code'] != '1435' ) {
1096 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1098 return false;
1100 return true;
1103 function strencode( $s ) {
1104 return str_replace( "'", "''", $s );
1107 function addQuotes( $s ) {
1108 global $wgContLang;
1109 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1110 $s = $wgContLang->checkTitleEncoding( $s );
1112 return "'" . $this->strencode( $s ) . "'";
1115 public function addIdentifierQuotes( $s ) {
1116 if ( !$this->mFlags & DBO_DDLMODE ) {
1117 $s = '"' . str_replace( '"', '""', $s ) . '"';
1119 return $s;
1122 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1123 global $wgContLang;
1125 if ($conds != null) {
1126 $conds2 = array();
1127 $conds = ( !is_array( $conds ) ) ? array( $conds ) : $conds;
1128 foreach ( $conds as $col => $val ) {
1129 $col_info = $this->fieldInfoMulti( $table, $col );
1130 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1131 if ( $col_type == 'CLOB' ) {
1132 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1133 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1134 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1135 } else {
1136 $conds2[$col] = $val;
1140 return parent::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1141 } else {
1142 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1147 * Returns an optional USE INDEX clause to go after the table, and a
1148 * string to go at the end of the query
1150 * @private
1152 * @param $options Array: an associative array of options to be turned into
1153 * an SQL query, valid keys are listed in the function.
1154 * @return array
1156 function makeSelectOptions( $options ) {
1157 $preLimitTail = $postLimitTail = '';
1158 $startOpts = '';
1160 $noKeyOptions = array();
1161 foreach ( $options as $key => $option ) {
1162 if ( is_numeric( $key ) ) {
1163 $noKeyOptions[$option] = true;
1167 if ( isset( $options['GROUP BY'] ) ) {
1168 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1170 if ( isset( $options['ORDER BY'] ) ) {
1171 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1174 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1175 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1176 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1177 $startOpts .= 'DISTINCT';
1180 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1181 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1182 } else {
1183 $useIndex = '';
1186 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1189 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1190 global $wgContLang;
1192 if ( $wgContLang != null && $conds != null && $conds != '*' ) {
1193 $conds2 = array();
1194 $conds = ( !is_array( $conds ) ) ? array( $conds ) : $conds;
1195 foreach ( $conds as $col => $val ) {
1196 $col_info = $this->fieldInfoMulti( $table, $col );
1197 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1198 if ( $col_type == 'CLOB' ) {
1199 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1200 } else {
1201 if ( is_array( $val ) ) {
1202 $conds2[$col] = $val;
1203 foreach ( $conds2[$col] as &$val2 ) {
1204 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1206 } else {
1207 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1212 return parent::delete( $table, $conds2, $fname );
1213 } else {
1214 return parent::delete( $table, $conds, $fname );
1218 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1219 global $wgContLang;
1221 $table = $this->tableName( $table );
1222 $opts = $this->makeUpdateOptions( $options );
1223 $sql = "UPDATE $opts $table SET ";
1225 $first = true;
1226 foreach ( $values as $col => &$val ) {
1227 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1229 if ( !$first ) {
1230 $sqlSet = ', ' . $sqlSet;
1231 } else {
1232 $first = false;
1234 $sql .= $sqlSet;
1237 if ( $conds != '*' ) {
1238 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1241 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1242 $e = oci_error( $this->mConn );
1243 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1244 return false;
1246 foreach ( $values as $col => &$val ) {
1247 $col_info = $this->fieldInfoMulti( $table, $col );
1248 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1250 if ( $val === null ) {
1251 // do nothing ... null was inserted in statement creation
1252 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1253 if ( is_object( $val ) ) {
1254 $val = $val->getData();
1257 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1258 $val = '31-12-2030 12:00:00.000000';
1261 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1262 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1263 $e = oci_error( $stmt );
1264 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1265 return false;
1267 } else {
1268 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1269 $e = oci_error( $stmt );
1270 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1273 if ( $col_type == 'BLOB' ) {
1274 $lob[$col]->writeTemporary( $val );
1275 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1276 } else {
1277 $lob[$col]->writeTemporary( $val );
1278 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1283 wfSuppressWarnings();
1285 if ( oci_execute( $stmt, OCI_DEFAULT ) === false ) {
1286 $e = oci_error( $stmt );
1287 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1288 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1289 return false;
1290 } else {
1291 $this->mAffectedRows = oci_num_rows( $stmt );
1293 } else {
1294 $this->mAffectedRows = oci_num_rows( $stmt );
1297 wfRestoreWarnings();
1299 if ( isset( $lob ) ) {
1300 foreach ( $lob as $lob_v ) {
1301 $lob_v->free();
1305 if ( !$this->mTrxLevel ) {
1306 oci_commit( $this->mConn );
1309 oci_free_statement( $stmt );
1312 function bitNot( $field ) {
1313 // expecting bit-fields smaller than 4bytes
1314 return 'BITNOT(' . $field . ')';
1317 function bitAnd( $fieldLeft, $fieldRight ) {
1318 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1321 function bitOr( $fieldLeft, $fieldRight ) {
1322 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1325 function setFakeMaster( $enabled = true ) { }
1327 function getDBname() {
1328 return $this->mDBname;
1331 function getServer() {
1332 return $this->mServer;
1335 public function getSearchEngine() {
1336 return 'SearchOracle';
1338 } // end DatabaseOracle class