8 * This is the Oracle database abstraction layer.
14 function __construct( $data ) {
24 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
25 * other things. We use a wrapper class to handle that and other
26 * 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 $key => $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'], '', __FUNCTION__
);
61 $this->rows
= $this->array_unique_md( $this->rows
);
62 $this->nrows
= count( $this->rows
);
69 public function free() {
70 oci_free_statement( $this->stmt
);
73 public function seek( $row ) {
74 $this->cursor
= min( $row, $this->nrows
);
77 public function numRows() {
81 public function numFields() {
82 return oci_num_fields( $this->stmt
);
85 public function fetchObject() {
86 if ( $this->cursor
>= $this->nrows
) {
89 $row = $this->rows
[$this->cursor++
];
90 $ret = new stdClass();
91 foreach ( $row as $k => $v ) {
92 $lc = strtolower( oci_field_name( $this->stmt
, $k +
1 ) );
99 public function fetchRow() {
100 if ( $this->cursor
>= $this->nrows
) {
104 $row = $this->rows
[$this->cursor++
];
106 foreach ( $row as $k => $v ) {
107 $lc = strtolower( oci_field_name( $this->stmt
, $k +
1 ) );
120 private $name, $tablename, $default, $max_length, $nullable,
121 $is_pk, $is_unique, $is_multiple, $is_key, $type;
123 function __construct( $info ) {
124 $this->name
= $info['column_name'];
125 $this->tablename
= $info['table_name'];
126 $this->default = $info['data_default'];
127 $this->max_length
= $info['data_length'];
128 $this->nullable
= $info['not_null'];
129 $this->is_pk
= isset( $info['prim'] ) && $info['prim'] == 1 ?
1 : 0;
130 $this->is_unique
= isset( $info['uniq'] ) && $info['uniq'] == 1 ?
1 : 0;
131 $this->is_multiple
= isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ?
1 : 0;
132 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
133 $this->type
= $info['data_type'];
140 function tableName() {
141 return $this->tablename
;
144 function defaultValue() {
145 return $this->default;
148 function maxLength() {
149 return $this->max_length
;
152 function nullable() {
153 return $this->nullable
;
157 return $this->is_key
;
160 function isMultipleKey() {
161 return $this->is_multiple
;
172 class DatabaseOracle
extends DatabaseBase
{
173 var $mInsertId = null;
174 var $mLastResult = null;
175 var $numeric_version = null;
176 var $lastResult = null;
180 var $ignore_DUP_VAL_ON_INDEX = false;
181 var $sequenceData = null;
183 var $defaultCharset = 'AL32UTF8';
185 var $mFieldInfoCache = array();
187 function __construct( $server = false, $user = false, $password = false, $dbName = false,
188 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
190 $tablePrefix = $tablePrefix == 'get from global' ?
$tablePrefix : strtoupper( $tablePrefix );
191 parent
::__construct( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
192 wfRunHooks( 'DatabaseOraclePostInit', array( &$this ) );
199 function cascadingDeletes() {
202 function cleanupTriggers() {
205 function strictIPs() {
208 function realTimestamps() {
211 function implicitGroupby() {
214 function implicitOrderby() {
217 function searchableIPs() {
221 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
223 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags );
227 * Usually aborts on failure
228 * If the failFunction is set to a non-zero integer, returns success
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->mServer
= $server;
237 $this->mUser
= $user;
238 $this->mPassword
= $password;
239 $this->mDBname
= $dbName;
241 if ( !strlen( $user ) ) { # e.g. the class is being loaded
245 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
246 if ( $this->mFlags
& DBO_DEFAULT
) {
247 $this->mConn
= oci_new_connect( $user, $password, $dbName, $this->defaultCharset
, $session_mode );
249 $this->mConn
= oci_connect( $user, $password, $dbName, $this->defaultCharset
, $session_mode );
252 if ( $this->mConn
== false ) {
253 wfDebug( "DB connection error\n" );
254 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
255 wfDebug( $this->lastError() . "\n" );
259 $this->mOpened
= true;
261 # removed putenv calls because they interfere with the system globaly
262 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
263 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
268 * Closes a database connection, if it is open
269 * Returns success, true if already closed
272 $this->mOpened
= false;
273 if ( $this->mConn
) {
274 return oci_close( $this->mConn
);
280 function execFlags() {
281 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
284 function doQuery( $sql ) {
285 wfDebug( "SQL: [$sql]\n" );
286 if ( !mb_check_encoding( $sql ) ) {
287 throw new MWException( "SQL encoding is invalid\n$sql" );
290 // handle some oracle specifics
291 // remove AS column/table/subquery namings
292 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
293 $sql = preg_replace( '/ as /i', ' ', $sql );
295 // Oracle has issues with UNION clause if the statement includes LOB fields
296 // So we do a UNION ALL and then filter the results array with array_unique
297 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
298 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
299 // you have to select data from plan table after explain
300 $explain_id = date( 'dmYHis' );
302 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
305 wfSuppressWarnings();
307 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
308 $e = oci_error( $this->mConn
);
309 $this->reportQueryError( $e['message'], $e['code'], $sql, __FUNCTION__
);
312 if ( oci_execute( $stmt, $this->execFlags() ) == false ) {
313 $e = oci_error( $stmt );
314 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
315 $this->reportQueryError( $e['message'], $e['code'], $sql, __FUNCTION__
);
321 if ( $explain_count > 0 ) {
322 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
323 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
324 return new ORAResult( $this, $stmt, $union_unique );
326 $this->mAffectedRows
= oci_num_rows( $stmt );
331 function queryIgnore( $sql, $fname = '' ) {
332 return $this->query( $sql, $fname, true );
335 function freeResult( $res ) {
336 if ( $res instanceof ORAResult
) {
339 $res->result
->free();
343 function fetchObject( $res ) {
344 if ( $res instanceof ORAResult
) {
345 return $res->numRows();
347 return $res->result
->fetchObject();
351 function fetchRow( $res ) {
352 if ( $res instanceof ORAResult
) {
353 return $res->fetchRow();
355 return $res->result
->fetchRow();
359 function numRows( $res ) {
360 if ( $res instanceof ORAResult
) {
361 return $res->numRows();
363 return $res->result
->numRows();
367 function numFields( $res ) {
368 if ( $res instanceof ORAResult
) {
369 return $res->numFields();
371 return $res->result
->numFields();
375 function fieldName( $stmt, $n ) {
376 return oci_field_name( $stmt, $n );
380 * This must be called after nextSequenceVal
382 function insertId() {
383 return $this->mInsertId
;
386 function dataSeek( $res, $row ) {
387 if ( $res instanceof ORAResult
) {
390 $res->result
->seek( $row );
394 function lastError() {
395 if ( $this->mConn
=== false ) {
398 $e = oci_error( $this->mConn
);
400 return $e['message'];
403 function lastErrno() {
404 if ( $this->mConn
=== false ) {
407 $e = oci_error( $this->mConn
);
412 function affectedRows() {
413 return $this->mAffectedRows
;
417 * Returns information about an index
418 * If errors are explicitly ignored, returns NULL on failure
420 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
424 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
428 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
429 if ( !count( $a ) ) {
433 if ( !is_array( $options ) ) {
434 $options = array( $options );
437 if ( in_array( 'IGNORE', $options ) ) {
438 $this->ignore_DUP_VAL_ON_INDEX
= true;
441 if ( !is_array( reset( $a ) ) ) {
445 foreach ( $a as &$row ) {
446 $this->insertOneRow( $table, $row, $fname );
450 if ( in_array( 'IGNORE', $options ) ) {
451 $this->ignore_DUP_VAL_ON_INDEX
= false;
457 function insertOneRow( $table, $row, $fname ) {
460 // "INSERT INTO tables (a, b, c)"
461 $sql = "INSERT INTO " . $this->tableName( $table ) . " (" . join( ',', array_keys( $row ) ) . ')';
464 // for each value, append ":key"
466 foreach ( $row as $col => $val ) {
468 $sql .= $val !== null ?
':' . $col : 'NULL';
470 $sql .= $val !== null ?
', :' . $col : ', NULL';
477 $stmt = oci_parse( $this->mConn
, $sql );
478 foreach ( $row as $col => &$val ) {
479 $col_type = $this->fieldInfo( $this->tableName( $table ), $col )->type();
481 if ( $val === null ) {
482 // do nothing ... null was inserted in statement creation
483 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
484 if ( is_object( $val ) ) {
485 $val = $val->getData();
488 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
489 $val = '31-12-2030 12:00:00.000000';
492 $val = ( $wgLang != null ) ?
$wgLang->checkTitleEncoding( $val ) : $val;
493 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
494 $this->reportQueryError( $this->lastErrno(), $this->lastError(), $sql, __METHOD__
);
497 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
498 $e = oci_error( $stmt );
499 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
502 if ( $col_type == 'BLOB' ) { // is_object($val)) {
503 $lob[$col]->writeTemporary( $val ); // ->getData());
504 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
506 $lob[$col]->writeTemporary( $val );
507 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
512 wfSuppressWarnings();
514 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
515 $e = oci_error( $stmt );
517 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
518 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
520 $this->mAffectedRows
= oci_num_rows( $stmt );
523 $this->mAffectedRows
= oci_num_rows( $stmt );
528 if ( isset( $lob ) ) {
529 foreach ( $lob as $lob_i => $lob_v ) {
534 if ( !$this->mTrxLevel
) {
535 oci_commit( $this->mConn
);
538 oci_free_statement( $stmt );
541 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
542 $insertOptions = array(), $selectOptions = array() )
544 $destTable = $this->tableName( $destTable );
545 if ( !is_array( $selectOptions ) ) {
546 $selectOptions = array( $selectOptions );
548 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
549 if ( is_array( $srcTable ) ) {
550 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
552 $srcTable = $this->tableName( $srcTable );
555 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
556 !isset( $varMap[$sequenceData['column']] ) )
557 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
559 // count-alias subselect fields to avoid abigious definition errors
561 foreach ( $varMap as $key => &$val ) {
562 $val = $val . ' field' . ( $i++
);
565 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
566 " SELECT $startOpts " . implode( ',', $varMap ) .
567 " FROM $srcTable $useIndex ";
568 if ( $conds != '*' ) {
569 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
571 $sql .= " $tailOpts";
573 if ( in_array( 'IGNORE', $insertOptions ) ) {
574 $this->ignore_DUP_VAL_ON_INDEX
= true;
577 $retval = $this->query( $sql, $fname );
579 if ( in_array( 'IGNORE', $insertOptions ) ) {
580 $this->ignore_DUP_VAL_ON_INDEX
= false;
586 function tableName( $name ) {
587 if (is_array($name)) {
588 foreach($name as &$single_name) {
589 $single_name = $this->tableName($single_name);
594 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
596 Replace reserved words with better ones
597 Using uppercase because that's the only way Oracle can handle
605 $name = 'PAGECONTENT';
610 The rest of procedure is equal to generic Databse class
611 except for the quoting style
613 if ( $name[0] == '"' && substr( $name, - 1, 1 ) == '"' ) {
616 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
619 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
620 if ( isset( $dbDetails[1] ) ) {
621 @list
( $table, $database ) = $dbDetails;
623 @list
( $table ) = $dbDetails;
626 $prefix = $this->mTablePrefix
;
628 if ( isset( $database ) ) {
629 $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
632 if ( !isset( $database ) && isset( $wgSharedDB ) && $table[0] != '"'
633 && isset( $wgSharedTables )
634 && is_array( $wgSharedTables )
635 && in_array( $table, $wgSharedTables )
637 $database = $wgSharedDB;
638 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
641 if ( isset( $database ) ) {
642 $database = ( $database[0] == '"' ?
$database : "\"{$database}\"" );
644 $table = ( $table[0] == '"' ?
$table : "\"{$prefix}{$table}\"" );
646 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
648 return strtoupper( $tableName );
652 * Return the next in a sequence, save the value for retrieval via insertId()
654 function nextSequenceValue( $seqName ) {
655 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
656 $row = $this->fetchRow( $res );
657 $this->mInsertId
= $row[0];
658 $this->freeResult( $res );
659 return $this->mInsertId
;
663 * Return sequence_name if table has a sequence
665 function getSequenceData( $table ) {
666 if ( $this->sequenceData
== null ) {
667 $result = $this->query( "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'" );
669 while ( ( $row = $result->fetchRow() ) !== false ) {
670 $this->sequenceData
[$this->tableName( $row[1] )] = array(
671 'sequence' => $row[0],
677 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
680 # REPLACE query wrapper
681 # Oracle simulates this with a DELETE followed by INSERT
682 # $row is the row to insert, an associative array
683 # $uniqueIndexes is an array of indexes. Each element may be either a
684 # field name or an array of field names
686 # It may be more efficient to leave off unique indexes which are unlikely to collide.
687 # However if you do this, you run the risk of encountering errors which wouldn't have
689 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
690 $table = $this->tableName( $table );
692 if ( count( $rows ) == 0 ) {
697 if ( !is_array( reset( $rows ) ) ) {
698 $rows = array( $rows );
701 $sequenceData = $this->getSequenceData( $table );
703 foreach ( $rows as $row ) {
704 # Delete rows which collide
705 if ( $uniqueIndexes ) {
706 $condsDelete = array();
707 foreach ( $uniqueIndexes as $index )
708 $condsDelete[$index] = $row[$index];
709 if (count($condsDelete) > 0) {
710 $this->delete( $table, $condsDelete, $fname );
714 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
715 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
719 $this->insert( $table, $row, $fname );
723 # DELETE where the condition is a join
724 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseOracle::deleteJoin" ) {
726 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
729 $delTable = $this->tableName( $delTable );
730 $joinTable = $this->tableName( $joinTable );
731 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
732 if ( $conds != '*' ) {
733 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
737 $this->query( $sql, $fname );
740 # Returns the size of a text field, or -1 for "unlimited"
741 function textFieldSize( $table, $field ) {
742 $table = $this->tableName( $table );
743 $sql = "SELECT t.typname as ftype,a.atttypmod as size
744 FROM pg_class c, pg_attribute a, pg_type t
745 WHERE relname='$table' AND a.attrelid=c.oid AND
746 a.atttypid=t.oid and a.attname='$field'";
747 $res = $this->query( $sql );
748 $row = $this->fetchObject( $res );
749 if ( $row->ftype
== "varchar" ) {
750 $size = $row->size
- 4;
754 $this->freeResult( $res );
758 function limitResult( $sql, $limit, $offset = false ) {
759 if ( $offset === false ) {
762 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
766 function unionQueries( $sqls, $all ) {
767 $glue = ' UNION ALL ';
768 return 'SELECT * ' . ( $all ?
'':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
771 function wasDeadlock() {
772 return $this->lastErrno() == 'OCI-00060';
776 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
777 $temporary = $temporary ?
'TRUE' : 'FALSE';
778 return $this->query( 'BEGIN DUPLICATE_TABLE(\'' . $oldName . '\', \'' . $newName . '\', ' . $temporary . '); END;', $fname );
781 function timestamp( $ts = 0 ) {
782 return wfTimestamp( TS_ORACLE
, $ts );
786 * Return aggregated value function call
788 function aggregateValue ( $valuedata, $valuename = 'value' ) {
792 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
793 # Ignore errors during error handling to avoid infinite
795 $ignore = $this->ignoreErrors( true );
796 ++
$this->mErrorCount
;
798 if ( $ignore ||
$tempIgnore ) {
799 wfDebug( "SQL ERROR (ignored): $error\n" );
800 $this->ignoreErrors( $ignore );
802 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
807 * @return string wikitext of a link to the server software's web site
809 function getSoftwareLink() {
810 return '[http://www.oracle.com/ Oracle]';
814 * @return string Version information from the database
816 function getServerVersion() {
817 return oci_server_version( $this->mConn
);
821 * Query whether a given table exists (in the given schema, or the default mw one if not given)
823 function tableExists( $table ) {
824 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
825 $res = $this->doQuery( $SQL );
827 $count = $res->numRows();
836 * Query whether a given column exists in the mediawiki schema
837 * based on prebuilt table to simulate MySQL field info and keep query speed minimal
839 function fieldExists( $table, $field, $fname = 'DatabaseOracle::fieldExists' ) {
841 if (is_array($table)) {
842 $tableWhere = 'IN (';
843 foreach($table as &$singleTable) {
844 $singleTable = trim( $singleTable, '"' );
845 if (isset($this->mFieldInfoCache
["$singleTable.$field"])) {
846 return $this->mFieldInfoCache
["$singleTable.$field"];
848 $tableWhere .= '\''.$singleTable.'\',';
850 $tableWhere = rtrim($tableWhere, ',').')';
852 $table = trim( $table, '"' );
853 if (isset($this->mFieldInfoCache
["$table.$field"])) {
854 return $this->mFieldInfoCache
["$table.$field"];
856 $tableWhere = '= upper(\''.$table.'\')';
859 $fieldInfoStmt = oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = UPPER(\''.$field.'\')' );
861 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT
) === false ) {
862 $e = oci_error( $fieldInfoStmt );
863 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
866 $res = new ORAResult( $this, $fieldInfoStmt );
867 if ($res->numRows() != 0) {
868 $fieldInfoTemp = new ORAField( $res->fetchRow() );
869 $table = $fieldInfoTemp->tableName();
870 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
877 function fieldInfo( $table, $field ) {
879 if (is_array($table)) {
880 $tableWhere = 'IN (';
881 foreach($table as &$singleTable) {
882 $singleTable = trim( $singleTable, '"' );
883 if (isset($this->mFieldInfoCache
["$singleTable.$field"])) {
884 return $this->mFieldInfoCache
["$singleTable.$field"];
886 $tableWhere .= '\''.$singleTable.'\',';
888 $tableWhere = rtrim($tableWhere, ',').')';
890 $table = trim( $table, '"' );
891 if (isset($this->mFieldInfoCache
["$table.$field"])) {
892 return $this->mFieldInfoCache
["$table.$field"];
894 $tableWhere = '= upper(\''.$table.'\')';
897 $fieldInfoStmt = oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = UPPER(\''.$field.'\')' );
899 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT
) === false ) {
900 $e = oci_error( $fieldInfoStmt );
901 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
904 $res = new ORAResult( $this, $fieldInfoStmt );
905 $fieldInfoTemp = new ORAField( $res->fetchRow() );
906 $table = $fieldInfoTemp->tableName();
907 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
908 return $fieldInfoTemp;
911 function begin( $fname = '' ) {
912 $this->mTrxLevel
= 1;
915 function immediateCommit( $fname = '' ) {
919 function commit( $fname = '' ) {
920 oci_commit( $this->mConn
);
921 $this->mTrxLevel
= 0;
924 /* Not even sure why this is used in the main codebase... */
925 function limitResultForUpdate( $sql, $num ) {
929 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
930 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
933 $dollarquote = false;
935 $replacements = array();
937 while ( ! feof( $fp ) ) {
938 if ( $lineCallback ) {
939 call_user_func( $lineCallback );
941 $line = trim( fgets( $fp, 1024 ) );
942 $sl = strlen( $line ) - 1;
947 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
951 // Allow dollar quoting for function declarations
952 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
953 if ( $dollarquote ) {
954 $dollarquote = false;
959 } elseif ( !$dollarquote ) {
960 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
962 $line = substr( $line, 0, $sl );
972 $cmd = str_replace( ';;', ";", $cmd );
973 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
974 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
975 $replacements[$defines[2]] = $defines[1];
978 foreach ( $replacements as $mwVar => $scVar ) {
979 $cmd = str_replace( '&' . $scVar . '.', '{$' . $mwVar . '}', $cmd );
982 $cmd = $this->replaceVars( $cmd );
983 $res = $this->query( $cmd, __METHOD__
);
984 if ( $resultCallback ) {
985 call_user_func( $resultCallback, $res, $this );
988 if ( false === $res ) {
989 $err = $this->lastError();
990 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1001 function setup_database() {
1002 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1004 echo "<li>Creating DB objects</li>\n";
1005 $res = $this->sourceFile( "../maintenance/ora/tables.sql" );
1007 // Avoid the non-standard "REPLACE INTO" syntax
1008 echo "<li>Populating table interwiki</li>\n";
1009 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1010 if ( $f == false ) {
1011 dieout( "<li>Could not find the interwiki.sql file</li>" );
1014 // do it like the postgres :D
1015 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1016 while ( !feof( $f ) ) {
1017 $line = fgets( $f, 1024 );
1019 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) {
1022 $this->query( "$SQL $matches[1],$matches[2])" );
1025 echo "<li>Table interwiki successfully populated</li>\n";
1028 function strencode( $s ) {
1029 return str_replace( "'", "''", $s );
1032 function addQuotes( $s ) {
1034 if ( isset( $wgLang->mLoaded
) && $wgLang->mLoaded
) {
1035 $s = $wgLang->checkTitleEncoding( $s );
1037 return "'" . $this->strencode( $s ) . "'";
1040 function quote_ident( $s ) {
1044 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1048 $conds = ($conds != null && !is_array($conds)) ?
array($conds) : $conds;
1049 foreach ( $conds as $col => $val ) {
1050 $col_type = $this->fieldInfo( $this->tableName( $table ), $col )->type();
1051 if ( $col_type == 'CLOB' ) {
1052 $conds2['TO_CHAR(' . $col . ')'] = $wgLang->checkTitleEncoding( $val );
1053 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1054 $conds2[$col] = $wgLang->checkTitleEncoding( $val );
1056 $conds2[$col] = $val;
1060 if ( is_array( $table ) ) {
1061 foreach ( $table as $tab ) {
1062 $tab = $this->tableName( $tab );
1065 $table = $this->tableName( $table );
1068 return parent
::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1072 * Returns an optional USE INDEX clause to go after the table, and a
1073 * string to go at the end of the query
1077 * @param $options Array: an associative array of options to be turned into
1078 * an SQL query, valid keys are listed in the function.
1081 function makeSelectOptions( $options ) {
1082 $preLimitTail = $postLimitTail = '';
1085 $noKeyOptions = array();
1086 foreach ( $options as $key => $option ) {
1087 if ( is_numeric( $key ) ) {
1088 $noKeyOptions[$option] = true;
1092 if ( isset( $options['GROUP BY'] ) ) {
1093 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1095 if ( isset( $options['ORDER BY'] ) ) {
1096 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1099 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1100 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1101 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1102 $startOpts .= 'DISTINCT';
1105 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1106 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1111 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1114 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1117 if ( $wgLang != null ) {
1119 $conds = ($conds != null && !is_array($conds)) ?
array($conds) : $conds;
1120 foreach ( $conds as $col => $val ) {
1121 $col_type = $this->fieldInfo( $this->tableName( $table ), $col )->type();
1122 if ( $col_type == 'CLOB' ) {
1123 $conds2['TO_CHAR(' . $col . ')'] = $wgLang->checkTitleEncoding( $val );
1125 if ( is_array( $val ) ) {
1126 $conds2[$col] = $val;
1127 foreach ( $conds2[$col] as &$val2 ) {
1128 $val2 = $wgLang->checkTitleEncoding( $val2 );
1131 $conds2[$col] = $wgLang->checkTitleEncoding( $val );
1136 return parent
::delete( $table, $conds2, $fname );
1138 return parent
::delete( $table, $conds, $fname );
1142 function bitNot( $field ) {
1143 // expecting bit-fields smaller than 4bytes
1144 return 'BITNOT(' . $bitField . ')';
1147 function bitAnd( $fieldLeft, $fieldRight ) {
1148 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1151 function bitOr( $fieldLeft, $fieldRight ) {
1152 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1156 * How lagged is this slave?
1160 public function getLag() {
1161 # Not implemented for Oracle
1165 function setFakeSlaveLag( $lag ) { }
1166 function setFakeMaster( $enabled = true ) { }
1168 function getDBname() {
1169 return $this->mDBname
;
1172 function getServer() {
1173 return $this->mServer
;
1176 public function replaceVars( $ins ) {
1177 $varnames = array( 'wgDBprefix' );
1178 if ( $this->mFlags
& DBO_SYSDBA
) {
1179 $varnames[] = 'wgDBOracleDefTS';
1180 $varnames[] = 'wgDBOracleTempTS';
1183 // Ordinary variables
1184 foreach ( $varnames as $var ) {
1185 if ( isset( $GLOBALS[$var] ) ) {
1186 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1187 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1188 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1189 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1193 return parent
::replaceVars( $ins );
1196 public function getSearchEngine() {
1197 return 'SearchOracle';
1199 } // end DatabaseOracle class