3 * This is the Oracle database abstraction layer.
15 function __construct( $data ) {
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;
52 function __construct( &$db, $stmt, $unique = false ) {
55 if ( ( $this->nrows
= oci_fetch_all( $stmt, $this->rows
, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM
) ) === false ) {
56 $e = oci_error( $stmt );
57 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__
);
63 $this->rows
= $this->array_unique_md( $this->rows
);
64 $this->nrows
= count( $this->rows
);
67 if ($this->nrows
> 0) {
68 foreach ( $this->rows
[0] as $k => $v ) {
69 $this->columns
[$k] = strtolower( oci_field_name( $stmt, $k +
1 ) );
74 oci_free_statement( $stmt );
77 public function free() {
81 public function seek( $row ) {
82 $this->cursor
= min( $row, $this->nrows
);
85 public function numRows() {
89 public function numFields() {
90 return count($this->columns
);
93 public function fetchObject() {
94 if ( $this->cursor
>= $this->nrows
) {
97 $row = $this->rows
[$this->cursor++
];
98 $ret = new stdClass();
99 foreach ( $row as $k => $v ) {
100 $lc = $this->columns
[$k];
107 public function fetchRow() {
108 if ( $this->cursor
>= $this->nrows
) {
112 $row = $this->rows
[$this->cursor++
];
114 foreach ( $row as $k => $v ) {
115 $lc = $this->columns
[$k];
128 private $name, $tablename, $default, $max_length, $nullable,
129 $is_pk, $is_unique, $is_multiple, $is_key, $type;
131 function __construct( $info ) {
132 $this->name
= $info['column_name'];
133 $this->tablename
= $info['table_name'];
134 $this->default = $info['data_default'];
135 $this->max_length
= $info['data_length'];
136 $this->nullable
= $info['not_null'];
137 $this->is_pk
= isset( $info['prim'] ) && $info['prim'] == 1 ?
1 : 0;
138 $this->is_unique
= isset( $info['uniq'] ) && $info['uniq'] == 1 ?
1 : 0;
139 $this->is_multiple
= isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ?
1 : 0;
140 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
141 $this->type
= $info['data_type'];
148 function tableName() {
149 return $this->tablename
;
152 function defaultValue() {
153 return $this->default;
156 function maxLength() {
157 return $this->max_length
;
160 function nullable() {
161 return $this->nullable
;
165 return $this->is_key
;
168 function isMultipleKey() {
169 return $this->is_multiple
;
180 class DatabaseOracle
extends DatabaseBase
{
181 var $mInsertId = null;
182 var $mLastResult = null;
183 var $numeric_version = null;
184 var $lastResult = null;
188 var $ignore_DUP_VAL_ON_INDEX = false;
189 var $sequenceData = null;
191 var $defaultCharset = 'AL32UTF8';
193 var $mFieldInfoCache = array();
195 function __construct( $server = false, $user = false, $password = false, $dbName = false,
196 $flags = 0, $tablePrefix = 'get from global' )
198 $tablePrefix = $tablePrefix == 'get from global' ?
$tablePrefix : strtoupper( $tablePrefix );
199 parent
::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
200 wfRunHooks( 'DatabaseOraclePostInit', array( &$this ) );
207 function cascadingDeletes() {
210 function cleanupTriggers() {
213 function strictIPs() {
216 function realTimestamps() {
219 function implicitGroupby() {
222 function implicitOrderby() {
225 function searchableIPs() {
229 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 )
231 return new DatabaseOracle( $server, $user, $password, $dbName, $flags );
235 * Usually aborts on failure
237 function open( $server, $user, $password, $dbName ) {
238 if ( !function_exists( 'oci_connect' ) ) {
239 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" );
243 $this->mUser
= $user;
244 $this->mPassword
= $password;
245 // changed internal variables functions
246 // mServer now holds the TNS endpoint
247 // mDBname is schema name if different from username
249 // backward compatibillity (server used to be null and TNS was supplied in dbname)
250 $this->mServer
= $dbName;
251 $this->mDBname
= $user;
253 $this->mServer
= $server;
255 $this->mDBname
= $user;
257 $this->mDBname
= $dbName;
261 if ( !strlen( $user ) ) { # e.g. the class is being loaded
265 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
266 if ( $this->mFlags
& DBO_DEFAULT
) {
267 $this->mConn
= oci_new_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
269 $this->mConn
= oci_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
272 if ( $this->mUser
!= $this->mDBname
) {
273 //change current schema in session
274 $this->selectDB( $this->mDBname
);
277 if ( !$this->mConn
) {
278 throw new DBConnectionError( $this, $this->lastError() );
281 $this->mOpened
= true;
283 # removed putenv calls because they interfere with the system globaly
284 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
285 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
290 * Closes a database connection, if it is open
291 * Returns success, true if already closed
294 $this->mOpened
= false;
295 if ( $this->mConn
) {
296 return oci_close( $this->mConn
);
302 function execFlags() {
303 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
306 function doQuery( $sql ) {
307 wfDebug( "SQL: [$sql]\n" );
308 if ( !mb_check_encoding( $sql ) ) {
309 throw new MWException( "SQL encoding is invalid\n$sql" );
312 // handle some oracle specifics
313 // remove AS column/table/subquery namings
314 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
315 $sql = preg_replace( '/ as /i', ' ', $sql );
317 // Oracle has issues with UNION clause if the statement includes LOB fields
318 // So we do a UNION ALL and then filter the results array with array_unique
319 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
320 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
321 // you have to select data from plan table after explain
322 $explain_id = date( 'dmYHis' );
324 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
326 wfSuppressWarnings();
328 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
329 $e = oci_error( $this->mConn
);
330 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
334 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
335 $e = oci_error( $stmt );
336 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
337 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
344 if ( $explain_count > 0 ) {
345 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
346 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
347 return new ORAResult( $this, $stmt, $union_unique );
349 $this->mAffectedRows
= oci_num_rows( $stmt );
354 function queryIgnore( $sql, $fname = '' ) {
355 return $this->query( $sql, $fname, true );
358 function freeResult( $res ) {
359 if ( $res instanceof ResultWrapper
) {
366 function fetchObject( $res ) {
367 if ( $res instanceof ResultWrapper
) {
371 return $res->fetchObject();
374 function fetchRow( $res ) {
375 if ( $res instanceof ResultWrapper
) {
379 return $res->fetchRow();
382 function numRows( $res ) {
383 if ( $res instanceof ResultWrapper
) {
387 return $res->numRows();
390 function numFields( $res ) {
391 if ( $res instanceof ResultWrapper
) {
395 return $res->numFields();
398 function fieldName( $stmt, $n ) {
399 return oci_field_name( $stmt, $n );
403 * This must be called after nextSequenceVal
405 function insertId() {
406 return $this->mInsertId
;
409 function dataSeek( $res, $row ) {
410 if ( $res instanceof ORAResult
) {
413 $res->result
->seek( $row );
417 function lastError() {
418 if ( $this->mConn
=== false ) {
421 $e = oci_error( $this->mConn
);
423 return $e['message'];
426 function lastErrno() {
427 if ( $this->mConn
=== false ) {
430 $e = oci_error( $this->mConn
);
435 function affectedRows() {
436 return $this->mAffectedRows
;
440 * Returns information about an index
441 * If errors are explicitly ignored, returns NULL on failure
443 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
447 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
451 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
452 if ( !count( $a ) ) {
456 if ( !is_array( $options ) ) {
457 $options = array( $options );
460 if ( in_array( 'IGNORE', $options ) ) {
461 $this->ignore_DUP_VAL_ON_INDEX
= true;
464 if ( !is_array( reset( $a ) ) ) {
468 foreach ( $a as &$row ) {
469 $this->insertOneRow( $table, $row, $fname );
473 if ( in_array( 'IGNORE', $options ) ) {
474 $this->ignore_DUP_VAL_ON_INDEX
= false;
480 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
481 $col_info = $this->fieldInfoMulti( $table, $col );
482 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
485 if ( is_numeric( $col ) ) {
489 } else if ( $includeCol ) {
493 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
497 if ( $val === null ) {
498 if ( $col_info != false && $col_info->nullable() == 0 && $col_info->defaultValue() != null ) {
510 private function insertOneRow( $table, $row, $fname ) {
513 $table = $this->tableName( $table );
514 // "INSERT INTO tables (a, b, c)"
515 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
518 // for each value, append ":key"
520 foreach ( $row as $col => &$val ) {
527 $sql .= $this->fieldBindStatement( $table, $col, $val );
531 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
532 $e = oci_error( $this->mConn
);
533 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
536 foreach ( $row as $col => &$val ) {
537 $col_info = $this->fieldInfoMulti( $table, $col );
538 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
540 if ( $val === null ) {
541 // do nothing ... null was inserted in statement creation
542 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
543 if ( is_object( $val ) ) {
544 $val = $val->fetch();
547 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
548 $val = '31-12-2030 12:00:00.000000';
551 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
552 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
553 $e = oci_error( $stmt );
554 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
558 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
559 $e = oci_error( $stmt );
560 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
563 if ( is_object( $val ) ) {
564 $val = $val->fetch();
567 if ( $col_type == 'BLOB' ) {
568 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
569 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB
);
571 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
572 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
577 wfSuppressWarnings();
579 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
580 $e = oci_error( $stmt );
581 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
582 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
585 $this->mAffectedRows
= oci_num_rows( $stmt );
588 $this->mAffectedRows
= oci_num_rows( $stmt );
593 if ( isset( $lob ) ) {
594 foreach ( $lob as $lob_v ) {
599 if ( !$this->mTrxLevel
) {
600 oci_commit( $this->mConn
);
603 oci_free_statement( $stmt );
606 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
607 $insertOptions = array(), $selectOptions = array() )
609 $destTable = $this->tableName( $destTable );
610 if ( !is_array( $selectOptions ) ) {
611 $selectOptions = array( $selectOptions );
613 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
614 if ( is_array( $srcTable ) ) {
615 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
617 $srcTable = $this->tableName( $srcTable );
620 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
621 !isset( $varMap[$sequenceData['column']] ) )
623 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
626 // count-alias subselect fields to avoid abigious definition errors
628 foreach ( $varMap as &$val ) {
629 $val = $val . ' field' . ( $i++
);
632 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
633 " SELECT $startOpts " . implode( ',', $varMap ) .
634 " FROM $srcTable $useIndex ";
635 if ( $conds != '*' ) {
636 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
638 $sql .= " $tailOpts";
640 if ( in_array( 'IGNORE', $insertOptions ) ) {
641 $this->ignore_DUP_VAL_ON_INDEX
= true;
644 $retval = $this->query( $sql, $fname );
646 if ( in_array( 'IGNORE', $insertOptions ) ) {
647 $this->ignore_DUP_VAL_ON_INDEX
= false;
653 function tableName( $name ) {
654 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
656 Replace reserved words with better ones
657 Using uppercase because that's the only way Oracle can handle
665 $name = 'PAGECONTENT';
670 The rest of procedure is equal to generic Databse class
671 except for the quoting style
673 if ( $name[0] == '"' && substr( $name, - 1, 1 ) == '"' ) {
676 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
679 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
680 if ( isset( $dbDetails[1] ) ) {
681 @list
( $table, $database ) = $dbDetails;
683 @list
( $table ) = $dbDetails;
686 $prefix = $this->mTablePrefix
;
688 if ( isset( $database ) ) {
689 $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
692 if ( !isset( $database ) && isset( $wgSharedDB ) && $table[0] != '"'
693 && isset( $wgSharedTables )
694 && is_array( $wgSharedTables )
695 && in_array( $table, $wgSharedTables )
697 $database = $wgSharedDB;
698 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
701 if ( isset( $database ) ) {
702 $database = ( $database[0] == '"' ?
$database : "\"{$database}\"" );
704 $table = ( $table[0] == '"') ?
$table : "\"{$prefix}{$table}\"" ;
706 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
708 return strtoupper( $tableName );
712 * Return the next in a sequence, save the value for retrieval via insertId()
714 function nextSequenceValue( $seqName ) {
715 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
716 $row = $this->fetchRow( $res );
717 $this->mInsertId
= $row[0];
718 return $this->mInsertId
;
722 * Return sequence_name if table has a sequence
724 private function getSequenceData( $table ) {
725 if ( $this->sequenceData
== null ) {
726 $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\'' );
728 while ( ( $row = $result->fetchRow() ) !== false ) {
729 $this->sequenceData
[$this->tableName( $row[1] )] = array(
730 'sequence' => $row[0],
736 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
740 * REPLACE query wrapper
741 * Oracle simulates this with a DELETE followed by INSERT
742 * $row is the row to insert, an associative array
743 * $uniqueIndexes is an array of indexes. Each element may be either a
744 * field name or an array of field names
746 * It may be more efficient to leave off unique indexes which are unlikely to collide.
747 * However if you do this, you run the risk of encountering errors which wouldn't have
750 * @param $table String: table name
751 * @param $uniqueIndexes Array: array of indexes. Each element may be
752 * either a field name or an array of field names
753 * @param $rows Array: rows to insert to $table
754 * @param $fname String: function name, you can use __METHOD__ here
756 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
757 $table = $this->tableName( $table );
759 if ( count( $rows ) == 0 ) {
764 if ( !is_array( reset( $rows ) ) ) {
765 $rows = array( $rows );
768 $sequenceData = $this->getSequenceData( $table );
770 foreach ( $rows as $row ) {
771 # Delete rows which collide
772 if ( $uniqueIndexes ) {
773 $condsDelete = array();
774 foreach ( $uniqueIndexes as $index ) {
775 $condsDelete[$index] = $row[$index];
777 if ( count( $condsDelete ) > 0 ) {
778 $this->delete( $table, $condsDelete, $fname );
782 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
783 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
787 $this->insert( $table, $row, $fname );
791 # DELETE where the condition is a join
792 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
794 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
797 $delTable = $this->tableName( $delTable );
798 $joinTable = $this->tableName( $joinTable );
799 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
800 if ( $conds != '*' ) {
801 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
805 $this->query( $sql, $fname );
808 # Returns the size of a text field, or -1 for "unlimited"
809 function textFieldSize( $table, $field ) {
810 $fieldInfoData = $this->fieldInfo( $table, $field);
811 if ( $fieldInfoData->type
== 'varchar' ) {
812 $size = $row->size
- 4;
819 function limitResult( $sql, $limit, $offset = false ) {
820 if ( $offset === false ) {
823 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
826 function encodeBlob( $b ) {
827 return new Blob( $b );
830 function decodeBlob( $b ) {
831 if ( $b instanceof Blob
) {
837 function unionQueries( $sqls, $all ) {
838 $glue = ' UNION ALL ';
839 return 'SELECT * ' . ( $all ?
'':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
842 function wasDeadlock() {
843 return $this->lastErrno() == 'OCI-00060';
846 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
849 $temporary = $temporary ?
'TRUE' : 'FALSE';
851 $newName = trim( strtoupper( $newName ), '"');
852 $oldName = trim( strtoupper( $oldName ), '"');
854 $tabName = substr( $newName, strlen( $wgDBprefix ) );
855 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
857 return $this->doQuery( 'BEGIN DUPLICATE_TABLE(\'' . $tabName . '\', \'' . $oldPrefix . '\', \'' . strtoupper( $wgDBprefix ) . '\', ' . $temporary . '); END;' );
860 function timestamp( $ts = 0 ) {
861 return wfTimestamp( TS_ORACLE
, $ts );
865 * Return aggregated value function call
867 function aggregateValue ( $valuedata, $valuename = 'value' ) {
871 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
872 # Ignore errors during error handling to avoid infinite
874 $ignore = $this->ignoreErrors( true );
875 ++
$this->mErrorCount
;
877 if ( $ignore ||
$tempIgnore ) {
878 wfDebug( "SQL ERROR (ignored): $error\n" );
879 $this->ignoreErrors( $ignore );
881 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
886 * @return string wikitext of a link to the server software's web site
888 public static function getSoftwareLink() {
889 return '[http://www.oracle.com/ Oracle]';
893 * @return string Version information from the database
895 function getServerVersion() {
896 //better version number, fallback on driver
897 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
898 if ( !( $row = $rset->fetchRow() ) ) {
899 return oci_server_version( $this->mConn
);
901 return $row['version'];
905 * Query whether a given table exists (in the given schema, or the default mw one if not given)
907 function tableExists( $table ) {
908 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
909 $res = $this->doQuery( $SQL );
911 $count = $res->numRows();
920 * Function translates mysql_fetch_field() functionality on ORACLE.
921 * Caching is present for reducing query time.
922 * For internal calls. Use fieldInfo for normal usage.
923 * Returns false if the field doesn't exist
925 * @param $table Array
926 * @param $field String
928 private function fieldInfoMulti( $table, $field ) {
929 $field = strtoupper( $field );
930 if ( is_array( $table ) ) {
931 $table = array_map( array( &$this, 'tableName' ), $table );
932 $tableWhere = 'IN (';
933 foreach( $table as &$singleTable ) {
934 $singleTable = strtoupper( trim( $singleTable, '"' ) );
935 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
936 return $this->mFieldInfoCache
["$singleTable.$field"];
938 $tableWhere .= '\'' . $singleTable . '\',';
940 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
942 $table = strtoupper( trim( $this->tableName( $table ), '"' ) );
943 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
944 return $this->mFieldInfoCache
["$table.$field"];
946 $tableWhere = '= \''.$table.'\'';
949 $fieldInfoStmt = oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
950 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT
) === false ) {
951 $e = oci_error( $fieldInfoStmt );
952 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
955 $res = new ORAResult( $this, $fieldInfoStmt );
956 if ( $res->numRows() == 0 ) {
957 if ( is_array( $table ) ) {
958 foreach( $table as &$singleTable ) {
959 $this->mFieldInfoCache
["$singleTable.$field"] = false;
962 $this->mFieldInfoCache
["$table.$field"] = false;
964 $fieldInfoTemp = null;
966 $fieldInfoTemp = new ORAField( $res->fetchRow() );
967 $table = $fieldInfoTemp->tableName();
968 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
971 return $fieldInfoTemp;
974 function fieldInfo( $table, $field ) {
975 if ( is_array( $table ) ) {
976 throw new DBUnexpectedError( $this, 'Database::fieldInfo called with table array!' );
978 return $this->fieldInfoMulti ($table, $field);
981 function begin( $fname = '' ) {
982 $this->mTrxLevel
= 1;
985 function commit( $fname = '' ) {
986 oci_commit( $this->mConn
);
987 $this->mTrxLevel
= 0;
990 /* Not even sure why this is used in the main codebase... */
991 function limitResultForUpdate( $sql, $num ) {
995 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
996 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
999 $dollarquote = false;
1001 $replacements = array();
1003 while ( ! feof( $fp ) ) {
1004 if ( $lineCallback ) {
1005 call_user_func( $lineCallback );
1007 $line = trim( fgets( $fp, 1024 ) );
1008 $sl = strlen( $line ) - 1;
1013 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1017 // Allow dollar quoting for function declarations
1018 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1019 if ( $dollarquote ) {
1020 $dollarquote = false;
1021 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1024 $dollarquote = true;
1026 } elseif ( !$dollarquote ) {
1027 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
1029 $line = substr( $line, 0, $sl );
1039 $cmd = str_replace( ';;', ";", $cmd );
1040 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1041 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1042 $replacements[$defines[2]] = $defines[1];
1045 foreach ( $replacements as $mwVar => $scVar ) {
1046 $cmd = str_replace( '&' . $scVar . '.', '{$' . $mwVar . '}', $cmd );
1049 $cmd = $this->replaceVars( $cmd );
1050 $res = $this->doQuery( $cmd );
1051 if ( $resultCallback ) {
1052 call_user_func( $resultCallback, $res, $this );
1055 if ( false === $res ) {
1056 $err = $this->lastError();
1057 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1068 function setup_database() {
1069 $res = $this->sourceFile( "../maintenance/oracle/tables.sql" );
1070 if ( $res === true ) {
1071 print " done.</li>\n";
1073 print " <b>FAILED</b></li>\n";
1074 dieout( htmlspecialchars( $res ) );
1077 // Avoid the non-standard "REPLACE INTO" syntax
1078 echo "<li>Populating interwiki table</li>\n";
1079 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1081 dieout( "Could not find the interwiki.sql file" );
1084 // do it like the postgres :D
1085 $SQL = "INSERT INTO " . $this->tableName( 'interwiki' ) . " (iw_prefix,iw_url,iw_local) VALUES ";
1086 while ( !feof( $f ) ) {
1087 $line = fgets( $f, 1024 );
1089 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) {
1092 $this->query( "$SQL $matches[1],$matches[2])" );
1095 echo "<li>Table interwiki successfully populated</li>\n";
1098 function selectDB( $db ) {
1099 if ( $db == null ||
$db == $this->mUser
) { return true; }
1100 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1101 $stmt = oci_parse( $this->mConn
, $sql );
1102 if ( !oci_execute( $stmt ) ) {
1103 $e = oci_error( $stmt );
1104 if ( $e['code'] != '1435' ) {
1105 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1112 function strencode( $s ) {
1113 return str_replace( "'", "''", $s );
1116 function addQuotes( $s ) {
1118 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1119 $s = $wgContLang->checkTitleEncoding( $s );
1121 return "'" . $this->strencode( $s ) . "'";
1124 function quote_ident( $s ) {
1128 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1132 $conds = ( $conds != null && !is_array( $conds ) ) ?
array( $conds ) : $conds;
1133 foreach ( $conds as $col => $val ) {
1134 $col_info = $this->fieldInfoMulti( $table, $col );
1135 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1136 if ( $col_type == 'CLOB' ) {
1137 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1138 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1139 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1141 $conds2[$col] = $val;
1145 return parent
::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1149 * Returns an optional USE INDEX clause to go after the table, and a
1150 * string to go at the end of the query
1154 * @param $options Array: an associative array of options to be turned into
1155 * an SQL query, valid keys are listed in the function.
1158 function makeSelectOptions( $options ) {
1159 $preLimitTail = $postLimitTail = '';
1162 $noKeyOptions = array();
1163 foreach ( $options as $key => $option ) {
1164 if ( is_numeric( $key ) ) {
1165 $noKeyOptions[$option] = true;
1169 if ( isset( $options['GROUP BY'] ) ) {
1170 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1172 if ( isset( $options['ORDER BY'] ) ) {
1173 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1176 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1177 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1178 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1179 $startOpts .= 'DISTINCT';
1182 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1183 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1188 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1191 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1194 if ( $wgContLang != null && $conds != '*' ) {
1196 $conds = ( $conds != null && !is_array( $conds ) ) ?
array( $conds ) : $conds;
1197 foreach ( $conds as $col => $val ) {
1198 $col_info = $this->fieldInfoMulti( $table, $col );
1199 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1200 if ( $col_type == 'CLOB' ) {
1201 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1203 if ( is_array( $val ) ) {
1204 $conds2[$col] = $val;
1205 foreach ( $conds2[$col] as &$val2 ) {
1206 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1209 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1214 return parent
::delete( $table, $conds2, $fname );
1216 return parent
::delete( $table, $conds, $fname );
1220 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1223 $table = $this->tableName( $table );
1224 $opts = $this->makeUpdateOptions( $options );
1225 $sql = "UPDATE $opts $table SET ";
1228 foreach ( $values as $col => &$val ) {
1229 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1232 $sqlSet = ', ' . $sqlSet;
1239 if ( $conds != '*' ) {
1240 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1243 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1244 $e = oci_error( $this->mConn
);
1245 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1248 foreach ( $values as $col => &$val ) {
1249 $col_info = $this->fieldInfoMulti( $table, $col );
1250 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1252 if ( $val === null ) {
1253 // do nothing ... null was inserted in statement creation
1254 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1255 if ( is_object( $val ) ) {
1256 $val = $val->getData();
1259 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1260 $val = '31-12-2030 12:00:00.000000';
1263 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1264 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1265 $e = oci_error( $stmt );
1266 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1270 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1271 $e = oci_error( $stmt );
1272 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1275 if ( $col_type == 'BLOB' ) {
1276 $lob[$col]->writeTemporary( $val );
1277 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
1279 $lob[$col]->writeTemporary( $val );
1280 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
1285 wfSuppressWarnings();
1287 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
1288 $e = oci_error( $stmt );
1289 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
1290 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1293 $this->mAffectedRows
= oci_num_rows( $stmt );
1296 $this->mAffectedRows
= oci_num_rows( $stmt );
1299 wfRestoreWarnings();
1301 if ( isset( $lob ) ) {
1302 foreach ( $lob as $lob_v ) {
1307 if ( !$this->mTrxLevel
) {
1308 oci_commit( $this->mConn
);
1311 oci_free_statement( $stmt );
1314 function bitNot( $field ) {
1315 // expecting bit-fields smaller than 4bytes
1316 return 'BITNOT(' . $field . ')';
1319 function bitAnd( $fieldLeft, $fieldRight ) {
1320 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1323 function bitOr( $fieldLeft, $fieldRight ) {
1324 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1327 function setFakeMaster( $enabled = true ) { }
1329 function getDBname() {
1330 return $this->mDBname
;
1333 function getServer() {
1334 return $this->mServer
;
1337 public function replaceVars( $ins ) {
1338 $varnames = array( 'wgDBprefix' );
1339 if ( $this->mFlags
& DBO_SYSDBA
) {
1340 $varnames[] = '_OracleDefTS';
1341 $varnames[] = '_OracleTempTS';
1344 // Ordinary variables
1345 foreach ( $varnames as $var ) {
1346 if ( isset( $GLOBALS[$var] ) ) {
1347 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1348 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1349 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1350 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1354 return parent
::replaceVars( $ins );
1357 public function getSearchEngine() {
1358 return 'SearchOracle';
1360 } // end DatabaseOracle class