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 $lastResult = null;
172 var $ignore_DUP_VAL_ON_INDEX = false;
173 var $sequenceData = null;
175 var $defaultCharset = 'AL32UTF8';
177 var $mFieldInfoCache = array();
179 function __construct( $server = false, $user = false, $password = false, $dbName = false,
180 $flags = 0, $tablePrefix = 'get from global' )
182 $tablePrefix = $tablePrefix == 'get from global' ?
$tablePrefix : strtoupper( $tablePrefix );
183 parent
::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
184 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
191 function cascadingDeletes() {
194 function cleanupTriggers() {
197 function strictIPs() {
200 function realTimestamps() {
203 function implicitGroupby() {
206 function implicitOrderby() {
209 function searchableIPs() {
214 * Usually aborts on failure
216 function open( $server, $user, $password, $dbName ) {
217 if ( !function_exists( 'oci_connect' ) ) {
218 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" );
222 $this->mUser
= $user;
223 $this->mPassword
= $password;
224 // changed internal variables functions
225 // mServer now holds the TNS endpoint
226 // mDBname is schema name if different from username
228 // backward compatibillity (server used to be null and TNS was supplied in dbname)
229 $this->mServer
= $dbName;
230 $this->mDBname
= $user;
232 $this->mServer
= $server;
234 $this->mDBname
= $user;
236 $this->mDBname
= $dbName;
240 if ( !strlen( $user ) ) { # e.g. the class is being loaded
244 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
245 wfSuppressWarnings();
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 );
253 if ( $this->mUser
!= $this->mDBname
) {
254 //change current schema in session
255 $this->selectDB( $this->mDBname
);
258 if ( !$this->mConn
) {
259 throw new DBConnectionError( $this, $this->lastError() );
262 $this->mOpened
= true;
264 # removed putenv calls because they interfere with the system globaly
265 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
266 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
271 * Closes a database connection, if it is open
272 * Returns success, true if already closed
275 $this->mOpened
= false;
276 if ( $this->mConn
) {
277 return oci_close( $this->mConn
);
283 function execFlags() {
284 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
287 function doQuery( $sql ) {
288 wfDebug( "SQL: [$sql]\n" );
289 if ( !mb_check_encoding( $sql ) ) {
290 throw new MWException( "SQL encoding is invalid\n$sql" );
293 // handle some oracle specifics
294 // remove AS column/table/subquery namings
295 if( !$this->getFlag( DBO_DDLMODE
) ) {
296 $sql = preg_replace( '/ as /i', ' ', $sql );
299 // Oracle has issues with UNION clause if the statement includes LOB fields
300 // So we do a UNION ALL and then filter the results array with array_unique
301 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
302 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
303 // you have to select data from plan table after explain
304 $explain_id = date( 'dmYHis' );
306 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
308 wfSuppressWarnings();
310 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
311 $e = oci_error( $this->mConn
);
312 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
316 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
317 $e = oci_error( $stmt );
318 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
319 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
326 if ( $explain_count > 0 ) {
327 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
328 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
329 return new ORAResult( $this, $stmt, $union_unique );
331 $this->mAffectedRows
= oci_num_rows( $stmt );
336 function queryIgnore( $sql, $fname = '' ) {
337 return $this->query( $sql, $fname, true );
340 function freeResult( $res ) {
341 if ( $res instanceof ResultWrapper
) {
348 function fetchObject( $res ) {
349 if ( $res instanceof ResultWrapper
) {
353 return $res->fetchObject();
356 function fetchRow( $res ) {
357 if ( $res instanceof ResultWrapper
) {
361 return $res->fetchRow();
364 function numRows( $res ) {
365 if ( $res instanceof ResultWrapper
) {
369 return $res->numRows();
372 function numFields( $res ) {
373 if ( $res instanceof ResultWrapper
) {
377 return $res->numFields();
380 function fieldName( $stmt, $n ) {
381 return oci_field_name( $stmt, $n );
385 * This must be called after nextSequenceVal
387 function insertId() {
388 return $this->mInsertId
;
391 function dataSeek( $res, $row ) {
392 if ( $res instanceof ORAResult
) {
395 $res->result
->seek( $row );
399 function lastError() {
400 if ( $this->mConn
=== false ) {
403 $e = oci_error( $this->mConn
);
405 return $e['message'];
408 function lastErrno() {
409 if ( $this->mConn
=== false ) {
412 $e = oci_error( $this->mConn
);
417 function affectedRows() {
418 return $this->mAffectedRows
;
422 * Returns information about an index
423 * If errors are explicitly ignored, returns NULL on failure
425 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
429 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
433 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
434 if ( !count( $a ) ) {
438 if ( !is_array( $options ) ) {
439 $options = array( $options );
442 if ( in_array( 'IGNORE', $options ) ) {
443 $this->ignore_DUP_VAL_ON_INDEX
= true;
446 if ( !is_array( reset( $a ) ) ) {
450 foreach ( $a as &$row ) {
451 $this->insertOneRow( $table, $row, $fname );
455 if ( in_array( 'IGNORE', $options ) ) {
456 $this->ignore_DUP_VAL_ON_INDEX
= false;
462 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
463 $col_info = $this->fieldInfoMulti( $table, $col );
464 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
467 if ( is_numeric( $col ) ) {
471 } else if ( $includeCol ) {
475 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
479 if ( $val === null ) {
480 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
492 private function insertOneRow( $table, $row, $fname ) {
495 $table = $this->tableName( $table );
496 // "INSERT INTO tables (a, b, c)"
497 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
500 // for each value, append ":key"
502 foreach ( $row as $col => &$val ) {
509 $sql .= $this->fieldBindStatement( $table, $col, $val );
513 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
514 $e = oci_error( $this->mConn
);
515 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
518 foreach ( $row as $col => &$val ) {
519 $col_info = $this->fieldInfoMulti( $table, $col );
520 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
522 if ( $val === null ) {
523 // do nothing ... null was inserted in statement creation
524 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
525 if ( is_object( $val ) ) {
526 $val = $val->fetch();
529 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
530 $val = '31-12-2030 12:00:00.000000';
533 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
534 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
535 $e = oci_error( $stmt );
536 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
540 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
541 $e = oci_error( $stmt );
542 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
545 if ( is_object( $val ) ) {
546 $val = $val->fetch();
549 if ( $col_type == 'BLOB' ) {
550 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
551 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB
);
553 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
554 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
559 wfSuppressWarnings();
561 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
562 $e = oci_error( $stmt );
563 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
564 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
567 $this->mAffectedRows
= oci_num_rows( $stmt );
570 $this->mAffectedRows
= oci_num_rows( $stmt );
575 if ( isset( $lob ) ) {
576 foreach ( $lob as $lob_v ) {
581 if ( !$this->mTrxLevel
) {
582 oci_commit( $this->mConn
);
585 oci_free_statement( $stmt );
588 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
589 $insertOptions = array(), $selectOptions = array() )
591 $destTable = $this->tableName( $destTable );
592 if ( !is_array( $selectOptions ) ) {
593 $selectOptions = array( $selectOptions );
595 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
596 if ( is_array( $srcTable ) ) {
597 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
599 $srcTable = $this->tableName( $srcTable );
602 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
603 !isset( $varMap[$sequenceData['column']] ) )
605 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
608 // count-alias subselect fields to avoid abigious definition errors
610 foreach ( $varMap as &$val ) {
611 $val = $val . ' field' . ( $i++
);
614 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
615 " SELECT $startOpts " . implode( ',', $varMap ) .
616 " FROM $srcTable $useIndex ";
617 if ( $conds != '*' ) {
618 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
620 $sql .= " $tailOpts";
622 if ( in_array( 'IGNORE', $insertOptions ) ) {
623 $this->ignore_DUP_VAL_ON_INDEX
= true;
626 $retval = $this->query( $sql, $fname );
628 if ( in_array( 'IGNORE', $insertOptions ) ) {
629 $this->ignore_DUP_VAL_ON_INDEX
= false;
635 function tableName( $name ) {
636 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
638 Replace reserved words with better ones
639 Using uppercase because that's the only way Oracle can handle
647 $name = 'PAGECONTENT';
652 The rest of procedure is equal to generic Databse class
653 except for the quoting style
655 if ( $name[0] == '"' && substr( $name, - 1, 1 ) == '"' ) {
658 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
661 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
662 if ( isset( $dbDetails[1] ) ) {
663 @list
( $table, $database ) = $dbDetails;
665 @list
( $table ) = $dbDetails;
668 $prefix = $this->mTablePrefix
;
670 if ( isset( $database ) ) {
671 $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
674 if ( !isset( $database ) && isset( $wgSharedDB ) && $table[0] != '"'
675 && isset( $wgSharedTables )
676 && is_array( $wgSharedTables )
677 && in_array( $table, $wgSharedTables )
679 $database = $wgSharedDB;
680 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
683 if ( isset( $database ) ) {
684 $database = ( $database[0] == '"' ?
$database : "\"{$database}\"" );
686 $table = ( $table[0] == '"') ?
$table : "\"{$prefix}{$table}\"" ;
688 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
690 return strtoupper( $tableName );
694 * Return the next in a sequence, save the value for retrieval via insertId()
696 function nextSequenceValue( $seqName ) {
697 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
698 $row = $this->fetchRow( $res );
699 $this->mInsertId
= $row[0];
700 return $this->mInsertId
;
704 * Return sequence_name if table has a sequence
706 private function getSequenceData( $table ) {
707 if ( $this->sequenceData
== null ) {
708 $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\'' );
710 while ( ( $row = $result->fetchRow() ) !== false ) {
711 $this->sequenceData
[$this->tableName( $row[1] )] = array(
712 'sequence' => $row[0],
718 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
722 * REPLACE query wrapper
723 * Oracle simulates this with a DELETE followed by INSERT
724 * $row is the row to insert, an associative array
725 * $uniqueIndexes is an array of indexes. Each element may be either a
726 * field name or an array of field names
728 * It may be more efficient to leave off unique indexes which are unlikely to collide.
729 * However if you do this, you run the risk of encountering errors which wouldn't have
732 * @param $table String: table name
733 * @param $uniqueIndexes Array: array of indexes. Each element may be
734 * either a field name or an array of field names
735 * @param $rows Array: rows to insert to $table
736 * @param $fname String: function name, you can use __METHOD__ here
738 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
739 $table = $this->tableName( $table );
741 if ( count( $rows ) == 0 ) {
746 if ( !is_array( reset( $rows ) ) ) {
747 $rows = array( $rows );
750 $sequenceData = $this->getSequenceData( $table );
752 foreach ( $rows as $row ) {
753 # Delete rows which collide
754 if ( $uniqueIndexes ) {
755 $condsDelete = array();
756 foreach ( $uniqueIndexes as $index ) {
757 $condsDelete[$index] = $row[$index];
759 if ( count( $condsDelete ) > 0 ) {
760 $this->delete( $table, $condsDelete, $fname );
764 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
765 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
769 $this->insert( $table, $row, $fname );
773 # DELETE where the condition is a join
774 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
776 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
779 $delTable = $this->tableName( $delTable );
780 $joinTable = $this->tableName( $joinTable );
781 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
782 if ( $conds != '*' ) {
783 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
787 $this->query( $sql, $fname );
790 # Returns the size of a text field, or -1 for "unlimited"
791 function textFieldSize( $table, $field ) {
792 $fieldInfoData = $this->fieldInfo( $table, $field );
793 return $fieldInfoData->maxLength();
796 function limitResult( $sql, $limit, $offset = false ) {
797 if ( $offset === false ) {
800 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
803 function encodeBlob( $b ) {
804 return new Blob( $b );
807 function decodeBlob( $b ) {
808 if ( $b instanceof Blob
) {
814 function unionQueries( $sqls, $all ) {
815 $glue = ' UNION ALL ';
816 return 'SELECT * ' . ( $all ?
'':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
819 function wasDeadlock() {
820 return $this->lastErrno() == 'OCI-00060';
823 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
826 $temporary = $temporary ?
'TRUE' : 'FALSE';
828 $newName = trim( strtoupper( $newName ), '"');
829 $oldName = trim( strtoupper( $oldName ), '"');
831 $tabName = substr( $newName, strlen( $wgDBprefix ) );
832 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
834 return $this->doQuery( 'BEGIN DUPLICATE_TABLE(\'' . $tabName . '\', \'' . $oldPrefix . '\', \'' . strtoupper( $wgDBprefix ) . '\', ' . $temporary . '); END;' );
837 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
839 if (!empty($prefix)) {
840 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
843 $result = $this->doQuery( "SELECT table_name FROM user_tables WHERE table_name NOT LIKE '%!_IDX$_' ESCAPE '!' $listWhere" );
845 // dirty code ... i know
847 $endArray[] = $prefix.'MWUSER';
848 $endArray[] = $prefix.'PAGE';
849 $endArray[] = $prefix.'IMAGE';
850 $fixedOrderTabs = $endArray;
851 while (($row = $result->fetchRow()) !== false) {
852 if (!in_array($row['table_name'], $fixedOrderTabs))
853 $endArray[] = $row['table_name'];
859 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
860 $tableName = $this->tableName($tableName);
861 if( !$this->tableExists( $tableName ) ) {
865 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
868 function timestamp( $ts = 0 ) {
869 return wfTimestamp( TS_ORACLE
, $ts );
873 * Return aggregated value function call
875 function aggregateValue ( $valuedata, $valuename = 'value' ) {
879 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
880 # Ignore errors during error handling to avoid infinite
882 $ignore = $this->ignoreErrors( true );
883 ++
$this->mErrorCount
;
885 if ( $ignore ||
$tempIgnore ) {
886 wfDebug( "SQL ERROR (ignored): $error\n" );
887 $this->ignoreErrors( $ignore );
889 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
894 * @return string wikitext of a link to the server software's web site
896 public static function getSoftwareLink() {
897 return '[http://www.oracle.com/ Oracle]';
901 * @return string Version information from the database
903 function getServerVersion() {
904 //better version number, fallback on driver
905 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
906 if ( !( $row = $rset->fetchRow() ) ) {
907 return oci_server_version( $this->mConn
);
909 return $row['version'];
913 * Query whether a given table exists (in the given schema, or the default mw one if not given)
915 function tableExists( $table ) {
916 $table = trim($this->tableName($table), '"');
917 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
918 $res = $this->doQuery( $SQL );
920 $count = $res->numRows();
929 * Function translates mysql_fetch_field() functionality on ORACLE.
930 * Caching is present for reducing query time.
931 * For internal calls. Use fieldInfo for normal usage.
932 * Returns false if the field doesn't exist
934 * @param $table Array
935 * @param $field String
938 private function fieldInfoMulti( $table, $field ) {
939 $field = strtoupper( $field );
940 if ( is_array( $table ) ) {
941 $table = array_map( array( &$this, 'tableName' ), $table );
942 $tableWhere = 'IN (';
943 foreach( $table as &$singleTable ) {
944 $singleTable = strtoupper( trim( $singleTable, '"' ) );
945 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
946 return $this->mFieldInfoCache
["$singleTable.$field"];
948 $tableWhere .= '\'' . $singleTable . '\',';
950 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
952 $table = strtoupper( trim( $this->tableName( $table ), '"' ) );
953 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
954 return $this->mFieldInfoCache
["$table.$field"];
956 $tableWhere = '= \''.$table.'\'';
959 $fieldInfoStmt = oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
960 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT
) === false ) {
961 $e = oci_error( $fieldInfoStmt );
962 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
965 $res = new ORAResult( $this, $fieldInfoStmt );
966 if ( $res->numRows() == 0 ) {
967 if ( is_array( $table ) ) {
968 foreach( $table as &$singleTable ) {
969 $this->mFieldInfoCache
["$singleTable.$field"] = false;
972 $this->mFieldInfoCache
["$table.$field"] = false;
974 $fieldInfoTemp = null;
976 $fieldInfoTemp = new ORAField( $res->fetchRow() );
977 $table = $fieldInfoTemp->tableName();
978 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
981 return $fieldInfoTemp;
985 * @throws DBUnexpectedError
990 function fieldInfo( $table, $field ) {
991 if ( is_array( $table ) ) {
992 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
994 return $this->fieldInfoMulti ($table, $field);
997 function begin( $fname = '' ) {
998 $this->mTrxLevel
= 1;
1001 function commit( $fname = '' ) {
1002 oci_commit( $this->mConn
);
1003 $this->mTrxLevel
= 0;
1006 /* Not even sure why this is used in the main codebase... */
1007 function limitResultForUpdate( $sql, $num ) {
1011 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
1012 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
1015 $dollarquote = false;
1017 $replacements = array();
1019 while ( ! feof( $fp ) ) {
1020 if ( $lineCallback ) {
1021 call_user_func( $lineCallback );
1023 $line = trim( fgets( $fp, 1024 ) );
1024 $sl = strlen( $line ) - 1;
1029 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1033 // Allow dollar quoting for function declarations
1034 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1035 if ( $dollarquote ) {
1036 $dollarquote = false;
1037 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1040 $dollarquote = true;
1042 } elseif ( !$dollarquote ) {
1043 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
1045 $line = substr( $line, 0, $sl );
1055 $cmd = str_replace( ';;', ";", $cmd );
1056 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1057 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1058 $replacements[$defines[2]] = $defines[1];
1061 foreach ( $replacements as $mwVar => $scVar ) {
1062 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1065 $cmd = $this->replaceVars( $cmd );
1066 $res = $this->doQuery( $cmd );
1067 if ( $resultCallback ) {
1068 call_user_func( $resultCallback, $res, $this );
1071 if ( false === $res ) {
1072 $err = $this->lastError();
1073 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1084 function selectDB( $db ) {
1085 $this->mDBname
= $db;
1086 if ( $db == null ||
$db == $this->mUser
) {
1089 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1090 $stmt = oci_parse( $this->mConn
, $sql );
1091 wfSuppressWarnings();
1092 $success = oci_execute( $stmt );
1093 wfRestoreWarnings();
1095 $e = oci_error( $stmt );
1096 if ( $e['code'] != '1435' ) {
1097 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1104 function strencode( $s ) {
1105 return str_replace( "'", "''", $s );
1108 function addQuotes( $s ) {
1110 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1111 $s = $wgContLang->checkTitleEncoding( $s );
1113 return "'" . $this->strencode( $s ) . "'";
1116 public function addIdentifierQuotes( $s ) {
1117 if ( !$this->mFlags
& DBO_DDLMODE
) {
1118 $s = '"' . str_replace( '"', '""', $s ) . '"';
1123 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1126 if ($conds != null) {
1128 $conds = ( !is_array( $conds ) ) ?
array( $conds ) : $conds;
1129 foreach ( $conds as $col => $val ) {
1130 $col_info = $this->fieldInfoMulti( $table, $col );
1131 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1132 if ( $col_type == 'CLOB' ) {
1133 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1134 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1135 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1137 $conds2[$col] = $val;
1141 return parent
::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1143 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1148 * Returns an optional USE INDEX clause to go after the table, and a
1149 * string to go at the end of the query
1153 * @param $options Array: an associative array of options to be turned into
1154 * an SQL query, valid keys are listed in the function.
1157 function makeSelectOptions( $options ) {
1158 $preLimitTail = $postLimitTail = '';
1161 $noKeyOptions = array();
1162 foreach ( $options as $key => $option ) {
1163 if ( is_numeric( $key ) ) {
1164 $noKeyOptions[$option] = true;
1168 if ( isset( $options['GROUP BY'] ) ) {
1169 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1171 if ( isset( $options['ORDER BY'] ) ) {
1172 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1175 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1176 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1177 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1178 $startOpts .= 'DISTINCT';
1181 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1182 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1187 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1190 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1193 if ( $wgContLang != null && $conds != null && $conds != '*' ) {
1195 $conds = ( !is_array( $conds ) ) ?
array( $conds ) : $conds;
1196 foreach ( $conds as $col => $val ) {
1197 $col_info = $this->fieldInfoMulti( $table, $col );
1198 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1199 if ( $col_type == 'CLOB' ) {
1200 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1202 if ( is_array( $val ) ) {
1203 $conds2[$col] = $val;
1204 foreach ( $conds2[$col] as &$val2 ) {
1205 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1208 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1213 return parent
::delete( $table, $conds2, $fname );
1215 return parent
::delete( $table, $conds, $fname );
1219 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1222 $table = $this->tableName( $table );
1223 $opts = $this->makeUpdateOptions( $options );
1224 $sql = "UPDATE $opts $table SET ";
1227 foreach ( $values as $col => &$val ) {
1228 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1231 $sqlSet = ', ' . $sqlSet;
1238 if ( $conds != '*' ) {
1239 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1242 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1243 $e = oci_error( $this->mConn
);
1244 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1247 foreach ( $values as $col => &$val ) {
1248 $col_info = $this->fieldInfoMulti( $table, $col );
1249 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1251 if ( $val === null ) {
1252 // do nothing ... null was inserted in statement creation
1253 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1254 if ( is_object( $val ) ) {
1255 $val = $val->getData();
1258 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1259 $val = '31-12-2030 12:00:00.000000';
1262 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1263 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1264 $e = oci_error( $stmt );
1265 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1269 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1270 $e = oci_error( $stmt );
1271 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1274 if ( $col_type == 'BLOB' ) {
1275 $lob[$col]->writeTemporary( $val );
1276 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
1278 $lob[$col]->writeTemporary( $val );
1279 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
1284 wfSuppressWarnings();
1286 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
1287 $e = oci_error( $stmt );
1288 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
1289 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1292 $this->mAffectedRows
= oci_num_rows( $stmt );
1295 $this->mAffectedRows
= oci_num_rows( $stmt );
1298 wfRestoreWarnings();
1300 if ( isset( $lob ) ) {
1301 foreach ( $lob as $lob_v ) {
1306 if ( !$this->mTrxLevel
) {
1307 oci_commit( $this->mConn
);
1310 oci_free_statement( $stmt );
1313 function bitNot( $field ) {
1314 // expecting bit-fields smaller than 4bytes
1315 return 'BITNOT(' . $field . ')';
1318 function bitAnd( $fieldLeft, $fieldRight ) {
1319 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1322 function bitOr( $fieldLeft, $fieldRight ) {
1323 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1326 function setFakeMaster( $enabled = true ) { }
1328 function getDBname() {
1329 return $this->mDBname
;
1332 function getServer() {
1333 return $this->mServer
;
1336 public function getSearchEngine() {
1337 return 'SearchOracle';
1339 } // end DatabaseOracle class