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
)
88 $row = $this->rows
[$this->cursor++
];
89 $ret = new stdClass();
90 foreach ( $row as $k => $v ) {
91 $lc = strtolower( oci_field_name( $this->stmt
, $k +
1 ) );
98 public function fetchRow() {
99 if ( $this->cursor
>= $this->nrows
)
102 $row = $this->rows
[$this->cursor++
];
104 foreach ( $row as $k => $v ) {
105 $lc = strtolower( oci_field_name( $this->stmt
, $k +
1 ) );
118 private $name, $tablename, $default, $max_length, $nullable,
119 $is_pk, $is_unique, $is_multiple, $is_key, $type;
121 function __construct( $info ) {
122 $this->name
= $info['column_name'];
123 $this->tablename
= $info['table_name'];
124 $this->default = $info['data_default'];
125 $this->max_length
= $info['data_length'];
126 $this->nullable
= $info['not_null'];
127 $this->is_pk
= isset( $info['prim'] ) && $info['prim'] == 1 ?
1 : 0;
128 $this->is_unique
= isset( $info['uniq'] ) && $info['uniq'] == 1 ?
1 : 0;
129 $this->is_multiple
= isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ?
1 : 0;
130 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
131 $this->type
= $info['data_type'];
138 function tableName() {
139 return $this->tablename
;
142 function defaultValue() {
143 return $this->default;
146 function maxLength() {
147 return $this->max_length
;
150 function nullable() {
151 return $this->nullable
;
155 return $this->is_key
;
158 function isMultipleKey() {
159 return $this->is_multiple
;
170 class DatabaseOracle
extends DatabaseBase
{
171 var $mInsertId = NULL;
172 var $mLastResult = NULL;
173 var $numeric_version = NULL;
174 var $lastResult = null;
178 var $ignore_DUP_VAL_ON_INDEX = false;
179 var $sequenceData = null;
181 var $defaultCharset = 'AL32UTF8';
183 function DatabaseOracle( $server = false, $user = false, $password = false, $dbName = false,
184 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
186 $tablePrefix = $tablePrefix == 'get from global' ?
$tablePrefix : strtoupper( $tablePrefix );
187 parent
::__construct( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
188 wfRunHooks( 'DatabaseOraclePostInit', array( &$this ) );
191 function cascadingDeletes() {
194 function cleanupTriggers() {
197 function strictIPs() {
200 function realTimestamps() {
203 function implicitGroupby() {
206 function implicitOrderby() {
209 function searchableIPs() {
213 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
215 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags );
219 * Usually aborts on failure
220 * If the failFunction is set to a non-zero integer, returns success
222 function open( $server, $user, $password, $dbName ) {
223 if ( !function_exists( 'oci_connect' ) ) {
224 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" );
227 // putenv("NLS_LANG=AMERICAN_AMERICA.AL32UTF8");
230 $this->mServer
= $server;
231 $this->mUser
= $user;
232 $this->mPassword
= $password;
233 $this->mDBname
= $dbName;
235 if ( !strlen( $user ) ) { # # e.g. the class is being loaded
239 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
240 if ( $this->mFlags
& DBO_DEFAULT
)
241 $this->mConn
= oci_new_connect( $user, $password, $dbName, $this->defaultCharset
, $session_mode );
243 $this->mConn
= oci_connect( $user, $password, $dbName, $this->defaultCharset
, $session_mode );
245 if ( $this->mConn
== false ) {
246 wfDebug( "DB connection error\n" );
247 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
248 wfDebug( $this->lastError() . "\n" );
252 $this->mOpened
= true;
254 # removed putenv calls because they interfere with the system globaly
255 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
256 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
261 * Closes a database connection, if it is open
262 * Returns success, true if already closed
265 $this->mOpened
= false;
266 if ( $this->mConn
) {
267 return oci_close( $this->mConn
);
273 function execFlags() {
274 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
277 function doQuery( $sql ) {
278 wfDebug( "SQL: [$sql]\n" );
279 if ( !mb_check_encoding( $sql ) ) {
280 throw new MWException( "SQL encoding is invalid\n$sql" );
283 // handle some oracle specifics
284 // remove AS column/table/subquery namings
285 if ( !defined( 'MEDIAWIKI_INSTALL' ) )
286 $sql = preg_replace( '/ as /i', ' ', $sql );
287 // Oracle has issues with UNION clause if the statement includes LOB fields
288 // So we do a UNION ALL and then filter the results array with array_unique
289 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
290 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
291 // you have to select data from plan table after explain
292 $olderr = error_reporting( E_ERROR
);
293 $explain_id = date( 'dmYHis' );
294 error_reporting( $olderr );
296 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
299 $olderr = error_reporting( E_ERROR
);
301 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
302 $e = oci_error( $this->mConn
);
303 $this->reportQueryError( $e['message'], $e['code'], $sql, __FUNCTION__
);
306 $olderr = error_reporting( E_ERROR
);
307 if ( oci_execute( $stmt, $this->execFlags() ) == false ) {
308 $e = oci_error( $stmt );
309 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' )
310 $this->reportQueryError( $e['message'], $e['code'], $sql, __FUNCTION__
);
312 error_reporting( $olderr );
314 if ( $explain_count > 0 ) {
315 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
316 } elseif ( oci_statement_type( $stmt ) == "SELECT" ) {
317 return new ORAResult( $this, $stmt, $union_unique );
319 $this->mAffectedRows
= oci_num_rows( $stmt );
324 function queryIgnore( $sql, $fname = '' ) {
325 return $this->query( $sql, $fname, true );
328 function freeResult( $res ) {
329 if ( $res instanceof ORAResult
) {
332 $res->result
->free();
336 function fetchObject( $res ) {
337 if ( $res instanceof ORAResult
) {
338 return $res->numRows();
340 return $res->result
->fetchObject();
344 function fetchRow( $res ) {
345 if ( $res instanceof ORAResult
) {
346 return $res->fetchRow();
348 return $res->result
->fetchRow();
352 function numRows( $res ) {
353 if ( $res instanceof ORAResult
) {
354 return $res->numRows();
356 return $res->result
->numRows();
360 function numFields( $res ) {
361 if ( $res instanceof ORAResult
) {
362 return $res->numFields();
364 return $res->result
->numFields();
368 function fieldName( $stmt, $n ) {
369 return oci_field_name( $stmt, $n );
373 * This must be called after nextSequenceVal
375 function insertId() {
376 return $this->mInsertId
;
379 function dataSeek( $res, $row ) {
380 if ( $res instanceof ORAResult
) {
383 $res->result
->seek( $row );
387 function lastError() {
388 if ( $this->mConn
=== false )
391 $e = oci_error( $this->mConn
);
392 return $e['message'];
395 function lastErrno() {
396 if ( $this->mConn
=== false )
399 $e = oci_error( $this->mConn
);
403 function affectedRows() {
404 return $this->mAffectedRows
;
408 * Returns information about an index
409 * If errors are explicitly ignored, returns NULL on failure
411 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
415 function indexUnique ( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
419 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
423 if ( !is_array( $options ) )
424 $options = array( $options );
426 if ( in_array( 'IGNORE', $options ) )
427 $this->ignore_DUP_VAL_ON_INDEX
= true;
429 if ( !is_array( reset( $a ) ) ) {
433 foreach ( $a as &$row ) {
434 $this->insertOneRow( $table, $row, $fname );
438 if ( in_array( 'IGNORE', $options ) )
439 $this->ignore_DUP_VAL_ON_INDEX
= false;
444 function insertOneRow( $table, $row, $fname ) {
447 // "INSERT INTO tables (a, b, c)"
448 $sql = "INSERT INTO " . $this->tableName( $table ) . " (" . join( ',', array_keys( $row ) ) . ')';
451 // for each value, append ":key"
453 foreach ( $row as $col => $val ) {
455 $sql .= $val !== NULL ?
':' . $col : 'NULL';
457 $sql .= $val !== NULL ?
', :' . $col : ', NULL';
464 $stmt = oci_parse( $this->mConn
, $sql );
465 foreach ( $row as $col => &$val ) {
466 $col_type = $this->fieldInfo( $this->tableName( $table ), $col )->type();
468 if ( $val === NULL ) {
469 // do nothing ... null was inserted in statement creation
470 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
471 if ( is_object( $val ) )
472 $val = $val->getData();
474 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' )
475 $val = '31-12-2030 12:00:00.000000';
477 $val = ( $wgLang != null ) ?
$wgLang->checkTitleEncoding( $val ) : $val;
478 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false )
479 $this->reportQueryError( $this->lastErrno(), $this->lastError(), $sql, __METHOD__
);
481 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
482 $e = oci_error( $stmt );
483 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
486 if ( $col_type == 'BLOB' ) { // is_object($val)) {
487 $lob[$col]->writeTemporary( $val ); // ->getData());
488 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
490 $lob[$col]->writeTemporary( $val );
491 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
496 $olderr = error_reporting( E_ERROR
);
497 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
498 $e = oci_error( $stmt );
500 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' )
501 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
503 $this->mAffectedRows
= oci_num_rows( $stmt );
505 $this->mAffectedRows
= oci_num_rows( $stmt );
506 error_reporting( $olderr );
508 if ( isset( $lob ) ) {
509 foreach ( $lob as $lob_i => $lob_v ) {
514 if ( !$this->mTrxLevel
)
515 oci_commit( $this->mConn
);
517 oci_free_statement( $stmt );
520 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
521 $insertOptions = array(), $selectOptions = array() )
523 $destTable = $this->tableName( $destTable );
524 if ( !is_array( $selectOptions ) ) {
525 $selectOptions = array( $selectOptions );
527 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
528 if ( is_array( $srcTable ) ) {
529 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
531 $srcTable = $this->tableName( $srcTable );
534 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
535 !isset( $varMap[$sequenceData['column']] ) )
536 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
538 // count-alias subselect fields to avoid abigious definition errors
540 foreach ( $varMap as $key => &$val )
541 $val = $val . ' field' . ( $i++
);
543 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
544 " SELECT $startOpts " . implode( ',', $varMap ) .
545 " FROM $srcTable $useIndex ";
546 if ( $conds != '*' ) {
547 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
549 $sql .= " $tailOpts";
551 if ( in_array( 'IGNORE', $insertOptions ) )
552 $this->ignore_DUP_VAL_ON_INDEX
= true;
554 $retval = $this->query( $sql, $fname );
556 if ( in_array( 'IGNORE', $insertOptions ) )
557 $this->ignore_DUP_VAL_ON_INDEX
= false;
562 function tableName( $name ) {
563 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
565 Replace reserved words with better ones
566 Useing uppercase, because that's the only way oracle can handle
571 $name = 'MWUSER'; break;
573 $name = 'PAGECONTENT'; break;
577 The rest of procedure is equal to generic Databse class
578 except for the quoting style
580 if ( $name[0] == '"' && substr( $name, - 1, 1 ) == '"' ) return $name;
582 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
583 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
584 if ( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
585 else @list
( $table ) = $dbDetails;
587 $prefix = $this->mTablePrefix
;
589 if ( isset( $database ) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
591 if ( !isset( $database )
592 && isset( $wgSharedDB )
594 && isset( $wgSharedTables )
595 && is_array( $wgSharedTables )
596 && in_array( $table, $wgSharedTables ) ) {
597 $database = $wgSharedDB;
598 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
601 if ( isset( $database ) ) $database = ( $database[0] == '"' ?
$database : "\"{$database}\"" );
602 $table = ( $table[0] == '"' ?
$table : "\"{$prefix}{$table}\"" );
604 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
606 return strtoupper( $tableName );
610 * Return the next in a sequence, save the value for retrieval via insertId()
612 function nextSequenceValue( $seqName ) {
613 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
614 $row = $this->fetchRow( $res );
615 $this->mInsertId
= $row[0];
616 $this->freeResult( $res );
617 return $this->mInsertId
;
621 * Return sequence_name if table has a sequence
623 function getSequenceData( $table ) {
624 if ( $this->sequenceData
== NULL ) {
625 $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'" );
627 while ( ( $row = $result->fetchRow() ) !== false )
628 $this->sequenceData
[$this->tableName( $row[1] )] = array( 'sequence' => $row[0], 'column' => $row[2] );
631 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
635 # REPLACE query wrapper
636 # Oracle simulates this with a DELETE followed by INSERT
637 # $row is the row to insert, an associative array
638 # $uniqueIndexes is an array of indexes. Each element may be either a
639 # field name or an array of field names
641 # It may be more efficient to leave off unique indexes which are unlikely to collide.
642 # However if you do this, you run the risk of encountering errors which wouldn't have
644 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
645 $table = $this->tableName( $table );
647 if ( count( $rows ) == 0 ) {
652 if ( !is_array( reset( $rows ) ) ) {
653 $rows = array( $rows );
656 $sequenceData = $this->getSequenceData( $table );
658 foreach ( $rows as $row ) {
659 # Delete rows which collide
660 if ( $uniqueIndexes ) {
661 $condsDelete = array();
662 foreach ( $uniqueIndexes as $index )
663 $condsDelete[$index] = $row[$index];
664 $this->delete( $table, $condsDelete, $fname );
666 $sql = "DELETE FROM $table WHERE ";
668 foreach ( $uniqueIndexes as $index ) {
675 if ( is_array( $index ) ) {
677 foreach ( $index as $col ) {
683 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
686 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
691 $this->doQuery( $sql);//, $fname );
695 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) )
696 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
699 $this->insert( $table, $row, $fname );
703 # DELETE where the condition is a join
704 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseOracle::deleteJoin" ) {
706 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
709 $delTable = $this->tableName( $delTable );
710 $joinTable = $this->tableName( $joinTable );
711 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
712 if ( $conds != '*' ) {
713 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
717 $this->query( $sql, $fname );
720 # Returns the size of a text field, or -1 for "unlimited"
721 function textFieldSize( $table, $field ) {
722 $table = $this->tableName( $table );
723 $sql = "SELECT t.typname as ftype,a.atttypmod as size
724 FROM pg_class c, pg_attribute a, pg_type t
725 WHERE relname='$table' AND a.attrelid=c.oid AND
726 a.atttypid=t.oid and a.attname='$field'";
727 $res = $this->query( $sql );
728 $row = $this->fetchObject( $res );
729 if ( $row->ftype
== "varchar" ) {
730 $size = $row->size
- 4;
734 $this->freeResult( $res );
738 function limitResult( $sql, $limit, $offset = false ) {
739 if ( $offset === false )
741 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
745 function unionQueries( $sqls, $all ) {
746 $glue = ' UNION ALL ';
747 return 'SELECT * ' . ( $all ?
'':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
750 function wasDeadlock() {
751 return $this->lastErrno() == 'OCI-00060';
755 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
756 $temporary = $temporary ?
'TRUE' : 'FALSE';
757 return $this->query( 'BEGIN DUPLICATE_TABLE(\'' . $oldName . '\', \'' . $newName . '\', ' . $temporary . '); END;', $fname );
760 function timestamp( $ts = 0 ) {
761 return wfTimestamp( TS_ORACLE
, $ts );
765 * Return aggregated value function call
767 function aggregateValue ( $valuedata, $valuename = 'value' ) {
771 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
772 # Ignore errors during error handling to avoid infinite
774 $ignore = $this->ignoreErrors( true );
775 ++
$this->mErrorCount
;
777 if ( $ignore ||
$tempIgnore ) {
778 wfDebug( "SQL ERROR (ignored): $error\n" );
779 $this->ignoreErrors( $ignore );
782 throw new DBQueryError($this, $error, $errno, $sql, $fname);
787 * @return string wikitext of a link to the server software's web site
789 function getSoftwareLink() {
790 return "[http://www.oracle.com/ Oracle]";
794 * @return string Version information from the database
796 function getServerVersion() {
797 return oci_server_version( $this->mConn
);
801 * Query whether a given table exists (in the given schema, or the default mw one if not given)
803 function tableExists( $table ) {
804 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
805 $res = $this->doQuery( $SQL );
807 $count = $res->numRows();
816 * Query whether a given column exists in the mediawiki schema
817 * based on prebuilt table to simulate MySQL field info and keep query speed minimal
819 function fieldExists( $table, $field, $fname = 'DatabaseOracle::fieldExists' ) {
820 if ( !isset( $this->fieldInfo_stmt
) )
821 $this->fieldInfo_stmt
= oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)' );
823 oci_bind_by_name( $this->fieldInfo_stmt
, ':tab', trim( $table, '"' ) );
824 oci_bind_by_name( $this->fieldInfo_stmt
, ':col', $field );
826 if ( oci_execute( $this->fieldInfo_stmt
, OCI_DEFAULT
) === false ) {
827 $e = oci_error( $this->fieldInfo_stmt
);
828 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
831 $res = new ORAResult( $this, $this->fieldInfo_stmt
);
832 return $res->numRows() != 0;
835 function fieldInfo( $table, $field ) {
836 if ( !isset( $this->fieldInfo_stmt
) )
837 $this->fieldInfo_stmt
= oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)' );
839 $table = trim( $table, '"' );
840 oci_bind_by_name( $this->fieldInfo_stmt
, ':tab', $table );
841 oci_bind_by_name( $this->fieldInfo_stmt
, ':col', $field );
843 if ( oci_execute( $this->fieldInfo_stmt
, OCI_DEFAULT
) === false ) {
844 $e = oci_error( $this->fieldInfo_stmt
);
845 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
848 $res = new ORAResult( $this, $this->fieldInfo_stmt
);
849 return new ORAField( $res->fetchRow() );
852 function begin( $fname = '' ) {
853 $this->mTrxLevel
= 1;
855 function immediateCommit( $fname = '' ) {
858 function commit( $fname = '' ) {
859 oci_commit( $this->mConn
);
860 $this->mTrxLevel
= 0;
863 /* Not even sure why this is used in the main codebase... */
864 function limitResultForUpdate( $sql, $num ) {
868 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
869 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
872 $dollarquote = false;
874 $replacements = array();
876 while ( ! feof( $fp ) ) {
877 if ( $lineCallback ) {
878 call_user_func( $lineCallback );
880 $line = trim( fgets( $fp, 1024 ) );
881 $sl = strlen( $line ) - 1;
883 if ( $sl < 0 ) { continue; }
884 if ( '-' == $line { 0 } && '-' == $line { 1 } ) { continue; }
886 // Allow dollar quoting for function declarations
887 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
888 if ( $dollarquote ) {
889 $dollarquote = false;
896 else if ( !$dollarquote ) {
897 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
899 $line = substr( $line, 0, $sl );
903 if ( '' != $cmd ) { $cmd .= ' '; }
907 $cmd = str_replace( ';;', ";", $cmd );
908 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
909 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
910 $replacements[$defines[2]] = $defines[1];
913 foreach ( $replacements as $mwVar => $scVar ) {
914 $cmd = str_replace( '&' . $scVar . '.', '{$' . $mwVar . '}', $cmd );
917 $cmd = $this->replaceVars( $cmd );
918 $res = $this->query( $cmd, __METHOD__
);
919 if ( $resultCallback ) {
920 call_user_func( $resultCallback, $res, $this );
923 if ( false === $res ) {
924 $err = $this->lastError();
925 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
936 function setup_database() {
937 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
939 echo "<li>Creating DB objects</li>\n";
940 $res = $this->sourceFile( "../maintenance/ora/tables.sql" );
942 // Avoid the non-standard "REPLACE INTO" syntax
943 echo "<li>Populating table interwiki</li>\n";
944 $f = fopen( "../maintenance/interwiki.sql", 'r' );
946 dieout( "<li>Could not find the interwiki.sql file</li>" );
949 // do it like the postgres :D
950 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
951 while ( ! feof( $f ) ) {
952 $line = fgets( $f, 1024 );
954 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) {
957 $this->query( "$SQL $matches[1],$matches[2])" );
960 echo "<li>Table interwiki successfully populated</li>\n";
963 function strencode( $s ) {
964 return str_replace( "'", "''", $s );
968 function encodeBlob($b) {
969 return $b; //new ORABlob($b);
971 function decodeBlob($b) {
972 return $b; //return $b->load();
975 function addQuotes( $s ) {
977 if ( isset( $wgLang->mLoaded
) && $wgLang->mLoaded
)
978 $s = $wgLang->checkTitleEncoding( $s );
979 return "'" . $this->strencode( $s ) . "'";
982 function quote_ident( $s ) {
986 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
990 foreach ( $conds as $col => $val ) {
991 $col_type = $this->fieldInfo( $this->tableName( $table ), $col )->type();
992 if ( $col_type == 'CLOB' )
993 $conds2['TO_CHAR(' . $col . ')'] = $wgLang->checkTitleEncoding( $val );
994 elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
995 $conds2[$col] = $wgLang->checkTitleEncoding( $val );
997 $conds2[$col] = $val;
1001 if ( is_array( $table ) )
1002 foreach ( $table as $tab )
1003 $tab = $this->tableName( $tab );
1005 $table = $this->tableName( $table );
1007 return parent
::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1011 * Returns an optional USE INDEX clause to go after the table, and a
1012 * string to go at the end of the query
1016 * @param $options Array: an associative array of options to be turned into
1017 * an SQL query, valid keys are listed in the function.
1020 function makeSelectOptions( $options ) {
1021 $preLimitTail = $postLimitTail = '';
1024 $noKeyOptions = array();
1025 foreach ( $options as $key => $option ) {
1026 if ( is_numeric( $key ) ) {
1027 $noKeyOptions[$option] = true;
1031 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1032 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1034 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1035 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1036 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1038 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1039 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1044 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1047 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1050 if ( $wgLang != null ) {
1052 foreach ( $conds as $col => $val ) {
1053 $col_type = $this->fieldInfo( $this->tableName( $table ), $col )->type();
1054 if ( $col_type == 'CLOB' )
1055 $conds2['TO_CHAR(' . $col . ')'] = $wgLang->checkTitleEncoding( $val );
1057 if ( is_array( $val ) ) {
1058 $conds2[$col] = $val;
1059 foreach ( $conds2[$col] as &$val2 )
1060 $val2 = $wgLang->checkTitleEncoding( $val2 );
1062 $conds2[$col] = $wgLang->checkTitleEncoding( $val );
1066 return parent
::delete( $table, $conds2, $fname );
1067 } else return parent
::delete( $table, $conds, $fname );
1070 function bitNot( $field ) {
1071 // expecting bit-fields smaller than 4bytes
1072 return 'BITNOT(' . $bitField . ')';
1075 function bitAnd( $fieldLeft, $fieldRight ) {
1076 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1079 function bitOr( $fieldLeft, $fieldRight ) {
1080 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1084 * How lagged is this slave?
1088 public function getLag() {
1089 # Not implemented for Oracle
1093 function setFakeSlaveLag( $lag ) { }
1094 function setFakeMaster( $enabled = true ) { }
1096 function getDBname() {
1097 return $this->mDBname
;
1100 function getServer() {
1101 return $this->mServer
;
1104 public function replaceVars( $ins ) {
1105 $varnames = array( 'wgDBprefix' );
1106 if ( $this->mFlags
& DBO_SYSDBA
) {
1107 $varnames[] = 'wgDBOracleDefTS';
1108 $varnames[] = 'wgDBOracleTempTS';
1111 // Ordinary variables
1112 foreach ( $varnames as $var ) {
1113 if ( isset( $GLOBALS[$var] ) ) {
1114 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1115 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1116 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1117 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1121 return parent
::replaceVars( $ins );
1124 public function getSearchEngine() {
1125 return "SearchOracle";
1127 } // end DatabaseOracle class