Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / db / DatabaseOracle.php
blobc197d91b1dd03a372791a9753de9d9e7bc1f680d
1 <?php
2 /**
3 * This is the Oracle database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Database
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 $nrows;
35 private $columns = array();
37 private function array_unique_md( $array_in ) {
38 $array_out = array();
39 $array_hashes = array();
41 foreach ( $array_in as $item ) {
42 $hash = md5( serialize( $item ) );
43 if ( !isset( $array_hashes[$hash] ) ) {
44 $array_hashes[$hash] = $hash;
45 $array_out[] = $item;
49 return $array_out;
52 /**
53 * @param $db DatabaseBase
54 * @param $stmt
55 * @param bool $unique
57 function __construct( &$db, $stmt, $unique = false ) {
58 $this->db =& $db;
60 if ( ( $this->nrows = oci_fetch_all( $stmt, $this->rows, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM ) ) === false ) {
61 $e = oci_error( $stmt );
62 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__ );
63 $this->free();
64 return;
67 if ( $unique ) {
68 $this->rows = $this->array_unique_md( $this->rows );
69 $this->nrows = count( $this->rows );
72 if ( $this->nrows > 0 ) {
73 foreach ( $this->rows[0] as $k => $v ) {
74 $this->columns[$k] = strtolower( oci_field_name( $stmt, $k + 1 ) );
78 $this->cursor = 0;
79 oci_free_statement( $stmt );
82 public function free() {
83 unset( $this->db );
86 public function seek( $row ) {
87 $this->cursor = min( $row, $this->nrows );
90 public function numRows() {
91 return $this->nrows;
94 public function numFields() {
95 return count( $this->columns );
98 public function fetchObject() {
99 if ( $this->cursor >= $this->nrows ) {
100 return false;
102 $row = $this->rows[$this->cursor++];
103 $ret = new stdClass();
104 foreach ( $row as $k => $v ) {
105 $lc = $this->columns[$k];
106 $ret->$lc = $v;
109 return $ret;
112 public function fetchRow() {
113 if ( $this->cursor >= $this->nrows ) {
114 return false;
117 $row = $this->rows[$this->cursor++];
118 $ret = array();
119 foreach ( $row as $k => $v ) {
120 $lc = $this->columns[$k];
121 $ret[$lc] = $v;
122 $ret[$k] = $v;
124 return $ret;
129 * Utility class.
130 * @ingroup Database
132 class ORAField implements Field {
133 private $name, $tablename, $default, $max_length, $nullable,
134 $is_pk, $is_unique, $is_multiple, $is_key, $type;
136 function __construct( $info ) {
137 $this->name = $info['column_name'];
138 $this->tablename = $info['table_name'];
139 $this->default = $info['data_default'];
140 $this->max_length = $info['data_length'];
141 $this->nullable = $info['not_null'];
142 $this->is_pk = isset( $info['prim'] ) && $info['prim'] == 1 ? 1 : 0;
143 $this->is_unique = isset( $info['uniq'] ) && $info['uniq'] == 1 ? 1 : 0;
144 $this->is_multiple = isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ? 1 : 0;
145 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
146 $this->type = $info['data_type'];
149 function name() {
150 return $this->name;
153 function tableName() {
154 return $this->tablename;
157 function defaultValue() {
158 return $this->default;
161 function maxLength() {
162 return $this->max_length;
165 function isNullable() {
166 return $this->nullable;
169 function isKey() {
170 return $this->is_key;
173 function isMultipleKey() {
174 return $this->is_multiple;
177 function type() {
178 return $this->type;
183 * @ingroup Database
185 class DatabaseOracle extends DatabaseBase {
186 var $mInsertId = null;
187 var $mLastResult = null;
188 var $lastResult = null;
189 var $cursor = 0;
190 var $mAffectedRows;
192 var $ignore_DUP_VAL_ON_INDEX = false;
193 var $sequenceData = null;
195 var $defaultCharset = 'AL32UTF8';
197 var $mFieldInfoCache = array();
199 function __construct( $server = false, $user = false, $password = false, $dbName = false,
200 $flags = 0, $tablePrefix = 'get from global' )
202 global $wgDBprefix;
203 $tablePrefix = $tablePrefix == 'get from global' ? strtoupper( $wgDBprefix ) : strtoupper( $tablePrefix );
204 parent::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
205 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
208 function __destruct() {
209 if ( $this->mOpened ) {
210 wfSuppressWarnings();
211 $this->close();
212 wfRestoreWarnings();
216 function getType() {
217 return 'oracle';
220 function cascadingDeletes() {
221 return true;
223 function cleanupTriggers() {
224 return true;
226 function strictIPs() {
227 return true;
229 function realTimestamps() {
230 return true;
232 function implicitGroupby() {
233 return false;
235 function implicitOrderby() {
236 return false;
238 function searchableIPs() {
239 return true;
243 * Usually aborts on failure
244 * @param string $server
245 * @param string $user
246 * @param string $password
247 * @param string $dbName
248 * @throws DBConnectionError
249 * @return DatabaseBase|null
251 function open( $server, $user, $password, $dbName ) {
252 if ( !function_exists( 'oci_connect' ) ) {
253 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" );
256 $this->close();
257 $this->mUser = $user;
258 $this->mPassword = $password;
259 // changed internal variables functions
260 // mServer now holds the TNS endpoint
261 // mDBname is schema name if different from username
262 if ( !$server ) {
263 // backward compatibillity (server used to be null and TNS was supplied in dbname)
264 $this->mServer = $dbName;
265 $this->mDBname = $user;
266 } else {
267 $this->mServer = $server;
268 if ( !$dbName ) {
269 $this->mDBname = $user;
270 } else {
271 $this->mDBname = $dbName;
275 if ( !strlen( $user ) ) { # e.g. the class is being loaded
276 return;
279 $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
280 wfSuppressWarnings();
281 if ( $this->mFlags & DBO_DEFAULT ) {
282 $this->mConn = oci_new_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
283 } else {
284 $this->mConn = oci_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
286 wfRestoreWarnings();
288 if ( $this->mUser != $this->mDBname ) {
289 //change current schema in session
290 $this->selectDB( $this->mDBname );
293 if ( !$this->mConn ) {
294 throw new DBConnectionError( $this, $this->lastError() );
297 $this->mOpened = true;
299 # removed putenv calls because they interfere with the system globaly
300 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
301 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
302 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
303 return $this->mConn;
307 * Closes a database connection, if it is open
308 * Returns success, true if already closed
309 * @return bool
311 protected function closeConnection() {
312 return oci_close( $this->mConn );
315 function execFlags() {
316 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT : OCI_COMMIT_ON_SUCCESS;
319 protected function doQuery( $sql ) {
320 wfDebug( "SQL: [$sql]\n" );
321 if ( !StringUtils::isUtf8( $sql ) ) {
322 throw new MWException( "SQL encoding is invalid\n$sql" );
325 // handle some oracle specifics
326 // remove AS column/table/subquery namings
327 if ( !$this->getFlag( DBO_DDLMODE ) ) {
328 $sql = preg_replace( '/ as /i', ' ', $sql );
331 // Oracle has issues with UNION clause if the statement includes LOB fields
332 // So we do a UNION ALL and then filter the results array with array_unique
333 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
334 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
335 // you have to select data from plan table after explain
336 $explain_id = date( 'dmYHis' );
338 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
340 wfSuppressWarnings();
342 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
343 $e = oci_error( $this->mConn );
344 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
345 return false;
348 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
349 $e = oci_error( $stmt );
350 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
351 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
352 return false;
356 wfRestoreWarnings();
358 if ( $explain_count > 0 ) {
359 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
360 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
361 return new ORAResult( $this, $stmt, $union_unique );
362 } else {
363 $this->mAffectedRows = oci_num_rows( $stmt );
364 return true;
368 function queryIgnore( $sql, $fname = '' ) {
369 return $this->query( $sql, $fname, true );
372 function freeResult( $res ) {
373 if ( $res instanceof ResultWrapper ) {
374 $res = $res->result;
377 $res->free();
380 function fetchObject( $res ) {
381 if ( $res instanceof ResultWrapper ) {
382 $res = $res->result;
385 return $res->fetchObject();
388 function fetchRow( $res ) {
389 if ( $res instanceof ResultWrapper ) {
390 $res = $res->result;
393 return $res->fetchRow();
396 function numRows( $res ) {
397 if ( $res instanceof ResultWrapper ) {
398 $res = $res->result;
401 return $res->numRows();
404 function numFields( $res ) {
405 if ( $res instanceof ResultWrapper ) {
406 $res = $res->result;
409 return $res->numFields();
412 function fieldName( $stmt, $n ) {
413 return oci_field_name( $stmt, $n );
417 * This must be called after nextSequenceVal
418 * @return null
420 function insertId() {
421 return $this->mInsertId;
424 function dataSeek( $res, $row ) {
425 if ( $res instanceof ORAResult ) {
426 $res->seek( $row );
427 } else {
428 $res->result->seek( $row );
432 function lastError() {
433 if ( $this->mConn === false ) {
434 $e = oci_error();
435 } else {
436 $e = oci_error( $this->mConn );
438 return $e['message'];
441 function lastErrno() {
442 if ( $this->mConn === false ) {
443 $e = oci_error();
444 } else {
445 $e = oci_error( $this->mConn );
447 return $e['code'];
450 function affectedRows() {
451 return $this->mAffectedRows;
455 * Returns information about an index
456 * If errors are explicitly ignored, returns NULL on failure
457 * @return bool
459 function indexInfo( $table, $index, $fname = __METHOD__ ) {
460 return false;
463 function indexUnique( $table, $index, $fname = __METHOD__ ) {
464 return false;
467 function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
468 if ( !count( $a ) ) {
469 return true;
472 if ( !is_array( $options ) ) {
473 $options = array( $options );
476 if ( in_array( 'IGNORE', $options ) ) {
477 $this->ignore_DUP_VAL_ON_INDEX = true;
480 if ( !is_array( reset( $a ) ) ) {
481 $a = array( $a );
484 foreach ( $a as &$row ) {
485 $this->insertOneRow( $table, $row, $fname );
487 $retVal = true;
489 if ( in_array( 'IGNORE', $options ) ) {
490 $this->ignore_DUP_VAL_ON_INDEX = false;
493 return $retVal;
496 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
497 $col_info = $this->fieldInfoMulti( $table, $col );
498 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
500 $bind = '';
501 if ( is_numeric( $col ) ) {
502 $bind = $val;
503 $val = null;
504 return $bind;
505 } elseif ( $includeCol ) {
506 $bind = "$col = ";
509 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
510 $val = null;
513 if ( $val === 'NULL' ) {
514 $val = null;
517 if ( $val === null ) {
518 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
519 $bind .= 'DEFAULT';
520 } else {
521 $bind .= 'NULL';
523 } else {
524 $bind .= ':' . $col;
527 return $bind;
530 private function insertOneRow( $table, $row, $fname ) {
531 global $wgContLang;
533 $table = $this->tableName( $table );
534 // "INSERT INTO tables (a, b, c)"
535 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
536 $sql .= " VALUES (";
538 // for each value, append ":key"
539 $first = true;
540 foreach ( $row as $col => &$val ) {
541 if ( !$first ) {
542 $sql .= ', ';
543 } else {
544 $first = false;
547 $sql .= $this->fieldBindStatement( $table, $col, $val );
549 $sql .= ')';
551 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
552 $e = oci_error( $this->mConn );
553 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
554 return false;
556 foreach ( $row as $col => &$val ) {
557 $col_info = $this->fieldInfoMulti( $table, $col );
558 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
560 if ( $val === null ) {
561 // do nothing ... null was inserted in statement creation
562 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
563 if ( is_object( $val ) ) {
564 $val = $val->fetch();
567 // backward compatibility
568 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
569 $val = $this->getInfinity();
572 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
573 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR ) === false ) {
574 $e = oci_error( $stmt );
575 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
576 return false;
578 } else {
579 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
580 $e = oci_error( $stmt );
581 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
584 if ( is_object( $val ) ) {
585 $val = $val->fetch();
588 if ( $col_type == 'BLOB' ) {
589 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
590 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB );
591 } else {
592 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
593 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
598 wfSuppressWarnings();
600 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
601 $e = oci_error( $stmt );
602 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
603 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
604 return false;
605 } else {
606 $this->mAffectedRows = oci_num_rows( $stmt );
608 } else {
609 $this->mAffectedRows = oci_num_rows( $stmt );
612 wfRestoreWarnings();
614 if ( isset( $lob ) ) {
615 foreach ( $lob as $lob_v ) {
616 $lob_v->free();
620 if ( !$this->mTrxLevel ) {
621 oci_commit( $this->mConn );
624 oci_free_statement( $stmt );
627 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
628 $insertOptions = array(), $selectOptions = array() )
630 $destTable = $this->tableName( $destTable );
631 if ( !is_array( $selectOptions ) ) {
632 $selectOptions = array( $selectOptions );
634 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
635 if ( is_array( $srcTable ) ) {
636 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
637 } else {
638 $srcTable = $this->tableName( $srcTable );
641 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
642 !isset( $varMap[$sequenceData['column']] ) )
644 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
647 // count-alias subselect fields to avoid abigious definition errors
648 $i = 0;
649 foreach ( $varMap as &$val ) {
650 $val = $val . ' field' . ( $i++ );
653 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
654 " SELECT $startOpts " . implode( ',', $varMap ) .
655 " FROM $srcTable $useIndex ";
656 if ( $conds != '*' ) {
657 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
659 $sql .= " $tailOpts";
661 if ( in_array( 'IGNORE', $insertOptions ) ) {
662 $this->ignore_DUP_VAL_ON_INDEX = true;
665 $retval = $this->query( $sql, $fname );
667 if ( in_array( 'IGNORE', $insertOptions ) ) {
668 $this->ignore_DUP_VAL_ON_INDEX = false;
671 return $retval;
674 function tableName( $name, $format = 'quoted' ) {
676 Replace reserved words with better ones
677 Using uppercase because that's the only way Oracle can handle
678 quoted tablenames
680 switch ( $name ) {
681 case 'user':
682 $name = 'MWUSER';
683 break;
684 case 'text':
685 $name = 'PAGECONTENT';
686 break;
689 return parent::tableName( strtoupper( $name ), $format );
692 function tableNameInternal( $name ) {
693 $name = $this->tableName( $name );
694 return preg_replace( '/.*\.(.*)/', '$1', $name );
697 * Return the next in a sequence, save the value for retrieval via insertId()
698 * @return null
700 function nextSequenceValue( $seqName ) {
701 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
702 $row = $this->fetchRow( $res );
703 $this->mInsertId = $row[0];
704 return $this->mInsertId;
708 * Return sequence_name if table has a sequence
709 * @return bool
711 private function getSequenceData( $table ) {
712 if ( $this->sequenceData == null ) {
713 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
714 lower(atc.table_name),
715 lower(atc.column_name)
716 FROM all_sequences asq, all_tab_columns atc
717 WHERE decode(atc.table_name, '{$this->mTablePrefix}MWUSER', '{$this->mTablePrefix}USER', atc.table_name) || '_' ||
718 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
719 AND asq.sequence_owner = upper('{$this->mDBname}')
720 AND atc.owner = upper('{$this->mDBname}')" );
722 while ( ( $row = $result->fetchRow() ) !== false ) {
723 $this->sequenceData[$row[1]] = array(
724 'sequence' => $row[0],
725 'column' => $row[2]
729 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
730 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
733 # Returns the size of a text field, or -1 for "unlimited"
734 function textFieldSize( $table, $field ) {
735 $fieldInfoData = $this->fieldInfo( $table, $field );
736 return $fieldInfoData->maxLength();
739 function limitResult( $sql, $limit, $offset = false ) {
740 if ( $offset === false ) {
741 $offset = 0;
743 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
746 function encodeBlob( $b ) {
747 return new Blob( $b );
750 function decodeBlob( $b ) {
751 if ( $b instanceof Blob ) {
752 $b = $b->fetch();
754 return $b;
757 function unionQueries( $sqls, $all ) {
758 $glue = ' UNION ALL ';
759 return 'SELECT * ' . ( $all ? '' : '/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')';
762 function wasDeadlock() {
763 return $this->lastErrno() == 'OCI-00060';
766 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
767 $temporary = $temporary ? 'TRUE' : 'FALSE';
769 $newName = strtoupper( $newName );
770 $oldName = strtoupper( $oldName );
772 $tabName = substr( $newName, strlen( $this->mTablePrefix ) );
773 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
774 $newPrefix = strtoupper( $this->mTablePrefix );
776 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', '$oldPrefix', '$newPrefix', $temporary ); END;" );
779 function listTables( $prefix = null, $fname = __METHOD__ ) {
780 $listWhere = '';
781 if ( !empty( $prefix ) ) {
782 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
785 $owner = strtoupper( $this->mDBname );
786 $result = $this->doQuery( "SELECT table_name FROM all_tables WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
788 // dirty code ... i know
789 $endArray = array();
790 $endArray[] = strtoupper( $prefix . 'MWUSER' );
791 $endArray[] = strtoupper( $prefix . 'PAGE' );
792 $endArray[] = strtoupper( $prefix . 'IMAGE' );
793 $fixedOrderTabs = $endArray;
794 while ( ( $row = $result->fetchRow() ) !== false ) {
795 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
796 $endArray[] = $row['table_name'];
800 return $endArray;
803 public function dropTable( $tableName, $fName = __METHOD__ ) {
804 $tableName = $this->tableName( $tableName );
805 if ( !$this->tableExists( $tableName ) ) {
806 return false;
809 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
812 function timestamp( $ts = 0 ) {
813 return wfTimestamp( TS_ORACLE, $ts );
817 * Return aggregated value function call
819 public function aggregateValue( $valuedata, $valuename = 'value' ) {
820 return $valuedata;
823 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
824 # Ignore errors during error handling to avoid infinite
825 # recursion
826 $ignore = $this->ignoreErrors( true );
827 ++$this->mErrorCount;
829 if ( $ignore || $tempIgnore ) {
830 wfDebug( "SQL ERROR (ignored): $error\n" );
831 $this->ignoreErrors( $ignore );
832 } else {
833 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
838 * @return string wikitext of a link to the server software's web site
840 public static function getSoftwareLink() {
841 return '[http://www.oracle.com/ Oracle]';
845 * @return string Version information from the database
847 function getServerVersion() {
848 //better version number, fallback on driver
849 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
850 if ( !( $row = $rset->fetchRow() ) ) {
851 return oci_server_version( $this->mConn );
853 return $row['version'];
857 * Query whether a given index exists
858 * @return bool
860 function indexExists( $table, $index, $fname = __METHOD__ ) {
861 $table = $this->tableName( $table );
862 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
863 $index = strtoupper( $index );
864 $owner = strtoupper( $this->mDBname );
865 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
866 $res = $this->doQuery( $SQL );
867 if ( $res ) {
868 $count = $res->numRows();
869 $res->free();
870 } else {
871 $count = 0;
873 return $count != 0;
877 * Query whether a given table exists (in the given schema, or the default mw one if not given)
878 * @return int
880 function tableExists( $table, $fname = __METHOD__ ) {
881 $table = $this->tableName( $table );
882 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
883 $owner = $this->addQuotes( strtoupper( $this->mDBname ) );
884 $SQL = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
885 $res = $this->doQuery( $SQL );
886 if ( $res ) {
887 $count = $res->numRows();
888 $res->free();
889 } else {
890 $count = 0;
892 return $count;
896 * Function translates mysql_fetch_field() functionality on ORACLE.
897 * Caching is present for reducing query time.
898 * For internal calls. Use fieldInfo for normal usage.
899 * Returns false if the field doesn't exist
901 * @param $table Array
902 * @param $field String
903 * @return ORAField|ORAResult
905 private function fieldInfoMulti( $table, $field ) {
906 $field = strtoupper( $field );
907 if ( is_array( $table ) ) {
908 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
909 $tableWhere = 'IN (';
910 foreach ( $table as &$singleTable ) {
911 $singleTable = $this->removeIdentifierQuotes( $singleTable );
912 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
913 return $this->mFieldInfoCache["$singleTable.$field"];
915 $tableWhere .= '\'' . $singleTable . '\',';
917 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
918 } else {
919 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
920 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
921 return $this->mFieldInfoCache["$table.$field"];
923 $tableWhere = '= \'' . $table . '\'';
926 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name ' . $tableWhere . ' and column_name = \'' . $field . '\'' );
927 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
928 $e = oci_error( $fieldInfoStmt );
929 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
930 return false;
932 $res = new ORAResult( $this, $fieldInfoStmt );
933 if ( $res->numRows() == 0 ) {
934 if ( is_array( $table ) ) {
935 foreach ( $table as &$singleTable ) {
936 $this->mFieldInfoCache["$singleTable.$field"] = false;
938 } else {
939 $this->mFieldInfoCache["$table.$field"] = false;
941 $fieldInfoTemp = null;
942 } else {
943 $fieldInfoTemp = new ORAField( $res->fetchRow() );
944 $table = $fieldInfoTemp->tableName();
945 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
947 $res->free();
948 return $fieldInfoTemp;
952 * @throws DBUnexpectedError
953 * @param $table
954 * @param $field
955 * @return ORAField
957 function fieldInfo( $table, $field ) {
958 if ( is_array( $table ) ) {
959 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
961 return $this->fieldInfoMulti( $table, $field );
964 protected function doBegin( $fname = __METHOD__ ) {
965 $this->mTrxLevel = 1;
966 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
969 protected function doCommit( $fname = __METHOD__ ) {
970 if ( $this->mTrxLevel ) {
971 $ret = oci_commit( $this->mConn );
972 if ( !$ret ) {
973 throw new DBUnexpectedError( $this, $this->lastError() );
975 $this->mTrxLevel = 0;
976 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
980 protected function doRollback( $fname = __METHOD__ ) {
981 if ( $this->mTrxLevel ) {
982 oci_rollback( $this->mConn );
983 $this->mTrxLevel = 0;
984 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
988 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
989 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
990 $fname = __METHOD__, $inputCallback = false ) {
991 $cmd = '';
992 $done = false;
993 $dollarquote = false;
995 $replacements = array();
997 while ( ! feof( $fp ) ) {
998 if ( $lineCallback ) {
999 call_user_func( $lineCallback );
1001 $line = trim( fgets( $fp, 1024 ) );
1002 $sl = strlen( $line ) - 1;
1004 if ( $sl < 0 ) {
1005 continue;
1007 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1008 continue;
1011 // Allow dollar quoting for function declarations
1012 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1013 if ( $dollarquote ) {
1014 $dollarquote = false;
1015 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1016 $done = true;
1017 } else {
1018 $dollarquote = true;
1020 } elseif ( !$dollarquote ) {
1021 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1022 $done = true;
1023 $line = substr( $line, 0, $sl );
1027 if ( $cmd != '' ) {
1028 $cmd .= ' ';
1030 $cmd .= "$line\n";
1032 if ( $done ) {
1033 $cmd = str_replace( ';;', ";", $cmd );
1034 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1035 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1036 $replacements[$defines[2]] = $defines[1];
1038 } else {
1039 foreach ( $replacements as $mwVar => $scVar ) {
1040 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1043 $cmd = $this->replaceVars( $cmd );
1044 if ( $inputCallback ) {
1045 call_user_func( $inputCallback, $cmd );
1047 $res = $this->doQuery( $cmd );
1048 if ( $resultCallback ) {
1049 call_user_func( $resultCallback, $res, $this );
1052 if ( false === $res ) {
1053 $err = $this->lastError();
1054 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1058 $cmd = '';
1059 $done = false;
1062 return true;
1065 function selectDB( $db ) {
1066 $this->mDBname = $db;
1067 if ( $db == null || $db == $this->mUser ) {
1068 return true;
1070 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1071 $stmt = oci_parse( $this->mConn, $sql );
1072 wfSuppressWarnings();
1073 $success = oci_execute( $stmt );
1074 wfRestoreWarnings();
1075 if ( !$success ) {
1076 $e = oci_error( $stmt );
1077 if ( $e['code'] != '1435' ) {
1078 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1080 return false;
1082 return true;
1085 function strencode( $s ) {
1086 return str_replace( "'", "''", $s );
1089 function addQuotes( $s ) {
1090 global $wgContLang;
1091 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1092 $s = $wgContLang->checkTitleEncoding( $s );
1094 return "'" . $this->strencode( $s ) . "'";
1097 public function addIdentifierQuotes( $s ) {
1098 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1099 $s = '/*Q*/' . $s;
1101 return $s;
1104 public function removeIdentifierQuotes( $s ) {
1105 return strpos( $s, '/*Q*/' ) === false ? $s : substr( $s, 5 );
1108 public function isQuotedIdentifier( $s ) {
1109 return strpos( $s, '/*Q*/' ) !== false;
1112 private function wrapFieldForWhere( $table, &$col, &$val ) {
1113 global $wgContLang;
1115 $col_info = $this->fieldInfoMulti( $table, $col );
1116 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1117 if ( $col_type == 'CLOB' ) {
1118 $col = 'TO_CHAR(' . $col . ')';
1119 $val = $wgContLang->checkTitleEncoding( $val );
1120 } elseif ( $col_type == 'VARCHAR2' ) {
1121 $val = $wgContLang->checkTitleEncoding( $val );
1125 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1126 $conds2 = array();
1127 foreach ( $conds as $col => $val ) {
1128 if ( is_array( $val ) ) {
1129 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1130 } else {
1131 if ( is_numeric( $col ) && $parentCol != null ) {
1132 $this->wrapFieldForWhere( $table, $parentCol, $val );
1133 } else {
1134 $this->wrapFieldForWhere( $table, $col, $val );
1136 $conds2[$col] = $val;
1139 return $conds2;
1142 function selectRow( $table, $vars, $conds, $fname = __METHOD__, $options = array(), $join_conds = array() ) {
1143 if ( is_array( $conds ) ) {
1144 $conds = $this->wrapConditionsForWhere( $table, $conds );
1146 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1150 * Returns an optional USE INDEX clause to go after the table, and a
1151 * string to go at the end of the query
1153 * @private
1155 * @param array $options an associative array of options to be turned into
1156 * an SQL query, valid keys are listed in the function.
1157 * @return array
1159 function makeSelectOptions( $options ) {
1160 $preLimitTail = $postLimitTail = '';
1161 $startOpts = '';
1163 $noKeyOptions = array();
1164 foreach ( $options as $key => $option ) {
1165 if ( is_numeric( $key ) ) {
1166 $noKeyOptions[$option] = true;
1170 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1172 $preLimitTail .= $this->makeOrderBy( $options );
1174 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1175 $postLimitTail .= ' FOR UPDATE';
1178 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1179 $startOpts .= 'DISTINCT';
1182 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1183 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1184 } else {
1185 $useIndex = '';
1188 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1191 public function delete( $table, $conds, $fname = __METHOD__ ) {
1192 if ( is_array( $conds ) ) {
1193 $conds = $this->wrapConditionsForWhere( $table, $conds );
1195 // a hack for deleting pages, users and images (which have non-nullable FKs)
1196 // all deletions on these tables have transactions so final failure rollbacks these updates
1197 $table = $this->tableName( $table );
1198 if ( $table == $this->tableName( 'user' ) ) {
1199 $this->update( 'archive', array( 'ar_user' => 0 ), array( 'ar_user' => $conds['user_id'] ), $fname );
1200 $this->update( 'ipblocks', array( 'ipb_user' => 0 ), array( 'ipb_user' => $conds['user_id'] ), $fname );
1201 $this->update( 'image', array( 'img_user' => 0 ), array( 'img_user' => $conds['user_id'] ), $fname );
1202 $this->update( 'oldimage', array( 'oi_user' => 0 ), array( 'oi_user' => $conds['user_id'] ), $fname );
1203 $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ), array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
1204 $this->update( 'filearchive', array( 'fa_user' => 0 ), array( 'fa_user' => $conds['user_id'] ), $fname );
1205 $this->update( 'uploadstash', array( 'us_user' => 0 ), array( 'us_user' => $conds['user_id'] ), $fname );
1206 $this->update( 'recentchanges', array( 'rc_user' => 0 ), array( 'rc_user' => $conds['user_id'] ), $fname );
1207 $this->update( 'logging', array( 'log_user' => 0 ), array( 'log_user' => $conds['user_id'] ), $fname );
1208 } elseif ( $table == $this->tableName( 'image' ) ) {
1209 $this->update( 'oldimage', array( 'oi_name' => 0 ), array( 'oi_name' => $conds['img_name'] ), $fname );
1211 return parent::delete( $table, $conds, $fname );
1214 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
1215 global $wgContLang;
1217 $table = $this->tableName( $table );
1218 $opts = $this->makeUpdateOptions( $options );
1219 $sql = "UPDATE $opts $table SET ";
1221 $first = true;
1222 foreach ( $values as $col => &$val ) {
1223 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1225 if ( !$first ) {
1226 $sqlSet = ', ' . $sqlSet;
1227 } else {
1228 $first = false;
1230 $sql .= $sqlSet;
1233 if ( $conds !== array() && $conds !== '*' ) {
1234 $conds = $this->wrapConditionsForWhere( $table, $conds );
1235 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1238 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1239 $e = oci_error( $this->mConn );
1240 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1241 return false;
1243 foreach ( $values as $col => &$val ) {
1244 $col_info = $this->fieldInfoMulti( $table, $col );
1245 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1247 if ( $val === null ) {
1248 // do nothing ... null was inserted in statement creation
1249 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1250 if ( is_object( $val ) ) {
1251 $val = $val->getData();
1254 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1255 $val = '31-12-2030 12:00:00.000000';
1258 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1259 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1260 $e = oci_error( $stmt );
1261 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1262 return false;
1264 } else {
1265 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1266 $e = oci_error( $stmt );
1267 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1270 if ( $col_type == 'BLOB' ) {
1271 $lob[$col]->writeTemporary( $val );
1272 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1273 } else {
1274 $lob[$col]->writeTemporary( $val );
1275 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1280 wfSuppressWarnings();
1282 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1283 $e = oci_error( $stmt );
1284 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1285 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1286 return false;
1287 } else {
1288 $this->mAffectedRows = oci_num_rows( $stmt );
1290 } else {
1291 $this->mAffectedRows = oci_num_rows( $stmt );
1294 wfRestoreWarnings();
1296 if ( isset( $lob ) ) {
1297 foreach ( $lob as $lob_v ) {
1298 $lob_v->free();
1302 if ( !$this->mTrxLevel ) {
1303 oci_commit( $this->mConn );
1306 oci_free_statement( $stmt );
1309 function bitNot( $field ) {
1310 // expecting bit-fields smaller than 4bytes
1311 return 'BITNOT(' . $field . ')';
1314 function bitAnd( $fieldLeft, $fieldRight ) {
1315 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1318 function bitOr( $fieldLeft, $fieldRight ) {
1319 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1322 function setFakeMaster( $enabled = true ) {
1325 function getDBname() {
1326 return $this->mDBname;
1329 function getServer() {
1330 return $this->mServer;
1333 public function getSearchEngine() {
1334 return 'SearchOracle';
1337 public function getInfinity() {
1338 return '31-12-2030 12:00:00.000000';
1341 } // end DatabaseOracle class