Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / db / DatabaseOracle.php
blob66004ec578e38b6fca799952e8e492b5f0741e72
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 DatabaseBase $db
54 * @param resource $stmt A valid OCI statement identifier
55 * @param bool $unique
57 function __construct( &$db, $stmt, $unique = false ) {
58 $this->db =& $db;
60 $this->nrows = oci_fetch_all( $stmt, $this->rows, 0, -1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM );
61 if ( $this->nrows === false ) {
62 $e = oci_error( $stmt );
63 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__ );
64 $this->free();
66 return;
69 if ( $unique ) {
70 $this->rows = $this->array_unique_md( $this->rows );
71 $this->nrows = count( $this->rows );
74 if ( $this->nrows > 0 ) {
75 foreach ( $this->rows[0] as $k => $v ) {
76 $this->columns[$k] = strtolower( oci_field_name( $stmt, $k + 1 ) );
80 $this->cursor = 0;
81 oci_free_statement( $stmt );
84 public function free() {
85 unset( $this->db );
88 public function seek( $row ) {
89 $this->cursor = min( $row, $this->nrows );
92 public function numRows() {
93 return $this->nrows;
96 public function numFields() {
97 return count( $this->columns );
100 public function fetchObject() {
101 if ( $this->cursor >= $this->nrows ) {
102 return false;
104 $row = $this->rows[$this->cursor++];
105 $ret = new stdClass();
106 foreach ( $row as $k => $v ) {
107 $lc = $this->columns[$k];
108 $ret->$lc = $v;
111 return $ret;
114 public function fetchRow() {
115 if ( $this->cursor >= $this->nrows ) {
116 return false;
119 $row = $this->rows[$this->cursor++];
120 $ret = array();
121 foreach ( $row as $k => $v ) {
122 $lc = $this->columns[$k];
123 $ret[$lc] = $v;
124 $ret[$k] = $v;
127 return $ret;
132 * Utility class.
133 * @ingroup Database
135 class ORAField implements Field {
136 private $name, $tablename, $default, $max_length, $nullable,
137 $is_pk, $is_unique, $is_multiple, $is_key, $type;
139 function __construct( $info ) {
140 $this->name = $info['column_name'];
141 $this->tablename = $info['table_name'];
142 $this->default = $info['data_default'];
143 $this->max_length = $info['data_length'];
144 $this->nullable = $info['not_null'];
145 $this->is_pk = isset( $info['prim'] ) && $info['prim'] == 1 ? 1 : 0;
146 $this->is_unique = isset( $info['uniq'] ) && $info['uniq'] == 1 ? 1 : 0;
147 $this->is_multiple = isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ? 1 : 0;
148 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
149 $this->type = $info['data_type'];
152 function name() {
153 return $this->name;
156 function tableName() {
157 return $this->tablename;
160 function defaultValue() {
161 return $this->default;
164 function maxLength() {
165 return $this->max_length;
168 function isNullable() {
169 return $this->nullable;
172 function isKey() {
173 return $this->is_key;
176 function isMultipleKey() {
177 return $this->is_multiple;
180 function type() {
181 return $this->type;
186 * @ingroup Database
188 class DatabaseOracle extends Database {
189 /** @var resource */
190 protected $mLastResult = null;
192 /** @var int The number of rows affected as an integer */
193 protected $mAffectedRows;
195 /** @var int */
196 private $mInsertId = null;
198 /** @var bool */
199 private $ignoreDupValOnIndex = false;
201 /** @var bool|array */
202 private $sequenceData = null;
204 /** @var string Character set for Oracle database */
205 private $defaultCharset = 'AL32UTF8';
207 /** @var array */
208 private $mFieldInfoCache = array();
210 function __construct( array $p ) {
211 global $wgDBprefix;
213 if ( $p['tablePrefix'] == 'get from global' ) {
214 $p['tablePrefix'] = $wgDBprefix;
216 $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
217 parent::__construct( $p );
218 Hooks::run( 'DatabaseOraclePostInit', array( $this ) );
221 function __destruct() {
222 if ( $this->mOpened ) {
223 MediaWiki\suppressWarnings();
224 $this->close();
225 MediaWiki\restoreWarnings();
229 function getType() {
230 return 'oracle';
233 function cascadingDeletes() {
234 return true;
237 function cleanupTriggers() {
238 return true;
241 function strictIPs() {
242 return true;
245 function realTimestamps() {
246 return true;
249 function implicitGroupby() {
250 return false;
253 function implicitOrderby() {
254 return false;
257 function searchableIPs() {
258 return true;
262 * Usually aborts on failure
263 * @param string $server
264 * @param string $user
265 * @param string $password
266 * @param string $dbName
267 * @throws DBConnectionError
268 * @return DatabaseBase|null
270 function open( $server, $user, $password, $dbName ) {
271 global $wgDBOracleDRCP;
272 if ( !function_exists( 'oci_connect' ) ) {
273 throw new DBConnectionError(
274 $this,
275 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
276 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
277 "and database)\n" );
280 $this->close();
281 $this->mUser = $user;
282 $this->mPassword = $password;
283 // changed internal variables functions
284 // mServer now holds the TNS endpoint
285 // mDBname is schema name if different from username
286 if ( !$server ) {
287 // backward compatibillity (server used to be null and TNS was supplied in dbname)
288 $this->mServer = $dbName;
289 $this->mDBname = $user;
290 } else {
291 $this->mServer = $server;
292 if ( !$dbName ) {
293 $this->mDBname = $user;
294 } else {
295 $this->mDBname = $dbName;
299 if ( !strlen( $user ) ) { # e.g. the class is being loaded
300 return null;
303 if ( $wgDBOracleDRCP ) {
304 $this->setFlag( DBO_PERSISTENT );
307 $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
309 MediaWiki\suppressWarnings();
310 if ( $this->mFlags & DBO_PERSISTENT ) {
311 $this->mConn = oci_pconnect(
312 $this->mUser,
313 $this->mPassword,
314 $this->mServer,
315 $this->defaultCharset,
316 $session_mode
318 } elseif ( $this->mFlags & DBO_DEFAULT ) {
319 $this->mConn = oci_new_connect(
320 $this->mUser,
321 $this->mPassword,
322 $this->mServer,
323 $this->defaultCharset,
324 $session_mode
326 } else {
327 $this->mConn = oci_connect(
328 $this->mUser,
329 $this->mPassword,
330 $this->mServer,
331 $this->defaultCharset,
332 $session_mode
335 MediaWiki\restoreWarnings();
337 if ( $this->mUser != $this->mDBname ) {
338 // change current schema in session
339 $this->selectDB( $this->mDBname );
342 if ( !$this->mConn ) {
343 throw new DBConnectionError( $this, $this->lastError() );
346 $this->mOpened = true;
348 # removed putenv calls because they interfere with the system globaly
349 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
350 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
351 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
353 return $this->mConn;
357 * Closes a database connection, if it is open
358 * Returns success, true if already closed
359 * @return bool
361 protected function closeConnection() {
362 return oci_close( $this->mConn );
365 function execFlags() {
366 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT : OCI_COMMIT_ON_SUCCESS;
369 protected function doQuery( $sql ) {
370 wfDebug( "SQL: [$sql]\n" );
371 if ( !StringUtils::isUtf8( $sql ) ) {
372 throw new MWException( "SQL encoding is invalid\n$sql" );
375 // handle some oracle specifics
376 // remove AS column/table/subquery namings
377 if ( !$this->getFlag( DBO_DDLMODE ) ) {
378 $sql = preg_replace( '/ as /i', ' ', $sql );
381 // Oracle has issues with UNION clause if the statement includes LOB fields
382 // So we do a UNION ALL and then filter the results array with array_unique
383 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
384 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
385 // you have to select data from plan table after explain
386 $explain_id = MWTimestamp::getLocalInstance()->format( 'dmYHis' );
388 $sql = preg_replace(
389 '/^EXPLAIN /',
390 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
391 $sql,
393 $explain_count
396 MediaWiki\suppressWarnings();
398 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
399 $e = oci_error( $this->mConn );
400 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
402 return false;
405 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
406 $e = oci_error( $stmt );
407 if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
408 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
410 return false;
414 MediaWiki\restoreWarnings();
416 if ( $explain_count > 0 ) {
417 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
418 'WHERE statement_id = \'' . $explain_id . '\'' );
419 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
420 return new ORAResult( $this, $stmt, $union_unique );
421 } else {
422 $this->mAffectedRows = oci_num_rows( $stmt );
424 return true;
428 function queryIgnore( $sql, $fname = '' ) {
429 return $this->query( $sql, $fname, true );
433 * Frees resources associated with the LOB descriptor
434 * @param ResultWrapper|resource $res
436 function freeResult( $res ) {
437 if ( $res instanceof ResultWrapper ) {
438 $res = $res->result;
441 $res->free();
445 * @param ResultWrapper|stdClass $res
446 * @return mixed
448 function fetchObject( $res ) {
449 if ( $res instanceof ResultWrapper ) {
450 $res = $res->result;
453 return $res->fetchObject();
456 function fetchRow( $res ) {
457 if ( $res instanceof ResultWrapper ) {
458 $res = $res->result;
461 return $res->fetchRow();
464 function numRows( $res ) {
465 if ( $res instanceof ResultWrapper ) {
466 $res = $res->result;
469 return $res->numRows();
472 function numFields( $res ) {
473 if ( $res instanceof ResultWrapper ) {
474 $res = $res->result;
477 return $res->numFields();
480 function fieldName( $stmt, $n ) {
481 return oci_field_name( $stmt, $n );
485 * This must be called after nextSequenceVal
486 * @return null|int
488 function insertId() {
489 return $this->mInsertId;
493 * @param mixed $res
494 * @param int $row
496 function dataSeek( $res, $row ) {
497 if ( $res instanceof ORAResult ) {
498 $res->seek( $row );
499 } else {
500 $res->result->seek( $row );
504 function lastError() {
505 if ( $this->mConn === false ) {
506 $e = oci_error();
507 } else {
508 $e = oci_error( $this->mConn );
511 return $e['message'];
514 function lastErrno() {
515 if ( $this->mConn === false ) {
516 $e = oci_error();
517 } else {
518 $e = oci_error( $this->mConn );
521 return $e['code'];
524 function affectedRows() {
525 return $this->mAffectedRows;
529 * Returns information about an index
530 * If errors are explicitly ignored, returns NULL on failure
531 * @param string $table
532 * @param string $index
533 * @param string $fname
534 * @return bool
536 function indexInfo( $table, $index, $fname = __METHOD__ ) {
537 return false;
540 function indexUnique( $table, $index, $fname = __METHOD__ ) {
541 return false;
544 function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
545 if ( !count( $a ) ) {
546 return true;
549 if ( !is_array( $options ) ) {
550 $options = array( $options );
553 if ( in_array( 'IGNORE', $options ) ) {
554 $this->ignoreDupValOnIndex = true;
557 if ( !is_array( reset( $a ) ) ) {
558 $a = array( $a );
561 foreach ( $a as &$row ) {
562 $this->insertOneRow( $table, $row, $fname );
564 $retVal = true;
566 if ( in_array( 'IGNORE', $options ) ) {
567 $this->ignoreDupValOnIndex = false;
570 return $retVal;
573 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
574 $col_info = $this->fieldInfoMulti( $table, $col );
575 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
577 $bind = '';
578 if ( is_numeric( $col ) ) {
579 $bind = $val;
580 $val = null;
582 return $bind;
583 } elseif ( $includeCol ) {
584 $bind = "$col = ";
587 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
588 $val = null;
591 if ( $val === 'NULL' ) {
592 $val = null;
595 if ( $val === null ) {
596 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
597 $bind .= 'DEFAULT';
598 } else {
599 $bind .= 'NULL';
601 } else {
602 $bind .= ':' . $col;
605 return $bind;
609 * @param string $table
610 * @param array $row
611 * @param string $fname
612 * @return bool
613 * @throws DBUnexpectedError
615 private function insertOneRow( $table, $row, $fname ) {
616 global $wgContLang;
618 $table = $this->tableName( $table );
619 // "INSERT INTO tables (a, b, c)"
620 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
621 $sql .= " VALUES (";
623 // for each value, append ":key"
624 $first = true;
625 foreach ( $row as $col => &$val ) {
626 if ( !$first ) {
627 $sql .= ', ';
628 } else {
629 $first = false;
631 if ( $this->isQuotedIdentifier( $val ) ) {
632 $sql .= $this->removeIdentifierQuotes( $val );
633 unset( $row[$col] );
634 } else {
635 $sql .= $this->fieldBindStatement( $table, $col, $val );
638 $sql .= ')';
640 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
641 $e = oci_error( $this->mConn );
642 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
644 return false;
646 foreach ( $row as $col => &$val ) {
647 $col_info = $this->fieldInfoMulti( $table, $col );
648 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
650 if ( $val === null ) {
651 // do nothing ... null was inserted in statement creation
652 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
653 if ( is_object( $val ) ) {
654 $val = $val->fetch();
657 // backward compatibility
658 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
659 $val = $this->getInfinity();
662 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
663 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR ) === false ) {
664 $e = oci_error( $stmt );
665 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
667 return false;
669 } else {
670 /** @var OCI_Lob[] $lob */
671 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
672 $e = oci_error( $stmt );
673 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
676 if ( is_object( $val ) ) {
677 $val = $val->fetch();
680 if ( $col_type == 'BLOB' ) {
681 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
682 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB );
683 } else {
684 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
685 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB );
690 MediaWiki\suppressWarnings();
692 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
693 $e = oci_error( $stmt );
694 if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
695 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
697 return false;
698 } else {
699 $this->mAffectedRows = oci_num_rows( $stmt );
701 } else {
702 $this->mAffectedRows = oci_num_rows( $stmt );
705 MediaWiki\restoreWarnings();
707 if ( isset( $lob ) ) {
708 foreach ( $lob as $lob_v ) {
709 $lob_v->free();
713 if ( !$this->mTrxLevel ) {
714 oci_commit( $this->mConn );
717 return oci_free_statement( $stmt );
720 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
721 $insertOptions = array(), $selectOptions = array()
723 $destTable = $this->tableName( $destTable );
724 if ( !is_array( $selectOptions ) ) {
725 $selectOptions = array( $selectOptions );
727 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
728 if ( is_array( $srcTable ) ) {
729 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
730 } else {
731 $srcTable = $this->tableName( $srcTable );
734 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
735 !isset( $varMap[$sequenceData['column']] )
737 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
740 // count-alias subselect fields to avoid abigious definition errors
741 $i = 0;
742 foreach ( $varMap as &$val ) {
743 $val = $val . ' field' . ( $i++ );
746 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
747 " SELECT $startOpts " . implode( ',', $varMap ) .
748 " FROM $srcTable $useIndex ";
749 if ( $conds != '*' ) {
750 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
752 $sql .= " $tailOpts";
754 if ( in_array( 'IGNORE', $insertOptions ) ) {
755 $this->ignoreDupValOnIndex = true;
758 $retval = $this->query( $sql, $fname );
760 if ( in_array( 'IGNORE', $insertOptions ) ) {
761 $this->ignoreDupValOnIndex = false;
764 return $retval;
767 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
768 $fname = __METHOD__
770 if ( !count( $rows ) ) {
771 return true; // nothing to do
774 if ( !is_array( reset( $rows ) ) ) {
775 $rows = array( $rows );
778 $sequenceData = $this->getSequenceData( $table );
779 if ( $sequenceData !== false ) {
780 // add sequence column to each list of columns, when not set
781 foreach ( $rows as &$row ) {
782 if ( !isset( $row[$sequenceData['column']] ) ) {
783 $row[$sequenceData['column']] =
784 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
785 $sequenceData['sequence'] . '\')' );
790 return parent::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
793 function tableName( $name, $format = 'quoted' ) {
795 Replace reserved words with better ones
796 Using uppercase because that's the only way Oracle can handle
797 quoted tablenames
799 switch ( $name ) {
800 case 'user':
801 $name = 'MWUSER';
802 break;
803 case 'text':
804 $name = 'PAGECONTENT';
805 break;
808 return strtoupper( parent::tableName( $name, $format ) );
811 function tableNameInternal( $name ) {
812 $name = $this->tableName( $name );
814 return preg_replace( '/.*\.(.*)/', '$1', $name );
818 * Return the next in a sequence, save the value for retrieval via insertId()
820 * @param string $seqName
821 * @return null|int
823 function nextSequenceValue( $seqName ) {
824 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
825 $row = $this->fetchRow( $res );
826 $this->mInsertId = $row[0];
828 return $this->mInsertId;
832 * Return sequence_name if table has a sequence
834 * @param string $table
835 * @return bool
837 private function getSequenceData( $table ) {
838 if ( $this->sequenceData == null ) {
839 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
840 lower(atc.table_name),
841 lower(atc.column_name)
842 FROM all_sequences asq, all_tab_columns atc
843 WHERE decode(
844 atc.table_name,
845 '{$this->mTablePrefix}MWUSER',
846 '{$this->mTablePrefix}USER',
847 atc.table_name
848 ) || '_' ||
849 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
850 AND asq.sequence_owner = upper('{$this->mDBname}')
851 AND atc.owner = upper('{$this->mDBname}')" );
853 while ( ( $row = $result->fetchRow() ) !== false ) {
854 $this->sequenceData[$row[1]] = array(
855 'sequence' => $row[0],
856 'column' => $row[2]
860 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
862 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
866 * Returns the size of a text field, or -1 for "unlimited"
868 * @param string $table
869 * @param string $field
870 * @return mixed
872 function textFieldSize( $table, $field ) {
873 $fieldInfoData = $this->fieldInfo( $table, $field );
875 return $fieldInfoData->maxLength();
878 function limitResult( $sql, $limit, $offset = false ) {
879 if ( $offset === false ) {
880 $offset = 0;
883 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
886 function encodeBlob( $b ) {
887 return new Blob( $b );
890 function decodeBlob( $b ) {
891 if ( $b instanceof Blob ) {
892 $b = $b->fetch();
895 return $b;
898 function unionQueries( $sqls, $all ) {
899 $glue = ' UNION ALL ';
901 return 'SELECT * ' . ( $all ? '' : '/* UNION_UNIQUE */ ' ) .
902 'FROM (' . implode( $glue, $sqls ) . ')';
905 function wasDeadlock() {
906 return $this->lastErrno() == 'OCI-00060';
909 function duplicateTableStructure( $oldName, $newName, $temporary = false,
910 $fname = __METHOD__
912 $temporary = $temporary ? 'TRUE' : 'FALSE';
914 $newName = strtoupper( $newName );
915 $oldName = strtoupper( $oldName );
917 $tabName = substr( $newName, strlen( $this->mTablePrefix ) );
918 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
919 $newPrefix = strtoupper( $this->mTablePrefix );
921 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
922 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
925 function listTables( $prefix = null, $fname = __METHOD__ ) {
926 $listWhere = '';
927 if ( !empty( $prefix ) ) {
928 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
931 $owner = strtoupper( $this->mDBname );
932 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
933 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
935 // dirty code ... i know
936 $endArray = array();
937 $endArray[] = strtoupper( $prefix . 'MWUSER' );
938 $endArray[] = strtoupper( $prefix . 'PAGE' );
939 $endArray[] = strtoupper( $prefix . 'IMAGE' );
940 $fixedOrderTabs = $endArray;
941 while ( ( $row = $result->fetchRow() ) !== false ) {
942 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
943 $endArray[] = $row['table_name'];
947 return $endArray;
950 public function dropTable( $tableName, $fName = __METHOD__ ) {
951 $tableName = $this->tableName( $tableName );
952 if ( !$this->tableExists( $tableName ) ) {
953 return false;
956 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
959 function timestamp( $ts = 0 ) {
960 return wfTimestamp( TS_ORACLE, $ts );
964 * Return aggregated value function call
966 * @param array $valuedata
967 * @param string $valuename
968 * @return mixed
970 public function aggregateValue( $valuedata, $valuename = 'value' ) {
971 return $valuedata;
975 * @return string Wikitext of a link to the server software's web site
977 public function getSoftwareLink() {
978 return '[{{int:version-db-oracle-url}} Oracle]';
982 * @return string Version information from the database
984 function getServerVersion() {
985 // better version number, fallback on driver
986 $rset = $this->doQuery(
987 'SELECT version FROM product_component_version ' .
988 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
990 if ( !( $row = $rset->fetchRow() ) ) {
991 return oci_server_version( $this->mConn );
994 return $row['version'];
998 * Query whether a given index exists
999 * @param string $table
1000 * @param string $index
1001 * @param string $fname
1002 * @return bool
1004 function indexExists( $table, $index, $fname = __METHOD__ ) {
1005 $table = $this->tableName( $table );
1006 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
1007 $index = strtoupper( $index );
1008 $owner = strtoupper( $this->mDBname );
1009 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
1010 $res = $this->doQuery( $sql );
1011 if ( $res ) {
1012 $count = $res->numRows();
1013 $res->free();
1014 } else {
1015 $count = 0;
1018 return $count != 0;
1022 * Query whether a given table exists (in the given schema, or the default mw one if not given)
1023 * @param string $table
1024 * @param string $fname
1025 * @return bool
1027 function tableExists( $table, $fname = __METHOD__ ) {
1028 $table = $this->tableName( $table );
1029 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
1030 $owner = $this->addQuotes( strtoupper( $this->mDBname ) );
1031 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
1032 $res = $this->doQuery( $sql );
1033 if ( $res && $res->numRows() > 0 ) {
1034 $exists = true;
1035 } else {
1036 $exists = false;
1039 $res->free();
1041 return $exists;
1045 * Function translates mysql_fetch_field() functionality on ORACLE.
1046 * Caching is present for reducing query time.
1047 * For internal calls. Use fieldInfo for normal usage.
1048 * Returns false if the field doesn't exist
1050 * @param array|string $table
1051 * @param string $field
1052 * @return ORAField|ORAResult
1054 private function fieldInfoMulti( $table, $field ) {
1055 $field = strtoupper( $field );
1056 if ( is_array( $table ) ) {
1057 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
1058 $tableWhere = 'IN (';
1059 foreach ( $table as &$singleTable ) {
1060 $singleTable = $this->removeIdentifierQuotes( $singleTable );
1061 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
1062 return $this->mFieldInfoCache["$singleTable.$field"];
1064 $tableWhere .= '\'' . $singleTable . '\',';
1066 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
1067 } else {
1068 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
1069 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
1070 return $this->mFieldInfoCache["$table.$field"];
1072 $tableWhere = '= \'' . $table . '\'';
1075 $fieldInfoStmt = oci_parse(
1076 $this->mConn,
1077 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
1078 $tableWhere . ' and column_name = \'' . $field . '\''
1080 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
1081 $e = oci_error( $fieldInfoStmt );
1082 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
1084 return false;
1086 $res = new ORAResult( $this, $fieldInfoStmt );
1087 if ( $res->numRows() == 0 ) {
1088 if ( is_array( $table ) ) {
1089 foreach ( $table as &$singleTable ) {
1090 $this->mFieldInfoCache["$singleTable.$field"] = false;
1092 } else {
1093 $this->mFieldInfoCache["$table.$field"] = false;
1095 $fieldInfoTemp = null;
1096 } else {
1097 $fieldInfoTemp = new ORAField( $res->fetchRow() );
1098 $table = $fieldInfoTemp->tableName();
1099 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
1101 $res->free();
1103 return $fieldInfoTemp;
1107 * @throws DBUnexpectedError
1108 * @param string $table
1109 * @param string $field
1110 * @return ORAField
1112 function fieldInfo( $table, $field ) {
1113 if ( is_array( $table ) ) {
1114 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
1117 return $this->fieldInfoMulti( $table, $field );
1120 protected function doBegin( $fname = __METHOD__ ) {
1121 $this->mTrxLevel = 1;
1122 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
1125 protected function doCommit( $fname = __METHOD__ ) {
1126 if ( $this->mTrxLevel ) {
1127 $ret = oci_commit( $this->mConn );
1128 if ( !$ret ) {
1129 throw new DBUnexpectedError( $this, $this->lastError() );
1131 $this->mTrxLevel = 0;
1132 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1136 protected function doRollback( $fname = __METHOD__ ) {
1137 if ( $this->mTrxLevel ) {
1138 oci_rollback( $this->mConn );
1139 $this->mTrxLevel = 0;
1140 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1145 * defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
1147 * @param resource $fp
1148 * @param bool|string $lineCallback
1149 * @param bool|callable $resultCallback
1150 * @param string $fname
1151 * @param bool|callable $inputCallback
1152 * @return bool|string
1154 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
1155 $fname = __METHOD__, $inputCallback = false ) {
1156 $cmd = '';
1157 $done = false;
1158 $dollarquote = false;
1160 $replacements = array();
1162 while ( !feof( $fp ) ) {
1163 if ( $lineCallback ) {
1164 call_user_func( $lineCallback );
1166 $line = trim( fgets( $fp, 1024 ) );
1167 $sl = strlen( $line ) - 1;
1169 if ( $sl < 0 ) {
1170 continue;
1172 if ( '-' == $line[0] && '-' == $line[1] ) {
1173 continue;
1176 // Allow dollar quoting for function declarations
1177 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1178 if ( $dollarquote ) {
1179 $dollarquote = false;
1180 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1181 $done = true;
1182 } else {
1183 $dollarquote = true;
1185 } elseif ( !$dollarquote ) {
1186 if ( ';' == $line[$sl] && ( $sl < 2 || ';' != $line[$sl - 1] ) ) {
1187 $done = true;
1188 $line = substr( $line, 0, $sl );
1192 if ( $cmd != '' ) {
1193 $cmd .= ' ';
1195 $cmd .= "$line\n";
1197 if ( $done ) {
1198 $cmd = str_replace( ';;', ";", $cmd );
1199 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1200 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1201 $replacements[$defines[2]] = $defines[1];
1203 } else {
1204 foreach ( $replacements as $mwVar => $scVar ) {
1205 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1208 $cmd = $this->replaceVars( $cmd );
1209 if ( $inputCallback ) {
1210 call_user_func( $inputCallback, $cmd );
1212 $res = $this->doQuery( $cmd );
1213 if ( $resultCallback ) {
1214 call_user_func( $resultCallback, $res, $this );
1217 if ( false === $res ) {
1218 $err = $this->lastError();
1220 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1224 $cmd = '';
1225 $done = false;
1229 return true;
1232 function selectDB( $db ) {
1233 $this->mDBname = $db;
1234 if ( $db == null || $db == $this->mUser ) {
1235 return true;
1237 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1238 $stmt = oci_parse( $this->mConn, $sql );
1239 MediaWiki\suppressWarnings();
1240 $success = oci_execute( $stmt );
1241 MediaWiki\restoreWarnings();
1242 if ( !$success ) {
1243 $e = oci_error( $stmt );
1244 if ( $e['code'] != '1435' ) {
1245 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1248 return false;
1251 return true;
1254 function strencode( $s ) {
1255 return str_replace( "'", "''", $s );
1258 function addQuotes( $s ) {
1259 global $wgContLang;
1260 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1261 $s = $wgContLang->checkTitleEncoding( $s );
1264 return "'" . $this->strencode( $s ) . "'";
1267 public function addIdentifierQuotes( $s ) {
1268 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1269 $s = '/*Q*/' . $s;
1272 return $s;
1275 public function removeIdentifierQuotes( $s ) {
1276 return strpos( $s, '/*Q*/' ) === false ? $s : substr( $s, 5 );
1279 public function isQuotedIdentifier( $s ) {
1280 return strpos( $s, '/*Q*/' ) !== false;
1283 private function wrapFieldForWhere( $table, &$col, &$val ) {
1284 global $wgContLang;
1286 $col_info = $this->fieldInfoMulti( $table, $col );
1287 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1288 if ( $col_type == 'CLOB' ) {
1289 $col = 'TO_CHAR(' . $col . ')';
1290 $val = $wgContLang->checkTitleEncoding( $val );
1291 } elseif ( $col_type == 'VARCHAR2' ) {
1292 $val = $wgContLang->checkTitleEncoding( $val );
1296 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1297 $conds2 = array();
1298 foreach ( $conds as $col => $val ) {
1299 if ( is_array( $val ) ) {
1300 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1301 } else {
1302 if ( is_numeric( $col ) && $parentCol != null ) {
1303 $this->wrapFieldForWhere( $table, $parentCol, $val );
1304 } else {
1305 $this->wrapFieldForWhere( $table, $col, $val );
1307 $conds2[$col] = $val;
1311 return $conds2;
1314 function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1315 $options = array(), $join_conds = array()
1317 if ( is_array( $conds ) ) {
1318 $conds = $this->wrapConditionsForWhere( $table, $conds );
1321 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1325 * Returns an optional USE INDEX clause to go after the table, and a
1326 * string to go at the end of the query
1328 * @param array $options An associative array of options to be turned into
1329 * an SQL query, valid keys are listed in the function.
1330 * @return array
1332 function makeSelectOptions( $options ) {
1333 $preLimitTail = $postLimitTail = '';
1334 $startOpts = '';
1336 $noKeyOptions = array();
1337 foreach ( $options as $key => $option ) {
1338 if ( is_numeric( $key ) ) {
1339 $noKeyOptions[$option] = true;
1343 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1345 $preLimitTail .= $this->makeOrderBy( $options );
1347 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1348 $postLimitTail .= ' FOR UPDATE';
1351 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1352 $startOpts .= 'DISTINCT';
1355 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1356 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1357 } else {
1358 $useIndex = '';
1361 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1364 public function delete( $table, $conds, $fname = __METHOD__ ) {
1365 if ( is_array( $conds ) ) {
1366 $conds = $this->wrapConditionsForWhere( $table, $conds );
1368 // a hack for deleting pages, users and images (which have non-nullable FKs)
1369 // all deletions on these tables have transactions so final failure rollbacks these updates
1370 $table = $this->tableName( $table );
1371 if ( $table == $this->tableName( 'user' ) ) {
1372 $this->update( 'archive', array( 'ar_user' => 0 ),
1373 array( 'ar_user' => $conds['user_id'] ), $fname );
1374 $this->update( 'ipblocks', array( 'ipb_user' => 0 ),
1375 array( 'ipb_user' => $conds['user_id'] ), $fname );
1376 $this->update( 'image', array( 'img_user' => 0 ),
1377 array( 'img_user' => $conds['user_id'] ), $fname );
1378 $this->update( 'oldimage', array( 'oi_user' => 0 ),
1379 array( 'oi_user' => $conds['user_id'] ), $fname );
1380 $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ),
1381 array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
1382 $this->update( 'filearchive', array( 'fa_user' => 0 ),
1383 array( 'fa_user' => $conds['user_id'] ), $fname );
1384 $this->update( 'uploadstash', array( 'us_user' => 0 ),
1385 array( 'us_user' => $conds['user_id'] ), $fname );
1386 $this->update( 'recentchanges', array( 'rc_user' => 0 ),
1387 array( 'rc_user' => $conds['user_id'] ), $fname );
1388 $this->update( 'logging', array( 'log_user' => 0 ),
1389 array( 'log_user' => $conds['user_id'] ), $fname );
1390 } elseif ( $table == $this->tableName( 'image' ) ) {
1391 $this->update( 'oldimage', array( 'oi_name' => 0 ),
1392 array( 'oi_name' => $conds['img_name'] ), $fname );
1395 return parent::delete( $table, $conds, $fname );
1399 * @param string $table
1400 * @param array $values
1401 * @param array $conds
1402 * @param string $fname
1403 * @param array $options
1404 * @return bool
1405 * @throws DBUnexpectedError
1407 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
1408 global $wgContLang;
1410 $table = $this->tableName( $table );
1411 $opts = $this->makeUpdateOptions( $options );
1412 $sql = "UPDATE $opts $table SET ";
1414 $first = true;
1415 foreach ( $values as $col => &$val ) {
1416 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1418 if ( !$first ) {
1419 $sqlSet = ', ' . $sqlSet;
1420 } else {
1421 $first = false;
1423 $sql .= $sqlSet;
1426 if ( $conds !== array() && $conds !== '*' ) {
1427 $conds = $this->wrapConditionsForWhere( $table, $conds );
1428 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1431 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1432 $e = oci_error( $this->mConn );
1433 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1435 return false;
1437 foreach ( $values as $col => &$val ) {
1438 $col_info = $this->fieldInfoMulti( $table, $col );
1439 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1441 if ( $val === null ) {
1442 // do nothing ... null was inserted in statement creation
1443 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1444 if ( is_object( $val ) ) {
1445 $val = $val->getData();
1448 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1449 $val = '31-12-2030 12:00:00.000000';
1452 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1453 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1454 $e = oci_error( $stmt );
1455 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1457 return false;
1459 } else {
1460 /** @var OCI_Lob[] $lob */
1461 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1462 $e = oci_error( $stmt );
1463 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1466 if ( is_object( $val ) ) {
1467 $val = $val->getData();
1470 if ( $col_type == 'BLOB' ) {
1471 $lob[$col]->writeTemporary( $val );
1472 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB );
1473 } else {
1474 $lob[$col]->writeTemporary( $val );
1475 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB );
1480 MediaWiki\suppressWarnings();
1482 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1483 $e = oci_error( $stmt );
1484 if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
1485 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1487 return false;
1488 } else {
1489 $this->mAffectedRows = oci_num_rows( $stmt );
1491 } else {
1492 $this->mAffectedRows = oci_num_rows( $stmt );
1495 MediaWiki\restoreWarnings();
1497 if ( isset( $lob ) ) {
1498 foreach ( $lob as $lob_v ) {
1499 $lob_v->free();
1503 if ( !$this->mTrxLevel ) {
1504 oci_commit( $this->mConn );
1507 return oci_free_statement( $stmt );
1510 function bitNot( $field ) {
1511 // expecting bit-fields smaller than 4bytes
1512 return 'BITNOT(' . $field . ')';
1515 function bitAnd( $fieldLeft, $fieldRight ) {
1516 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1519 function bitOr( $fieldLeft, $fieldRight ) {
1520 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1523 function getDBname() {
1524 return $this->mDBname;
1527 function getServer() {
1528 return $this->mServer;
1531 public function buildGroupConcatField(
1532 $delim, $table, $field, $conds = '', $join_conds = array()
1534 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1536 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1539 public function getSearchEngine() {
1540 return 'SearchOracle';
1543 public function getInfinity() {
1544 return '31-12-2030 12:00:00.000000';