* Installer for Oracle fixes
[mediawiki.git] / includes / db / DatabaseOracle.php
blob5789d1101737467f19e5c574d29b7231864461de
1 <?php
2 /**
3 * This is the Oracle database abstraction layer.
5 * @file
6 * @ingroup Database
7 */
9 /**
10 * @ingroup Database
12 class ORABlob {
13 var $mData;
15 function __construct( $data ) {
16 $this->mData = $data;
19 function getData() {
20 return $this->mData;
24 /**
25 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
26 * other things. We use a wrapper class to handle that and other
27 * Oracle-specific bits, like converting column names back to lowercase.
28 * @ingroup Database
30 class ORAResult {
31 private $rows;
32 private $cursor;
33 private $stmt;
34 private $nrows;
36 private function array_unique_md( $array_in ) {
37 $array_out = array();
38 $array_hashes = array();
40 foreach ( $array_in as $item ) {
41 $hash = md5( serialize( $item ) );
42 if ( !isset( $array_hashes[$hash] ) ) {
43 $array_hashes[$hash] = $hash;
44 $array_out[] = $item;
48 return $array_out;
51 function __construct( &$db, $stmt, $unique = false ) {
52 $this->db =& $db;
54 if ( ( $this->nrows = oci_fetch_all( $stmt, $this->rows, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM ) ) === false ) {
55 $e = oci_error( $stmt );
56 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__ );
57 $this->free();
58 return;
61 if ( $unique ) {
62 $this->rows = $this->array_unique_md( $this->rows );
63 $this->nrows = count( $this->rows );
66 $this->cursor = 0;
67 $this->stmt = $stmt;
70 public function free() {
71 oci_free_statement( $this->stmt );
74 public function seek( $row ) {
75 $this->cursor = min( $row, $this->nrows );
78 public function numRows() {
79 return $this->nrows;
82 public function numFields() {
83 return oci_num_fields( $this->stmt );
86 public function fetchObject() {
87 if ( $this->cursor >= $this->nrows ) {
88 return false;
90 $row = $this->rows[$this->cursor++];
91 $ret = new stdClass();
92 foreach ( $row as $k => $v ) {
93 $lc = strtolower( oci_field_name( $this->stmt, $k + 1 ) );
94 $ret->$lc = $v;
97 return $ret;
100 public function fetchRow() {
101 if ( $this->cursor >= $this->nrows ) {
102 return false;
105 $row = $this->rows[$this->cursor++];
106 $ret = array();
107 foreach ( $row as $k => $v ) {
108 $lc = strtolower( oci_field_name( $this->stmt, $k + 1 ) );
109 $ret[$lc] = $v;
110 $ret[$k] = $v;
112 return $ret;
117 * Utility class.
118 * @ingroup Database
120 class ORAField {
121 private $name, $tablename, $default, $max_length, $nullable,
122 $is_pk, $is_unique, $is_multiple, $is_key, $type;
124 function __construct( $info ) {
125 $this->name = $info['column_name'];
126 $this->tablename = $info['table_name'];
127 $this->default = $info['data_default'];
128 $this->max_length = $info['data_length'];
129 $this->nullable = $info['not_null'];
130 $this->is_pk = isset( $info['prim'] ) && $info['prim'] == 1 ? 1 : 0;
131 $this->is_unique = isset( $info['uniq'] ) && $info['uniq'] == 1 ? 1 : 0;
132 $this->is_multiple = isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ? 1 : 0;
133 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
134 $this->type = $info['data_type'];
137 function name() {
138 return $this->name;
141 function tableName() {
142 return $this->tablename;
145 function defaultValue() {
146 return $this->default;
149 function maxLength() {
150 return $this->max_length;
153 function nullable() {
154 return $this->nullable;
157 function isKey() {
158 return $this->is_key;
161 function isMultipleKey() {
162 return $this->is_multiple;
165 function type() {
166 return $this->type;
171 * @ingroup Database
173 class DatabaseOracle extends DatabaseBase {
174 var $mInsertId = null;
175 var $mLastResult = null;
176 var $numeric_version = null;
177 var $lastResult = null;
178 var $cursor = 0;
179 var $mAffectedRows;
181 var $ignore_DUP_VAL_ON_INDEX = false;
182 var $sequenceData = null;
184 var $defaultCharset = 'AL32UTF8';
186 var $mFieldInfoCache = array();
188 function __construct( $server = false, $user = false, $password = false, $dbName = false,
189 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
191 $tablePrefix = $tablePrefix == 'get from global' ? $tablePrefix : strtoupper( $tablePrefix );
192 parent::__construct( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
193 wfRunHooks( 'DatabaseOraclePostInit', array( &$this ) );
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;
222 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0, $tablePrefix )
224 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
228 * Usually aborts on failure
229 * If the failFunction is set to a non-zero integer, returns success
231 function open( $server, $user, $password, $dbName ) {
232 if ( !function_exists( 'oci_connect' ) ) {
233 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->close();
237 $this->mUser = $user;
238 $this->mPassword = $password;
239 // changed internal variables functions
240 // mServer now holds the TNS endpoint
241 // mDBname is schema name if different from username
242 if ( !$server ) {
243 // backward compatibillity (server used to be null and TNS was supplied in dbname)
244 $this->mServer = $dbName;
245 $this->mDBname = $user;
246 } else {
247 $this->mServer = $server;
248 if ( !$dbName ) {
249 $this->mDBname = $user;
250 } else {
251 $this->mDBname = $dbName;
255 if ( !strlen( $user ) ) { # e.g. the class is being loaded
256 return;
259 $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
260 if ( $this->mFlags & DBO_DEFAULT ) {
261 $this->mConn = oci_new_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
262 } else {
263 $this->mConn = oci_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
266 if ( $this->mUser != $this->mDBname ) {
267 //change current schema in session
268 $this->selectDB( $this->mDBname );
271 if ( !$this->mConn ) {
272 wfDebug( "DB connection error\n" );
273 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
274 wfDebug( $this->lastError() . "\n" );
275 return false;
278 $this->mOpened = true;
280 # removed putenv calls because they interfere with the system globaly
281 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
282 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
283 return $this->mConn;
287 * Closes a database connection, if it is open
288 * Returns success, true if already closed
290 function close() {
291 $this->mOpened = false;
292 if ( $this->mConn ) {
293 return oci_close( $this->mConn );
294 } else {
295 return true;
299 function execFlags() {
300 return $this->mTrxLevel ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
303 function doQuery( $sql ) {
304 wfDebug( "SQL: [$sql]\n" );
305 if ( !mb_check_encoding( $sql ) ) {
306 throw new MWException( "SQL encoding is invalid\n$sql" );
309 // handle some oracle specifics
310 // remove AS column/table/subquery namings
311 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
312 $sql = preg_replace( '/ as /i', ' ', $sql );
314 // Oracle has issues with UNION clause if the statement includes LOB fields
315 // So we do a UNION ALL and then filter the results array with array_unique
316 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
317 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
318 // you have to select data from plan table after explain
319 $explain_id = date( 'dmYHis' );
321 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
323 wfSuppressWarnings();
325 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
326 $e = oci_error( $this->mConn );
327 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
328 return false;
331 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
332 $e = oci_error( $stmt );
333 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
334 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
335 return false;
339 wfRestoreWarnings();
341 if ( $explain_count > 0 ) {
342 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
343 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
344 return new ORAResult( $this, $stmt, $union_unique );
345 } else {
346 $this->mAffectedRows = oci_num_rows( $stmt );
347 return true;
351 function queryIgnore( $sql, $fname = '' ) {
352 return $this->query( $sql, $fname, true );
355 function freeResult( $res ) {
356 if ( $res instanceof ORAResult ) {
357 $res->free();
358 } else {
359 $res->result->free();
363 function fetchObject( $res ) {
364 if ( $res instanceof ORAResult ) {
365 return $res->numRows();
366 } else {
367 return $res->result->fetchObject();
371 function fetchRow( $res ) {
372 if ( $res instanceof ORAResult ) {
373 return $res->fetchRow();
374 } else {
375 return $res->result->fetchRow();
379 function numRows( $res ) {
380 if ( $res instanceof ORAResult ) {
381 return $res->numRows();
382 } else {
383 return $res->result->numRows();
387 function numFields( $res ) {
388 if ( $res instanceof ORAResult ) {
389 return $res->numFields();
390 } else {
391 return $res->result->numFields();
395 function fieldName( $stmt, $n ) {
396 return oci_field_name( $stmt, $n );
400 * This must be called after nextSequenceVal
402 function insertId() {
403 return $this->mInsertId;
406 function dataSeek( $res, $row ) {
407 if ( $res instanceof ORAResult ) {
408 $res->seek( $row );
409 } else {
410 $res->result->seek( $row );
414 function lastError() {
415 if ( $this->mConn === false ) {
416 $e = oci_error();
417 } else {
418 $e = oci_error( $this->mConn );
420 return $e['message'];
423 function lastErrno() {
424 if ( $this->mConn === false ) {
425 $e = oci_error();
426 } else {
427 $e = oci_error( $this->mConn );
429 return $e['code'];
432 function affectedRows() {
433 return $this->mAffectedRows;
437 * Returns information about an index
438 * If errors are explicitly ignored, returns NULL on failure
440 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
441 return false;
444 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
445 return false;
448 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
449 if ( !count( $a ) ) {
450 return true;
453 if ( !is_array( $options ) ) {
454 $options = array( $options );
457 if ( in_array( 'IGNORE', $options ) ) {
458 $this->ignore_DUP_VAL_ON_INDEX = true;
461 if ( !is_array( reset( $a ) ) ) {
462 $a = array( $a );
465 foreach ( $a as &$row ) {
466 $this->insertOneRow( $table, $row, $fname );
468 $retVal = true;
470 if ( in_array( 'IGNORE', $options ) ) {
471 $this->ignore_DUP_VAL_ON_INDEX = false;
474 return $retVal;
477 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
478 $col_info = $this->fieldInfoMulti( $table, $col );
479 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
481 $bind = '';
482 if ( is_numeric( $col ) ) {
483 $bind = $val;
484 $val = null;
485 return $bind;
486 } else if ( $includeCol ) {
487 $bind = "$col = ";
490 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
491 $val = null;
494 if ( $val === null ) {
495 if ( $col_info != false && $col_info->nullable() == 0 && $col_info->defaultValue() != null ) {
496 $bind .= 'DEFAULT';
497 } else {
498 $bind .= 'NULL';
500 } else {
501 $bind .= ':' . $col;
504 return $bind;
507 private function insertOneRow( $table, $row, $fname ) {
508 global $wgContLang;
510 $table = $this->tableName( $table );
511 // "INSERT INTO tables (a, b, c)"
512 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
513 $sql .= " VALUES (";
515 // for each value, append ":key"
516 $first = true;
517 foreach ( $row as $col => &$val ) {
518 if ( !$first ) {
519 $sql .= ', ';
520 } else {
521 $first = false;
524 $sql .= $this->fieldBindStatement( $table, $col, $val );
526 $sql .= ')';
528 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
529 $e = oci_error( $this->mConn );
530 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
531 return false;
533 foreach ( $row as $col => &$val ) {
534 $col_info = $this->fieldInfoMulti( $table, $col );
535 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
537 if ( $val === null ) {
538 // do nothing ... null was inserted in statement creation
539 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
540 if ( is_object( $val ) ) {
541 $val = $val->getData();
544 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
545 $val = '31-12-2030 12:00:00.000000';
548 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
549 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
550 $e = oci_error( $stmt );
551 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
552 return false;
554 } else {
555 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
556 $e = oci_error( $stmt );
557 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
560 if ( $col_type == 'BLOB' ) {
561 $lob[$col]->writeTemporary( $val );
562 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
563 } else {
564 $lob[$col]->writeTemporary( $val );
565 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
570 wfSuppressWarnings();
572 if ( oci_execute( $stmt, OCI_DEFAULT ) === false ) {
573 $e = oci_error( $stmt );
574 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
575 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
576 return false;
577 } else {
578 $this->mAffectedRows = oci_num_rows( $stmt );
580 } else {
581 $this->mAffectedRows = oci_num_rows( $stmt );
584 wfRestoreWarnings();
586 if ( isset( $lob ) ) {
587 foreach ( $lob as $lob_v ) {
588 $lob_v->free();
592 if ( !$this->mTrxLevel ) {
593 oci_commit( $this->mConn );
596 oci_free_statement( $stmt );
599 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
600 $insertOptions = array(), $selectOptions = array() )
602 $destTable = $this->tableName( $destTable );
603 if ( !is_array( $selectOptions ) ) {
604 $selectOptions = array( $selectOptions );
606 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
607 if ( is_array( $srcTable ) ) {
608 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
609 } else {
610 $srcTable = $this->tableName( $srcTable );
613 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
614 !isset( $varMap[$sequenceData['column']] ) )
616 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
619 // count-alias subselect fields to avoid abigious definition errors
620 $i = 0;
621 foreach ( $varMap as &$val ) {
622 $val = $val . ' field' . ( $i++ );
625 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
626 " SELECT $startOpts " . implode( ',', $varMap ) .
627 " FROM $srcTable $useIndex ";
628 if ( $conds != '*' ) {
629 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
631 $sql .= " $tailOpts";
633 if ( in_array( 'IGNORE', $insertOptions ) ) {
634 $this->ignore_DUP_VAL_ON_INDEX = true;
637 $retval = $this->query( $sql, $fname );
639 if ( in_array( 'IGNORE', $insertOptions ) ) {
640 $this->ignore_DUP_VAL_ON_INDEX = false;
643 return $retval;
646 function tableName( $name ) {
647 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
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;
663 The rest of procedure is equal to generic Databse class
664 except for the quoting style
666 if ( $name[0] == '"' && substr( $name, - 1, 1 ) == '"' ) {
667 return $name;
669 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
670 return $name;
672 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
673 if ( isset( $dbDetails[1] ) ) {
674 @list( $table, $database ) = $dbDetails;
675 } else {
676 @list( $table ) = $dbDetails;
679 $prefix = $this->mTablePrefix;
681 if ( isset( $database ) ) {
682 $table = ( $table[0] == '`' ? $table : "`{$table}`" );
685 if ( !isset( $database ) && isset( $wgSharedDB ) && $table[0] != '"'
686 && isset( $wgSharedTables )
687 && is_array( $wgSharedTables )
688 && in_array( $table, $wgSharedTables )
690 $database = $wgSharedDB;
691 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
694 if ( isset( $database ) ) {
695 $database = ( $database[0] == '"' ? $database : "\"{$database}\"" );
697 $table = ( $table[0] == '"') ? $table : "\"{$prefix}{$table}\"" ;
699 $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
701 return strtoupper( $tableName );
705 * Return the next in a sequence, save the value for retrieval via insertId()
707 function nextSequenceValue( $seqName ) {
708 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
709 $row = $this->fetchRow( $res );
710 $this->mInsertId = $row[0];
711 return $this->mInsertId;
715 * Return sequence_name if table has a sequence
717 private function getSequenceData( $table ) {
718 if ( $this->sequenceData == null ) {
719 $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\'' );
721 while ( ( $row = $result->fetchRow() ) !== false ) {
722 $this->sequenceData[$this->tableName( $row[1] )] = array(
723 'sequence' => $row[0],
724 'column' => $row[2]
729 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
733 * REPLACE query wrapper
734 * Oracle simulates this with a DELETE followed by INSERT
735 * $row is the row to insert, an associative array
736 * $uniqueIndexes is an array of indexes. Each element may be either a
737 * field name or an array of field names
739 * It may be more efficient to leave off unique indexes which are unlikely to collide.
740 * However if you do this, you run the risk of encountering errors which wouldn't have
741 * occurred in MySQL.
743 * @param $table String: table name
744 * @param $uniqueIndexes Array: array of indexes. Each element may be
745 * either a field name or an array of field names
746 * @param $rows Array: rows to insert to $table
747 * @param $fname String: function name, you can use __METHOD__ here
749 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
750 $table = $this->tableName( $table );
752 if ( count( $rows ) == 0 ) {
753 return;
756 # Single row case
757 if ( !is_array( reset( $rows ) ) ) {
758 $rows = array( $rows );
761 $sequenceData = $this->getSequenceData( $table );
763 foreach ( $rows as $row ) {
764 # Delete rows which collide
765 if ( $uniqueIndexes ) {
766 $condsDelete = array();
767 foreach ( $uniqueIndexes as $index ) {
768 $condsDelete[$index] = $row[$index];
770 if ( count( $condsDelete ) > 0 ) {
771 $this->delete( $table, $condsDelete, $fname );
775 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
776 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
779 # Now insert the row
780 $this->insert( $table, $row, $fname );
784 # DELETE where the condition is a join
785 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
786 if ( !$conds ) {
787 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
790 $delTable = $this->tableName( $delTable );
791 $joinTable = $this->tableName( $joinTable );
792 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
793 if ( $conds != '*' ) {
794 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
796 $sql .= ')';
798 $this->query( $sql, $fname );
801 # Returns the size of a text field, or -1 for "unlimited"
802 function textFieldSize( $table, $field ) {
803 $fieldInfoData = $this->fieldInfo( $table, $field);
804 if ( $fieldInfoData->type == 'varchar' ) {
805 $size = $row->size - 4;
806 } else {
807 $size = $row->size;
809 return $size;
812 function limitResult( $sql, $limit, $offset = false ) {
813 if ( $offset === false ) {
814 $offset = 0;
816 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
819 function unionQueries( $sqls, $all ) {
820 $glue = ' UNION ALL ';
821 return 'SELECT * ' . ( $all ? '':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
824 function wasDeadlock() {
825 return $this->lastErrno() == 'OCI-00060';
828 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
829 global $wgDBprefix;
831 $temporary = $temporary ? 'TRUE' : 'FALSE';
833 $newName = trim( strtoupper( $newName ), '"');
834 $oldName = trim( strtoupper( $oldName ), '"');
836 $tabName = substr( $newName, strlen( $wgDBprefix ) );
837 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
839 return $this->doQuery( 'BEGIN DUPLICATE_TABLE(\'' . $tabName . '\', \'' . $oldPrefix . '\', \'' . strtoupper( $wgDBprefix ) . '\', ' . $temporary . '); END;' );
842 function timestamp( $ts = 0 ) {
843 return wfTimestamp( TS_ORACLE, $ts );
847 * Return aggregated value function call
849 function aggregateValue ( $valuedata, $valuename = 'value' ) {
850 return $valuedata;
853 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
854 # Ignore errors during error handling to avoid infinite
855 # recursion
856 $ignore = $this->ignoreErrors( true );
857 ++$this->mErrorCount;
859 if ( $ignore || $tempIgnore ) {
860 wfDebug( "SQL ERROR (ignored): $error\n" );
861 $this->ignoreErrors( $ignore );
862 } else {
863 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
868 * @return string wikitext of a link to the server software's web site
870 public static function getSoftwareLink() {
871 return '[http://www.oracle.com/ Oracle]';
875 * @return string Version information from the database
877 function getServerVersion() {
878 //better version number, fallback on driver
879 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
880 if ( !( $row = $rset->fetchRow() ) ) {
881 return oci_server_version( $this->mConn );
883 return $row['version'];
887 * Query whether a given table exists (in the given schema, or the default mw one if not given)
889 function tableExists( $table ) {
890 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
891 $res = $this->doQuery( $SQL );
892 if ( $res ) {
893 $count = $res->numRows();
894 $res->free();
895 } else {
896 $count = 0;
898 return $count;
902 * Function translates mysql_fetch_field() functionality on ORACLE.
903 * Caching is present for reducing query time.
904 * For internal calls. Use fieldInfo for normal usage.
905 * Returns false if the field doesn't exist
907 * @param $table Array
908 * @param $field String
910 private function fieldInfoMulti( $table, $field ) {
911 $field = strtoupper( $field );
912 if ( is_array( $table ) ) {
913 $table = array_map( array( &$this, 'tableName' ), $table );
914 $tableWhere = 'IN (';
915 foreach( $table as &$singleTable ) {
916 $singleTable = strtoupper( trim( $singleTable, '"' ) );
917 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
918 return $this->mFieldInfoCache["$singleTable.$field"];
920 $tableWhere .= '\'' . $singleTable . '\',';
922 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
923 } else {
924 $table = strtoupper( trim( $this->tableName( $table ), '"' ) );
925 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
926 return $this->mFieldInfoCache["$table.$field"];
928 $tableWhere = '= \''.$table.'\'';
931 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
932 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT ) === false ) {
933 $e = oci_error( $fieldInfoStmt );
934 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
935 return false;
937 $res = new ORAResult( $this, $fieldInfoStmt );
938 if ( $res->numRows() == 0 ) {
939 if ( is_array( $table ) ) {
940 foreach( $table as &$singleTable ) {
941 $this->mFieldInfoCache["$singleTable.$field"] = false;
943 } else {
944 $this->mFieldInfoCache["$table.$field"] = false;
946 $fieldInfoTemp = null;
947 } else {
948 $fieldInfoTemp = new ORAField( $res->fetchRow() );
949 $table = $fieldInfoTemp->tableName();
950 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
952 $res->free();
953 return $fieldInfoTemp;
956 function fieldInfo( $table, $field ) {
957 if ( is_array( $table ) ) {
958 throw new DBUnexpectedError( $this, 'Database::fieldInfo called with table array!' );
960 return $this->fieldInfoMulti ($table, $field);
963 function begin( $fname = '' ) {
964 $this->mTrxLevel = 1;
967 function commit( $fname = '' ) {
968 oci_commit( $this->mConn );
969 $this->mTrxLevel = 0;
972 /* Not even sure why this is used in the main codebase... */
973 function limitResultForUpdate( $sql, $num ) {
974 return $sql;
977 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
978 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
979 $cmd = '';
980 $done = false;
981 $dollarquote = false;
983 $replacements = array();
985 while ( ! feof( $fp ) ) {
986 if ( $lineCallback ) {
987 call_user_func( $lineCallback );
989 $line = trim( fgets( $fp, 1024 ) );
990 $sl = strlen( $line ) - 1;
992 if ( $sl < 0 ) {
993 continue;
995 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
996 continue;
999 // Allow dollar quoting for function declarations
1000 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1001 if ( $dollarquote ) {
1002 $dollarquote = false;
1003 $done = true;
1004 } else {
1005 $dollarquote = true;
1007 } elseif ( !$dollarquote ) {
1008 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1009 $done = true;
1010 $line = substr( $line, 0, $sl );
1014 if ( $cmd != '' ) {
1015 $cmd .= ' ';
1017 $cmd .= "$line\n";
1019 if ( $done ) {
1020 $cmd = str_replace( ';;', ";", $cmd );
1021 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1022 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1023 $replacements[$defines[2]] = $defines[1];
1025 } else {
1026 foreach ( $replacements as $mwVar => $scVar ) {
1027 $cmd = str_replace( '&' . $scVar . '.', '{$' . $mwVar . '}', $cmd );
1030 $cmd = $this->replaceVars( $cmd );
1031 $res = $this->doQuery( $cmd );
1032 if ( $resultCallback ) {
1033 call_user_func( $resultCallback, $res, $this );
1036 if ( false === $res ) {
1037 $err = $this->lastError();
1038 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1042 $cmd = '';
1043 $done = false;
1046 return true;
1049 function setup_database() {
1050 $res = $this->sourceFile( "../maintenance/oracle/tables.sql" );
1051 if ( $res === true ) {
1052 print " done.</li>\n";
1053 } else {
1054 print " <b>FAILED</b></li>\n";
1055 dieout( htmlspecialchars( $res ) );
1058 // Avoid the non-standard "REPLACE INTO" syntax
1059 echo "<li>Populating interwiki table</li>\n";
1060 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1061 if ( !$f ) {
1062 dieout( "Could not find the interwiki.sql file" );
1065 // do it like the postgres :D
1066 $SQL = "INSERT INTO " . $this->tableName( 'interwiki' ) . " (iw_prefix,iw_url,iw_local) VALUES ";
1067 while ( !feof( $f ) ) {
1068 $line = fgets( $f, 1024 );
1069 $matches = array();
1070 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) {
1071 continue;
1073 $this->query( "$SQL $matches[1],$matches[2])" );
1076 echo "<li>Table interwiki successfully populated</li>\n";
1079 function selectDB( $db ) {
1080 if ( $db == null || $db == $this->mUser ) { return true; }
1081 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1082 $stmt = oci_parse( $this->mConn, $sql );
1083 if ( !oci_execute( $stmt ) ) {
1084 $e = oci_error( $stmt );
1085 if ( $e['code'] != '1435' ) {
1086 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1088 return false;
1090 return true;
1093 function strencode( $s ) {
1094 return str_replace( "'", "''", $s );
1097 function addQuotes( $s ) {
1098 global $wgContLang;
1099 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1100 $s = $wgContLang->checkTitleEncoding( $s );
1102 return "'" . $this->strencode( $s ) . "'";
1105 function quote_ident( $s ) {
1106 return $s;
1109 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1110 global $wgContLang;
1112 $conds2 = array();
1113 $conds = ( $conds != null && !is_array( $conds ) ) ? array( $conds ) : $conds;
1114 foreach ( $conds as $col => $val ) {
1115 $col_info = $this->fieldInfoMulti( $table, $col );
1116 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1117 if ( $col_type == 'CLOB' ) {
1118 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1119 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1120 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1121 } else {
1122 $conds2[$col] = $val;
1126 return parent::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1130 * Returns an optional USE INDEX clause to go after the table, and a
1131 * string to go at the end of the query
1133 * @private
1135 * @param $options Array: an associative array of options to be turned into
1136 * an SQL query, valid keys are listed in the function.
1137 * @return array
1139 function makeSelectOptions( $options ) {
1140 $preLimitTail = $postLimitTail = '';
1141 $startOpts = '';
1143 $noKeyOptions = array();
1144 foreach ( $options as $key => $option ) {
1145 if ( is_numeric( $key ) ) {
1146 $noKeyOptions[$option] = true;
1150 if ( isset( $options['GROUP BY'] ) ) {
1151 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1153 if ( isset( $options['ORDER BY'] ) ) {
1154 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1157 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1158 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1159 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1160 $startOpts .= 'DISTINCT';
1163 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1164 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1165 } else {
1166 $useIndex = '';
1169 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1172 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1173 global $wgContLang;
1175 if ( $wgContLang != null && $conds != '*' ) {
1176 $conds2 = array();
1177 $conds = ( $conds != null && !is_array( $conds ) ) ? array( $conds ) : $conds;
1178 foreach ( $conds as $col => $val ) {
1179 $col_info = $this->fieldInfoMulti( $table, $col );
1180 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1181 if ( $col_type == 'CLOB' ) {
1182 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1183 } else {
1184 if ( is_array( $val ) ) {
1185 $conds2[$col] = $val;
1186 foreach ( $conds2[$col] as &$val2 ) {
1187 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1189 } else {
1190 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1195 return parent::delete( $table, $conds2, $fname );
1196 } else {
1197 return parent::delete( $table, $conds, $fname );
1201 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1202 $table = $this->tableName( $table );
1203 $opts = $this->makeUpdateOptions( $options );
1204 $sql = "UPDATE $opts $table SET ";
1206 $first = true;
1207 foreach ( $values as $col => &$val ) {
1208 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1210 if ( !$first ) {
1211 $sqlSet = ', ' . $sqlSet;
1212 } else {
1213 $first = false;
1215 $sql .= $sqlSet;
1218 if ( $conds != '*' ) {
1219 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1222 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1223 $e = oci_error( $this->mConn );
1224 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1225 return false;
1227 foreach ( $values as $col => &$val ) {
1228 $col_info = $this->fieldInfoMulti( $table, $col );
1229 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1231 if ( $val === null ) {
1232 // do nothing ... null was inserted in statement creation
1233 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1234 if ( is_object( $val ) ) {
1235 $val = $val->getData();
1238 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1239 $val = '31-12-2030 12:00:00.000000';
1242 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1243 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1244 $e = oci_error( $stmt );
1245 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1246 return false;
1248 } else {
1249 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1250 $e = oci_error( $stmt );
1251 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1254 if ( $col_type == 'BLOB' ) {
1255 $lob[$col]->writeTemporary( $val );
1256 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1257 } else {
1258 $lob[$col]->writeTemporary( $val );
1259 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1264 wfSuppressWarnings();
1266 if ( oci_execute( $stmt, OCI_DEFAULT ) === false ) {
1267 $e = oci_error( $stmt );
1268 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1269 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1270 return false;
1271 } else {
1272 $this->mAffectedRows = oci_num_rows( $stmt );
1274 } else {
1275 $this->mAffectedRows = oci_num_rows( $stmt );
1278 wfRestoreWarnings();
1280 if ( isset( $lob ) ) {
1281 foreach ( $lob as $lob_v ) {
1282 $lob_v->free();
1286 if ( !$this->mTrxLevel ) {
1287 oci_commit( $this->mConn );
1290 oci_free_statement( $stmt );
1293 function bitNot( $field ) {
1294 // expecting bit-fields smaller than 4bytes
1295 return 'BITNOT(' . $field . ')';
1298 function bitAnd( $fieldLeft, $fieldRight ) {
1299 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1302 function bitOr( $fieldLeft, $fieldRight ) {
1303 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1306 function setFakeMaster( $enabled = true ) { }
1308 function getDBname() {
1309 return $this->mDBname;
1312 function getServer() {
1313 return $this->mServer;
1316 public function replaceVars( $ins ) {
1317 $varnames = array( 'wgDBprefix' );
1318 if ( $this->mFlags & DBO_SYSDBA ) {
1319 $varnames[] = '_OracleDefTS';
1320 $varnames[] = '_OracleTempTS';
1323 // Ordinary variables
1324 foreach ( $varnames as $var ) {
1325 if ( isset( $GLOBALS[$var] ) ) {
1326 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1327 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1328 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1329 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1333 return parent::replaceVars( $ins );
1336 public function getSearchEngine() {
1337 return 'SearchOracle';
1339 } // end DatabaseOracle class