Merge "Whitelist the <wbr> element."
[mediawiki.git] / includes / db / DatabaseOracle.php
blob2ccc056273ff1b496db37ce8fd83ce7cc7ddbe9e
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 global $wgDBOracleDRCP;
253 if ( !function_exists( 'oci_connect' ) ) {
254 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" );
257 $this->close();
258 $this->mUser = $user;
259 $this->mPassword = $password;
260 // changed internal variables functions
261 // mServer now holds the TNS endpoint
262 // mDBname is schema name if different from username
263 if ( !$server ) {
264 // backward compatibillity (server used to be null and TNS was supplied in dbname)
265 $this->mServer = $dbName;
266 $this->mDBname = $user;
267 } else {
268 $this->mServer = $server;
269 if ( !$dbName ) {
270 $this->mDBname = $user;
271 } else {
272 $this->mDBname = $dbName;
276 if ( !strlen( $user ) ) { # e.g. the class is being loaded
277 return;
280 if ( $wgDBOracleDRCP ) {
281 $this->setFlag( DBO_PERSISTENT );
284 $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
286 wfSuppressWarnings();
287 if ( $this->mFlags & DBO_PERSISTENT ) {
288 $this->mConn = oci_pconnect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
289 } else if ( $this->mFlags & DBO_DEFAULT ) {
290 $this->mConn = oci_new_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
291 } else {
292 $this->mConn = oci_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
294 wfRestoreWarnings();
296 if ( $this->mUser != $this->mDBname ) {
297 //change current schema in session
298 $this->selectDB( $this->mDBname );
301 if ( !$this->mConn ) {
302 throw new DBConnectionError( $this, $this->lastError() );
305 $this->mOpened = true;
307 # removed putenv calls because they interfere with the system globaly
308 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
309 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
310 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
311 return $this->mConn;
315 * Closes a database connection, if it is open
316 * Returns success, true if already closed
317 * @return bool
319 protected function closeConnection() {
320 return oci_close( $this->mConn );
323 function execFlags() {
324 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT : OCI_COMMIT_ON_SUCCESS;
327 protected function doQuery( $sql ) {
328 wfDebug( "SQL: [$sql]\n" );
329 if ( !StringUtils::isUtf8( $sql ) ) {
330 throw new MWException( "SQL encoding is invalid\n$sql" );
333 // handle some oracle specifics
334 // remove AS column/table/subquery namings
335 if ( !$this->getFlag( DBO_DDLMODE ) ) {
336 $sql = preg_replace( '/ as /i', ' ', $sql );
339 // Oracle has issues with UNION clause if the statement includes LOB fields
340 // So we do a UNION ALL and then filter the results array with array_unique
341 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
342 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
343 // you have to select data from plan table after explain
344 $explain_id = MWTimestamp::getLocalInstance()->format( 'dmYHis' );
346 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
348 wfSuppressWarnings();
350 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
351 $e = oci_error( $this->mConn );
352 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
353 return false;
356 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
357 $e = oci_error( $stmt );
358 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
359 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
360 return false;
364 wfRestoreWarnings();
366 if ( $explain_count > 0 ) {
367 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
368 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
369 return new ORAResult( $this, $stmt, $union_unique );
370 } else {
371 $this->mAffectedRows = oci_num_rows( $stmt );
372 return true;
376 function queryIgnore( $sql, $fname = '' ) {
377 return $this->query( $sql, $fname, true );
380 function freeResult( $res ) {
381 if ( $res instanceof ResultWrapper ) {
382 $res = $res->result;
385 $res->free();
388 function fetchObject( $res ) {
389 if ( $res instanceof ResultWrapper ) {
390 $res = $res->result;
393 return $res->fetchObject();
396 function fetchRow( $res ) {
397 if ( $res instanceof ResultWrapper ) {
398 $res = $res->result;
401 return $res->fetchRow();
404 function numRows( $res ) {
405 if ( $res instanceof ResultWrapper ) {
406 $res = $res->result;
409 return $res->numRows();
412 function numFields( $res ) {
413 if ( $res instanceof ResultWrapper ) {
414 $res = $res->result;
417 return $res->numFields();
420 function fieldName( $stmt, $n ) {
421 return oci_field_name( $stmt, $n );
425 * This must be called after nextSequenceVal
426 * @return null
428 function insertId() {
429 return $this->mInsertId;
432 function dataSeek( $res, $row ) {
433 if ( $res instanceof ORAResult ) {
434 $res->seek( $row );
435 } else {
436 $res->result->seek( $row );
440 function lastError() {
441 if ( $this->mConn === false ) {
442 $e = oci_error();
443 } else {
444 $e = oci_error( $this->mConn );
446 return $e['message'];
449 function lastErrno() {
450 if ( $this->mConn === false ) {
451 $e = oci_error();
452 } else {
453 $e = oci_error( $this->mConn );
455 return $e['code'];
458 function affectedRows() {
459 return $this->mAffectedRows;
463 * Returns information about an index
464 * If errors are explicitly ignored, returns NULL on failure
465 * @return bool
467 function indexInfo( $table, $index, $fname = __METHOD__ ) {
468 return false;
471 function indexUnique( $table, $index, $fname = __METHOD__ ) {
472 return false;
475 function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
476 if ( !count( $a ) ) {
477 return true;
480 if ( !is_array( $options ) ) {
481 $options = array( $options );
484 if ( in_array( 'IGNORE', $options ) ) {
485 $this->ignore_DUP_VAL_ON_INDEX = true;
488 if ( !is_array( reset( $a ) ) ) {
489 $a = array( $a );
492 foreach ( $a as &$row ) {
493 $this->insertOneRow( $table, $row, $fname );
495 $retVal = true;
497 if ( in_array( 'IGNORE', $options ) ) {
498 $this->ignore_DUP_VAL_ON_INDEX = false;
501 return $retVal;
504 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
505 $col_info = $this->fieldInfoMulti( $table, $col );
506 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
508 $bind = '';
509 if ( is_numeric( $col ) ) {
510 $bind = $val;
511 $val = null;
512 return $bind;
513 } elseif ( $includeCol ) {
514 $bind = "$col = ";
517 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
518 $val = null;
521 if ( $val === 'NULL' ) {
522 $val = null;
525 if ( $val === null ) {
526 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
527 $bind .= 'DEFAULT';
528 } else {
529 $bind .= 'NULL';
531 } else {
532 $bind .= ':' . $col;
535 return $bind;
538 private function insertOneRow( $table, $row, $fname ) {
539 global $wgContLang;
541 $table = $this->tableName( $table );
542 // "INSERT INTO tables (a, b, c)"
543 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
544 $sql .= " VALUES (";
546 // for each value, append ":key"
547 $first = true;
548 foreach ( $row as $col => &$val ) {
549 if ( !$first ) {
550 $sql .= ', ';
551 } else {
552 $first = false;
555 $sql .= $this->fieldBindStatement( $table, $col, $val );
557 $sql .= ')';
559 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
560 $e = oci_error( $this->mConn );
561 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
562 return false;
564 foreach ( $row as $col => &$val ) {
565 $col_info = $this->fieldInfoMulti( $table, $col );
566 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
568 if ( $val === null ) {
569 // do nothing ... null was inserted in statement creation
570 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
571 if ( is_object( $val ) ) {
572 $val = $val->fetch();
575 // backward compatibility
576 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
577 $val = $this->getInfinity();
580 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
581 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR ) === false ) {
582 $e = oci_error( $stmt );
583 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
584 return false;
586 } else {
587 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
588 $e = oci_error( $stmt );
589 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
592 if ( is_object( $val ) ) {
593 $val = $val->fetch();
596 if ( $col_type == 'BLOB' ) {
597 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
598 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB );
599 } else {
600 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
601 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
606 wfSuppressWarnings();
608 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
609 $e = oci_error( $stmt );
610 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
611 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
612 return false;
613 } else {
614 $this->mAffectedRows = oci_num_rows( $stmt );
616 } else {
617 $this->mAffectedRows = oci_num_rows( $stmt );
620 wfRestoreWarnings();
622 if ( isset( $lob ) ) {
623 foreach ( $lob as $lob_v ) {
624 $lob_v->free();
628 if ( !$this->mTrxLevel ) {
629 oci_commit( $this->mConn );
632 oci_free_statement( $stmt );
635 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
636 $insertOptions = array(), $selectOptions = array() )
638 $destTable = $this->tableName( $destTable );
639 if ( !is_array( $selectOptions ) ) {
640 $selectOptions = array( $selectOptions );
642 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
643 if ( is_array( $srcTable ) ) {
644 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
645 } else {
646 $srcTable = $this->tableName( $srcTable );
649 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
650 !isset( $varMap[$sequenceData['column']] ) )
652 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
655 // count-alias subselect fields to avoid abigious definition errors
656 $i = 0;
657 foreach ( $varMap as &$val ) {
658 $val = $val . ' field' . ( $i++ );
661 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
662 " SELECT $startOpts " . implode( ',', $varMap ) .
663 " FROM $srcTable $useIndex ";
664 if ( $conds != '*' ) {
665 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
667 $sql .= " $tailOpts";
669 if ( in_array( 'IGNORE', $insertOptions ) ) {
670 $this->ignore_DUP_VAL_ON_INDEX = true;
673 $retval = $this->query( $sql, $fname );
675 if ( in_array( 'IGNORE', $insertOptions ) ) {
676 $this->ignore_DUP_VAL_ON_INDEX = false;
679 return $retval;
682 function tableName( $name, $format = 'quoted' ) {
684 Replace reserved words with better ones
685 Using uppercase because that's the only way Oracle can handle
686 quoted tablenames
688 switch ( $name ) {
689 case 'user':
690 $name = 'MWUSER';
691 break;
692 case 'text':
693 $name = 'PAGECONTENT';
694 break;
697 return parent::tableName( strtoupper( $name ), $format );
700 function tableNameInternal( $name ) {
701 $name = $this->tableName( $name );
702 return preg_replace( '/.*\.(.*)/', '$1', $name );
705 * Return the next in a sequence, save the value for retrieval via insertId()
706 * @return null
708 function nextSequenceValue( $seqName ) {
709 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
710 $row = $this->fetchRow( $res );
711 $this->mInsertId = $row[0];
712 return $this->mInsertId;
716 * Return sequence_name if table has a sequence
717 * @return bool
719 private function getSequenceData( $table ) {
720 if ( $this->sequenceData == null ) {
721 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
722 lower(atc.table_name),
723 lower(atc.column_name)
724 FROM all_sequences asq, all_tab_columns atc
725 WHERE decode(atc.table_name, '{$this->mTablePrefix}MWUSER', '{$this->mTablePrefix}USER', atc.table_name) || '_' ||
726 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
727 AND asq.sequence_owner = upper('{$this->mDBname}')
728 AND atc.owner = upper('{$this->mDBname}')" );
730 while ( ( $row = $result->fetchRow() ) !== false ) {
731 $this->sequenceData[$row[1]] = array(
732 'sequence' => $row[0],
733 'column' => $row[2]
737 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
738 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
741 # Returns the size of a text field, or -1 for "unlimited"
742 function textFieldSize( $table, $field ) {
743 $fieldInfoData = $this->fieldInfo( $table, $field );
744 return $fieldInfoData->maxLength();
747 function limitResult( $sql, $limit, $offset = false ) {
748 if ( $offset === false ) {
749 $offset = 0;
751 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
754 function encodeBlob( $b ) {
755 return new Blob( $b );
758 function decodeBlob( $b ) {
759 if ( $b instanceof Blob ) {
760 $b = $b->fetch();
762 return $b;
765 function unionQueries( $sqls, $all ) {
766 $glue = ' UNION ALL ';
767 return 'SELECT * ' . ( $all ? '' : '/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')';
770 function wasDeadlock() {
771 return $this->lastErrno() == 'OCI-00060';
774 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
775 $temporary = $temporary ? 'TRUE' : 'FALSE';
777 $newName = strtoupper( $newName );
778 $oldName = strtoupper( $oldName );
780 $tabName = substr( $newName, strlen( $this->mTablePrefix ) );
781 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
782 $newPrefix = strtoupper( $this->mTablePrefix );
784 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', '$oldPrefix', '$newPrefix', $temporary ); END;" );
787 function listTables( $prefix = null, $fname = __METHOD__ ) {
788 $listWhere = '';
789 if ( !empty( $prefix ) ) {
790 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
793 $owner = strtoupper( $this->mDBname );
794 $result = $this->doQuery( "SELECT table_name FROM all_tables WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
796 // dirty code ... i know
797 $endArray = array();
798 $endArray[] = strtoupper( $prefix . 'MWUSER' );
799 $endArray[] = strtoupper( $prefix . 'PAGE' );
800 $endArray[] = strtoupper( $prefix . 'IMAGE' );
801 $fixedOrderTabs = $endArray;
802 while ( ( $row = $result->fetchRow() ) !== false ) {
803 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
804 $endArray[] = $row['table_name'];
808 return $endArray;
811 public function dropTable( $tableName, $fName = __METHOD__ ) {
812 $tableName = $this->tableName( $tableName );
813 if ( !$this->tableExists( $tableName ) ) {
814 return false;
817 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
820 function timestamp( $ts = 0 ) {
821 return wfTimestamp( TS_ORACLE, $ts );
825 * Return aggregated value function call
827 public function aggregateValue( $valuedata, $valuename = 'value' ) {
828 return $valuedata;
831 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
832 # Ignore errors during error handling to avoid infinite
833 # recursion
834 $ignore = $this->ignoreErrors( true );
835 ++$this->mErrorCount;
837 if ( $ignore || $tempIgnore ) {
838 wfDebug( "SQL ERROR (ignored): $error\n" );
839 $this->ignoreErrors( $ignore );
840 } else {
841 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
846 * @return string wikitext of a link to the server software's web site
848 public function getSoftwareLink() {
849 return '[http://www.oracle.com/ Oracle]';
853 * @return string Version information from the database
855 function getServerVersion() {
856 //better version number, fallback on driver
857 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
858 if ( !( $row = $rset->fetchRow() ) ) {
859 return oci_server_version( $this->mConn );
861 return $row['version'];
865 * Query whether a given index exists
866 * @return bool
868 function indexExists( $table, $index, $fname = __METHOD__ ) {
869 $table = $this->tableName( $table );
870 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
871 $index = strtoupper( $index );
872 $owner = strtoupper( $this->mDBname );
873 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
874 $res = $this->doQuery( $SQL );
875 if ( $res ) {
876 $count = $res->numRows();
877 $res->free();
878 } else {
879 $count = 0;
881 return $count != 0;
885 * Query whether a given table exists (in the given schema, or the default mw one if not given)
886 * @return int
888 function tableExists( $table, $fname = __METHOD__ ) {
889 $table = $this->tableName( $table );
890 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
891 $owner = $this->addQuotes( strtoupper( $this->mDBname ) );
892 $SQL = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
893 $res = $this->doQuery( $SQL );
894 if ( $res ) {
895 $count = $res->numRows();
896 $res->free();
897 } else {
898 $count = 0;
900 return $count;
904 * Function translates mysql_fetch_field() functionality on ORACLE.
905 * Caching is present for reducing query time.
906 * For internal calls. Use fieldInfo for normal usage.
907 * Returns false if the field doesn't exist
909 * @param $table Array
910 * @param $field String
911 * @return ORAField|ORAResult
913 private function fieldInfoMulti( $table, $field ) {
914 $field = strtoupper( $field );
915 if ( is_array( $table ) ) {
916 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
917 $tableWhere = 'IN (';
918 foreach ( $table as &$singleTable ) {
919 $singleTable = $this->removeIdentifierQuotes( $singleTable );
920 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
921 return $this->mFieldInfoCache["$singleTable.$field"];
923 $tableWhere .= '\'' . $singleTable . '\',';
925 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
926 } else {
927 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
928 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
929 return $this->mFieldInfoCache["$table.$field"];
931 $tableWhere = '= \'' . $table . '\'';
934 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name ' . $tableWhere . ' and column_name = \'' . $field . '\'' );
935 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
936 $e = oci_error( $fieldInfoStmt );
937 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
938 return false;
940 $res = new ORAResult( $this, $fieldInfoStmt );
941 if ( $res->numRows() == 0 ) {
942 if ( is_array( $table ) ) {
943 foreach ( $table as &$singleTable ) {
944 $this->mFieldInfoCache["$singleTable.$field"] = false;
946 } else {
947 $this->mFieldInfoCache["$table.$field"] = false;
949 $fieldInfoTemp = null;
950 } else {
951 $fieldInfoTemp = new ORAField( $res->fetchRow() );
952 $table = $fieldInfoTemp->tableName();
953 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
955 $res->free();
956 return $fieldInfoTemp;
960 * @throws DBUnexpectedError
961 * @param $table
962 * @param $field
963 * @return ORAField
965 function fieldInfo( $table, $field ) {
966 if ( is_array( $table ) ) {
967 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
969 return $this->fieldInfoMulti( $table, $field );
972 protected function doBegin( $fname = __METHOD__ ) {
973 $this->mTrxLevel = 1;
974 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
977 protected function doCommit( $fname = __METHOD__ ) {
978 if ( $this->mTrxLevel ) {
979 $ret = oci_commit( $this->mConn );
980 if ( !$ret ) {
981 throw new DBUnexpectedError( $this, $this->lastError() );
983 $this->mTrxLevel = 0;
984 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
988 protected function doRollback( $fname = __METHOD__ ) {
989 if ( $this->mTrxLevel ) {
990 oci_rollback( $this->mConn );
991 $this->mTrxLevel = 0;
992 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
996 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
997 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
998 $fname = __METHOD__, $inputCallback = false ) {
999 $cmd = '';
1000 $done = false;
1001 $dollarquote = false;
1003 $replacements = array();
1005 while ( ! feof( $fp ) ) {
1006 if ( $lineCallback ) {
1007 call_user_func( $lineCallback );
1009 $line = trim( fgets( $fp, 1024 ) );
1010 $sl = strlen( $line ) - 1;
1012 if ( $sl < 0 ) {
1013 continue;
1015 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1016 continue;
1019 // Allow dollar quoting for function declarations
1020 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1021 if ( $dollarquote ) {
1022 $dollarquote = false;
1023 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1024 $done = true;
1025 } else {
1026 $dollarquote = true;
1028 } elseif ( !$dollarquote ) {
1029 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1030 $done = true;
1031 $line = substr( $line, 0, $sl );
1035 if ( $cmd != '' ) {
1036 $cmd .= ' ';
1038 $cmd .= "$line\n";
1040 if ( $done ) {
1041 $cmd = str_replace( ';;', ";", $cmd );
1042 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1043 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1044 $replacements[$defines[2]] = $defines[1];
1046 } else {
1047 foreach ( $replacements as $mwVar => $scVar ) {
1048 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1051 $cmd = $this->replaceVars( $cmd );
1052 if ( $inputCallback ) {
1053 call_user_func( $inputCallback, $cmd );
1055 $res = $this->doQuery( $cmd );
1056 if ( $resultCallback ) {
1057 call_user_func( $resultCallback, $res, $this );
1060 if ( false === $res ) {
1061 $err = $this->lastError();
1062 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1066 $cmd = '';
1067 $done = false;
1070 return true;
1073 function selectDB( $db ) {
1074 $this->mDBname = $db;
1075 if ( $db == null || $db == $this->mUser ) {
1076 return true;
1078 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1079 $stmt = oci_parse( $this->mConn, $sql );
1080 wfSuppressWarnings();
1081 $success = oci_execute( $stmt );
1082 wfRestoreWarnings();
1083 if ( !$success ) {
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 public function addIdentifierQuotes( $s ) {
1106 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1107 $s = '/*Q*/' . $s;
1109 return $s;
1112 public function removeIdentifierQuotes( $s ) {
1113 return strpos( $s, '/*Q*/' ) === false ? $s : substr( $s, 5 );
1116 public function isQuotedIdentifier( $s ) {
1117 return strpos( $s, '/*Q*/' ) !== false;
1120 private function wrapFieldForWhere( $table, &$col, &$val ) {
1121 global $wgContLang;
1123 $col_info = $this->fieldInfoMulti( $table, $col );
1124 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1125 if ( $col_type == 'CLOB' ) {
1126 $col = 'TO_CHAR(' . $col . ')';
1127 $val = $wgContLang->checkTitleEncoding( $val );
1128 } elseif ( $col_type == 'VARCHAR2' ) {
1129 $val = $wgContLang->checkTitleEncoding( $val );
1133 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1134 $conds2 = array();
1135 foreach ( $conds as $col => $val ) {
1136 if ( is_array( $val ) ) {
1137 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1138 } else {
1139 if ( is_numeric( $col ) && $parentCol != null ) {
1140 $this->wrapFieldForWhere( $table, $parentCol, $val );
1141 } else {
1142 $this->wrapFieldForWhere( $table, $col, $val );
1144 $conds2[$col] = $val;
1147 return $conds2;
1150 function selectRow( $table, $vars, $conds, $fname = __METHOD__, $options = array(), $join_conds = array() ) {
1151 if ( is_array( $conds ) ) {
1152 $conds = $this->wrapConditionsForWhere( $table, $conds );
1154 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1158 * Returns an optional USE INDEX clause to go after the table, and a
1159 * string to go at the end of the query
1161 * @private
1163 * @param array $options an associative array of options to be turned into
1164 * an SQL query, valid keys are listed in the function.
1165 * @return array
1167 function makeSelectOptions( $options ) {
1168 $preLimitTail = $postLimitTail = '';
1169 $startOpts = '';
1171 $noKeyOptions = array();
1172 foreach ( $options as $key => $option ) {
1173 if ( is_numeric( $key ) ) {
1174 $noKeyOptions[$option] = true;
1178 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1180 $preLimitTail .= $this->makeOrderBy( $options );
1182 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1183 $postLimitTail .= ' FOR UPDATE';
1186 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1187 $startOpts .= 'DISTINCT';
1190 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1191 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1192 } else {
1193 $useIndex = '';
1196 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1199 public function delete( $table, $conds, $fname = __METHOD__ ) {
1200 if ( is_array( $conds ) ) {
1201 $conds = $this->wrapConditionsForWhere( $table, $conds );
1203 // a hack for deleting pages, users and images (which have non-nullable FKs)
1204 // all deletions on these tables have transactions so final failure rollbacks these updates
1205 $table = $this->tableName( $table );
1206 if ( $table == $this->tableName( 'user' ) ) {
1207 $this->update( 'archive', array( 'ar_user' => 0 ), array( 'ar_user' => $conds['user_id'] ), $fname );
1208 $this->update( 'ipblocks', array( 'ipb_user' => 0 ), array( 'ipb_user' => $conds['user_id'] ), $fname );
1209 $this->update( 'image', array( 'img_user' => 0 ), array( 'img_user' => $conds['user_id'] ), $fname );
1210 $this->update( 'oldimage', array( 'oi_user' => 0 ), array( 'oi_user' => $conds['user_id'] ), $fname );
1211 $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ), array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
1212 $this->update( 'filearchive', array( 'fa_user' => 0 ), array( 'fa_user' => $conds['user_id'] ), $fname );
1213 $this->update( 'uploadstash', array( 'us_user' => 0 ), array( 'us_user' => $conds['user_id'] ), $fname );
1214 $this->update( 'recentchanges', array( 'rc_user' => 0 ), array( 'rc_user' => $conds['user_id'] ), $fname );
1215 $this->update( 'logging', array( 'log_user' => 0 ), array( 'log_user' => $conds['user_id'] ), $fname );
1216 } elseif ( $table == $this->tableName( 'image' ) ) {
1217 $this->update( 'oldimage', array( 'oi_name' => 0 ), array( 'oi_name' => $conds['img_name'] ), $fname );
1219 return parent::delete( $table, $conds, $fname );
1222 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
1223 global $wgContLang;
1225 $table = $this->tableName( $table );
1226 $opts = $this->makeUpdateOptions( $options );
1227 $sql = "UPDATE $opts $table SET ";
1229 $first = true;
1230 foreach ( $values as $col => &$val ) {
1231 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1233 if ( !$first ) {
1234 $sqlSet = ', ' . $sqlSet;
1235 } else {
1236 $first = false;
1238 $sql .= $sqlSet;
1241 if ( $conds !== array() && $conds !== '*' ) {
1242 $conds = $this->wrapConditionsForWhere( $table, $conds );
1243 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1246 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1247 $e = oci_error( $this->mConn );
1248 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1249 return false;
1251 foreach ( $values as $col => &$val ) {
1252 $col_info = $this->fieldInfoMulti( $table, $col );
1253 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1255 if ( $val === null ) {
1256 // do nothing ... null was inserted in statement creation
1257 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1258 if ( is_object( $val ) ) {
1259 $val = $val->getData();
1262 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1263 $val = '31-12-2030 12:00:00.000000';
1266 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1267 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1268 $e = oci_error( $stmt );
1269 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1270 return false;
1272 } else {
1273 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1274 $e = oci_error( $stmt );
1275 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1278 if ( $col_type == 'BLOB' ) {
1279 $lob[$col]->writeTemporary( $val );
1280 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1281 } else {
1282 $lob[$col]->writeTemporary( $val );
1283 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1288 wfSuppressWarnings();
1290 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1291 $e = oci_error( $stmt );
1292 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1293 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1294 return false;
1295 } else {
1296 $this->mAffectedRows = oci_num_rows( $stmt );
1298 } else {
1299 $this->mAffectedRows = oci_num_rows( $stmt );
1302 wfRestoreWarnings();
1304 if ( isset( $lob ) ) {
1305 foreach ( $lob as $lob_v ) {
1306 $lob_v->free();
1310 if ( !$this->mTrxLevel ) {
1311 oci_commit( $this->mConn );
1314 oci_free_statement( $stmt );
1317 function bitNot( $field ) {
1318 // expecting bit-fields smaller than 4bytes
1319 return 'BITNOT(' . $field . ')';
1322 function bitAnd( $fieldLeft, $fieldRight ) {
1323 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1326 function bitOr( $fieldLeft, $fieldRight ) {
1327 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1330 function setFakeMaster( $enabled = true ) {
1333 function getDBname() {
1334 return $this->mDBname;
1337 function getServer() {
1338 return $this->mServer;
1341 public function getSearchEngine() {
1342 return 'SearchOracle';
1345 public function getInfinity() {
1346 return '31-12-2030 12:00:00.000000';
1349 } // end DatabaseOracle class