3 * This is the Oracle database abstraction layer.
10 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
11 * other things. We use a wrapper class to handle that and other
12 * Oracle-specific bits, like converting column names back to lowercase.
20 private $columns = array();
22 private function array_unique_md( $array_in ) {
24 $array_hashes = array();
26 foreach ( $array_in as $item ) {
27 $hash = md5( serialize( $item ) );
28 if ( !isset( $array_hashes[$hash] ) ) {
29 $array_hashes[$hash] = $hash;
37 function __construct( &$db, $stmt, $unique = false ) {
40 if ( ( $this->nrows
= oci_fetch_all( $stmt, $this->rows
, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM
) ) === false ) {
41 $e = oci_error( $stmt );
42 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__
);
48 $this->rows
= $this->array_unique_md( $this->rows
);
49 $this->nrows
= count( $this->rows
);
52 if ($this->nrows
> 0) {
53 foreach ( $this->rows
[0] as $k => $v ) {
54 $this->columns
[$k] = strtolower( oci_field_name( $stmt, $k +
1 ) );
59 oci_free_statement( $stmt );
62 public function free() {
66 public function seek( $row ) {
67 $this->cursor
= min( $row, $this->nrows
);
70 public function numRows() {
74 public function numFields() {
75 return count($this->columns
);
78 public function fetchObject() {
79 if ( $this->cursor
>= $this->nrows
) {
82 $row = $this->rows
[$this->cursor++
];
83 $ret = new stdClass();
84 foreach ( $row as $k => $v ) {
85 $lc = $this->columns
[$k];
92 public function fetchRow() {
93 if ( $this->cursor
>= $this->nrows
) {
97 $row = $this->rows
[$this->cursor++
];
99 foreach ( $row as $k => $v ) {
100 $lc = $this->columns
[$k];
112 class ORAField
implements Field
{
113 private $name, $tablename, $default, $max_length, $nullable,
114 $is_pk, $is_unique, $is_multiple, $is_key, $type;
116 function __construct( $info ) {
117 $this->name
= $info['column_name'];
118 $this->tablename
= $info['table_name'];
119 $this->default = $info['data_default'];
120 $this->max_length
= $info['data_length'];
121 $this->nullable
= $info['not_null'];
122 $this->is_pk
= isset( $info['prim'] ) && $info['prim'] == 1 ?
1 : 0;
123 $this->is_unique
= isset( $info['uniq'] ) && $info['uniq'] == 1 ?
1 : 0;
124 $this->is_multiple
= isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ?
1 : 0;
125 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
126 $this->type
= $info['data_type'];
133 function tableName() {
134 return $this->tablename
;
137 function defaultValue() {
138 return $this->default;
141 function maxLength() {
142 return $this->max_length
;
145 function isNullable() {
146 return $this->nullable
;
150 return $this->is_key
;
153 function isMultipleKey() {
154 return $this->is_multiple
;
165 class DatabaseOracle
extends DatabaseBase
{
166 var $mInsertId = null;
167 var $mLastResult = null;
168 var $numeric_version = null;
169 var $lastResult = null;
173 var $ignore_DUP_VAL_ON_INDEX = false;
174 var $sequenceData = null;
176 var $defaultCharset = 'AL32UTF8';
178 var $mFieldInfoCache = array();
180 function __construct( $server = false, $user = false, $password = false, $dbName = false,
181 $flags = 0, $tablePrefix = 'get from global' )
183 $tablePrefix = $tablePrefix == 'get from global' ?
$tablePrefix : strtoupper( $tablePrefix );
184 parent
::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
185 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
192 function cascadingDeletes() {
195 function cleanupTriggers() {
198 function strictIPs() {
201 function realTimestamps() {
204 function implicitGroupby() {
207 function implicitOrderby() {
210 function searchableIPs() {
215 * Usually aborts on failure
217 function open( $server, $user, $password, $dbName ) {
218 if ( !function_exists( 'oci_connect' ) ) {
219 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" );
223 $this->mUser
= $user;
224 $this->mPassword
= $password;
225 // changed internal variables functions
226 // mServer now holds the TNS endpoint
227 // mDBname is schema name if different from username
229 // backward compatibillity (server used to be null and TNS was supplied in dbname)
230 $this->mServer
= $dbName;
231 $this->mDBname
= $user;
233 $this->mServer
= $server;
235 $this->mDBname
= $user;
237 $this->mDBname
= $dbName;
241 if ( !strlen( $user ) ) { # e.g. the class is being loaded
245 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
246 if ( $this->mFlags
& DBO_DEFAULT
) {
247 $this->mConn
= @oci_new_connect
( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
249 $this->mConn
= @oci_connect
( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
252 if ( $this->mUser
!= $this->mDBname
) {
253 //change current schema in session
254 $this->selectDB( $this->mDBname
);
257 if ( !$this->mConn
) {
258 throw new DBConnectionError( $this, $this->lastError() );
261 $this->mOpened
= true;
263 # removed putenv calls because they interfere with the system globaly
264 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
265 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
270 * Closes a database connection, if it is open
271 * Returns success, true if already closed
274 $this->mOpened
= false;
275 if ( $this->mConn
) {
276 return oci_close( $this->mConn
);
282 function execFlags() {
283 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
286 function doQuery( $sql ) {
287 wfDebug( "SQL: [$sql]\n" );
288 if ( !mb_check_encoding( $sql ) ) {
289 throw new MWException( "SQL encoding is invalid\n$sql" );
292 // handle some oracle specifics
293 // remove AS column/table/subquery namings
294 if( !$this->getFlag( DBO_DDLMODE
) ) {
295 $sql = preg_replace( '/ as /i', ' ', $sql );
298 // Oracle has issues with UNION clause if the statement includes LOB fields
299 // So we do a UNION ALL and then filter the results array with array_unique
300 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
301 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
302 // you have to select data from plan table after explain
303 $explain_id = date( 'dmYHis' );
305 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
307 wfSuppressWarnings();
309 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
310 $e = oci_error( $this->mConn
);
311 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
315 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
316 $e = oci_error( $stmt );
317 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
318 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
325 if ( $explain_count > 0 ) {
326 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
327 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
328 return new ORAResult( $this, $stmt, $union_unique );
330 $this->mAffectedRows
= oci_num_rows( $stmt );
335 function queryIgnore( $sql, $fname = '' ) {
336 return $this->query( $sql, $fname, true );
339 function freeResult( $res ) {
340 if ( $res instanceof ResultWrapper
) {
347 function fetchObject( $res ) {
348 if ( $res instanceof ResultWrapper
) {
352 return $res->fetchObject();
355 function fetchRow( $res ) {
356 if ( $res instanceof ResultWrapper
) {
360 return $res->fetchRow();
363 function numRows( $res ) {
364 if ( $res instanceof ResultWrapper
) {
368 return $res->numRows();
371 function numFields( $res ) {
372 if ( $res instanceof ResultWrapper
) {
376 return $res->numFields();
379 function fieldName( $stmt, $n ) {
380 return oci_field_name( $stmt, $n );
384 * This must be called after nextSequenceVal
386 function insertId() {
387 return $this->mInsertId
;
390 function dataSeek( $res, $row ) {
391 if ( $res instanceof ORAResult
) {
394 $res->result
->seek( $row );
398 function lastError() {
399 if ( $this->mConn
=== false ) {
402 $e = oci_error( $this->mConn
);
404 return $e['message'];
407 function lastErrno() {
408 if ( $this->mConn
=== false ) {
411 $e = oci_error( $this->mConn
);
416 function affectedRows() {
417 return $this->mAffectedRows
;
421 * Returns information about an index
422 * If errors are explicitly ignored, returns NULL on failure
424 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
428 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
432 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
433 if ( !count( $a ) ) {
437 if ( !is_array( $options ) ) {
438 $options = array( $options );
441 if ( in_array( 'IGNORE', $options ) ) {
442 $this->ignore_DUP_VAL_ON_INDEX
= true;
445 if ( !is_array( reset( $a ) ) ) {
449 foreach ( $a as &$row ) {
450 $this->insertOneRow( $table, $row, $fname );
454 if ( in_array( 'IGNORE', $options ) ) {
455 $this->ignore_DUP_VAL_ON_INDEX
= false;
461 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
462 $col_info = $this->fieldInfoMulti( $table, $col );
463 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
466 if ( is_numeric( $col ) ) {
470 } else if ( $includeCol ) {
474 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
478 if ( $val === null ) {
479 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
491 private function insertOneRow( $table, $row, $fname ) {
494 $table = $this->tableName( $table );
495 // "INSERT INTO tables (a, b, c)"
496 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
499 // for each value, append ":key"
501 foreach ( $row as $col => &$val ) {
508 $sql .= $this->fieldBindStatement( $table, $col, $val );
512 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
513 $e = oci_error( $this->mConn
);
514 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
517 foreach ( $row as $col => &$val ) {
518 $col_info = $this->fieldInfoMulti( $table, $col );
519 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
521 if ( $val === null ) {
522 // do nothing ... null was inserted in statement creation
523 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
524 if ( is_object( $val ) ) {
525 $val = $val->fetch();
528 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
529 $val = '31-12-2030 12:00:00.000000';
532 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
533 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
534 $e = oci_error( $stmt );
535 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
539 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
540 $e = oci_error( $stmt );
541 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
544 if ( is_object( $val ) ) {
545 $val = $val->fetch();
548 if ( $col_type == 'BLOB' ) {
549 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
550 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB
);
552 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
553 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
558 wfSuppressWarnings();
560 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
561 $e = oci_error( $stmt );
562 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
563 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
566 $this->mAffectedRows
= oci_num_rows( $stmt );
569 $this->mAffectedRows
= oci_num_rows( $stmt );
574 if ( isset( $lob ) ) {
575 foreach ( $lob as $lob_v ) {
580 if ( !$this->mTrxLevel
) {
581 oci_commit( $this->mConn
);
584 oci_free_statement( $stmt );
587 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
588 $insertOptions = array(), $selectOptions = array() )
590 $destTable = $this->tableName( $destTable );
591 if ( !is_array( $selectOptions ) ) {
592 $selectOptions = array( $selectOptions );
594 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
595 if ( is_array( $srcTable ) ) {
596 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
598 $srcTable = $this->tableName( $srcTable );
601 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
602 !isset( $varMap[$sequenceData['column']] ) )
604 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
607 // count-alias subselect fields to avoid abigious definition errors
609 foreach ( $varMap as &$val ) {
610 $val = $val . ' field' . ( $i++
);
613 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
614 " SELECT $startOpts " . implode( ',', $varMap ) .
615 " FROM $srcTable $useIndex ";
616 if ( $conds != '*' ) {
617 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
619 $sql .= " $tailOpts";
621 if ( in_array( 'IGNORE', $insertOptions ) ) {
622 $this->ignore_DUP_VAL_ON_INDEX
= true;
625 $retval = $this->query( $sql, $fname );
627 if ( in_array( 'IGNORE', $insertOptions ) ) {
628 $this->ignore_DUP_VAL_ON_INDEX
= false;
634 function tableName( $name ) {
635 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
637 Replace reserved words with better ones
638 Using uppercase because that's the only way Oracle can handle
646 $name = 'PAGECONTENT';
651 The rest of procedure is equal to generic Databse class
652 except for the quoting style
654 if ( $name[0] == '"' && substr( $name, - 1, 1 ) == '"' ) {
657 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
660 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
661 if ( isset( $dbDetails[1] ) ) {
662 @list
( $table, $database ) = $dbDetails;
664 @list
( $table ) = $dbDetails;
667 $prefix = $this->mTablePrefix
;
669 if ( isset( $database ) ) {
670 $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
673 if ( !isset( $database ) && isset( $wgSharedDB ) && $table[0] != '"'
674 && isset( $wgSharedTables )
675 && is_array( $wgSharedTables )
676 && in_array( $table, $wgSharedTables )
678 $database = $wgSharedDB;
679 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
682 if ( isset( $database ) ) {
683 $database = ( $database[0] == '"' ?
$database : "\"{$database}\"" );
685 $table = ( $table[0] == '"') ?
$table : "\"{$prefix}{$table}\"" ;
687 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
689 return strtoupper( $tableName );
693 * Return the next in a sequence, save the value for retrieval via insertId()
695 function nextSequenceValue( $seqName ) {
696 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
697 $row = $this->fetchRow( $res );
698 $this->mInsertId
= $row[0];
699 return $this->mInsertId
;
703 * Return sequence_name if table has a sequence
705 private function getSequenceData( $table ) {
706 if ( $this->sequenceData
== null ) {
707 $result = $this->doQuery( 'SELECT lower(us.sequence_name), lower(utc.table_name), lower(utc.column_name) from user_sequences us, user_tab_columns utc where us.sequence_name = utc.table_name||\'_\'||utc.column_name||\'_SEQ\'' );
709 while ( ( $row = $result->fetchRow() ) !== false ) {
710 $this->sequenceData
[$this->tableName( $row[1] )] = array(
711 'sequence' => $row[0],
717 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
721 * REPLACE query wrapper
722 * Oracle simulates this with a DELETE followed by INSERT
723 * $row is the row to insert, an associative array
724 * $uniqueIndexes is an array of indexes. Each element may be either a
725 * field name or an array of field names
727 * It may be more efficient to leave off unique indexes which are unlikely to collide.
728 * However if you do this, you run the risk of encountering errors which wouldn't have
731 * @param $table String: table name
732 * @param $uniqueIndexes Array: array of indexes. Each element may be
733 * either a field name or an array of field names
734 * @param $rows Array: rows to insert to $table
735 * @param $fname String: function name, you can use __METHOD__ here
737 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
738 $table = $this->tableName( $table );
740 if ( count( $rows ) == 0 ) {
745 if ( !is_array( reset( $rows ) ) ) {
746 $rows = array( $rows );
749 $sequenceData = $this->getSequenceData( $table );
751 foreach ( $rows as $row ) {
752 # Delete rows which collide
753 if ( $uniqueIndexes ) {
754 $condsDelete = array();
755 foreach ( $uniqueIndexes as $index ) {
756 $condsDelete[$index] = $row[$index];
758 if ( count( $condsDelete ) > 0 ) {
759 $this->delete( $table, $condsDelete, $fname );
763 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
764 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
768 $this->insert( $table, $row, $fname );
772 # DELETE where the condition is a join
773 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
775 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
778 $delTable = $this->tableName( $delTable );
779 $joinTable = $this->tableName( $joinTable );
780 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
781 if ( $conds != '*' ) {
782 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
786 $this->query( $sql, $fname );
789 # Returns the size of a text field, or -1 for "unlimited"
790 function textFieldSize( $table, $field ) {
791 $fieldInfoData = $this->fieldInfo( $table, $field );
792 return $fieldInfoData->maxLength();
795 function limitResult( $sql, $limit, $offset = false ) {
796 if ( $offset === false ) {
799 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
802 function encodeBlob( $b ) {
803 return new Blob( $b );
806 function decodeBlob( $b ) {
807 if ( $b instanceof Blob
) {
813 function unionQueries( $sqls, $all ) {
814 $glue = ' UNION ALL ';
815 return 'SELECT * ' . ( $all ?
'':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
818 function wasDeadlock() {
819 return $this->lastErrno() == 'OCI-00060';
822 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
825 $temporary = $temporary ?
'TRUE' : 'FALSE';
827 $newName = trim( strtoupper( $newName ), '"');
828 $oldName = trim( strtoupper( $oldName ), '"');
830 $tabName = substr( $newName, strlen( $wgDBprefix ) );
831 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
833 return $this->doQuery( 'BEGIN DUPLICATE_TABLE(\'' . $tabName . '\', \'' . $oldPrefix . '\', \'' . strtoupper( $wgDBprefix ) . '\', ' . $temporary . '); END;' );
836 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
838 if (!empty($prefix)) {
839 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
842 $result = $this->doQuery( "SELECT table_name FROM user_tables WHERE table_name NOT LIKE '%!_IDX$_' ESCAPE '!' $listWhere" );
844 // dirty code ... i know
846 $endArray[] = $prefix.'MWUSER';
847 $endArray[] = $prefix.'PAGE';
848 $endArray[] = $prefix.'IMAGE';
849 $fixedOrderTabs = $endArray;
850 while (($row = $result->fetchRow()) !== false) {
851 if (!in_array($row['table_name'], $fixedOrderTabs))
852 $endArray[] = $row['table_name'];
858 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
859 $tableName = $this->tableName($tableName);
860 if( !$this->tableExists( $tableName ) ) {
864 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
867 function timestamp( $ts = 0 ) {
868 return wfTimestamp( TS_ORACLE
, $ts );
872 * Return aggregated value function call
874 function aggregateValue ( $valuedata, $valuename = 'value' ) {
878 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
879 # Ignore errors during error handling to avoid infinite
881 $ignore = $this->ignoreErrors( true );
882 ++
$this->mErrorCount
;
884 if ( $ignore ||
$tempIgnore ) {
885 wfDebug( "SQL ERROR (ignored): $error\n" );
886 $this->ignoreErrors( $ignore );
888 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
893 * @return string wikitext of a link to the server software's web site
895 public static function getSoftwareLink() {
896 return '[http://www.oracle.com/ Oracle]';
900 * @return string Version information from the database
902 function getServerVersion() {
903 //better version number, fallback on driver
904 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
905 if ( !( $row = $rset->fetchRow() ) ) {
906 return oci_server_version( $this->mConn
);
908 return $row['version'];
912 * Query whether a given table exists (in the given schema, or the default mw one if not given)
914 function tableExists( $table ) {
915 $table = trim($this->tableName($table), '"');
916 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
917 $res = $this->doQuery( $SQL );
919 $count = $res->numRows();
928 * Function translates mysql_fetch_field() functionality on ORACLE.
929 * Caching is present for reducing query time.
930 * For internal calls. Use fieldInfo for normal usage.
931 * Returns false if the field doesn't exist
933 * @param $table Array
934 * @param $field String
937 private function fieldInfoMulti( $table, $field ) {
938 $field = strtoupper( $field );
939 if ( is_array( $table ) ) {
940 $table = array_map( array( &$this, 'tableName' ), $table );
941 $tableWhere = 'IN (';
942 foreach( $table as &$singleTable ) {
943 $singleTable = strtoupper( trim( $singleTable, '"' ) );
944 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
945 return $this->mFieldInfoCache
["$singleTable.$field"];
947 $tableWhere .= '\'' . $singleTable . '\',';
949 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
951 $table = strtoupper( trim( $this->tableName( $table ), '"' ) );
952 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
953 return $this->mFieldInfoCache
["$table.$field"];
955 $tableWhere = '= \''.$table.'\'';
958 $fieldInfoStmt = oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
959 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT
) === false ) {
960 $e = oci_error( $fieldInfoStmt );
961 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
964 $res = new ORAResult( $this, $fieldInfoStmt );
965 if ( $res->numRows() == 0 ) {
966 if ( is_array( $table ) ) {
967 foreach( $table as &$singleTable ) {
968 $this->mFieldInfoCache
["$singleTable.$field"] = false;
971 $this->mFieldInfoCache
["$table.$field"] = false;
973 $fieldInfoTemp = null;
975 $fieldInfoTemp = new ORAField( $res->fetchRow() );
976 $table = $fieldInfoTemp->tableName();
977 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
980 return $fieldInfoTemp;
984 * @throws DBUnexpectedError
989 function fieldInfo( $table, $field ) {
990 if ( is_array( $table ) ) {
991 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
993 return $this->fieldInfoMulti ($table, $field);
996 function begin( $fname = '' ) {
997 $this->mTrxLevel
= 1;
1000 function commit( $fname = '' ) {
1001 oci_commit( $this->mConn
);
1002 $this->mTrxLevel
= 0;
1005 /* Not even sure why this is used in the main codebase... */
1006 function limitResultForUpdate( $sql, $num ) {
1010 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
1011 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
1014 $dollarquote = false;
1016 $replacements = array();
1018 while ( ! feof( $fp ) ) {
1019 if ( $lineCallback ) {
1020 call_user_func( $lineCallback );
1022 $line = trim( fgets( $fp, 1024 ) );
1023 $sl = strlen( $line ) - 1;
1028 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1032 // Allow dollar quoting for function declarations
1033 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1034 if ( $dollarquote ) {
1035 $dollarquote = false;
1036 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1039 $dollarquote = true;
1041 } elseif ( !$dollarquote ) {
1042 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
1044 $line = substr( $line, 0, $sl );
1054 $cmd = str_replace( ';;', ";", $cmd );
1055 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1056 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1057 $replacements[$defines[2]] = $defines[1];
1060 foreach ( $replacements as $mwVar => $scVar ) {
1061 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1064 $cmd = $this->replaceVars( $cmd );
1065 $res = $this->doQuery( $cmd );
1066 if ( $resultCallback ) {
1067 call_user_func( $resultCallback, $res, $this );
1070 if ( false === $res ) {
1071 $err = $this->lastError();
1072 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1083 function selectDB( $db ) {
1084 $this->mDBname
= $db;
1085 if ( $db == null ||
$db == $this->mUser
) {
1088 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1089 $stmt = oci_parse( $this->mConn
, $sql );
1090 wfSuppressWarnings();
1091 $success = oci_execute( $stmt );
1092 wfRestoreWarnings();
1094 $e = oci_error( $stmt );
1095 if ( $e['code'] != '1435' ) {
1096 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1103 function strencode( $s ) {
1104 return str_replace( "'", "''", $s );
1107 function addQuotes( $s ) {
1109 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1110 $s = $wgContLang->checkTitleEncoding( $s );
1112 return "'" . $this->strencode( $s ) . "'";
1115 public function addIdentifierQuotes( $s ) {
1116 if ( !$this->mFlags
& DBO_DDLMODE
) {
1117 $s = '"' . str_replace( '"', '""', $s ) . '"';
1122 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1125 if ($conds != null) {
1127 $conds = ( !is_array( $conds ) ) ?
array( $conds ) : $conds;
1128 foreach ( $conds as $col => $val ) {
1129 $col_info = $this->fieldInfoMulti( $table, $col );
1130 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1131 if ( $col_type == 'CLOB' ) {
1132 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1133 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1134 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1136 $conds2[$col] = $val;
1140 return parent
::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1142 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1147 * Returns an optional USE INDEX clause to go after the table, and a
1148 * string to go at the end of the query
1152 * @param $options Array: an associative array of options to be turned into
1153 * an SQL query, valid keys are listed in the function.
1156 function makeSelectOptions( $options ) {
1157 $preLimitTail = $postLimitTail = '';
1160 $noKeyOptions = array();
1161 foreach ( $options as $key => $option ) {
1162 if ( is_numeric( $key ) ) {
1163 $noKeyOptions[$option] = true;
1167 if ( isset( $options['GROUP BY'] ) ) {
1168 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1170 if ( isset( $options['ORDER BY'] ) ) {
1171 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1174 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1175 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1176 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1177 $startOpts .= 'DISTINCT';
1180 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1181 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1186 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1189 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1192 if ( $wgContLang != null && $conds != null && $conds != '*' ) {
1194 $conds = ( !is_array( $conds ) ) ?
array( $conds ) : $conds;
1195 foreach ( $conds as $col => $val ) {
1196 $col_info = $this->fieldInfoMulti( $table, $col );
1197 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1198 if ( $col_type == 'CLOB' ) {
1199 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1201 if ( is_array( $val ) ) {
1202 $conds2[$col] = $val;
1203 foreach ( $conds2[$col] as &$val2 ) {
1204 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1207 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1212 return parent
::delete( $table, $conds2, $fname );
1214 return parent
::delete( $table, $conds, $fname );
1218 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1221 $table = $this->tableName( $table );
1222 $opts = $this->makeUpdateOptions( $options );
1223 $sql = "UPDATE $opts $table SET ";
1226 foreach ( $values as $col => &$val ) {
1227 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1230 $sqlSet = ', ' . $sqlSet;
1237 if ( $conds != '*' ) {
1238 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1241 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1242 $e = oci_error( $this->mConn
);
1243 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1246 foreach ( $values as $col => &$val ) {
1247 $col_info = $this->fieldInfoMulti( $table, $col );
1248 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1250 if ( $val === null ) {
1251 // do nothing ... null was inserted in statement creation
1252 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1253 if ( is_object( $val ) ) {
1254 $val = $val->getData();
1257 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1258 $val = '31-12-2030 12:00:00.000000';
1261 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1262 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1263 $e = oci_error( $stmt );
1264 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1268 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1269 $e = oci_error( $stmt );
1270 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1273 if ( $col_type == 'BLOB' ) {
1274 $lob[$col]->writeTemporary( $val );
1275 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
1277 $lob[$col]->writeTemporary( $val );
1278 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
1283 wfSuppressWarnings();
1285 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
1286 $e = oci_error( $stmt );
1287 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
1288 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1291 $this->mAffectedRows
= oci_num_rows( $stmt );
1294 $this->mAffectedRows
= oci_num_rows( $stmt );
1297 wfRestoreWarnings();
1299 if ( isset( $lob ) ) {
1300 foreach ( $lob as $lob_v ) {
1305 if ( !$this->mTrxLevel
) {
1306 oci_commit( $this->mConn
);
1309 oci_free_statement( $stmt );
1312 function bitNot( $field ) {
1313 // expecting bit-fields smaller than 4bytes
1314 return 'BITNOT(' . $field . ')';
1317 function bitAnd( $fieldLeft, $fieldRight ) {
1318 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1321 function bitOr( $fieldLeft, $fieldRight ) {
1322 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1325 function setFakeMaster( $enabled = true ) { }
1327 function getDBname() {
1328 return $this->mDBname
;
1331 function getServer() {
1332 return $this->mServer
;
1335 public function getSearchEngine() {
1336 return 'SearchOracle';
1338 } // end DatabaseOracle class