Web installation support for Oracle.
[lhc/web/wiklou.git] / includes / db / DatabaseOracle.php
1 <?php
2 /**
3 * @ingroup Database
4 * @file
5 */
6
7 /**
8 * This is the Oracle database abstraction layer.
9 * @ingroup Database
10 */
11 class ORABlob {
12 var $mData;
13
14 function __construct($data) {
15 $this->mData = $data;
16 }
17
18 function getData() {
19 return $this->mData;
20 }
21 }
22
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
28 */
29 class ORAResult {
30 private $rows;
31 private $cursor;
32 private $stmt;
33 private $nrows;
34
35 private $unique;
36
37 function __construct(&$db, $stmt, $unique = false) {
38 $this->db =& $db;
39
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;
44 }
45
46 if ($unique) {
47 $this->rows = array_unique($this->rows);
48 $this->nrows = count($this->rows);
49 }
50
51 $this->cursor = 0;
52 $this->stmt = $stmt;
53 }
54
55 public function free() {
56 oci_free_statement($this->stmt);
57 }
58
59 public function seek($row) {
60 $this->cursor = min($row, $this->nrows);
61 }
62
63 public function numRows() {
64 return $this->nrows;
65 }
66
67 public function numFields() {
68 return oci_num_fields($this->stmt);
69 }
70
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;
79 }
80
81 return $ret;
82 }
83
84 public function fetchRow() {
85 if ($this->cursor >= $this->nrows)
86 return false;
87
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;
94 }
95 return $ret;
96 }
97 }
98
99 /**
100 * Utility class.
101 * @ingroup Database
102 */
103 class ORAField {
104 private $name, $tablename, $default, $max_length, $nullable,
105 $is_pk, $is_unique, $is_multiple, $is_key, $type;
106
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'];
118 }
119
120 function name() {
121 return $this->name;
122 }
123
124 function tableName() {
125 return $this->tablename;
126 }
127
128 function defaultValue() {
129 return $this->default;
130 }
131
132 function maxLength() {
133 return $this->max_length;
134 }
135
136 function nullable() {
137 return $this->nullable;
138 }
139
140 function isKey() {
141 return $this->is_key;
142 }
143
144 function isMultipleKey() {
145 return $this->is_multiple;
146 }
147
148 function type() {
149 return $this->type;
150 }
151 }
152
153 /**
154 * @ingroup Database
155 */
156 class DatabaseOracle extends Database {
157 var $mInsertId = NULL;
158 var $mLastResult = NULL;
159 var $numeric_version = NULL;
160 var $lastResult = null;
161 var $cursor = 0;
162 var $mAffectedRows;
163
164 var $ignore_DUP_VAL_ON_INDEX = false;
165
166 function DatabaseOracle($server = false, $user = false, $password = false, $dbName = false,
167 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
168 {
169 $tablePrefix = $tablePrefix == 'get from global' ? $tablePrefix : strtoupper($tablePrefix);
170 parent::__construct($server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix);
171 wfRunHooks( 'DatabaseOraclePostInit', array(&$this));
172 }
173
174 function cascadingDeletes() {
175 return true;
176 }
177 function cleanupTriggers() {
178 return true;
179 }
180 function strictIPs() {
181 return true;
182 }
183 function realTimestamps() {
184 return true;
185 }
186 function implicitGroupby() {
187 return false;
188 }
189 function implicitOrderby() {
190 return false;
191 }
192 function searchableIPs() {
193 return true;
194 }
195
196 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
197 $failFunction = false, $flags = 0)
198 {
199 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags );
200 }
201
202 /**
203 * Usually aborts on failure
204 * If the failFunction is set to a non-zero integer, returns success
205 */
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" );
209 }
210
211 putenv("NLS_LANG=AMERICAN_AMERICA.AL32UTF8");
212
213 $this->close();
214 $this->mServer = $server;
215 $this->mUser = $user;
216 $this->mPassword = $password;
217 $this->mDBname = $dbName;
218
219 if (!strlen($user)) { ## e.g. the class is being loaded
220 return;
221 }
222
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);
229
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;
235 }
236
237 $this->mOpened = true;
238
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\'');
242
243 return $this->mConn;
244 }
245
246 /**
247 * Closes a database connection, if it is open
248 * Returns success, true if already closed
249 */
250 function close() {
251 $this->mOpened = false;
252 if ( $this->mConn ) {
253 return oci_close( $this->mConn );
254 } else {
255 return true;
256 }
257 }
258
259 function execFlags() {
260 return $this->mTrxLevel ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
261 }
262
263 function doQuery($sql) {
264 wfDebug("SQL: [$sql]\n");
265 if (!mb_check_encoding($sql)) {
266 throw new MWException("SQL encoding is invalid");
267 }
268
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);
279
280
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__);
284 }
285
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__);
291 }
292 error_reporting($olderr);
293
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;
301 }
302 }
303
304 function queryIgnore($sql, $fname = '') {
305 return $this->query($sql, $fname, true);
306 }
307
308 function freeResult($res) {
309 if ( $res instanceof ORAResult ) {
310 $res->free();
311 } else {
312 $res->result->free();
313 }
314 }
315
316 function fetchObject($res) {
317 if ( $res instanceof ORAResult ) {
318 return $res->numRows();
319 } else {
320 return $res->result->fetchObject();
321 }
322 }
323
324 function fetchRow($res) {
325 if ( $res instanceof ORAResult ) {
326 return $res->fetchRow();
327 } else {
328 return $res->result->fetchRow();
329 }
330 }
331
332 function numRows($res) {
333 if ( $res instanceof ORAResult ) {
334 return $res->numRows();
335 } else {
336 return $res->result->numRows();
337 }
338 }
339
340 function numFields($res) {
341 if ( $res instanceof ORAResult ) {
342 return $res->numFields();
343 } else {
344 return $res->result->numFields();
345 }
346 }
347
348 function fieldName($stmt, $n) {
349 return oci_field_name($stmt, $n);
350 }
351
352 /**
353 * This must be called after nextSequenceVal
354 */
355 function insertId() {
356 return $this->mInsertId;
357 }
358
359 function dataSeek($res, $row) {
360 if ( $res instanceof ORAResult ) {
361 $res->seek($row);
362 } else {
363 $res->result->seek($row);
364 }
365 }
366
367 function lastError() {
368 if ($this->mConn === false)
369 $e = oci_error();
370 else
371 $e = oci_error($this->mConn);
372 return $e['message'];
373 }
374
375 function lastErrno() {
376 if ($this->mConn === false)
377 $e = oci_error();
378 else
379 $e = oci_error($this->mConn);
380 return $e['code'];
381 }
382
383 function affectedRows() {
384 return $this->mAffectedRows;
385 }
386
387 /**
388 * Returns information about an index
389 * If errors are explicitly ignored, returns NULL on failure
390 */
391 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
392 return false;
393 }
394
395 function indexUnique ($table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
396 return false;
397 }
398
399 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
400 if ( !count( $a ) )
401 return true;
402
403 if (!is_array($options))
404 $options = array($options);
405
406 if (in_array('IGNORE', $options))
407 $this->ignore_DUP_VAL_ON_INDEX = true;
408
409 if (!is_array(reset($a))) {
410 $a = array($a);
411 }
412 foreach ($a as $row) {
413 $this->insertOneRow($table, $row, $fname);
414 }
415 $retVal = true;
416
417 if (in_array('IGNORE', $options))
418 $this->ignore_DUP_VAL_ON_INDEX = false;
419
420 return $retVal;
421 }
422
423 function insertOneRow($table, $row, $fname) {
424 global $wgLang;
425
426 // "INSERT INTO tables (a, b, c)"
427 $sql = "INSERT INTO " . $this->tableName($table) . " (" . join(',', array_keys($row)) . ')';
428 $sql .= " VALUES (";
429
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;
437
438 $first = false;
439 }
440 $sql .= ')';
441
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__);
447 }
448 }
449
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();
456
457 if (preg_match('/^timestamp.*/i', $col_type) == 1 && strtolower($val) == 'infinity')
458 $val = '31-12-2030 12:00:00.000000';
459
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']);
466 }
467
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);
474 }
475 }
476 }
477
478 $olderr = error_reporting(E_ERROR);
479 if (oci_execute($stmt, OCI_DEFAULT) === false) {
480 $e = oci_error($stmt);
481
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);
489
490 if (isset($lob)){
491 foreach ($lob as $lob_i => $lob_v) {
492 $lob_v->free();
493 }
494 }
495
496 if (!$this->mTrxLevel)
497 oci_commit($this->mConn);
498
499 oci_free_statement($stmt);
500 }
501
502 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
503 $insertOptions = array(), $selectOptions = array() )
504 {
505 $destTable = $this->tableName( $destTable );
506 if( !is_array( $selectOptions ) ) {
507 $selectOptions = array( $selectOptions );
508 }
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 );
514 }
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 );
520 }
521 $sql .= " $tailOpts";
522
523 if (in_array('IGNORE', $insertOptions))
524 $this->ignore_DUP_VAL_ON_INDEX = true;
525
526 $retval = $this->query( $sql, $fname );
527
528 if (in_array('IGNORE', $insertOptions))
529 $this->ignore_DUP_VAL_ON_INDEX = false;
530
531 return $retval;
532 }
533
534 function tableName( $name ) {
535 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
536 /*
537 Replace reserved words with better ones
538 Useing uppercase, because that's the only way oracle can handle
539 quoted tablenames
540 */
541 switch( $name ) {
542 case 'user':
543 $name = 'MWUSER'; break;
544 case 'text':
545 $name = 'PAGECONTENT'; break;
546 }
547
548 /*
549 The rest of procedure is equal to generic Databse class
550 except for the quoting style
551 */
552 if ( $name[0] == '"' && substr( $name, -1, 1 ) == '"' ) return $name;
553
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;
558
559 $prefix = $this->mTablePrefix;
560
561 if( isset($database) ) $table = ( $table[0] == '`' ? $table : "`{$table}`" );
562
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;
571 }
572
573 if( isset($database) ) $database = ( $database[0] == '"' ? $database : "\"{$database}\"" );
574 $table = ( $table[0] == '"' ? $table : "\"{$prefix}{$table}\"" );
575
576 $tableName = ( isset($database) ? "{$database}.{$table}" : "{$table}" );
577
578 return strtoupper($tableName);
579 }
580
581 /**
582 * Return the next in a sequence, save the value for retrieval via insertId()
583 */
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;
590 }
591
592 /**
593 * Oracle does not have a "USE INDEX" clause, so return an empty string
594 */
595 function useIndexClause($index) {
596 return '';
597 }
598
599 # REPLACE query wrapper
600 # Oracle simulates this with a DELETE followed by INSERT
601 # $row is the row to insert, an associative array
602 # $uniqueIndexes is an array of indexes. Each element may be either a
603 # field name or an array of field names
604 #
605 # It may be more efficient to leave off unique indexes which are unlikely to collide.
606 # However if you do this, you run the risk of encountering errors which wouldn't have
607 # occurred in MySQL
608 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
609 $table = $this->tableName($table);
610
611 if (count($rows)==0) {
612 return;
613 }
614
615 # Single row case
616 if (!is_array(reset($rows))) {
617 $rows = array($rows);
618 }
619
620 foreach( $rows as $row ) {
621 # Delete rows which collide
622 if ( $uniqueIndexes ) {
623 $sql = "DELETE FROM $table WHERE ";
624 $first = true;
625 foreach ( $uniqueIndexes as $index ) {
626 if ( $first ) {
627 $first = false;
628 $sql .= "(";
629 } else {
630 $sql .= ') OR (';
631 }
632 if ( is_array( $index ) ) {
633 $first2 = true;
634 foreach ( $index as $col ) {
635 if ( $first2 ) {
636 $first2 = false;
637 } else {
638 $sql .= ' AND ';
639 }
640 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
641 }
642 } else {
643 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
644 }
645 }
646 $sql .= ')';
647 $this->query( $sql, $fname );
648 }
649
650 # Now insert the row
651 $this->insert( $table, $row, $fname );
652 }
653 }
654
655 # DELETE where the condition is a join
656 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseOracle::deleteJoin" ) {
657 if ( !$conds ) {
658 throw new DBUnexpectedError($this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
659 }
660
661 $delTable = $this->tableName( $delTable );
662 $joinTable = $this->tableName( $joinTable );
663 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
664 if ( $conds != '*' ) {
665 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
666 }
667 $sql .= ')';
668
669 $this->query( $sql, $fname );
670 }
671
672 # Returns the size of a text field, or -1 for "unlimited"
673 function textFieldSize( $table, $field ) {
674 $table = $this->tableName( $table );
675 $sql = "SELECT t.typname as ftype,a.atttypmod as size
676 FROM pg_class c, pg_attribute a, pg_type t
677 WHERE relname='$table' AND a.attrelid=c.oid AND
678 a.atttypid=t.oid and a.attname='$field'";
679 $res =$this->query($sql);
680 $row=$this->fetchObject($res);
681 if ($row->ftype=="varchar") {
682 $size=$row->size-4;
683 } else {
684 $size=$row->size;
685 }
686 $this->freeResult( $res );
687 return $size;
688 }
689
690 function lowPriorityOption() {
691 return '';
692 }
693
694 function limitResult($sql, $limit, $offset) {
695 if ($offset === false)
696 $offset = 0;
697 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
698 }
699
700
701 function unionQueries($sqls, $all = false) {
702 $glue = ' UNION ALL ';
703 return 'SELECT * '.($all?'':'/* UNION_UNIQUE */ ').'FROM ('.implode( $glue, $sqls ).')' ;
704 }
705
706 /**
707 * Returns an SQL expression for a simple conditional.
708 * Uses CASE on Oracle
709 *
710 * @param $cond String: SQL expression which will result in a boolean value
711 * @param $trueVal String: SQL expression to return if true
712 * @param $falseVal String: SQL expression to return if false
713 * @return String: SQL fragment
714 */
715 function conditional( $cond, $trueVal, $falseVal ) {
716 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
717 }
718
719 function wasDeadlock() {
720 return $this->lastErrno() == 'OCI-00060';
721 }
722
723 function timestamp($ts = 0) {
724 return wfTimestamp(TS_ORACLE, $ts);
725 }
726
727 /**
728 * Return aggregated value function call
729 */
730 function aggregateValue ($valuedata,$valuename='value') {
731 return $valuedata;
732 }
733
734 function reportQueryError($error, $errno, $sql, $fname, $tempIgnore = false) {
735 # Ignore errors during error handling to avoid infinite
736 # recursion
737 $ignore = $this->ignoreErrors(true);
738 ++$this->mErrorCount;
739
740 if ($ignore || $tempIgnore) {
741 //echo "error ignored! query = [$sql]\n";
742 wfDebug("SQL ERROR (ignored): $error\n");
743 $this->ignoreErrors( $ignore );
744 }
745 else {
746 //echo "error!\n";
747 $message = "A database error has occurred\n" .
748 "Query: $sql\n" .
749 "Function: $fname\n" .
750 "Error: $errno $error\n";
751 throw new DBUnexpectedError($this, $message);
752 }
753 }
754
755 /**
756 * @return string wikitext of a link to the server software's web site
757 */
758 function getSoftwareLink() {
759 return "[http://www.oracle.com/ Oracle]";
760 }
761
762 /**
763 * @return string Version information from the database
764 */
765 function getServerVersion() {
766 return oci_server_version($this->mConn);
767 }
768
769 /**
770 * Query whether a given table exists (in the given schema, or the default mw one if not given)
771 */
772 function tableExists($table) {
773 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
774 $res = $this->doQuery($SQL);
775 if ($res) {
776 $count = $res->numRows();
777 $res->free();
778 } else {
779 $count = 0;
780 }
781 return $count;
782 }
783
784 /**
785 * Query whether a given column exists in the mediawiki schema
786 * based on prebuilt table to simulate MySQL field info and keep query speed minimal
787 */
788 function fieldExists( $table, $field ) {
789 if (!isset($this->fieldInfo_stmt))
790 $this->fieldInfo_stmt = oci_parse($this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)');
791
792 oci_bind_by_name($this->fieldInfo_stmt, ':tab', trim($table, '"'));
793 oci_bind_by_name($this->fieldInfo_stmt, ':col', $field);
794
795 if (oci_execute($this->fieldInfo_stmt, OCI_DEFAULT) === false) {
796 $e = oci_error($this->fieldInfo_stmt);
797 $this->reportQueryError($e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__);
798 return false;
799 }
800 $res = new ORAResult($this,$this->fieldInfo_stmt);
801 return $res->numRows() != 0;
802 }
803
804 function fieldInfo( $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)');
807
808 oci_bind_by_name($this->fieldInfo_stmt, ':tab', trim($table, '"'));
809 oci_bind_by_name($this->fieldInfo_stmt, ':col', $field);
810
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__);
814 return false;
815 }
816 $res = new ORAResult($this,$this->fieldInfo_stmt);
817 return new ORAField($res->fetchRow());
818 }
819
820 function begin( $fname = '' ) {
821 $this->mTrxLevel = 1;
822 }
823 function immediateCommit( $fname = '' ) {
824 return true;
825 }
826 function commit( $fname = '' ) {
827 oci_commit($this->mConn);
828 $this->mTrxLevel = 0;
829 }
830
831 /* Not even sure why this is used in the main codebase... */
832 function limitResultForUpdate($sql, $num) {
833 return $sql;
834 }
835
836 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
837 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
838 $cmd = "";
839 $done = false;
840 $dollarquote = false;
841
842 $replacements = array();
843
844 while ( ! feof( $fp ) ) {
845 if ( $lineCallback ) {
846 call_user_func( $lineCallback );
847 }
848 $line = trim( fgets( $fp, 1024 ) );
849 $sl = strlen( $line ) - 1;
850
851 if ( $sl < 0 ) { continue; }
852 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
853
854 // Allow dollar quoting for function declarations
855 if (substr($line,0,8) == '/*$mw$*/') {
856 if ($dollarquote) {
857 $dollarquote = false;
858 $done = true;
859 }
860 else {
861 $dollarquote = true;
862 }
863 }
864 else if (!$dollarquote) {
865 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
866 $done = true;
867 $line = substr( $line, 0, $sl );
868 }
869 }
870
871 if ( '' != $cmd ) { $cmd .= ' '; }
872 $cmd .= "$line\n";
873
874 if ( $done ) {
875 $cmd = str_replace(';;', ";", $cmd);
876 if (strtolower(substr($cmd, 0, 6)) == 'define' ) {
877 if (preg_match('/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines)) {
878 $replacements[$defines[2]] = $defines[1];
879 }
880 } else {
881 foreach ( $replacements as $mwVar=>$scVar ) {
882 $cmd = str_replace( '&' . $scVar . '.', '{$'.$mwVar.'}', $cmd );
883 }
884
885 $cmd = $this->replaceVars( $cmd );
886 $res = $this->query( $cmd, __METHOD__ );
887 if ( $resultCallback ) {
888 call_user_func( $resultCallback, $res, $this );
889 }
890
891 if ( false === $res ) {
892 $err = $this->lastError();
893 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
894 }
895 }
896
897 $cmd = '';
898 $done = false;
899 }
900 }
901 return true;
902 }
903
904 function setup_database() {
905 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
906
907 echo "<li>Creating DB objects</li>\n";
908 $res = dbsource( "../maintenance/ora/tables.sql", $this);
909
910 // Avoid the non-standard "REPLACE INTO" syntax
911 echo "<li>Populating table interwiki</li>\n";
912 $f = fopen( "../maintenance/interwiki.sql", 'r' );
913 if ($f == false ) {
914 dieout( "<li>Could not find the interwiki.sql file</li>");
915 }
916
917 //do it like the postgres :D
918 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
919 while ( ! feof( $f ) ) {
920 $line = fgets($f,1024);
921 $matches = array();
922 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
923 continue;
924 }
925 $this->query("$SQL $matches[1],$matches[2])");
926 }
927
928 echo "<li>Table interwiki successfully populated</li>\n";
929 }
930
931 function strencode($s) {
932 return str_replace("'", "''", $s);
933 }
934
935 function encodeBlob($b) {
936 return new ORABlob($b);
937 }
938 function decodeBlob($b) {
939 return $b; //return $b->load();
940 }
941
942 function addQuotes( $s ) {
943 global $wgLang;
944 if (isset($wgLang->mLoaded) && $wgLang->mLoaded)
945 $s = $wgLang->checkTitleEncoding($s);
946 return "'" . $this->strencode($s) . "'";
947 }
948
949 function quote_ident( $s ) {
950 return $s;
951 }
952
953 /* For now, does nothing */
954 function selectDB( $db ) {
955 return true;
956 }
957
958 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
959 if (is_array($table))
960 foreach ($table as $tab)
961 $tab = $this->tableName($tab);
962 else
963 $table = $this->tableName($table);
964 return parent::selectRow($table, $vars, $conds, $fname, $options, $join_conds);
965 }
966
967 /**
968 * Returns an optional USE INDEX clause to go after the table, and a
969 * string to go at the end of the query
970 *
971 * @private
972 *
973 * @param $options Array: an associative array of options to be turned into
974 * an SQL query, valid keys are listed in the function.
975 * @return array
976 */
977 function makeSelectOptions( $options ) {
978 $preLimitTail = $postLimitTail = '';
979 $startOpts = '';
980
981 $noKeyOptions = array();
982 foreach ( $options as $key => $option ) {
983 if ( is_numeric( $key ) ) {
984 $noKeyOptions[$option] = true;
985 }
986 }
987
988 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
989 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
990
991 #if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
992 #if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
993 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
994
995 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
996 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
997 } else {
998 $useIndex = '';
999 }
1000
1001 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1002 }
1003
1004 public function makeList( $a, $mode = LIST_COMMA ) {
1005 if ( !is_array( $a ) ) {
1006 throw new DBUnexpectedError( $this, 'DatabaseOracle::makeList called with incorrect parameters' );
1007 }
1008 $a2 = array();
1009 foreach ($a as $key => $value) {
1010 if (strpos($key, ' & ') !== FALSE)
1011 $a2[preg_replace('/(.*)\s&\s(.*)/', 'BITAND($1, $2)', $key)] = $value;
1012 elseif (strpos($key, ' | ') !== FALSE)
1013 $a2[preg_replace('/(.*)\s|\s(.*)/', 'BITOR($1, $2)', $key)] = $value;
1014 elseif (!is_array($value)) {
1015 if (strpos($value, ' = ') !== FALSE) {
1016 if (strpos($value, ' & ') !== FALSE)
1017 $a2[$key] = preg_replace('/(.*)\s&\s(.*?)\s=\s(.*)/', 'BITAND($1, $2) = $3', $value);
1018 elseif (strpos($value, ' | ') !== FALSE)
1019 $a2[$key] = preg_replace('/(.*)\s|\s(.*?)\s=\s(.*)/', 'BITOR($1, $2) = $3', $value);
1020 else $a2[$key] = $value;
1021 }
1022 elseif (strpos($value, ' & ') !== FALSE)
1023 $a2[$key] = preg_replace('/(.*)\s&\s(.*)/', 'BITAND($1, $2)', $value);
1024 elseif (strpos($value, ' | ') !== FALSE)
1025 $a2[$key] = preg_replace('/(.*)\s|\s(.*)/', 'BITOR($1, $2)', $value);
1026 else
1027 $a2[$key] = $value;
1028 }
1029 else
1030 $a2[$key] = $value;
1031 }
1032
1033 return parent::makeList($a2, $mode);
1034 }
1035
1036 public function setTimeout( $timeout ) {
1037 // @todo fixme no-op
1038 }
1039
1040 function ping() {
1041 wfDebug( "Function ping() not written for DatabaseOracle.php yet");
1042 return true;
1043 }
1044
1045 /**
1046 * How lagged is this slave?
1047 *
1048 * @return int
1049 */
1050 public function getLag() {
1051 # Not implemented for Oracle
1052 return 0;
1053 }
1054
1055 function setFakeSlaveLag( $lag ) {}
1056 function setFakeMaster( $enabled = true ) {}
1057
1058 function getDBname() {
1059 return $this->mDBname;
1060 }
1061
1062 function getServer() {
1063 return $this->mServer;
1064 }
1065
1066 public function replaceVars( $ins ) {
1067 $varnames = array('wgDBprefix');
1068 if ($this->mFlags & DBO_SYSDBA) {
1069 $varnames[] = 'wgDBOracleDefTS';
1070 $varnames[] = 'wgDBOracleTempTS';
1071 }
1072
1073 // Ordinary variables
1074 foreach ( $varnames as $var ) {
1075 if( isset( $GLOBALS[$var] ) ) {
1076 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1077 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1078 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1079 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1080 }
1081 }
1082
1083 return parent::replaceVars($ins);
1084 }
1085
1086 /**
1087 * No-op lock functions
1088 */
1089 public function lock( $lockName, $method ) {
1090 return true;
1091 }
1092 public function unlock( $lockName, $method ) {
1093 return true;
1094 }
1095
1096 public function getSearchEngine() {
1097 return "SearchOracle";
1098 }
1099
1100 /** No-op */
1101 public function setBigSelects( $value = true ) {}
1102
1103 } // end DatabaseOracle class