more specific error message, using WikiError, if user trys to create account with...
[mediawiki.git] / includes / db / DatabaseOracle.php
blobdfbc769c9369e2972ab0dc0f4be6492138b5cd7c
1 <?php
2 /**
3 * @ingroup Database
4 * @file
5 */
7 /**
8 * This is the Oracle database abstraction layer.
9 * @ingroup Database
11 class ORABlob {
12 var $mData;
14 function __construct($data) {
15 $this->mData = $data;
18 function getData() {
19 return $this->mData;
23 /**
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.
27 * @ingroup Database
29 class ORAResult {
30 private $rows;
31 private $cursor;
32 private $stmt;
33 private $nrows;
35 private $unique;
37 function __construct(&$db, $stmt, $unique = false) {
38 $this->db =& $db;
40 if (($this->nrows = oci_fetch_all($stmt, $this->rows, 0, -1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM)) === false) {
41 $e = oci_error($stmt);
42 $db->reportQueryError($e['message'], $e['code'], '', __FUNCTION__);
43 return;
46 if ($unique) {
47 $this->rows = array_unique($this->rows);
48 $this->nrows = count($this->rows);
51 $this->cursor = 0;
52 $this->stmt = $stmt;
55 public function free() {
56 oci_free_statement($this->stmt);
59 public function seek($row) {
60 $this->cursor = min($row, $this->nrows);
63 public function numRows() {
64 return $this->nrows;
67 public function numFields() {
68 return oci_num_fields($this->stmt);
71 public function fetchObject() {
72 if ($this->cursor >= $this->nrows)
73 return false;
74 $row = $this->rows[$this->cursor++];
75 $ret = new stdClass();
76 foreach ($row as $k => $v) {
77 $lc = strtolower(oci_field_name($this->stmt, $k + 1));
78 $ret->$lc = $v;
81 return $ret;
84 public function fetchRow() {
85 if ($this->cursor >= $this->nrows)
86 return false;
88 $row = $this->rows[$this->cursor++];
89 $ret = array();
90 foreach ($row as $k => $v) {
91 $lc = strtolower(oci_field_name($this->stmt, $k + 1));
92 $ret[$lc] = $v;
93 $ret[$k] = $v;
95 return $ret;
99 /**
100 * Utility class.
101 * @ingroup Database
103 class ORAField {
104 private $name, $tablename, $default, $max_length, $nullable,
105 $is_pk, $is_unique, $is_multiple, $is_key, $type;
107 function __construct($info) {
108 $this->name = $info['column_name'];
109 $this->tablename = $info['table_name'];
110 $this->default = $info['data_default'];
111 $this->max_length = $info['data_length'];
112 $this->nullable = $info['not_null'];
113 $this->is_pk = isset($info['prim']) && $info['prim'] == 1 ? 1 : 0;
114 $this->is_unique = isset($info['uniq']) && $info['uniq'] == 1 ? 1 : 0;
115 $this->is_multiple = isset($info['nonuniq']) && $info['nonuniq'] == 1 ? 1 : 0;
116 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
117 $this->type = $info['data_type'];
120 function name() {
121 return $this->name;
124 function tableName() {
125 return $this->tablename;
128 function defaultValue() {
129 return $this->default;
132 function maxLength() {
133 return $this->max_length;
136 function nullable() {
137 return $this->nullable;
140 function isKey() {
141 return $this->is_key;
144 function isMultipleKey() {
145 return $this->is_multiple;
148 function type() {
149 return $this->type;
154 * @ingroup Database
156 class DatabaseOracle extends DatabaseBase {
157 var $mInsertId = NULL;
158 var $mLastResult = NULL;
159 var $numeric_version = NULL;
160 var $lastResult = null;
161 var $cursor = 0;
162 var $mAffectedRows;
164 var $ignore_DUP_VAL_ON_INDEX = false;
166 function DatabaseOracle($server = false, $user = false, $password = false, $dbName = false,
167 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
169 $tablePrefix = $tablePrefix == 'get from global' ? $tablePrefix : strtoupper($tablePrefix);
170 parent::__construct($server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix);
171 wfRunHooks( 'DatabaseOraclePostInit', array(&$this));
174 function cascadingDeletes() {
175 return true;
177 function cleanupTriggers() {
178 return true;
180 function strictIPs() {
181 return true;
183 function realTimestamps() {
184 return true;
186 function implicitGroupby() {
187 return false;
189 function implicitOrderby() {
190 return false;
192 function searchableIPs() {
193 return true;
196 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
197 $failFunction = false, $flags = 0)
199 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags );
203 * Usually aborts on failure
204 * If the failFunction is set to a non-zero integer, returns success
206 function open( $server, $user, $password, $dbName ) {
207 if ( !function_exists( 'oci_connect' ) ) {
208 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" );
211 putenv("NLS_LANG=AMERICAN_AMERICA.AL32UTF8");
213 $this->close();
214 $this->mServer = $server;
215 $this->mUser = $user;
216 $this->mPassword = $password;
217 $this->mDBname = $dbName;
219 if (!strlen($user)) { ## e.g. the class is being loaded
220 return;
223 //error_reporting( E_ALL ); //whoever had this bright idea
224 $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
225 if ( $this->mFlags & DBO_DEFAULT )
226 $this->mConn = oci_new_connect($user, $password, $dbName, null, $session_mode);
227 else
228 $this->mConn = oci_connect($user, $password, $dbName, null, $session_mode);
230 if ($this->mConn == false) {
231 wfDebug("DB connection error\n");
232 wfDebug("Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n");
233 wfDebug($this->lastError()."\n");
234 return false;
237 $this->mOpened = true;
239 #removed putenv calls because they interfere with the system globaly
240 $this->doQuery('ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'');
241 $this->doQuery('ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'');
243 return $this->mConn;
247 * Closes a database connection, if it is open
248 * Returns success, true if already closed
250 function close() {
251 $this->mOpened = false;
252 if ( $this->mConn ) {
253 return oci_close( $this->mConn );
254 } else {
255 return true;
259 function execFlags() {
260 return $this->mTrxLevel ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
263 function doQuery($sql) {
264 wfDebug("SQL: [$sql]\n");
265 if (!mb_check_encoding($sql)) {
266 throw new MWException("SQL encoding is invalid");
269 //handle some oracle specifics
270 //remove AS column/table/subquery namings
271 $sql = preg_replace('/ as /i', ' ', $sql);
272 // Oracle has issues with UNION clause if the statement includes LOB fields
273 // So we do a UNION ALL and then filter the results array with array_unique
274 $union_unique = (preg_match('/\/\* UNION_UNIQUE \*\/ /', $sql) != 0);
275 //EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
276 //you have to select data from plan table after explain
277 $explain_id = date('dmYHis');
278 $sql = preg_replace('/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \''.$explain_id.'\' FOR', $sql, 1, $explain_count);
281 if (($this->mLastResult = $stmt = oci_parse($this->mConn, $sql)) === false) {
282 $e = oci_error($this->mConn);
283 $this->reportQueryError($e['message'], $e['code'], $sql, __FUNCTION__);
286 $olderr = error_reporting(E_ERROR);
287 if (oci_execute($stmt, $this->execFlags()) == false) {
288 $e = oci_error($stmt);
289 if (!$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1')
290 $this->reportQueryError($e['message'], $e['code'], $sql, __FUNCTION__);
292 error_reporting($olderr);
294 if ($explain_count > 0) {
295 return $this->doQuery('SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \''.$explain_id.'\'');
296 } elseif (oci_statement_type($stmt) == "SELECT") {
297 return new ORAResult($this, $stmt, $union_unique);
298 } else {
299 $this->mAffectedRows = oci_num_rows($stmt);
300 return true;
304 function queryIgnore($sql, $fname = '') {
305 return $this->query($sql, $fname, true);
308 function freeResult($res) {
309 if ( $res instanceof ORAResult ) {
310 $res->free();
311 } else {
312 $res->result->free();
316 function fetchObject($res) {
317 if ( $res instanceof ORAResult ) {
318 return $res->numRows();
319 } else {
320 return $res->result->fetchObject();
324 function fetchRow($res) {
325 if ( $res instanceof ORAResult ) {
326 return $res->fetchRow();
327 } else {
328 return $res->result->fetchRow();
332 function numRows($res) {
333 if ( $res instanceof ORAResult ) {
334 return $res->numRows();
335 } else {
336 return $res->result->numRows();
340 function numFields($res) {
341 if ( $res instanceof ORAResult ) {
342 return $res->numFields();
343 } else {
344 return $res->result->numFields();
348 function fieldName($stmt, $n) {
349 return oci_field_name($stmt, $n);
353 * This must be called after nextSequenceVal
355 function insertId() {
356 return $this->mInsertId;
359 function dataSeek($res, $row) {
360 if ( $res instanceof ORAResult ) {
361 $res->seek($row);
362 } else {
363 $res->result->seek($row);
367 function lastError() {
368 if ($this->mConn === false)
369 $e = oci_error();
370 else
371 $e = oci_error($this->mConn);
372 return $e['message'];
375 function lastErrno() {
376 if ($this->mConn === false)
377 $e = oci_error();
378 else
379 $e = oci_error($this->mConn);
380 return $e['code'];
383 function affectedRows() {
384 return $this->mAffectedRows;
388 * Returns information about an index
389 * If errors are explicitly ignored, returns NULL on failure
391 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
392 return false;
395 function indexUnique ($table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
396 return false;
399 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
400 if ( !count( $a ) )
401 return true;
403 if (!is_array($options))
404 $options = array($options);
406 if (in_array('IGNORE', $options))
407 $this->ignore_DUP_VAL_ON_INDEX = true;
409 if (!is_array(reset($a))) {
410 $a = array($a);
412 foreach ($a as $row) {
413 $this->insertOneRow($table, $row, $fname);
415 $retVal = true;
417 if (in_array('IGNORE', $options))
418 $this->ignore_DUP_VAL_ON_INDEX = false;
420 return $retVal;
423 function insertOneRow($table, $row, $fname) {
424 global $wgLang;
426 // "INSERT INTO tables (a, b, c)"
427 $sql = "INSERT INTO " . $this->tableName($table) . " (" . join(',', array_keys($row)) . ')';
428 $sql .= " VALUES (";
430 // for each value, append ":key"
431 $first = true;
432 foreach ($row as $col => $val) {
433 if ($first)
434 $sql .= ':'.$col;
435 else
436 $sql.= ', :'.$col;
438 $first = false;
440 $sql .= ')';
442 $stmt = oci_parse($this->mConn, $sql);
443 foreach ($row as $col => $val) {
444 if (!is_object($val)) {
445 if (oci_bind_by_name($stmt, ":$col", $row[$col]) === false)
446 $this->reportQueryError($this->lastErrno(), $this->lastError(), $sql, __METHOD__);
450 $stmt = oci_parse($this->mConn, $sql);
451 foreach ($row as $col => $val) {
452 $col_type=$this->fieldInfo($this->tableName($table), $col)->type();
453 if ($col_type != 'BLOB' && $col_type != 'CLOB') {
454 if (is_object($val))
455 $val = $val->getData();
457 if (preg_match('/^timestamp.*/i', $col_type) == 1 && strtolower($val) == 'infinity')
458 $val = '31-12-2030 12:00:00.000000';
460 if (oci_bind_by_name($stmt, ":$col", $wgLang->checkTitleEncoding($val)) === false)
461 $this->reportQueryError($this->lastErrno(), $this->lastError(), $sql, __METHOD__);
462 } else {
463 if (($lob[$col] = oci_new_descriptor($this->mConn, OCI_D_LOB)) === false) {
464 $e = oci_error($stmt);
465 throw new DBUnexpectedError($this, "Cannot create LOB descriptor: " . $e['message']);
468 if (is_object($val)) {
469 $lob[$col]->writeTemporary($val->getData());
470 oci_bind_by_name($stmt, ":$col", $lob[$col], -1, SQLT_BLOB);
471 } else {
472 $lob[$col]->writeTemporary($val);
473 oci_bind_by_name($stmt, ":$col", $lob[$col], -1, OCI_B_CLOB);
478 $olderr = error_reporting(E_ERROR);
479 if (oci_execute($stmt, OCI_DEFAULT) === false) {
480 $e = oci_error($stmt);
482 if (!$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1')
483 $this->reportQueryError($e['message'], $e['code'], $sql, __METHOD__);
484 else
485 $this->mAffectedRows = oci_num_rows($stmt);
486 } else
487 $this->mAffectedRows = oci_num_rows($stmt);
488 error_reporting($olderr);
490 if (isset($lob)){
491 foreach ($lob as $lob_i => $lob_v) {
492 $lob_v->free();
496 if (!$this->mTrxLevel)
497 oci_commit($this->mConn);
499 oci_free_statement($stmt);
502 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
503 $insertOptions = array(), $selectOptions = array() )
505 $destTable = $this->tableName( $destTable );
506 if( !is_array( $selectOptions ) ) {
507 $selectOptions = array( $selectOptions );
509 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
510 if( is_array( $srcTable ) ) {
511 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
512 } else {
513 $srcTable = $this->tableName( $srcTable );
515 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
516 " SELECT $startOpts " . implode( ',', $varMap ) .
517 " FROM $srcTable $useIndex ";
518 if ( $conds != '*' ) {
519 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
521 $sql .= " $tailOpts";
523 if (in_array('IGNORE', $insertOptions))
524 $this->ignore_DUP_VAL_ON_INDEX = true;
526 $retval = $this->query( $sql, $fname );
528 if (in_array('IGNORE', $insertOptions))
529 $this->ignore_DUP_VAL_ON_INDEX = false;
531 return $retval;
534 function tableName( $name ) {
535 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
537 Replace reserved words with better ones
538 Useing uppercase, because that's the only way oracle can handle
539 quoted tablenames
541 switch( $name ) {
542 case 'user':
543 $name = 'MWUSER'; break;
544 case 'text':
545 $name = 'PAGECONTENT'; break;
549 The rest of procedure is equal to generic Databse class
550 except for the quoting style
552 if ( $name[0] == '"' && substr( $name, -1, 1 ) == '"' ) return $name;
554 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
555 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
556 if( isset( $dbDetails[1] ) ) @list( $table, $database ) = $dbDetails;
557 else @list( $table ) = $dbDetails;
559 $prefix = $this->mTablePrefix;
561 if( isset($database) ) $table = ( $table[0] == '`' ? $table : "`{$table}`" );
563 if( !isset( $database )
564 && isset( $wgSharedDB )
565 && $table[0] != '"'
566 && isset( $wgSharedTables )
567 && is_array( $wgSharedTables )
568 && in_array( $table, $wgSharedTables ) ) {
569 $database = $wgSharedDB;
570 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
573 if( isset($database) ) $database = ( $database[0] == '"' ? $database : "\"{$database}\"" );
574 $table = ( $table[0] == '"' ? $table : "\"{$prefix}{$table}\"" );
576 $tableName = ( isset($database) ? "{$database}.{$table}" : "{$table}" );
578 return strtoupper($tableName);
582 * Return the next in a sequence, save the value for retrieval via insertId()
584 function nextSequenceValue($seqName) {
585 $res = $this->query("SELECT $seqName.nextval FROM dual");
586 $row = $this->fetchRow($res);
587 $this->mInsertId = $row[0];
588 $this->freeResult($res);
589 return $this->mInsertId;
592 # REPLACE query wrapper
593 # Oracle simulates this with a DELETE followed by INSERT
594 # $row is the row to insert, an associative array
595 # $uniqueIndexes is an array of indexes. Each element may be either a
596 # field name or an array of field names
598 # It may be more efficient to leave off unique indexes which are unlikely to collide.
599 # However if you do this, you run the risk of encountering errors which wouldn't have
600 # occurred in MySQL
601 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
602 $table = $this->tableName($table);
604 if (count($rows)==0) {
605 return;
608 # Single row case
609 if (!is_array(reset($rows))) {
610 $rows = array($rows);
613 foreach( $rows as $row ) {
614 # Delete rows which collide
615 if ( $uniqueIndexes ) {
616 $sql = "DELETE FROM $table WHERE ";
617 $first = true;
618 foreach ( $uniqueIndexes as $index ) {
619 if ( $first ) {
620 $first = false;
621 $sql .= "(";
622 } else {
623 $sql .= ') OR (';
625 if ( is_array( $index ) ) {
626 $first2 = true;
627 foreach ( $index as $col ) {
628 if ( $first2 ) {
629 $first2 = false;
630 } else {
631 $sql .= ' AND ';
633 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
635 } else {
636 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
639 $sql .= ')';
640 $this->query( $sql, $fname );
643 # Now insert the row
644 $this->insert( $table, $row, $fname );
648 # DELETE where the condition is a join
649 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseOracle::deleteJoin" ) {
650 if ( !$conds ) {
651 throw new DBUnexpectedError($this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
654 $delTable = $this->tableName( $delTable );
655 $joinTable = $this->tableName( $joinTable );
656 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
657 if ( $conds != '*' ) {
658 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
660 $sql .= ')';
662 $this->query( $sql, $fname );
665 # Returns the size of a text field, or -1 for "unlimited"
666 function textFieldSize( $table, $field ) {
667 $table = $this->tableName( $table );
668 $sql = "SELECT t.typname as ftype,a.atttypmod as size
669 FROM pg_class c, pg_attribute a, pg_type t
670 WHERE relname='$table' AND a.attrelid=c.oid AND
671 a.atttypid=t.oid and a.attname='$field'";
672 $res =$this->query($sql);
673 $row=$this->fetchObject($res);
674 if ($row->ftype=="varchar") {
675 $size=$row->size-4;
676 } else {
677 $size=$row->size;
679 $this->freeResult( $res );
680 return $size;
683 function limitResult($sql, $limit, $offset) {
684 if ($offset === false)
685 $offset = 0;
686 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
690 function unionQueries($sqls, $all = false) {
691 $glue = ' UNION ALL ';
692 return 'SELECT * '.($all?'':'/* UNION_UNIQUE */ ').'FROM ('.implode( $glue, $sqls ).')' ;
695 function wasDeadlock() {
696 return $this->lastErrno() == 'OCI-00060';
699 function timestamp($ts = 0) {
700 return wfTimestamp(TS_ORACLE, $ts);
704 * Return aggregated value function call
706 function aggregateValue ($valuedata,$valuename='value') {
707 return $valuedata;
710 function reportQueryError($error, $errno, $sql, $fname, $tempIgnore = false) {
711 # Ignore errors during error handling to avoid infinite
712 # recursion
713 $ignore = $this->ignoreErrors(true);
714 ++$this->mErrorCount;
716 if ($ignore || $tempIgnore) {
717 //echo "error ignored! query = [$sql]\n";
718 wfDebug("SQL ERROR (ignored): $error\n");
719 $this->ignoreErrors( $ignore );
721 else {
722 //echo "error!\n";
723 $message = "A database error has occurred\n" .
724 "Query: $sql\n" .
725 "Function: $fname\n" .
726 "Error: $errno $error\n";
727 throw new DBUnexpectedError($this, $message);
732 * @return string wikitext of a link to the server software's web site
734 function getSoftwareLink() {
735 return "[http://www.oracle.com/ Oracle]";
739 * @return string Version information from the database
741 function getServerVersion() {
742 return oci_server_version($this->mConn);
746 * Query whether a given table exists (in the given schema, or the default mw one if not given)
748 function tableExists($table) {
749 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
750 $res = $this->doQuery($SQL);
751 if ($res) {
752 $count = $res->numRows();
753 $res->free();
754 } else {
755 $count = 0;
757 return $count;
761 * Query whether a given column exists in the mediawiki schema
762 * based on prebuilt table to simulate MySQL field info and keep query speed minimal
764 function fieldExists( $table, $field ) {
765 if (!isset($this->fieldInfo_stmt))
766 $this->fieldInfo_stmt = oci_parse($this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)');
768 oci_bind_by_name($this->fieldInfo_stmt, ':tab', trim($table, '"'));
769 oci_bind_by_name($this->fieldInfo_stmt, ':col', $field);
771 if (oci_execute($this->fieldInfo_stmt, OCI_DEFAULT) === false) {
772 $e = oci_error($this->fieldInfo_stmt);
773 $this->reportQueryError($e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__);
774 return false;
776 $res = new ORAResult($this,$this->fieldInfo_stmt);
777 return $res->numRows() != 0;
780 function fieldInfo( $table, $field ) {
781 if (!isset($this->fieldInfo_stmt))
782 $this->fieldInfo_stmt = oci_parse($this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)');
784 oci_bind_by_name($this->fieldInfo_stmt, ':tab', trim($table, '"'));
785 oci_bind_by_name($this->fieldInfo_stmt, ':col', $field);
787 if (oci_execute($this->fieldInfo_stmt, OCI_DEFAULT) === false) {
788 $e = oci_error($this->fieldInfo_stmt);
789 $this->reportQueryError($e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__);
790 return false;
792 $res = new ORAResult($this,$this->fieldInfo_stmt);
793 return new ORAField($res->fetchRow());
796 function begin( $fname = '' ) {
797 $this->mTrxLevel = 1;
799 function immediateCommit( $fname = '' ) {
800 return true;
802 function commit( $fname = '' ) {
803 oci_commit($this->mConn);
804 $this->mTrxLevel = 0;
807 /* Not even sure why this is used in the main codebase... */
808 function limitResultForUpdate($sql, $num) {
809 return $sql;
812 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
813 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
814 $cmd = "";
815 $done = false;
816 $dollarquote = false;
818 $replacements = array();
820 while ( ! feof( $fp ) ) {
821 if ( $lineCallback ) {
822 call_user_func( $lineCallback );
824 $line = trim( fgets( $fp, 1024 ) );
825 $sl = strlen( $line ) - 1;
827 if ( $sl < 0 ) { continue; }
828 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
830 // Allow dollar quoting for function declarations
831 if (substr($line,0,8) == '/*$mw$*/') {
832 if ($dollarquote) {
833 $dollarquote = false;
834 $done = true;
836 else {
837 $dollarquote = true;
840 else if (!$dollarquote) {
841 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
842 $done = true;
843 $line = substr( $line, 0, $sl );
847 if ( '' != $cmd ) { $cmd .= ' '; }
848 $cmd .= "$line\n";
850 if ( $done ) {
851 $cmd = str_replace(';;', ";", $cmd);
852 if (strtolower(substr($cmd, 0, 6)) == 'define' ) {
853 if (preg_match('/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines)) {
854 $replacements[$defines[2]] = $defines[1];
856 } else {
857 foreach ( $replacements as $mwVar=>$scVar ) {
858 $cmd = str_replace( '&' . $scVar . '.', '{$'.$mwVar.'}', $cmd );
861 $cmd = $this->replaceVars( $cmd );
862 $res = $this->query( $cmd, __METHOD__ );
863 if ( $resultCallback ) {
864 call_user_func( $resultCallback, $res, $this );
867 if ( false === $res ) {
868 $err = $this->lastError();
869 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
873 $cmd = '';
874 $done = false;
877 return true;
880 function setup_database() {
881 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
883 echo "<li>Creating DB objects</li>\n";
884 $res = $this->sourceFile( "../maintenance/ora/tables.sql" );
886 // Avoid the non-standard "REPLACE INTO" syntax
887 echo "<li>Populating table interwiki</li>\n";
888 $f = fopen( "../maintenance/interwiki.sql", 'r' );
889 if ($f == false ) {
890 dieout( "<li>Could not find the interwiki.sql file</li>");
893 //do it like the postgres :D
894 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
895 while ( ! feof( $f ) ) {
896 $line = fgets($f,1024);
897 $matches = array();
898 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
899 continue;
901 $this->query("$SQL $matches[1],$matches[2])");
904 echo "<li>Table interwiki successfully populated</li>\n";
907 function strencode($s) {
908 return str_replace("'", "''", $s);
911 function encodeBlob($b) {
912 return new ORABlob($b);
914 function decodeBlob($b) {
915 return $b; //return $b->load();
918 function addQuotes( $s ) {
919 global $wgLang;
920 if (isset($wgLang->mLoaded) && $wgLang->mLoaded)
921 $s = $wgLang->checkTitleEncoding($s);
922 return "'" . $this->strencode($s) . "'";
925 function quote_ident( $s ) {
926 return $s;
929 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
930 if (is_array($table))
931 foreach ($table as $tab)
932 $tab = $this->tableName($tab);
933 else
934 $table = $this->tableName($table);
935 return parent::selectRow($table, $vars, $conds, $fname, $options, $join_conds);
939 * Returns an optional USE INDEX clause to go after the table, and a
940 * string to go at the end of the query
942 * @private
944 * @param $options Array: an associative array of options to be turned into
945 * an SQL query, valid keys are listed in the function.
946 * @return array
948 function makeSelectOptions( $options ) {
949 $preLimitTail = $postLimitTail = '';
950 $startOpts = '';
952 $noKeyOptions = array();
953 foreach ( $options as $key => $option ) {
954 if ( is_numeric( $key ) ) {
955 $noKeyOptions[$option] = true;
959 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
960 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
962 #if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
963 #if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
964 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
966 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
967 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
968 } else {
969 $useIndex = '';
972 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
975 /* redundand ... will remove after confirming bitwise operations functionality
976 public function makeList( $a, $mode = LIST_COMMA ) {
977 if ( !is_array( $a ) ) {
978 throw new DBUnexpectedError( $this, 'DatabaseOracle::makeList called with incorrect parameters' );
980 $a2 = array();
981 foreach ($a as $key => $value) {
982 if (strpos($key, ' & ') !== FALSE)
983 $a2[preg_replace('/(.*)\s&\s(.*)/', 'BITAND($1, $2)', $key)] = $value;
984 elseif (strpos($key, ' | ') !== FALSE)
985 $a2[preg_replace('/(.*)\s|\s(.*)/', 'BITOR($1, $2)', $key)] = $value;
986 elseif (!is_array($value)) {
987 if (strpos($value, ' = ') !== FALSE) {
988 if (strpos($value, ' & ') !== FALSE)
989 $a2[$key] = preg_replace('/(.*)\s&\s(.*?)\s=\s(.*)/', 'BITAND($1, $2) = $3', $value);
990 elseif (strpos($value, ' | ') !== FALSE)
991 $a2[$key] = preg_replace('/(.*)\s|\s(.*?)\s=\s(.*)/', 'BITOR($1, $2) = $3', $value);
992 else $a2[$key] = $value;
994 elseif (strpos($value, ' & ') !== FALSE)
995 $a2[$key] = preg_replace('/(.*)\s&\s(.*)/', 'BITAND($1, $2)', $value);
996 elseif (strpos($value, ' | ') !== FALSE)
997 $a2[$key] = preg_replace('/(.*)\s|\s(.*)/', 'BITOR($1, $2)', $value);
998 else
999 $a2[$key] = $value;
1001 else
1002 $a2[$key] = $value;
1005 return parent::makeList($a2, $mode);
1009 function bitNot($field) {
1010 //expecting bit-fields smaller than 4bytes
1011 return 'BITNOT('.$bitField.')';
1014 function bitAnd($fieldLeft, $fieldRight) {
1015 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1018 function bitOr($fieldLeft, $fieldRight) {
1019 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';
1023 * How lagged is this slave?
1025 * @return int
1027 public function getLag() {
1028 # Not implemented for Oracle
1029 return 0;
1032 function setFakeSlaveLag( $lag ) {}
1033 function setFakeMaster( $enabled = true ) {}
1035 function getDBname() {
1036 return $this->mDBname;
1039 function getServer() {
1040 return $this->mServer;
1043 public function replaceVars( $ins ) {
1044 $varnames = array('wgDBprefix');
1045 if ($this->mFlags & DBO_SYSDBA) {
1046 $varnames[] = 'wgDBOracleDefTS';
1047 $varnames[] = 'wgDBOracleTempTS';
1050 // Ordinary variables
1051 foreach ( $varnames as $var ) {
1052 if( isset( $GLOBALS[$var] ) ) {
1053 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1054 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1055 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1056 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1060 return parent::replaceVars($ins);
1063 public function getSearchEngine() {
1064 return "SearchOracle";
1066 } // end DatabaseOracle class