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.
36 private function array_unique_md( $array_in ) {
38 $array_hashes = array();
40 foreach ( $array_in as $item ) {
41 $hash = md5( serialize( $item ) );
42 if ( !isset( $array_hashes[$hash] ) ) {
43 $array_hashes[$hash] = $hash;
51 function __construct( &$db, $stmt, $unique = false ) {
54 if ( ( $this->nrows
= oci_fetch_all( $stmt, $this->rows
, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM
) ) === false ) {
55 $e = oci_error( $stmt );
56 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__
);
62 $this->rows
= $this->array_unique_md( $this->rows
);
63 $this->nrows
= count( $this->rows
);
70 public function free() {
71 oci_free_statement( $this->stmt
);
74 public function seek( $row ) {
75 $this->cursor
= min( $row, $this->nrows
);
78 public function numRows() {
82 public function numFields() {
83 return oci_num_fields( $this->stmt
);
86 public function fetchObject() {
87 if ( $this->cursor
>= $this->nrows
) {
90 $row = $this->rows
[$this->cursor++
];
91 $ret = new stdClass();
92 foreach ( $row as $k => $v ) {
93 $lc = strtolower( oci_field_name( $this->stmt
, $k +
1 ) );
100 public function fetchRow() {
101 if ( $this->cursor
>= $this->nrows
) {
105 $row = $this->rows
[$this->cursor++
];
107 foreach ( $row as $k => $v ) {
108 $lc = strtolower( oci_field_name( $this->stmt
, $k +
1 ) );
121 private $name, $tablename, $default, $max_length, $nullable,
122 $is_pk, $is_unique, $is_multiple, $is_key, $type;
124 function __construct( $info ) {
125 $this->name
= $info['column_name'];
126 $this->tablename
= $info['table_name'];
127 $this->default = $info['data_default'];
128 $this->max_length
= $info['data_length'];
129 $this->nullable
= $info['not_null'];
130 $this->is_pk
= isset( $info['prim'] ) && $info['prim'] == 1 ?
1 : 0;
131 $this->is_unique
= isset( $info['uniq'] ) && $info['uniq'] == 1 ?
1 : 0;
132 $this->is_multiple
= isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ?
1 : 0;
133 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
134 $this->type
= $info['data_type'];
141 function tableName() {
142 return $this->tablename
;
145 function defaultValue() {
146 return $this->default;
149 function maxLength() {
150 return $this->max_length
;
153 function nullable() {
154 return $this->nullable
;
158 return $this->is_key
;
161 function isMultipleKey() {
162 return $this->is_multiple
;
173 class DatabaseOracle
extends DatabaseBase
{
174 var $mInsertId = null;
175 var $mLastResult = null;
176 var $numeric_version = null;
177 var $lastResult = null;
181 var $ignore_DUP_VAL_ON_INDEX = false;
182 var $sequenceData = null;
184 var $defaultCharset = 'AL32UTF8';
186 var $mFieldInfoCache = array();
188 function __construct( $server = false, $user = false, $password = false, $dbName = false,
189 $flags = 0, $tablePrefix = 'get from global' )
191 $tablePrefix = $tablePrefix == 'get from global' ?
$tablePrefix : strtoupper( $tablePrefix );
192 parent
::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
193 wfRunHooks( 'DatabaseOraclePostInit', array( &$this ) );
200 function cascadingDeletes() {
203 function cleanupTriggers() {
206 function strictIPs() {
209 function realTimestamps() {
212 function implicitGroupby() {
215 function implicitOrderby() {
218 function searchableIPs() {
222 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 )
224 return new DatabaseOracle( $server, $user, $password, $dbName, $flags );
228 * Usually aborts on failure
230 function open( $server, $user, $password, $dbName ) {
231 if ( !function_exists( 'oci_connect' ) ) {
232 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" );
236 $this->mUser
= $user;
237 $this->mPassword
= $password;
238 // changed internal variables functions
239 // mServer now holds the TNS endpoint
240 // mDBname is schema name if different from username
242 // backward compatibillity (server used to be null and TNS was supplied in dbname)
243 $this->mServer
= $dbName;
244 $this->mDBname
= $user;
246 $this->mServer
= $server;
248 $this->mDBname
= $user;
250 $this->mDBname
= $dbName;
254 if ( !strlen( $user ) ) { # e.g. the class is being loaded
258 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
259 if ( $this->mFlags
& DBO_DEFAULT
) {
260 $this->mConn
= oci_new_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
262 $this->mConn
= oci_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
265 if ( $this->mUser
!= $this->mDBname
) {
266 //change current schema in session
267 $this->selectDB( $this->mDBname
);
270 if ( !$this->mConn
) {
271 throw new DBConnectionError( $this, $this->lastError() );
274 $this->mOpened
= true;
276 # removed putenv calls because they interfere with the system globaly
277 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
278 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
283 * Closes a database connection, if it is open
284 * Returns success, true if already closed
287 $this->mOpened
= false;
288 if ( $this->mConn
) {
289 return oci_close( $this->mConn
);
295 function execFlags() {
296 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
299 function doQuery( $sql ) {
300 wfDebug( "SQL: [$sql]\n" );
301 if ( !mb_check_encoding( $sql ) ) {
302 throw new MWException( "SQL encoding is invalid\n$sql" );
305 // handle some oracle specifics
306 // remove AS column/table/subquery namings
307 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
308 $sql = preg_replace( '/ as /i', ' ', $sql );
310 // Oracle has issues with UNION clause if the statement includes LOB fields
311 // So we do a UNION ALL and then filter the results array with array_unique
312 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
313 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
314 // you have to select data from plan table after explain
315 $explain_id = date( 'dmYHis' );
317 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
319 wfSuppressWarnings();
321 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
322 $e = oci_error( $this->mConn
);
323 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
327 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
328 $e = oci_error( $stmt );
329 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
330 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
337 if ( $explain_count > 0 ) {
338 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
339 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
340 return new ORAResult( $this, $stmt, $union_unique );
342 $this->mAffectedRows
= oci_num_rows( $stmt );
347 function queryIgnore( $sql, $fname = '' ) {
348 return $this->query( $sql, $fname, true );
351 function freeResult( $res ) {
352 if ( $res instanceof ORAResult
) {
355 $res->result
->free();
359 function fetchObject( $res ) {
360 if ( $res instanceof ORAResult
) {
361 return $res->numRows();
363 return $res->result
->fetchObject();
367 function fetchRow( $res ) {
368 if ( $res instanceof ORAResult
) {
369 return $res->fetchRow();
371 return $res->result
->fetchRow();
375 function numRows( $res ) {
376 if ( $res instanceof ORAResult
) {
377 return $res->numRows();
379 return $res->result
->numRows();
383 function numFields( $res ) {
384 if ( $res instanceof ORAResult
) {
385 return $res->numFields();
387 return $res->result
->numFields();
391 function fieldName( $stmt, $n ) {
392 return oci_field_name( $stmt, $n );
396 * This must be called after nextSequenceVal
398 function insertId() {
399 return $this->mInsertId
;
402 function dataSeek( $res, $row ) {
403 if ( $res instanceof ORAResult
) {
406 $res->result
->seek( $row );
410 function lastError() {
411 if ( $this->mConn
=== false ) {
414 $e = oci_error( $this->mConn
);
416 return $e['message'];
419 function lastErrno() {
420 if ( $this->mConn
=== false ) {
423 $e = oci_error( $this->mConn
);
428 function affectedRows() {
429 return $this->mAffectedRows
;
433 * Returns information about an index
434 * If errors are explicitly ignored, returns NULL on failure
436 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
440 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
444 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
445 if ( !count( $a ) ) {
449 if ( !is_array( $options ) ) {
450 $options = array( $options );
453 if ( in_array( 'IGNORE', $options ) ) {
454 $this->ignore_DUP_VAL_ON_INDEX
= true;
457 if ( !is_array( reset( $a ) ) ) {
461 foreach ( $a as &$row ) {
462 $this->insertOneRow( $table, $row, $fname );
466 if ( in_array( 'IGNORE', $options ) ) {
467 $this->ignore_DUP_VAL_ON_INDEX
= false;
473 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
474 $col_info = $this->fieldInfoMulti( $table, $col );
475 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
478 if ( is_numeric( $col ) ) {
482 } else if ( $includeCol ) {
486 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
490 if ( $val === null ) {
491 if ( $col_info != false && $col_info->nullable() == 0 && $col_info->defaultValue() != null ) {
503 private function insertOneRow( $table, $row, $fname ) {
506 $table = $this->tableName( $table );
507 // "INSERT INTO tables (a, b, c)"
508 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
511 // for each value, append ":key"
513 foreach ( $row as $col => &$val ) {
520 $sql .= $this->fieldBindStatement( $table, $col, $val );
524 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
525 $e = oci_error( $this->mConn
);
526 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
529 foreach ( $row as $col => &$val ) {
530 $col_info = $this->fieldInfoMulti( $table, $col );
531 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
533 if ( $val === null ) {
534 // do nothing ... null was inserted in statement creation
535 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
536 if ( is_object( $val ) ) {
537 $val = $val->getData();
540 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
541 $val = '31-12-2030 12:00:00.000000';
544 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
545 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
546 $e = oci_error( $stmt );
547 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
551 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
552 $e = oci_error( $stmt );
553 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
556 if ( $col_type == 'BLOB' ) {
557 $lob[$col]->writeTemporary( $val );
558 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
560 $lob[$col]->writeTemporary( $val );
561 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
566 wfSuppressWarnings();
568 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
569 $e = oci_error( $stmt );
570 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
571 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
574 $this->mAffectedRows
= oci_num_rows( $stmt );
577 $this->mAffectedRows
= oci_num_rows( $stmt );
582 if ( isset( $lob ) ) {
583 foreach ( $lob as $lob_v ) {
588 if ( !$this->mTrxLevel
) {
589 oci_commit( $this->mConn
);
592 oci_free_statement( $stmt );
595 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
596 $insertOptions = array(), $selectOptions = array() )
598 $destTable = $this->tableName( $destTable );
599 if ( !is_array( $selectOptions ) ) {
600 $selectOptions = array( $selectOptions );
602 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
603 if ( is_array( $srcTable ) ) {
604 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
606 $srcTable = $this->tableName( $srcTable );
609 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
610 !isset( $varMap[$sequenceData['column']] ) )
612 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
615 // count-alias subselect fields to avoid abigious definition errors
617 foreach ( $varMap as &$val ) {
618 $val = $val . ' field' . ( $i++
);
621 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
622 " SELECT $startOpts " . implode( ',', $varMap ) .
623 " FROM $srcTable $useIndex ";
624 if ( $conds != '*' ) {
625 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
627 $sql .= " $tailOpts";
629 if ( in_array( 'IGNORE', $insertOptions ) ) {
630 $this->ignore_DUP_VAL_ON_INDEX
= true;
633 $retval = $this->query( $sql, $fname );
635 if ( in_array( 'IGNORE', $insertOptions ) ) {
636 $this->ignore_DUP_VAL_ON_INDEX
= false;
642 function tableName( $name ) {
643 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
645 Replace reserved words with better ones
646 Using uppercase because that's the only way Oracle can handle
654 $name = 'PAGECONTENT';
659 The rest of procedure is equal to generic Databse class
660 except for the quoting style
662 if ( $name[0] == '"' && substr( $name, - 1, 1 ) == '"' ) {
665 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
668 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
669 if ( isset( $dbDetails[1] ) ) {
670 @list
( $table, $database ) = $dbDetails;
672 @list
( $table ) = $dbDetails;
675 $prefix = $this->mTablePrefix
;
677 if ( isset( $database ) ) {
678 $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
681 if ( !isset( $database ) && isset( $wgSharedDB ) && $table[0] != '"'
682 && isset( $wgSharedTables )
683 && is_array( $wgSharedTables )
684 && in_array( $table, $wgSharedTables )
686 $database = $wgSharedDB;
687 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
690 if ( isset( $database ) ) {
691 $database = ( $database[0] == '"' ?
$database : "\"{$database}\"" );
693 $table = ( $table[0] == '"') ?
$table : "\"{$prefix}{$table}\"" ;
695 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
697 return strtoupper( $tableName );
701 * Return the next in a sequence, save the value for retrieval via insertId()
703 function nextSequenceValue( $seqName ) {
704 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
705 $row = $this->fetchRow( $res );
706 $this->mInsertId
= $row[0];
707 return $this->mInsertId
;
711 * Return sequence_name if table has a sequence
713 private function getSequenceData( $table ) {
714 if ( $this->sequenceData
== null ) {
715 $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\'' );
717 while ( ( $row = $result->fetchRow() ) !== false ) {
718 $this->sequenceData
[$this->tableName( $row[1] )] = array(
719 'sequence' => $row[0],
725 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
729 * REPLACE query wrapper
730 * Oracle simulates this with a DELETE followed by INSERT
731 * $row is the row to insert, an associative array
732 * $uniqueIndexes is an array of indexes. Each element may be either a
733 * field name or an array of field names
735 * It may be more efficient to leave off unique indexes which are unlikely to collide.
736 * However if you do this, you run the risk of encountering errors which wouldn't have
739 * @param $table String: table name
740 * @param $uniqueIndexes Array: array of indexes. Each element may be
741 * either a field name or an array of field names
742 * @param $rows Array: rows to insert to $table
743 * @param $fname String: function name, you can use __METHOD__ here
745 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
746 $table = $this->tableName( $table );
748 if ( count( $rows ) == 0 ) {
753 if ( !is_array( reset( $rows ) ) ) {
754 $rows = array( $rows );
757 $sequenceData = $this->getSequenceData( $table );
759 foreach ( $rows as $row ) {
760 # Delete rows which collide
761 if ( $uniqueIndexes ) {
762 $condsDelete = array();
763 foreach ( $uniqueIndexes as $index ) {
764 $condsDelete[$index] = $row[$index];
766 if ( count( $condsDelete ) > 0 ) {
767 $this->delete( $table, $condsDelete, $fname );
771 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
772 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
776 $this->insert( $table, $row, $fname );
780 # DELETE where the condition is a join
781 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
783 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
786 $delTable = $this->tableName( $delTable );
787 $joinTable = $this->tableName( $joinTable );
788 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
789 if ( $conds != '*' ) {
790 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
794 $this->query( $sql, $fname );
797 # Returns the size of a text field, or -1 for "unlimited"
798 function textFieldSize( $table, $field ) {
799 $fieldInfoData = $this->fieldInfo( $table, $field);
800 if ( $fieldInfoData->type
== 'varchar' ) {
801 $size = $row->size
- 4;
808 function limitResult( $sql, $limit, $offset = false ) {
809 if ( $offset === false ) {
812 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
815 function unionQueries( $sqls, $all ) {
816 $glue = ' UNION ALL ';
817 return 'SELECT * ' . ( $all ?
'':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
820 function wasDeadlock() {
821 return $this->lastErrno() == 'OCI-00060';
824 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
827 $temporary = $temporary ?
'TRUE' : 'FALSE';
829 $newName = trim( strtoupper( $newName ), '"');
830 $oldName = trim( strtoupper( $oldName ), '"');
832 $tabName = substr( $newName, strlen( $wgDBprefix ) );
833 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
835 return $this->doQuery( 'BEGIN DUPLICATE_TABLE(\'' . $tabName . '\', \'' . $oldPrefix . '\', \'' . strtoupper( $wgDBprefix ) . '\', ' . $temporary . '); END;' );
838 function timestamp( $ts = 0 ) {
839 return wfTimestamp( TS_ORACLE
, $ts );
843 * Return aggregated value function call
845 function aggregateValue ( $valuedata, $valuename = 'value' ) {
849 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
850 # Ignore errors during error handling to avoid infinite
852 $ignore = $this->ignoreErrors( true );
853 ++
$this->mErrorCount
;
855 if ( $ignore ||
$tempIgnore ) {
856 wfDebug( "SQL ERROR (ignored): $error\n" );
857 $this->ignoreErrors( $ignore );
859 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
864 * @return string wikitext of a link to the server software's web site
866 public static function getSoftwareLink() {
867 return '[http://www.oracle.com/ Oracle]';
871 * @return string Version information from the database
873 function getServerVersion() {
874 //better version number, fallback on driver
875 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
876 if ( !( $row = $rset->fetchRow() ) ) {
877 return oci_server_version( $this->mConn
);
879 return $row['version'];
883 * Query whether a given table exists (in the given schema, or the default mw one if not given)
885 function tableExists( $table ) {
886 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
887 $res = $this->doQuery( $SQL );
889 $count = $res->numRows();
898 * Function translates mysql_fetch_field() functionality on ORACLE.
899 * Caching is present for reducing query time.
900 * For internal calls. Use fieldInfo for normal usage.
901 * Returns false if the field doesn't exist
903 * @param $table Array
904 * @param $field String
906 private function fieldInfoMulti( $table, $field ) {
907 $field = strtoupper( $field );
908 if ( is_array( $table ) ) {
909 $table = array_map( array( &$this, 'tableName' ), $table );
910 $tableWhere = 'IN (';
911 foreach( $table as &$singleTable ) {
912 $singleTable = strtoupper( trim( $singleTable, '"' ) );
913 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
914 return $this->mFieldInfoCache
["$singleTable.$field"];
916 $tableWhere .= '\'' . $singleTable . '\',';
918 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
920 $table = strtoupper( trim( $this->tableName( $table ), '"' ) );
921 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
922 return $this->mFieldInfoCache
["$table.$field"];
924 $tableWhere = '= \''.$table.'\'';
927 $fieldInfoStmt = oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
928 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT
) === false ) {
929 $e = oci_error( $fieldInfoStmt );
930 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
933 $res = new ORAResult( $this, $fieldInfoStmt );
934 if ( $res->numRows() == 0 ) {
935 if ( is_array( $table ) ) {
936 foreach( $table as &$singleTable ) {
937 $this->mFieldInfoCache
["$singleTable.$field"] = false;
940 $this->mFieldInfoCache
["$table.$field"] = false;
942 $fieldInfoTemp = null;
944 $fieldInfoTemp = new ORAField( $res->fetchRow() );
945 $table = $fieldInfoTemp->tableName();
946 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
949 return $fieldInfoTemp;
952 function fieldInfo( $table, $field ) {
953 if ( is_array( $table ) ) {
954 throw new DBUnexpectedError( $this, 'Database::fieldInfo called with table array!' );
956 return $this->fieldInfoMulti ($table, $field);
959 function begin( $fname = '' ) {
960 $this->mTrxLevel
= 1;
963 function commit( $fname = '' ) {
964 oci_commit( $this->mConn
);
965 $this->mTrxLevel
= 0;
968 /* Not even sure why this is used in the main codebase... */
969 function limitResultForUpdate( $sql, $num ) {
973 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
974 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
977 $dollarquote = false;
979 $replacements = array();
981 while ( ! feof( $fp ) ) {
982 if ( $lineCallback ) {
983 call_user_func( $lineCallback );
985 $line = trim( fgets( $fp, 1024 ) );
986 $sl = strlen( $line ) - 1;
991 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
995 // Allow dollar quoting for function declarations
996 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
997 if ( $dollarquote ) {
998 $dollarquote = false;
999 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1002 $dollarquote = true;
1004 } elseif ( !$dollarquote ) {
1005 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
1007 $line = substr( $line, 0, $sl );
1017 $cmd = str_replace( ';;', ";", $cmd );
1018 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1019 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1020 $replacements[$defines[2]] = $defines[1];
1023 foreach ( $replacements as $mwVar => $scVar ) {
1024 $cmd = str_replace( '&' . $scVar . '.', '{$' . $mwVar . '}', $cmd );
1027 $cmd = $this->replaceVars( $cmd );
1028 $res = $this->doQuery( $cmd );
1029 if ( $resultCallback ) {
1030 call_user_func( $resultCallback, $res, $this );
1033 if ( false === $res ) {
1034 $err = $this->lastError();
1035 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1046 function setup_database() {
1047 $res = $this->sourceFile( "../maintenance/oracle/tables.sql" );
1048 if ( $res === true ) {
1049 print " done.</li>\n";
1051 print " <b>FAILED</b></li>\n";
1052 dieout( htmlspecialchars( $res ) );
1055 // Avoid the non-standard "REPLACE INTO" syntax
1056 echo "<li>Populating interwiki table</li>\n";
1057 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1059 dieout( "Could not find the interwiki.sql file" );
1062 // do it like the postgres :D
1063 $SQL = "INSERT INTO " . $this->tableName( 'interwiki' ) . " (iw_prefix,iw_url,iw_local) VALUES ";
1064 while ( !feof( $f ) ) {
1065 $line = fgets( $f, 1024 );
1067 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) {
1070 $this->query( "$SQL $matches[1],$matches[2])" );
1073 echo "<li>Table interwiki successfully populated</li>\n";
1076 function selectDB( $db ) {
1077 if ( $db == null ||
$db == $this->mUser
) { return true; }
1078 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1079 $stmt = oci_parse( $this->mConn
, $sql );
1080 if ( !oci_execute( $stmt ) ) {
1081 $e = oci_error( $stmt );
1082 if ( $e['code'] != '1435' ) {
1083 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1090 function strencode( $s ) {
1091 return str_replace( "'", "''", $s );
1094 function addQuotes( $s ) {
1096 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1097 $s = $wgContLang->checkTitleEncoding( $s );
1099 return "'" . $this->strencode( $s ) . "'";
1102 function quote_ident( $s ) {
1106 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1110 $conds = ( $conds != null && !is_array( $conds ) ) ?
array( $conds ) : $conds;
1111 foreach ( $conds as $col => $val ) {
1112 $col_info = $this->fieldInfoMulti( $table, $col );
1113 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1114 if ( $col_type == 'CLOB' ) {
1115 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1116 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1117 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1119 $conds2[$col] = $val;
1123 return parent
::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1127 * Returns an optional USE INDEX clause to go after the table, and a
1128 * string to go at the end of the query
1132 * @param $options Array: an associative array of options to be turned into
1133 * an SQL query, valid keys are listed in the function.
1136 function makeSelectOptions( $options ) {
1137 $preLimitTail = $postLimitTail = '';
1140 $noKeyOptions = array();
1141 foreach ( $options as $key => $option ) {
1142 if ( is_numeric( $key ) ) {
1143 $noKeyOptions[$option] = true;
1147 if ( isset( $options['GROUP BY'] ) ) {
1148 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1150 if ( isset( $options['ORDER BY'] ) ) {
1151 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1154 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1155 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1156 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1157 $startOpts .= 'DISTINCT';
1160 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1161 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1166 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1169 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1172 if ( $wgContLang != null && $conds != '*' ) {
1174 $conds = ( $conds != null && !is_array( $conds ) ) ?
array( $conds ) : $conds;
1175 foreach ( $conds as $col => $val ) {
1176 $col_info = $this->fieldInfoMulti( $table, $col );
1177 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1178 if ( $col_type == 'CLOB' ) {
1179 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1181 if ( is_array( $val ) ) {
1182 $conds2[$col] = $val;
1183 foreach ( $conds2[$col] as &$val2 ) {
1184 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1187 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1192 return parent
::delete( $table, $conds2, $fname );
1194 return parent
::delete( $table, $conds, $fname );
1198 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1201 $table = $this->tableName( $table );
1202 $opts = $this->makeUpdateOptions( $options );
1203 $sql = "UPDATE $opts $table SET ";
1206 foreach ( $values as $col => &$val ) {
1207 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1210 $sqlSet = ', ' . $sqlSet;
1217 if ( $conds != '*' ) {
1218 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1221 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1222 $e = oci_error( $this->mConn
);
1223 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1226 foreach ( $values as $col => &$val ) {
1227 $col_info = $this->fieldInfoMulti( $table, $col );
1228 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1230 if ( $val === null ) {
1231 // do nothing ... null was inserted in statement creation
1232 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1233 if ( is_object( $val ) ) {
1234 $val = $val->getData();
1237 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1238 $val = '31-12-2030 12:00:00.000000';
1241 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1242 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1243 $e = oci_error( $stmt );
1244 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1248 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1249 $e = oci_error( $stmt );
1250 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1253 if ( $col_type == 'BLOB' ) {
1254 $lob[$col]->writeTemporary( $val );
1255 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
1257 $lob[$col]->writeTemporary( $val );
1258 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
1263 wfSuppressWarnings();
1265 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
1266 $e = oci_error( $stmt );
1267 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
1268 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1271 $this->mAffectedRows
= oci_num_rows( $stmt );
1274 $this->mAffectedRows
= oci_num_rows( $stmt );
1277 wfRestoreWarnings();
1279 if ( isset( $lob ) ) {
1280 foreach ( $lob as $lob_v ) {
1285 if ( !$this->mTrxLevel
) {
1286 oci_commit( $this->mConn
);
1289 oci_free_statement( $stmt );
1292 function bitNot( $field ) {
1293 // expecting bit-fields smaller than 4bytes
1294 return 'BITNOT(' . $field . ')';
1297 function bitAnd( $fieldLeft, $fieldRight ) {
1298 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1301 function bitOr( $fieldLeft, $fieldRight ) {
1302 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1305 function setFakeMaster( $enabled = true ) { }
1307 function getDBname() {
1308 return $this->mDBname
;
1311 function getServer() {
1312 return $this->mServer
;
1315 public function replaceVars( $ins ) {
1316 $varnames = array( 'wgDBprefix' );
1317 if ( $this->mFlags
& DBO_SYSDBA
) {
1318 $varnames[] = '_OracleDefTS';
1319 $varnames[] = '_OracleTempTS';
1322 // Ordinary variables
1323 foreach ( $varnames as $var ) {
1324 if ( isset( $GLOBALS[$var] ) ) {
1325 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1326 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1327 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1328 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1332 return parent
::replaceVars( $ins );
1335 public function getSearchEngine() {
1336 return 'SearchOracle';
1338 } // end DatabaseOracle class