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 function DatabaseOracle($server = false, $user = false, $password = false, $dbName = false,
182 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
184 $tablePrefix = $tablePrefix == 'get from global' ?
$tablePrefix : strtoupper($tablePrefix);
185 parent
::__construct($server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix);
186 wfRunHooks( 'DatabaseOraclePostInit', array(&$this));
189 function cascadingDeletes() {
192 function cleanupTriggers() {
195 function strictIPs() {
198 function realTimestamps() {
201 function implicitGroupby() {
204 function implicitOrderby() {
207 function searchableIPs() {
211 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
212 $failFunction = false, $flags = 0)
214 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags );
218 * Usually aborts on failure
219 * If the failFunction is set to a non-zero integer, returns success
221 function open( $server, $user, $password, $dbName ) {
222 if ( !function_exists( 'oci_connect' ) ) {
223 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" );
226 putenv("NLS_LANG=AMERICAN_AMERICA.AL32UTF8");
229 $this->mServer
= $server;
230 $this->mUser
= $user;
231 $this->mPassword
= $password;
232 $this->mDBname
= $dbName;
234 if (!strlen($user)) { ## e.g. the class is being loaded
238 //error_reporting( E_ALL ); //whoever had this bright idea
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, null, $session_mode);
243 $this->mConn
= oci_connect($user, $password, $dbName, null, $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\'');
262 * Closes a database connection, if it is open
263 * Returns success, true if already closed
266 $this->mOpened
= false;
267 if ( $this->mConn
) {
268 return oci_close( $this->mConn
);
274 function execFlags() {
275 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
278 function doQuery($sql) {
279 wfDebug("SQL: [$sql]\n");
280 if (!mb_check_encoding($sql)) {
281 throw new MWException("SQL encoding is invalid");
284 //handle some oracle specifics
285 //remove AS column/table/subquery namings
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 $explain_id = date('dmYHis');
293 $sql = preg_replace('/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \''.$explain_id.'\' FOR', $sql, 1, $explain_count);
296 if (($this->mLastResult
= $stmt = oci_parse($this->mConn
, $sql)) === false) {
297 $e = oci_error($this->mConn
);
298 $this->reportQueryError($e['message'], $e['code'], $sql, __FUNCTION__
);
301 $olderr = error_reporting(E_ERROR
);
302 if (oci_execute($stmt, $this->execFlags()) == false) {
303 $e = oci_error($stmt);
304 if (!$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1')
305 $this->reportQueryError($e['message'], $e['code'], $sql, __FUNCTION__
);
307 error_reporting($olderr);
309 if ($explain_count > 0) {
310 return $this->doQuery('SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \''.$explain_id.'\'');
311 } elseif (oci_statement_type($stmt) == "SELECT") {
312 return new ORAResult($this, $stmt, $union_unique);
314 $this->mAffectedRows
= oci_num_rows($stmt);
319 function queryIgnore($sql, $fname = '') {
320 return $this->query($sql, $fname, true);
323 function freeResult($res) {
324 if ( $res instanceof ORAResult
) {
327 $res->result
->free();
331 function fetchObject($res) {
332 if ( $res instanceof ORAResult
) {
333 return $res->numRows();
335 return $res->result
->fetchObject();
339 function fetchRow($res) {
340 if ( $res instanceof ORAResult
) {
341 return $res->fetchRow();
343 return $res->result
->fetchRow();
347 function numRows($res) {
348 if ( $res instanceof ORAResult
) {
349 return $res->numRows();
351 return $res->result
->numRows();
355 function numFields($res) {
356 if ( $res instanceof ORAResult
) {
357 return $res->numFields();
359 return $res->result
->numFields();
363 function fieldName($stmt, $n) {
364 return oci_field_name($stmt, $n);
368 * This must be called after nextSequenceVal
370 function insertId() {
371 return $this->mInsertId
;
374 function dataSeek($res, $row) {
375 if ( $res instanceof ORAResult
) {
378 $res->result
->seek($row);
382 function lastError() {
383 if ($this->mConn
=== false)
386 $e = oci_error($this->mConn
);
387 return $e['message'];
390 function lastErrno() {
391 if ($this->mConn
=== false)
394 $e = oci_error($this->mConn
);
398 function affectedRows() {
399 return $this->mAffectedRows
;
403 * Returns information about an index
404 * If errors are explicitly ignored, returns NULL on failure
406 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
410 function indexUnique ($table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
414 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
418 if (!is_array($options))
419 $options = array($options);
421 if (in_array('IGNORE', $options))
422 $this->ignore_DUP_VAL_ON_INDEX
= true;
424 if (!is_array(reset($a))) {
427 foreach ($a as $row) {
428 $this->insertOneRow($table, $row, $fname);
432 if (in_array('IGNORE', $options))
433 $this->ignore_DUP_VAL_ON_INDEX
= false;
438 function insertOneRow($table, $row, $fname) {
441 // "INSERT INTO tables (a, b, c)"
442 $sql = "INSERT INTO " . $this->tableName($table) . " (" . join(',', array_keys($row)) . ')';
445 // for each value, append ":key"
447 foreach ($row as $col => $val) {
457 $stmt = oci_parse($this->mConn
, $sql);
458 foreach ($row as $col => $val) {
459 if (!is_object($val)) {
460 if (oci_bind_by_name($stmt, ":$col", $row[$col]) === false)
461 $this->reportQueryError($this->lastErrno(), $this->lastError(), $sql, __METHOD__
);
465 $stmt = oci_parse($this->mConn
, $sql);
466 foreach ($row as $col => $val) {
467 $col_type=$this->fieldInfo($this->tableName($table), $col)->type();
468 if ($col_type != 'BLOB' && $col_type != 'CLOB') {
470 $val = $val->getData();
472 if (preg_match('/^timestamp.*/i', $col_type) == 1 && strtolower($val) == 'infinity')
473 $val = '31-12-2030 12:00:00.000000';
475 if (oci_bind_by_name($stmt, ":$col", $wgLang->checkTitleEncoding($val)) === false)
476 $this->reportQueryError($this->lastErrno(), $this->lastError(), $sql, __METHOD__
);
478 if (($lob[$col] = oci_new_descriptor($this->mConn
, OCI_D_LOB
)) === false) {
479 $e = oci_error($stmt);
480 throw new DBUnexpectedError($this, "Cannot create LOB descriptor: " . $e['message']);
483 if (is_object($val)) {
484 $lob[$col]->writeTemporary($val->getData());
485 oci_bind_by_name($stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
487 $lob[$col]->writeTemporary($val);
488 oci_bind_by_name($stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
493 $olderr = error_reporting(E_ERROR
);
494 if (oci_execute($stmt, OCI_DEFAULT
) === false) {
495 $e = oci_error($stmt);
497 if (!$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1')
498 $this->reportQueryError($e['message'], $e['code'], $sql, __METHOD__
);
500 $this->mAffectedRows
= oci_num_rows($stmt);
502 $this->mAffectedRows
= oci_num_rows($stmt);
503 error_reporting($olderr);
506 foreach ($lob as $lob_i => $lob_v) {
511 if (!$this->mTrxLevel
)
512 oci_commit($this->mConn
);
514 oci_free_statement($stmt);
517 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
518 $insertOptions = array(), $selectOptions = array() )
520 $destTable = $this->tableName( $destTable );
521 if( !is_array( $selectOptions ) ) {
522 $selectOptions = array( $selectOptions );
524 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
525 if( is_array( $srcTable ) ) {
526 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
528 $srcTable = $this->tableName( $srcTable );
531 if (($sequenceData = $this->getSequenceData($destTable)) !== false &&
532 !isset($varMap[$sequenceData['column']]))
533 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\''.$sequenceData['sequence'].'\')';
535 // count-alias subselect fields to avoid abigious definition errors
537 foreach($varMap as $key=>&$val)
538 $val=$val.' field'.($i++
);
540 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
541 " SELECT $startOpts " . implode( ',', $varMap ) .
542 " FROM $srcTable $useIndex ";
543 if ( $conds != '*' ) {
544 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
546 $sql .= " $tailOpts";
548 if (in_array('IGNORE', $insertOptions))
549 $this->ignore_DUP_VAL_ON_INDEX
= true;
551 $retval = $this->query( $sql, $fname );
553 if (in_array('IGNORE', $insertOptions))
554 $this->ignore_DUP_VAL_ON_INDEX
= false;
559 function tableName( $name ) {
560 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
562 Replace reserved words with better ones
563 Useing uppercase, because that's the only way oracle can handle
568 $name = 'MWUSER'; break;
570 $name = 'PAGECONTENT'; break;
574 The rest of procedure is equal to generic Databse class
575 except for the quoting style
577 if ( $name[0] == '"' && substr( $name, -1, 1 ) == '"' ) return $name;
579 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
580 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
581 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
582 else @list
( $table ) = $dbDetails;
584 $prefix = $this->mTablePrefix
;
586 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
588 if( !isset( $database )
589 && isset( $wgSharedDB )
591 && isset( $wgSharedTables )
592 && is_array( $wgSharedTables )
593 && in_array( $table, $wgSharedTables ) ) {
594 $database = $wgSharedDB;
595 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
598 if( isset($database) ) $database = ( $database[0] == '"' ?
$database : "\"{$database}\"" );
599 $table = ( $table[0] == '"' ?
$table : "\"{$prefix}{$table}\"" );
601 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
603 return strtoupper($tableName);
607 * Return the next in a sequence, save the value for retrieval via insertId()
609 function nextSequenceValue($seqName) {
610 $res = $this->query("SELECT $seqName.nextval FROM dual");
611 $row = $this->fetchRow($res);
612 $this->mInsertId
= $row[0];
613 $this->freeResult($res);
614 return $this->mInsertId
;
618 * Return sequence_name if table has a sequence
620 function getSequenceData($table) {
621 if ($this->sequenceData
== NULL) {
622 $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'");
624 while(($row = $result->fetchRow()) !== false)
625 $this->sequenceData
[$this->tableName($row[1])] = array('sequence' => $row[0], 'column' => $row[2]);
628 return (isset($this->sequenceData
[$table])) ?
$this->sequenceData
[$table] : false;
632 # REPLACE query wrapper
633 # Oracle simulates this with a DELETE followed by INSERT
634 # $row is the row to insert, an associative array
635 # $uniqueIndexes is an array of indexes. Each element may be either a
636 # field name or an array of field names
638 # It may be more efficient to leave off unique indexes which are unlikely to collide.
639 # However if you do this, you run the risk of encountering errors which wouldn't have
641 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
642 $table = $this->tableName($table);
644 if (count($rows)==0) {
649 if (!is_array(reset($rows))) {
650 $rows = array($rows);
653 foreach( $rows as $row ) {
654 # Delete rows which collide
655 if ( $uniqueIndexes ) {
656 $sql = "DELETE FROM $table WHERE ";
658 foreach ( $uniqueIndexes as $index ) {
665 if ( is_array( $index ) ) {
667 foreach ( $index as $col ) {
673 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
676 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
680 $this->query( $sql, $fname );
684 $this->insert( $table, $row, $fname );
688 # DELETE where the condition is a join
689 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseOracle::deleteJoin" ) {
691 throw new DBUnexpectedError($this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
694 $delTable = $this->tableName( $delTable );
695 $joinTable = $this->tableName( $joinTable );
696 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
697 if ( $conds != '*' ) {
698 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
702 $this->query( $sql, $fname );
705 # Returns the size of a text field, or -1 for "unlimited"
706 function textFieldSize( $table, $field ) {
707 $table = $this->tableName( $table );
708 $sql = "SELECT t.typname as ftype,a.atttypmod as size
709 FROM pg_class c, pg_attribute a, pg_type t
710 WHERE relname='$table' AND a.attrelid=c.oid AND
711 a.atttypid=t.oid and a.attname='$field'";
712 $res =$this->query($sql);
713 $row=$this->fetchObject($res);
714 if ($row->ftype
=="varchar") {
719 $this->freeResult( $res );
723 function limitResult($sql, $limit, $offset) {
724 if ($offset === false)
726 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
730 function unionQueries($sqls, $all = false) {
731 $glue = ' UNION ALL ';
732 return 'SELECT * '.($all?
'':'/* UNION_UNIQUE */ ').'FROM ('.implode( $glue, $sqls ).')' ;
735 function wasDeadlock() {
736 return $this->lastErrno() == 'OCI-00060';
739 function timestamp($ts = 0) {
740 return wfTimestamp(TS_ORACLE
, $ts);
744 * Return aggregated value function call
746 function aggregateValue ($valuedata,$valuename='value') {
750 function reportQueryError($error, $errno, $sql, $fname, $tempIgnore = false) {
751 # Ignore errors during error handling to avoid infinite
753 $ignore = $this->ignoreErrors(true);
754 ++
$this->mErrorCount
;
756 if ($ignore ||
$tempIgnore) {
757 //echo "error ignored! query = [$sql]\n";
758 wfDebug("SQL ERROR (ignored): $error\n");
759 $this->ignoreErrors( $ignore );
763 $message = "A database error has occurred\n" .
765 "Function: $fname\n" .
766 "Error: $errno $error\n";
767 throw new DBUnexpectedError($this, $message);
772 * @return string wikitext of a link to the server software's web site
774 function getSoftwareLink() {
775 return "[http://www.oracle.com/ Oracle]";
779 * @return string Version information from the database
781 function getServerVersion() {
782 return oci_server_version($this->mConn
);
786 * Query whether a given table exists (in the given schema, or the default mw one if not given)
788 function tableExists($table) {
789 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
790 $res = $this->doQuery($SQL);
792 $count = $res->numRows();
801 * Query whether a given column exists in the mediawiki schema
802 * based on prebuilt table to simulate MySQL field info and keep query speed minimal
804 function fieldExists( $table, $field ) {
805 if (!isset($this->fieldInfo_stmt
))
806 $this->fieldInfo_stmt
= oci_parse($this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)');
808 oci_bind_by_name($this->fieldInfo_stmt
, ':tab', trim($table, '"'));
809 oci_bind_by_name($this->fieldInfo_stmt
, ':col', $field);
811 if (oci_execute($this->fieldInfo_stmt
, OCI_DEFAULT
) === false) {
812 $e = oci_error($this->fieldInfo_stmt
);
813 $this->reportQueryError($e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
816 $res = new ORAResult($this,$this->fieldInfo_stmt
);
817 return $res->numRows() != 0;
820 function fieldInfo( $table, $field ) {
821 if (!isset($this->fieldInfo_stmt
))
822 $this->fieldInfo_stmt
= oci_parse($this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)');
824 oci_bind_by_name($this->fieldInfo_stmt
, ':tab', trim($table, '"'));
825 oci_bind_by_name($this->fieldInfo_stmt
, ':col', $field);
827 if (oci_execute($this->fieldInfo_stmt
, OCI_DEFAULT
) === false) {
828 $e = oci_error($this->fieldInfo_stmt
);
829 $this->reportQueryError($e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
832 $res = new ORAResult($this,$this->fieldInfo_stmt
);
833 return new ORAField($res->fetchRow());
836 function begin( $fname = '' ) {
837 $this->mTrxLevel
= 1;
839 function immediateCommit( $fname = '' ) {
842 function commit( $fname = '' ) {
843 oci_commit($this->mConn
);
844 $this->mTrxLevel
= 0;
847 /* Not even sure why this is used in the main codebase... */
848 function limitResultForUpdate($sql, $num) {
852 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
853 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
856 $dollarquote = false;
858 $replacements = array();
860 while ( ! feof( $fp ) ) {
861 if ( $lineCallback ) {
862 call_user_func( $lineCallback );
864 $line = trim( fgets( $fp, 1024 ) );
865 $sl = strlen( $line ) - 1;
867 if ( $sl < 0 ) { continue; }
868 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
870 // Allow dollar quoting for function declarations
871 if (substr($line,0,8) == '/*$mw$*/') {
873 $dollarquote = false;
880 else if (!$dollarquote) {
881 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
883 $line = substr( $line, 0, $sl );
887 if ( '' != $cmd ) { $cmd .= ' '; }
891 $cmd = str_replace(';;', ";", $cmd);
892 if (strtolower(substr($cmd, 0, 6)) == 'define' ) {
893 if (preg_match('/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines)) {
894 $replacements[$defines[2]] = $defines[1];
897 foreach ( $replacements as $mwVar=>$scVar ) {
898 $cmd = str_replace( '&' . $scVar . '.', '{$'.$mwVar.'}', $cmd );
901 $cmd = $this->replaceVars( $cmd );
902 $res = $this->query( $cmd, __METHOD__
);
903 if ( $resultCallback ) {
904 call_user_func( $resultCallback, $res, $this );
907 if ( false === $res ) {
908 $err = $this->lastError();
909 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
920 function setup_database() {
921 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
923 echo "<li>Creating DB objects</li>\n";
924 $res = $this->sourceFile( "../maintenance/ora/tables.sql" );
926 // Avoid the non-standard "REPLACE INTO" syntax
927 echo "<li>Populating table interwiki</li>\n";
928 $f = fopen( "../maintenance/interwiki.sql", 'r' );
930 dieout( "<li>Could not find the interwiki.sql file</li>");
933 //do it like the postgres :D
934 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
935 while ( ! feof( $f ) ) {
936 $line = fgets($f,1024);
938 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
941 $this->query("$SQL $matches[1],$matches[2])");
944 echo "<li>Table interwiki successfully populated</li>\n";
947 function strencode($s) {
948 return str_replace("'", "''", $s);
951 function encodeBlob($b) {
952 return new ORABlob($b);
954 function decodeBlob($b) {
955 return $b; //return $b->load();
958 function addQuotes( $s ) {
960 if (isset($wgLang->mLoaded
) && $wgLang->mLoaded
)
961 $s = $wgLang->checkTitleEncoding($s);
962 return "'" . $this->strencode($s) . "'";
965 function quote_ident( $s ) {
969 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
970 if (is_array($table))
971 foreach ($table as $tab)
972 $tab = $this->tableName($tab);
974 $table = $this->tableName($table);
975 return parent
::selectRow($table, $vars, $conds, $fname, $options, $join_conds);
979 * Returns an optional USE INDEX clause to go after the table, and a
980 * string to go at the end of the query
984 * @param $options Array: an associative array of options to be turned into
985 * an SQL query, valid keys are listed in the function.
988 function makeSelectOptions( $options ) {
989 $preLimitTail = $postLimitTail = '';
992 $noKeyOptions = array();
993 foreach ( $options as $key => $option ) {
994 if ( is_numeric( $key ) ) {
995 $noKeyOptions[$option] = true;
999 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1000 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1002 #if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1003 #if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1004 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1006 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1007 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1012 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1015 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1018 foreach($conds as $col=>$val) {
1019 $col_type=$this->fieldInfo($this->tableName($table), $col)->type();
1020 if ($col_type == 'CLOB')
1021 $conds2['TO_CHAR('.$col.')'] = $val;
1023 $conds2[$col] = $val;
1026 return parent
::delete( $table, $conds2, $fname );
1029 function bitNot($field) {
1030 //expecting bit-fields smaller than 4bytes
1031 return 'BITNOT('.$bitField.')';
1034 function bitAnd($fieldLeft, $fieldRight) {
1035 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1038 function bitOr($fieldLeft, $fieldRight) {
1039 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';
1043 * How lagged is this slave?
1047 public function getLag() {
1048 # Not implemented for Oracle
1052 function setFakeSlaveLag( $lag ) {}
1053 function setFakeMaster( $enabled = true ) {}
1055 function getDBname() {
1056 return $this->mDBname
;
1059 function getServer() {
1060 return $this->mServer
;
1063 public function replaceVars( $ins ) {
1064 $varnames = array('wgDBprefix');
1065 if ($this->mFlags
& DBO_SYSDBA
) {
1066 $varnames[] = 'wgDBOracleDefTS';
1067 $varnames[] = 'wgDBOracleTempTS';
1070 // Ordinary variables
1071 foreach ( $varnames as $var ) {
1072 if( isset( $GLOBALS[$var] ) ) {
1073 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1074 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1075 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1076 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1080 return parent
::replaceVars($ins);
1083 public function getSearchEngine() {
1084 return "SearchOracle";
1086 } // end DatabaseOracle class