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
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.
35 private $columns = array();
37 private function array_unique_md( $array_in ) {
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;
53 * @param $db DatabaseBase
57 function __construct( &$db, $stmt, $unique = false ) {
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__
);
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 ) );
81 oci_free_statement( $stmt );
84 public function free() {
88 public function seek( $row ) {
89 $this->cursor
= min( $row, $this->nrows
);
92 public function numRows() {
96 public function numFields() {
97 return count( $this->columns
);
100 public function fetchObject() {
101 if ( $this->cursor
>= $this->nrows
) {
104 $row = $this->rows
[$this->cursor++
];
105 $ret = new stdClass();
106 foreach ( $row as $k => $v ) {
107 $lc = $this->columns
[$k];
114 public function fetchRow() {
115 if ( $this->cursor
>= $this->nrows
) {
119 $row = $this->rows
[$this->cursor++
];
121 foreach ( $row as $k => $v ) {
122 $lc = $this->columns
[$k];
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'];
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
;
173 return $this->is_key
;
176 function isMultipleKey() {
177 return $this->is_multiple
;
188 class DatabaseOracle
extends DatabaseBase
{
189 var $mInsertId = null;
190 var $mLastResult = null;
191 var $lastResult = null;
195 var $ignore_DUP_VAL_ON_INDEX = false;
196 var $sequenceData = null;
198 var $defaultCharset = 'AL32UTF8';
200 var $mFieldInfoCache = array();
202 function __construct( $p = null ) {
205 if ( !is_array( $p ) ) { // legacy calling pattern
206 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.22" );
207 $args = func_get_args();
209 'host' => isset( $args[0] ) ?
$args[0] : false,
210 'user' => isset( $args[1] ) ?
$args[1] : false,
211 'password' => isset( $args[2] ) ?
$args[2] : false,
212 'dbname' => isset( $args[3] ) ?
$args[3] : false,
213 'flags' => isset( $args[4] ) ?
$args[4] : 0,
214 'tablePrefix' => isset( $args[5] ) ?
$args[5] : 'get from global',
215 'foreign' => isset( $args[6] ) ?
$args[6] : false
218 if ( $p['tablePrefix'] == 'get from global' ) {
219 $p['tablePrefix'] = $wgDBprefix;
221 $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
222 parent
::__construct( $p );
223 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
226 function __destruct() {
227 if ( $this->mOpened
) {
228 wfSuppressWarnings();
238 function cascadingDeletes() {
242 function cleanupTriggers() {
246 function strictIPs() {
250 function realTimestamps() {
254 function implicitGroupby() {
258 function implicitOrderby() {
262 function searchableIPs() {
267 * Usually aborts on failure
268 * @param string $server
269 * @param string $user
270 * @param string $password
271 * @param string $dbName
272 * @throws DBConnectionError
273 * @return DatabaseBase|null
275 function open( $server, $user, $password, $dbName ) {
276 global $wgDBOracleDRCP;
277 if ( !function_exists( 'oci_connect' ) ) {
278 throw new DBConnectionError(
280 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
281 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
286 $this->mUser
= $user;
287 $this->mPassword
= $password;
288 // changed internal variables functions
289 // mServer now holds the TNS endpoint
290 // mDBname is schema name if different from username
292 // backward compatibillity (server used to be null and TNS was supplied in dbname)
293 $this->mServer
= $dbName;
294 $this->mDBname
= $user;
296 $this->mServer
= $server;
298 $this->mDBname
= $user;
300 $this->mDBname
= $dbName;
304 if ( !strlen( $user ) ) { # e.g. the class is being loaded
308 if ( $wgDBOracleDRCP ) {
309 $this->setFlag( DBO_PERSISTENT
);
312 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
314 wfSuppressWarnings();
315 if ( $this->mFlags
& DBO_PERSISTENT
) {
316 $this->mConn
= oci_pconnect(
320 $this->defaultCharset
,
323 } elseif ( $this->mFlags
& DBO_DEFAULT
) {
324 $this->mConn
= oci_new_connect(
328 $this->defaultCharset
,
332 $this->mConn
= oci_connect(
336 $this->defaultCharset
,
342 if ( $this->mUser
!= $this->mDBname
) {
343 //change current schema in session
344 $this->selectDB( $this->mDBname
);
347 if ( !$this->mConn
) {
348 throw new DBConnectionError( $this, $this->lastError() );
351 $this->mOpened
= true;
353 # removed putenv calls because they interfere with the system globaly
354 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
355 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
356 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
362 * Closes a database connection, if it is open
363 * Returns success, true if already closed
366 protected function closeConnection() {
367 return oci_close( $this->mConn
);
370 function execFlags() {
371 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
374 protected function doQuery( $sql ) {
375 wfDebug( "SQL: [$sql]\n" );
376 if ( !StringUtils
::isUtf8( $sql ) ) {
377 throw new MWException( "SQL encoding is invalid\n$sql" );
380 // handle some oracle specifics
381 // remove AS column/table/subquery namings
382 if ( !$this->getFlag( DBO_DDLMODE
) ) {
383 $sql = preg_replace( '/ as /i', ' ', $sql );
386 // Oracle has issues with UNION clause if the statement includes LOB fields
387 // So we do a UNION ALL and then filter the results array with array_unique
388 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
389 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
390 // you have to select data from plan table after explain
391 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
395 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
401 wfSuppressWarnings();
403 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
404 $e = oci_error( $this->mConn
);
405 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
410 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
411 $e = oci_error( $stmt );
412 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
413 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
421 if ( $explain_count > 0 ) {
422 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
423 'WHERE statement_id = \'' . $explain_id . '\'' );
424 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
425 return new ORAResult( $this, $stmt, $union_unique );
427 $this->mAffectedRows
= oci_num_rows( $stmt );
433 function queryIgnore( $sql, $fname = '' ) {
434 return $this->query( $sql, $fname, true );
437 function freeResult( $res ) {
438 if ( $res instanceof ResultWrapper
) {
445 function fetchObject( $res ) {
446 if ( $res instanceof ResultWrapper
) {
450 return $res->fetchObject();
453 function fetchRow( $res ) {
454 if ( $res instanceof ResultWrapper
) {
458 return $res->fetchRow();
461 function numRows( $res ) {
462 if ( $res instanceof ResultWrapper
) {
466 return $res->numRows();
469 function numFields( $res ) {
470 if ( $res instanceof ResultWrapper
) {
474 return $res->numFields();
477 function fieldName( $stmt, $n ) {
478 return oci_field_name( $stmt, $n );
482 * This must be called after nextSequenceVal
485 function insertId() {
486 return $this->mInsertId
;
489 function dataSeek( $res, $row ) {
490 if ( $res instanceof ORAResult
) {
493 $res->result
->seek( $row );
497 function lastError() {
498 if ( $this->mConn
=== false ) {
501 $e = oci_error( $this->mConn
);
504 return $e['message'];
507 function lastErrno() {
508 if ( $this->mConn
=== false ) {
511 $e = oci_error( $this->mConn
);
517 function affectedRows() {
518 return $this->mAffectedRows
;
522 * Returns information about an index
523 * If errors are explicitly ignored, returns NULL on failure
526 function indexInfo( $table, $index, $fname = __METHOD__
) {
530 function indexUnique( $table, $index, $fname = __METHOD__
) {
534 function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
535 if ( !count( $a ) ) {
539 if ( !is_array( $options ) ) {
540 $options = array( $options );
543 if ( in_array( 'IGNORE', $options ) ) {
544 $this->ignore_DUP_VAL_ON_INDEX
= true;
547 if ( !is_array( reset( $a ) ) ) {
551 foreach ( $a as &$row ) {
552 $this->insertOneRow( $table, $row, $fname );
556 if ( in_array( 'IGNORE', $options ) ) {
557 $this->ignore_DUP_VAL_ON_INDEX
= false;
563 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
564 $col_info = $this->fieldInfoMulti( $table, $col );
565 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
568 if ( is_numeric( $col ) ) {
573 } elseif ( $includeCol ) {
577 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
581 if ( $val === 'NULL' ) {
585 if ( $val === null ) {
586 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
598 private function insertOneRow( $table, $row, $fname ) {
601 $table = $this->tableName( $table );
602 // "INSERT INTO tables (a, b, c)"
603 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
606 // for each value, append ":key"
608 foreach ( $row as $col => &$val ) {
615 $sql .= $this->fieldBindStatement( $table, $col, $val );
619 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
620 $e = oci_error( $this->mConn
);
621 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
625 foreach ( $row as $col => &$val ) {
626 $col_info = $this->fieldInfoMulti( $table, $col );
627 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
629 if ( $val === null ) {
630 // do nothing ... null was inserted in statement creation
631 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
632 if ( is_object( $val ) ) {
633 $val = $val->fetch();
636 // backward compatibility
637 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
638 $val = $this->getInfinity();
641 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
642 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
643 $e = oci_error( $stmt );
644 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
649 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
650 $e = oci_error( $stmt );
651 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
654 if ( is_object( $val ) ) {
655 $val = $val->fetch();
658 if ( $col_type == 'BLOB' ) {
659 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
660 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
662 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
663 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
668 wfSuppressWarnings();
670 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
671 $e = oci_error( $stmt );
672 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
673 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
677 $this->mAffectedRows
= oci_num_rows( $stmt );
680 $this->mAffectedRows
= oci_num_rows( $stmt );
685 if ( isset( $lob ) ) {
686 foreach ( $lob as $lob_v ) {
691 if ( !$this->mTrxLevel
) {
692 oci_commit( $this->mConn
);
695 oci_free_statement( $stmt );
698 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
699 $insertOptions = array(), $selectOptions = array()
701 $destTable = $this->tableName( $destTable );
702 if ( !is_array( $selectOptions ) ) {
703 $selectOptions = array( $selectOptions );
705 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
706 if ( is_array( $srcTable ) ) {
707 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
709 $srcTable = $this->tableName( $srcTable );
712 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
713 !isset( $varMap[$sequenceData['column']] )
715 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
718 // count-alias subselect fields to avoid abigious definition errors
720 foreach ( $varMap as &$val ) {
721 $val = $val . ' field' . ( $i++
);
724 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
725 " SELECT $startOpts " . implode( ',', $varMap ) .
726 " FROM $srcTable $useIndex ";
727 if ( $conds != '*' ) {
728 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
730 $sql .= " $tailOpts";
732 if ( in_array( 'IGNORE', $insertOptions ) ) {
733 $this->ignore_DUP_VAL_ON_INDEX
= true;
736 $retval = $this->query( $sql, $fname );
738 if ( in_array( 'IGNORE', $insertOptions ) ) {
739 $this->ignore_DUP_VAL_ON_INDEX
= false;
745 function tableName( $name, $format = 'quoted' ) {
747 Replace reserved words with better ones
748 Using uppercase because that's the only way Oracle can handle
756 $name = 'PAGECONTENT';
760 return strtoupper( parent
::tableName( $name, $format ) );
763 function tableNameInternal( $name ) {
764 $name = $this->tableName( $name );
766 return preg_replace( '/.*\.(.*)/', '$1', $name );
770 * Return the next in a sequence, save the value for retrieval via insertId()
773 function nextSequenceValue( $seqName ) {
774 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
775 $row = $this->fetchRow( $res );
776 $this->mInsertId
= $row[0];
778 return $this->mInsertId
;
782 * Return sequence_name if table has a sequence
785 private function getSequenceData( $table ) {
786 if ( $this->sequenceData
== null ) {
787 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
788 lower(atc.table_name),
789 lower(atc.column_name)
790 FROM all_sequences asq, all_tab_columns atc
793 '{$this->mTablePrefix}MWUSER',
794 '{$this->mTablePrefix}USER',
797 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
798 AND asq.sequence_owner = upper('{$this->mDBname}')
799 AND atc.owner = upper('{$this->mDBname}')" );
801 while ( ( $row = $result->fetchRow() ) !== false ) {
802 $this->sequenceData
[$row[1]] = array(
803 'sequence' => $row[0],
808 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
810 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
813 # Returns the size of a text field, or -1 for "unlimited"
814 function textFieldSize( $table, $field ) {
815 $fieldInfoData = $this->fieldInfo( $table, $field );
817 return $fieldInfoData->maxLength();
820 function limitResult( $sql, $limit, $offset = false ) {
821 if ( $offset === false ) {
825 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
828 function encodeBlob( $b ) {
829 return new Blob( $b );
832 function decodeBlob( $b ) {
833 if ( $b instanceof Blob
) {
840 function unionQueries( $sqls, $all ) {
841 $glue = ' UNION ALL ';
843 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
844 'FROM (' . implode( $glue, $sqls ) . ')';
847 function wasDeadlock() {
848 return $this->lastErrno() == 'OCI-00060';
851 function duplicateTableStructure( $oldName, $newName, $temporary = false,
854 $temporary = $temporary ?
'TRUE' : 'FALSE';
856 $newName = strtoupper( $newName );
857 $oldName = strtoupper( $oldName );
859 $tabName = substr( $newName, strlen( $this->mTablePrefix
) );
860 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
861 $newPrefix = strtoupper( $this->mTablePrefix
);
863 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
864 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
867 function listTables( $prefix = null, $fname = __METHOD__
) {
869 if ( !empty( $prefix ) ) {
870 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
873 $owner = strtoupper( $this->mDBname
);
874 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
875 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
877 // dirty code ... i know
879 $endArray[] = strtoupper( $prefix . 'MWUSER' );
880 $endArray[] = strtoupper( $prefix . 'PAGE' );
881 $endArray[] = strtoupper( $prefix . 'IMAGE' );
882 $fixedOrderTabs = $endArray;
883 while ( ( $row = $result->fetchRow() ) !== false ) {
884 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
885 $endArray[] = $row['table_name'];
892 public function dropTable( $tableName, $fName = __METHOD__
) {
893 $tableName = $this->tableName( $tableName );
894 if ( !$this->tableExists( $tableName ) ) {
898 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
901 function timestamp( $ts = 0 ) {
902 return wfTimestamp( TS_ORACLE
, $ts );
906 * Return aggregated value function call
908 public function aggregateValue( $valuedata, $valuename = 'value' ) {
912 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
913 # Ignore errors during error handling to avoid infinite
915 $ignore = $this->ignoreErrors( true );
916 ++
$this->mErrorCount
;
918 if ( $ignore ||
$tempIgnore ) {
919 wfDebug( "SQL ERROR (ignored): $error\n" );
920 $this->ignoreErrors( $ignore );
922 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
927 * @return string wikitext of a link to the server software's web site
929 public function getSoftwareLink() {
930 return '[http://www.oracle.com/ Oracle]';
934 * @return string Version information from the database
936 function getServerVersion() {
937 //better version number, fallback on driver
938 $rset = $this->doQuery(
939 'SELECT version FROM product_component_version ' .
940 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
942 if ( !( $row = $rset->fetchRow() ) ) {
943 return oci_server_version( $this->mConn
);
946 return $row['version'];
950 * Query whether a given index exists
953 function indexExists( $table, $index, $fname = __METHOD__
) {
954 $table = $this->tableName( $table );
955 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
956 $index = strtoupper( $index );
957 $owner = strtoupper( $this->mDBname
);
958 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
959 $res = $this->doQuery( $SQL );
961 $count = $res->numRows();
971 * Query whether a given table exists (in the given schema, or the default mw one if not given)
974 function tableExists( $table, $fname = __METHOD__
) {
975 $table = $this->tableName( $table );
976 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
977 $owner = $this->addQuotes( strtoupper( $this->mDBname
) );
978 $SQL = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
979 $res = $this->doQuery( $SQL );
980 if ( $res && $res->numRows() > 0 ) {
992 * Function translates mysql_fetch_field() functionality on ORACLE.
993 * Caching is present for reducing query time.
994 * For internal calls. Use fieldInfo for normal usage.
995 * Returns false if the field doesn't exist
997 * @param $table Array
998 * @param $field String
999 * @return ORAField|ORAResult
1001 private function fieldInfoMulti( $table, $field ) {
1002 $field = strtoupper( $field );
1003 if ( is_array( $table ) ) {
1004 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
1005 $tableWhere = 'IN (';
1006 foreach ( $table as &$singleTable ) {
1007 $singleTable = $this->removeIdentifierQuotes( $singleTable );
1008 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
1009 return $this->mFieldInfoCache
["$singleTable.$field"];
1011 $tableWhere .= '\'' . $singleTable . '\',';
1013 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
1015 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
1016 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
1017 return $this->mFieldInfoCache
["$table.$field"];
1019 $tableWhere = '= \'' . $table . '\'';
1022 $fieldInfoStmt = oci_parse(
1024 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
1025 $tableWhere . ' and column_name = \'' . $field . '\''
1027 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
1028 $e = oci_error( $fieldInfoStmt );
1029 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
1033 $res = new ORAResult( $this, $fieldInfoStmt );
1034 if ( $res->numRows() == 0 ) {
1035 if ( is_array( $table ) ) {
1036 foreach ( $table as &$singleTable ) {
1037 $this->mFieldInfoCache
["$singleTable.$field"] = false;
1040 $this->mFieldInfoCache
["$table.$field"] = false;
1042 $fieldInfoTemp = null;
1044 $fieldInfoTemp = new ORAField( $res->fetchRow() );
1045 $table = $fieldInfoTemp->tableName();
1046 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
1050 return $fieldInfoTemp;
1054 * @throws DBUnexpectedError
1059 function fieldInfo( $table, $field ) {
1060 if ( is_array( $table ) ) {
1061 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
1064 return $this->fieldInfoMulti( $table, $field );
1067 protected function doBegin( $fname = __METHOD__
) {
1068 $this->mTrxLevel
= 1;
1069 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
1072 protected function doCommit( $fname = __METHOD__
) {
1073 if ( $this->mTrxLevel
) {
1074 $ret = oci_commit( $this->mConn
);
1076 throw new DBUnexpectedError( $this, $this->lastError() );
1078 $this->mTrxLevel
= 0;
1079 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1083 protected function doRollback( $fname = __METHOD__
) {
1084 if ( $this->mTrxLevel
) {
1085 oci_rollback( $this->mConn
);
1086 $this->mTrxLevel
= 0;
1087 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1091 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
1092 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
1093 $fname = __METHOD__
, $inputCallback = false ) {
1096 $dollarquote = false;
1098 $replacements = array();
1100 while ( !feof( $fp ) ) {
1101 if ( $lineCallback ) {
1102 call_user_func( $lineCallback );
1104 $line = trim( fgets( $fp, 1024 ) );
1105 $sl = strlen( $line ) - 1;
1110 if ( '-' == $line[0] && '-' == $line[1] ) {
1114 // Allow dollar quoting for function declarations
1115 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1116 if ( $dollarquote ) {
1117 $dollarquote = false;
1118 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1121 $dollarquote = true;
1123 } elseif ( !$dollarquote ) {
1124 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
1126 $line = substr( $line, 0, $sl );
1136 $cmd = str_replace( ';;', ";", $cmd );
1137 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1138 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1139 $replacements[$defines[2]] = $defines[1];
1142 foreach ( $replacements as $mwVar => $scVar ) {
1143 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1146 $cmd = $this->replaceVars( $cmd );
1147 if ( $inputCallback ) {
1148 call_user_func( $inputCallback, $cmd );
1150 $res = $this->doQuery( $cmd );
1151 if ( $resultCallback ) {
1152 call_user_func( $resultCallback, $res, $this );
1155 if ( false === $res ) {
1156 $err = $this->lastError();
1158 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1170 function selectDB( $db ) {
1171 $this->mDBname
= $db;
1172 if ( $db == null ||
$db == $this->mUser
) {
1175 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1176 $stmt = oci_parse( $this->mConn
, $sql );
1177 wfSuppressWarnings();
1178 $success = oci_execute( $stmt );
1179 wfRestoreWarnings();
1181 $e = oci_error( $stmt );
1182 if ( $e['code'] != '1435' ) {
1183 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1192 function strencode( $s ) {
1193 return str_replace( "'", "''", $s );
1196 function addQuotes( $s ) {
1198 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1199 $s = $wgContLang->checkTitleEncoding( $s );
1202 return "'" . $this->strencode( $s ) . "'";
1205 public function addIdentifierQuotes( $s ) {
1206 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1213 public function removeIdentifierQuotes( $s ) {
1214 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1217 public function isQuotedIdentifier( $s ) {
1218 return strpos( $s, '/*Q*/' ) !== false;
1221 private function wrapFieldForWhere( $table, &$col, &$val ) {
1224 $col_info = $this->fieldInfoMulti( $table, $col );
1225 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1226 if ( $col_type == 'CLOB' ) {
1227 $col = 'TO_CHAR(' . $col . ')';
1228 $val = $wgContLang->checkTitleEncoding( $val );
1229 } elseif ( $col_type == 'VARCHAR2' ) {
1230 $val = $wgContLang->checkTitleEncoding( $val );
1234 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1236 foreach ( $conds as $col => $val ) {
1237 if ( is_array( $val ) ) {
1238 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1240 if ( is_numeric( $col ) && $parentCol != null ) {
1241 $this->wrapFieldForWhere( $table, $parentCol, $val );
1243 $this->wrapFieldForWhere( $table, $col, $val );
1245 $conds2[$col] = $val;
1252 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1253 $options = array(), $join_conds = array()
1255 if ( is_array( $conds ) ) {
1256 $conds = $this->wrapConditionsForWhere( $table, $conds );
1259 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1263 * Returns an optional USE INDEX clause to go after the table, and a
1264 * string to go at the end of the query
1268 * @param array $options an associative array of options to be turned into
1269 * an SQL query, valid keys are listed in the function.
1272 function makeSelectOptions( $options ) {
1273 $preLimitTail = $postLimitTail = '';
1276 $noKeyOptions = array();
1277 foreach ( $options as $key => $option ) {
1278 if ( is_numeric( $key ) ) {
1279 $noKeyOptions[$option] = true;
1283 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1285 $preLimitTail .= $this->makeOrderBy( $options );
1287 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1288 $postLimitTail .= ' FOR UPDATE';
1291 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1292 $startOpts .= 'DISTINCT';
1295 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1296 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1301 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1304 public function delete( $table, $conds, $fname = __METHOD__
) {
1305 if ( is_array( $conds ) ) {
1306 $conds = $this->wrapConditionsForWhere( $table, $conds );
1308 // a hack for deleting pages, users and images (which have non-nullable FKs)
1309 // all deletions on these tables have transactions so final failure rollbacks these updates
1310 $table = $this->tableName( $table );
1311 if ( $table == $this->tableName( 'user' ) ) {
1312 $this->update( 'archive', array( 'ar_user' => 0 ),
1313 array( 'ar_user' => $conds['user_id'] ), $fname );
1314 $this->update( 'ipblocks', array( 'ipb_user' => 0 ),
1315 array( 'ipb_user' => $conds['user_id'] ), $fname );
1316 $this->update( 'image', array( 'img_user' => 0 ),
1317 array( 'img_user' => $conds['user_id'] ), $fname );
1318 $this->update( 'oldimage', array( 'oi_user' => 0 ),
1319 array( 'oi_user' => $conds['user_id'] ), $fname );
1320 $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ),
1321 array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
1322 $this->update( 'filearchive', array( 'fa_user' => 0 ),
1323 array( 'fa_user' => $conds['user_id'] ), $fname );
1324 $this->update( 'uploadstash', array( 'us_user' => 0 ),
1325 array( 'us_user' => $conds['user_id'] ), $fname );
1326 $this->update( 'recentchanges', array( 'rc_user' => 0 ),
1327 array( 'rc_user' => $conds['user_id'] ), $fname );
1328 $this->update( 'logging', array( 'log_user' => 0 ),
1329 array( 'log_user' => $conds['user_id'] ), $fname );
1330 } elseif ( $table == $this->tableName( 'image' ) ) {
1331 $this->update( 'oldimage', array( 'oi_name' => 0 ),
1332 array( 'oi_name' => $conds['img_name'] ), $fname );
1335 return parent
::delete( $table, $conds, $fname );
1338 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1341 $table = $this->tableName( $table );
1342 $opts = $this->makeUpdateOptions( $options );
1343 $sql = "UPDATE $opts $table SET ";
1346 foreach ( $values as $col => &$val ) {
1347 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1350 $sqlSet = ', ' . $sqlSet;
1357 if ( $conds !== array() && $conds !== '*' ) {
1358 $conds = $this->wrapConditionsForWhere( $table, $conds );
1359 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1362 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1363 $e = oci_error( $this->mConn
);
1364 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1368 foreach ( $values as $col => &$val ) {
1369 $col_info = $this->fieldInfoMulti( $table, $col );
1370 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1372 if ( $val === null ) {
1373 // do nothing ... null was inserted in statement creation
1374 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1375 if ( is_object( $val ) ) {
1376 $val = $val->getData();
1379 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1380 $val = '31-12-2030 12:00:00.000000';
1383 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1384 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1385 $e = oci_error( $stmt );
1386 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1391 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1392 $e = oci_error( $stmt );
1393 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1396 if ( $col_type == 'BLOB' ) {
1397 $lob[$col]->writeTemporary( $val );
1398 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1400 $lob[$col]->writeTemporary( $val );
1401 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1406 wfSuppressWarnings();
1408 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1409 $e = oci_error( $stmt );
1410 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
1411 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1415 $this->mAffectedRows
= oci_num_rows( $stmt );
1418 $this->mAffectedRows
= oci_num_rows( $stmt );
1421 wfRestoreWarnings();
1423 if ( isset( $lob ) ) {
1424 foreach ( $lob as $lob_v ) {
1429 if ( !$this->mTrxLevel
) {
1430 oci_commit( $this->mConn
);
1433 oci_free_statement( $stmt );
1436 function bitNot( $field ) {
1437 // expecting bit-fields smaller than 4bytes
1438 return 'BITNOT(' . $field . ')';
1441 function bitAnd( $fieldLeft, $fieldRight ) {
1442 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1445 function bitOr( $fieldLeft, $fieldRight ) {
1446 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1449 function setFakeMaster( $enabled = true ) {
1452 function getDBname() {
1453 return $this->mDBname
;
1456 function getServer() {
1457 return $this->mServer
;
1460 public function buildGroupConcatField(
1461 $delim, $table, $field, $conds = '', $join_conds = array()
1463 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1465 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1468 public function getSearchEngine() {
1469 return 'SearchOracle';
1472 public function getInfinity() {
1473 return '31-12-2030 12:00:00.000000';
1475 } // end DatabaseOracle class