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();
469 // do nothing ... null was inserted in statement creation
470 } elseif ($col_type != 'BLOB' && $col_type != 'CLOB') {
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);
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") {
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 $message = "A database error has occurred\n" .
784 "Function: $fname\n" .
785 "Error: $errno $error\n";
786 throw new DBUnexpectedError($this, $message);
791 * @return string wikitext of a link to the server software's web site
793 function getSoftwareLink() {
794 return "[http://www.oracle.com/ Oracle]";
798 * @return string Version information from the database
800 function getServerVersion() {
801 return oci_server_version($this->mConn
);
805 * Query whether a given table exists (in the given schema, or the default mw one if not given)
807 function tableExists($table) {
808 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
809 $res = $this->doQuery($SQL);
811 $count = $res->numRows();
820 * Query whether a given column exists in the mediawiki schema
821 * based on prebuilt table to simulate MySQL field info and keep query speed minimal
823 function fieldExists( $table, $field, $fname = 'DatabaseOracle::fieldExists' ) {
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 oci_bind_by_name($this->fieldInfo_stmt
, ':tab', trim($table, '"'));
828 oci_bind_by_name($this->fieldInfo_stmt
, ':col', $field);
830 if (oci_execute($this->fieldInfo_stmt
, OCI_DEFAULT
) === false) {
831 $e = oci_error($this->fieldInfo_stmt
);
832 $this->reportQueryError($e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
835 $res = new ORAResult($this,$this->fieldInfo_stmt
);
836 return $res->numRows() != 0;
839 function fieldInfo( $table, $field ) {
840 if (!isset($this->fieldInfo_stmt
))
841 $this->fieldInfo_stmt
= oci_parse($this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)');
843 $table = trim($table, '"');
844 oci_bind_by_name($this->fieldInfo_stmt
, ':tab', $table);
845 oci_bind_by_name($this->fieldInfo_stmt
, ':col', $field);
847 if (oci_execute($this->fieldInfo_stmt
, OCI_DEFAULT
) === false) {
848 $e = oci_error($this->fieldInfo_stmt
);
849 $this->reportQueryError($e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
852 $res = new ORAResult($this,$this->fieldInfo_stmt
);
853 return new ORAField($res->fetchRow());
856 function begin( $fname = '' ) {
857 $this->mTrxLevel
= 1;
859 function immediateCommit( $fname = '' ) {
862 function commit( $fname = '' ) {
863 oci_commit($this->mConn
);
864 $this->mTrxLevel
= 0;
867 /* Not even sure why this is used in the main codebase... */
868 function limitResultForUpdate($sql, $num) {
872 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
873 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
876 $dollarquote = false;
878 $replacements = array();
880 while ( ! feof( $fp ) ) {
881 if ( $lineCallback ) {
882 call_user_func( $lineCallback );
884 $line = trim( fgets( $fp, 1024 ) );
885 $sl = strlen( $line ) - 1;
887 if ( $sl < 0 ) { continue; }
888 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
890 // Allow dollar quoting for function declarations
891 if (substr($line,0,8) == '/*$mw$*/') {
893 $dollarquote = false;
900 else if (!$dollarquote) {
901 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
903 $line = substr( $line, 0, $sl );
907 if ( '' != $cmd ) { $cmd .= ' '; }
911 $cmd = str_replace(';;', ";", $cmd);
912 if (strtolower(substr($cmd, 0, 6)) == 'define' ) {
913 if (preg_match('/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines)) {
914 $replacements[$defines[2]] = $defines[1];
917 foreach ( $replacements as $mwVar=>$scVar ) {
918 $cmd = str_replace( '&' . $scVar . '.', '{$'.$mwVar.'}', $cmd );
921 $cmd = $this->replaceVars( $cmd );
922 $res = $this->query( $cmd, __METHOD__
);
923 if ( $resultCallback ) {
924 call_user_func( $resultCallback, $res, $this );
927 if ( false === $res ) {
928 $err = $this->lastError();
929 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
940 function setup_database() {
941 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
943 echo "<li>Creating DB objects</li>\n";
944 $res = $this->sourceFile( "../maintenance/ora/tables.sql" );
946 // Avoid the non-standard "REPLACE INTO" syntax
947 echo "<li>Populating table interwiki</li>\n";
948 $f = fopen( "../maintenance/interwiki.sql", 'r' );
950 dieout( "<li>Could not find the interwiki.sql file</li>");
953 //do it like the postgres :D
954 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
955 while ( ! feof( $f ) ) {
956 $line = fgets($f,1024);
958 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
961 $this->query("$SQL $matches[1],$matches[2])");
964 echo "<li>Table interwiki successfully populated</li>\n";
967 function strencode($s) {
968 return str_replace("'", "''", $s);
972 function encodeBlob($b) {
973 return $b; //new ORABlob($b);
975 function decodeBlob($b) {
976 return $b; //return $b->load();
979 function addQuotes( $s ) {
981 if (isset($wgLang->mLoaded
) && $wgLang->mLoaded
)
982 $s = $wgLang->checkTitleEncoding($s);
983 return "'" . $this->strencode($s) . "'";
986 function quote_ident( $s ) {
990 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
994 foreach($conds as $col=>$val) {
995 $col_type=$this->fieldInfo($this->tableName($table), $col)->type();
996 if ($col_type == 'CLOB')
997 $conds2['TO_CHAR('.$col.')'] = $wgLang->checkTitleEncoding($val);
998 elseif ($col_type == 'VARCHAR2' && !mb_check_encoding($val)) {
999 $conds2[$col] = $wgLang->checkTitleEncoding($val);
1001 $conds2[$col] = $val;
1005 if (is_array($table))
1006 foreach ($table as $tab)
1007 $tab = $this->tableName($tab);
1009 $table = $this->tableName($table);
1011 return parent
::selectRow($table, $vars, $conds2, $fname, $options, $join_conds);
1015 * Returns an optional USE INDEX clause to go after the table, and a
1016 * string to go at the end of the query
1020 * @param $options Array: an associative array of options to be turned into
1021 * an SQL query, valid keys are listed in the function.
1024 function makeSelectOptions( $options ) {
1025 $preLimitTail = $postLimitTail = '';
1028 $noKeyOptions = array();
1029 foreach ( $options as $key => $option ) {
1030 if ( is_numeric( $key ) ) {
1031 $noKeyOptions[$option] = true;
1035 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1036 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1038 #if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1039 #if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1040 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1042 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1043 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1048 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1051 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1054 if ($wgLang != null) {
1056 foreach($conds as $col=>$val) {
1057 $col_type=$this->fieldInfo($this->tableName($table), $col)->type();
1058 if ($col_type == 'CLOB')
1059 $conds2['TO_CHAR('.$col.')'] = $wgLang->checkTitleEncoding($val);
1061 $conds2[$col] = $wgLang->checkTitleEncoding($val);
1064 return parent
::delete( $table, $conds2, $fname );
1065 } else return parent
::delete( $table, $conds, $fname );
1068 function bitNot($field) {
1069 //expecting bit-fields smaller than 4bytes
1070 return 'BITNOT('.$bitField.')';
1073 function bitAnd($fieldLeft, $fieldRight) {
1074 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1077 function bitOr($fieldLeft, $fieldRight) {
1078 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';
1082 * How lagged is this slave?
1086 public function getLag() {
1087 # Not implemented for Oracle
1091 function setFakeSlaveLag( $lag ) {}
1092 function setFakeMaster( $enabled = true ) {}
1094 function getDBname() {
1095 return $this->mDBname
;
1098 function getServer() {
1099 return $this->mServer
;
1102 public function replaceVars( $ins ) {
1103 $varnames = array('wgDBprefix');
1104 if ($this->mFlags
& DBO_SYSDBA
) {
1105 $varnames[] = 'wgDBOracleDefTS';
1106 $varnames[] = 'wgDBOracleTempTS';
1109 // Ordinary variables
1110 foreach ( $varnames as $var ) {
1111 if( isset( $GLOBALS[$var] ) ) {
1112 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1113 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1114 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1115 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1119 return parent
::replaceVars($ins);
1122 public function getSearchEngine() {
1123 return "SearchOracle";
1125 } // end DatabaseOracle class