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, $user, $password, $dbName, $failFunction = false, $flags = 0 )
213 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags );
217 * Usually aborts on failure
218 * If the failFunction is set to a non-zero integer, returns success
220 function open( $server, $user, $password, $dbName ) {
221 if ( !function_exists( 'oci_connect' ) ) {
222 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" );
225 putenv("NLS_LANG=AMERICAN_AMERICA.AL32UTF8");
228 $this->mServer
= $server;
229 $this->mUser
= $user;
230 $this->mPassword
= $password;
231 $this->mDBname
= $dbName;
233 if (!strlen($user)) { ## e.g. the class is being loaded
237 //error_reporting( E_ALL ); //whoever had this bright idea
238 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
239 if ( $this->mFlags
& DBO_DEFAULT
)
240 $this->mConn
= oci_new_connect($user, $password, $dbName, null, $session_mode);
242 $this->mConn
= oci_connect($user, $password, $dbName, null, $session_mode);
244 if ($this->mConn
== false) {
245 wfDebug("DB connection error\n");
246 wfDebug("Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n");
247 wfDebug($this->lastError()."\n");
251 $this->mOpened
= true;
253 #removed putenv calls because they interfere with the system globaly
254 $this->doQuery('ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'');
255 $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 $sql = preg_replace('/ as /i', ' ', $sql);
286 // Oracle has issues with UNION clause if the statement includes LOB fields
287 // So we do a UNION ALL and then filter the results array with array_unique
288 $union_unique = (preg_match('/\/\* UNION_UNIQUE \*\/ /', $sql) != 0);
289 //EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
290 //you have to select data from plan table after explain
291 $olderr = error_reporting(E_ERROR
);
292 $explain_id = date('dmYHis');
293 error_reporting($olderr);
294 $sql = preg_replace('/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \''.$explain_id.'\' FOR', $sql, 1, $explain_count);
297 if (($this->mLastResult
= $stmt = oci_parse($this->mConn
, $sql)) === false) {
298 $e = oci_error($this->mConn
);
299 $this->reportQueryError($e['message'], $e['code'], $sql, __FUNCTION__
);
302 $olderr = error_reporting(E_ERROR
);
303 if (oci_execute($stmt, $this->execFlags()) == false) {
304 $e = oci_error($stmt);
305 if (!$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1')
306 $this->reportQueryError($e['message'], $e['code'], $sql, __FUNCTION__
);
308 error_reporting($olderr);
310 if ($explain_count > 0) {
311 return $this->doQuery('SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \''.$explain_id.'\'');
312 } elseif (oci_statement_type($stmt) == "SELECT") {
313 return new ORAResult($this, $stmt, $union_unique);
315 $this->mAffectedRows
= oci_num_rows($stmt);
320 function queryIgnore($sql, $fname = '') {
321 return $this->query($sql, $fname, true);
324 function freeResult($res) {
325 if ( $res instanceof ORAResult
) {
328 $res->result
->free();
332 function fetchObject($res) {
333 if ( $res instanceof ORAResult
) {
334 return $res->numRows();
336 return $res->result
->fetchObject();
340 function fetchRow($res) {
341 if ( $res instanceof ORAResult
) {
342 return $res->fetchRow();
344 return $res->result
->fetchRow();
348 function numRows($res) {
349 if ( $res instanceof ORAResult
) {
350 return $res->numRows();
352 return $res->result
->numRows();
356 function numFields($res) {
357 if ( $res instanceof ORAResult
) {
358 return $res->numFields();
360 return $res->result
->numFields();
364 function fieldName($stmt, $n) {
365 return oci_field_name($stmt, $n);
369 * This must be called after nextSequenceVal
371 function insertId() {
372 return $this->mInsertId
;
375 function dataSeek($res, $row) {
376 if ( $res instanceof ORAResult
) {
379 $res->result
->seek($row);
383 function lastError() {
384 if ($this->mConn
=== false)
387 $e = oci_error($this->mConn
);
388 return $e['message'];
391 function lastErrno() {
392 if ($this->mConn
=== false)
395 $e = oci_error($this->mConn
);
399 function affectedRows() {
400 return $this->mAffectedRows
;
404 * Returns information about an index
405 * If errors are explicitly ignored, returns NULL on failure
407 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
411 function indexUnique ($table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
415 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
419 if (!is_array($options))
420 $options = array($options);
422 if (in_array('IGNORE', $options))
423 $this->ignore_DUP_VAL_ON_INDEX
= true;
425 if (!is_array(reset($a))) {
428 foreach ($a as $row) {
429 $this->insertOneRow($table, $row, $fname);
433 if (in_array('IGNORE', $options))
434 $this->ignore_DUP_VAL_ON_INDEX
= false;
439 function insertOneRow($table, $row, $fname) {
442 // "INSERT INTO tables (a, b, c)"
443 $sql = "INSERT INTO " . $this->tableName($table) . " (" . join(',', array_keys($row)) . ')';
446 // for each value, append ":key"
448 foreach ($row as $col => $val) {
450 $sql .= $val !== NULL ?
':'.$col : 'NULL';
452 $sql .= $val !== NULL ?
', :'.$col : ', NULL';
459 $stmt = oci_parse($this->mConn
, $sql);
460 foreach ($row as $col => &$val) {
461 $col_type=$this->fieldInfo($this->tableName($table), $col)->type();
464 // do nothing ... null was inserted in statement creation
465 } elseif ($col_type != 'BLOB' && $col_type != 'CLOB') {
467 $val = $val->getData();
469 if (preg_match('/^timestamp.*/i', $col_type) == 1 && strtolower($val) == 'infinity')
470 $val = '31-12-2030 12:00:00.000000';
472 $val = $wgLang->checkTitleEncoding($val);
473 if (oci_bind_by_name($stmt, ":$col", $val) === false)
474 $this->reportQueryError($this->lastErrno(), $this->lastError(), $sql, __METHOD__
);
476 if (($lob[$col] = oci_new_descriptor($this->mConn
, OCI_D_LOB
)) === false) {
477 $e = oci_error($stmt);
478 throw new DBUnexpectedError($this, "Cannot create LOB descriptor: " . $e['message']);
481 if ($col_type == 'BLOB') { //is_object($val)) {
482 $lob[$col]->writeTemporary($val); //->getData());
483 oci_bind_by_name($stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
485 $lob[$col]->writeTemporary($val);
486 oci_bind_by_name($stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
491 $olderr = error_reporting(E_ERROR
);
492 if (oci_execute($stmt, OCI_DEFAULT
) === false) {
493 $e = oci_error($stmt);
495 if (!$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1')
496 $this->reportQueryError($e['message'], $e['code'], $sql, __METHOD__
);
498 $this->mAffectedRows
= oci_num_rows($stmt);
500 $this->mAffectedRows
= oci_num_rows($stmt);
501 error_reporting($olderr);
504 foreach ($lob as $lob_i => $lob_v) {
509 if (!$this->mTrxLevel
)
510 oci_commit($this->mConn
);
512 oci_free_statement($stmt);
515 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
516 $insertOptions = array(), $selectOptions = array() )
518 $destTable = $this->tableName( $destTable );
519 if( !is_array( $selectOptions ) ) {
520 $selectOptions = array( $selectOptions );
522 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
523 if( is_array( $srcTable ) ) {
524 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
526 $srcTable = $this->tableName( $srcTable );
529 if (($sequenceData = $this->getSequenceData($destTable)) !== false &&
530 !isset($varMap[$sequenceData['column']]))
531 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\''.$sequenceData['sequence'].'\')';
533 // count-alias subselect fields to avoid abigious definition errors
535 foreach($varMap as $key=>&$val)
536 $val=$val.' field'.($i++
);
538 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
539 " SELECT $startOpts " . implode( ',', $varMap ) .
540 " FROM $srcTable $useIndex ";
541 if ( $conds != '*' ) {
542 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
544 $sql .= " $tailOpts";
546 if (in_array('IGNORE', $insertOptions))
547 $this->ignore_DUP_VAL_ON_INDEX
= true;
549 $retval = $this->query( $sql, $fname );
551 if (in_array('IGNORE', $insertOptions))
552 $this->ignore_DUP_VAL_ON_INDEX
= false;
557 function tableName( $name ) {
558 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
560 Replace reserved words with better ones
561 Useing uppercase, because that's the only way oracle can handle
566 $name = 'MWUSER'; break;
568 $name = 'PAGECONTENT'; break;
572 The rest of procedure is equal to generic Databse class
573 except for the quoting style
575 if ( $name[0] == '"' && substr( $name, -1, 1 ) == '"' ) return $name;
577 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
578 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
579 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
580 else @list
( $table ) = $dbDetails;
582 $prefix = $this->mTablePrefix
;
584 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
586 if( !isset( $database )
587 && isset( $wgSharedDB )
589 && isset( $wgSharedTables )
590 && is_array( $wgSharedTables )
591 && in_array( $table, $wgSharedTables ) ) {
592 $database = $wgSharedDB;
593 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
596 if( isset($database) ) $database = ( $database[0] == '"' ?
$database : "\"{$database}\"" );
597 $table = ( $table[0] == '"' ?
$table : "\"{$prefix}{$table}\"" );
599 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
601 return strtoupper($tableName);
605 * Return the next in a sequence, save the value for retrieval via insertId()
607 function nextSequenceValue($seqName) {
608 $res = $this->query("SELECT $seqName.nextval FROM dual");
609 $row = $this->fetchRow($res);
610 $this->mInsertId
= $row[0];
611 $this->freeResult($res);
612 return $this->mInsertId
;
616 * Return sequence_name if table has a sequence
618 function getSequenceData($table) {
619 if ($this->sequenceData
== NULL) {
620 $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'");
622 while(($row = $result->fetchRow()) !== false)
623 $this->sequenceData
[$this->tableName($row[1])] = array('sequence' => $row[0], 'column' => $row[2]);
626 return (isset($this->sequenceData
[$table])) ?
$this->sequenceData
[$table] : false;
630 # REPLACE query wrapper
631 # Oracle simulates this with a DELETE followed by INSERT
632 # $row is the row to insert, an associative array
633 # $uniqueIndexes is an array of indexes. Each element may be either a
634 # field name or an array of field names
636 # It may be more efficient to leave off unique indexes which are unlikely to collide.
637 # However if you do this, you run the risk of encountering errors which wouldn't have
639 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
640 $table = $this->tableName($table);
642 if (count($rows)==0) {
647 if (!is_array(reset($rows))) {
648 $rows = array($rows);
651 $sequenceData = $this->getSequenceData($table);
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 );
683 if ($sequenceData !== false && !isset($row[$sequenceData['column']]))
684 $row[$sequenceData['column']] = $this->nextSequenceValue($sequenceData['sequence']);
687 $this->insert( $table, $row, $fname );
691 # DELETE where the condition is a join
692 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseOracle::deleteJoin" ) {
694 throw new DBUnexpectedError($this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
697 $delTable = $this->tableName( $delTable );
698 $joinTable = $this->tableName( $joinTable );
699 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
700 if ( $conds != '*' ) {
701 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
705 $this->query( $sql, $fname );
708 # Returns the size of a text field, or -1 for "unlimited"
709 function textFieldSize( $table, $field ) {
710 $table = $this->tableName( $table );
711 $sql = "SELECT t.typname as ftype,a.atttypmod as size
712 FROM pg_class c, pg_attribute a, pg_type t
713 WHERE relname='$table' AND a.attrelid=c.oid AND
714 a.atttypid=t.oid and a.attname='$field'";
715 $res =$this->query($sql);
716 $row=$this->fetchObject($res);
717 if ($row->ftype
=="varchar") {
722 $this->freeResult( $res );
726 function limitResult( $sql, $limit, $offset=false ) {
727 if ($offset === false)
729 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
733 function unionQueries($sqls, $all) {
734 $glue = ' UNION ALL ';
735 return 'SELECT * '.($all?
'':'/* UNION_UNIQUE */ ').'FROM ('.implode( $glue, $sqls ).')' ;
738 function wasDeadlock() {
739 return $this->lastErrno() == 'OCI-00060';
742 function timestamp($ts = 0) {
743 return wfTimestamp(TS_ORACLE
, $ts);
747 * Return aggregated value function call
749 function aggregateValue ($valuedata,$valuename='value') {
753 function reportQueryError($error, $errno, $sql, $fname, $tempIgnore = false) {
754 # Ignore errors during error handling to avoid infinite
756 $ignore = $this->ignoreErrors(true);
757 ++
$this->mErrorCount
;
759 if ($ignore ||
$tempIgnore) {
760 //echo "error ignored! query = [$sql]\n";
761 wfDebug("SQL ERROR (ignored): $error\n");
762 $this->ignoreErrors( $ignore );
766 $message = "A database error has occurred\n" .
768 "Function: $fname\n" .
769 "Error: $errno $error\n";
770 throw new DBUnexpectedError($this, $message);
775 * @return string wikitext of a link to the server software's web site
777 function getSoftwareLink() {
778 return "[http://www.oracle.com/ Oracle]";
782 * @return string Version information from the database
784 function getServerVersion() {
785 return oci_server_version($this->mConn
);
789 * Query whether a given table exists (in the given schema, or the default mw one if not given)
791 function tableExists($table) {
792 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
793 $res = $this->doQuery($SQL);
795 $count = $res->numRows();
804 * Query whether a given column exists in the mediawiki schema
805 * based on prebuilt table to simulate MySQL field info and keep query speed minimal
807 function fieldExists( $table, $field, $fname = 'DatabaseOracle::fieldExists' ) {
808 if (!isset($this->fieldInfo_stmt
))
809 $this->fieldInfo_stmt
= oci_parse($this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)');
811 oci_bind_by_name($this->fieldInfo_stmt
, ':tab', trim($table, '"'));
812 oci_bind_by_name($this->fieldInfo_stmt
, ':col', $field);
814 if (oci_execute($this->fieldInfo_stmt
, OCI_DEFAULT
) === false) {
815 $e = oci_error($this->fieldInfo_stmt
);
816 $this->reportQueryError($e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
819 $res = new ORAResult($this,$this->fieldInfo_stmt
);
820 return $res->numRows() != 0;
823 function fieldInfo( $table, $field ) {
824 if (!isset($this->fieldInfo_stmt
))
825 $this->fieldInfo_stmt
= oci_parse($this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)');
827 $table = trim($table, '"');
828 oci_bind_by_name($this->fieldInfo_stmt
, ':tab', $table);
829 oci_bind_by_name($this->fieldInfo_stmt
, ':col', $field);
831 if (oci_execute($this->fieldInfo_stmt
, OCI_DEFAULT
) === false) {
832 $e = oci_error($this->fieldInfo_stmt
);
833 $this->reportQueryError($e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
836 $res = new ORAResult($this,$this->fieldInfo_stmt
);
837 return new ORAField($res->fetchRow());
840 function begin( $fname = '' ) {
841 $this->mTrxLevel
= 1;
843 function immediateCommit( $fname = '' ) {
846 function commit( $fname = '' ) {
847 oci_commit($this->mConn
);
848 $this->mTrxLevel
= 0;
851 /* Not even sure why this is used in the main codebase... */
852 function limitResultForUpdate($sql, $num) {
856 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
857 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
860 $dollarquote = false;
862 $replacements = array();
864 while ( ! feof( $fp ) ) {
865 if ( $lineCallback ) {
866 call_user_func( $lineCallback );
868 $line = trim( fgets( $fp, 1024 ) );
869 $sl = strlen( $line ) - 1;
871 if ( $sl < 0 ) { continue; }
872 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
874 // Allow dollar quoting for function declarations
875 if (substr($line,0,8) == '/*$mw$*/') {
877 $dollarquote = false;
884 else if (!$dollarquote) {
885 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
887 $line = substr( $line, 0, $sl );
891 if ( '' != $cmd ) { $cmd .= ' '; }
895 $cmd = str_replace(';;', ";", $cmd);
896 if (strtolower(substr($cmd, 0, 6)) == 'define' ) {
897 if (preg_match('/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines)) {
898 $replacements[$defines[2]] = $defines[1];
901 foreach ( $replacements as $mwVar=>$scVar ) {
902 $cmd = str_replace( '&' . $scVar . '.', '{$'.$mwVar.'}', $cmd );
905 $cmd = $this->replaceVars( $cmd );
906 $res = $this->query( $cmd, __METHOD__
);
907 if ( $resultCallback ) {
908 call_user_func( $resultCallback, $res, $this );
911 if ( false === $res ) {
912 $err = $this->lastError();
913 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
924 function setup_database() {
925 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
927 echo "<li>Creating DB objects</li>\n";
928 $res = $this->sourceFile( "../maintenance/ora/tables.sql" );
930 // Avoid the non-standard "REPLACE INTO" syntax
931 echo "<li>Populating table interwiki</li>\n";
932 $f = fopen( "../maintenance/interwiki.sql", 'r' );
934 dieout( "<li>Could not find the interwiki.sql file</li>");
937 //do it like the postgres :D
938 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
939 while ( ! feof( $f ) ) {
940 $line = fgets($f,1024);
942 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
945 $this->query("$SQL $matches[1],$matches[2])");
948 echo "<li>Table interwiki successfully populated</li>\n";
951 function strencode($s) {
952 return str_replace("'", "''", $s);
956 function encodeBlob($b) {
957 return $b; //new ORABlob($b);
959 function decodeBlob($b) {
960 return $b; //return $b->load();
963 function addQuotes( $s ) {
965 if (isset($wgLang->mLoaded
) && $wgLang->mLoaded
)
966 $s = $wgLang->checkTitleEncoding($s);
967 return "'" . $this->strencode($s) . "'";
970 function quote_ident( $s ) {
974 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
975 if (is_array($table))
976 foreach ($table as $tab)
977 $tab = $this->tableName($tab);
979 $table = $this->tableName($table);
980 return parent
::selectRow($table, $vars, $conds, $fname, $options, $join_conds);
984 * Returns an optional USE INDEX clause to go after the table, and a
985 * string to go at the end of the query
989 * @param $options Array: an associative array of options to be turned into
990 * an SQL query, valid keys are listed in the function.
993 function makeSelectOptions( $options ) {
994 $preLimitTail = $postLimitTail = '';
997 $noKeyOptions = array();
998 foreach ( $options as $key => $option ) {
999 if ( is_numeric( $key ) ) {
1000 $noKeyOptions[$option] = true;
1004 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1005 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1007 #if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1008 #if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1009 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1011 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1012 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1017 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1020 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1023 foreach($conds as $col=>$val) {
1024 $col_type=$this->fieldInfo($this->tableName($table), $col)->type();
1025 if ($col_type == 'CLOB')
1026 $conds2['TO_CHAR('.$col.')'] = $val;
1028 $conds2[$col] = $val;
1031 return parent
::delete( $table, $conds2, $fname );
1034 function bitNot($field) {
1035 //expecting bit-fields smaller than 4bytes
1036 return 'BITNOT('.$bitField.')';
1039 function bitAnd($fieldLeft, $fieldRight) {
1040 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1043 function bitOr($fieldLeft, $fieldRight) {
1044 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';
1048 * How lagged is this slave?
1052 public function getLag() {
1053 # Not implemented for Oracle
1057 function setFakeSlaveLag( $lag ) {}
1058 function setFakeMaster( $enabled = true ) {}
1060 function getDBname() {
1061 return $this->mDBname
;
1064 function getServer() {
1065 return $this->mServer
;
1068 public function replaceVars( $ins ) {
1069 $varnames = array('wgDBprefix');
1070 if ($this->mFlags
& DBO_SYSDBA
) {
1071 $varnames[] = 'wgDBOracleDefTS';
1072 $varnames[] = 'wgDBOracleTempTS';
1075 // Ordinary variables
1076 foreach ( $varnames as $var ) {
1077 if( isset( $GLOBALS[$var] ) ) {
1078 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1079 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1080 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1081 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1085 return parent
::replaceVars($ins);
1088 public function getSearchEngine() {
1089 return "SearchOracle";
1091 } // end DatabaseOracle class