* Move generic return true; various for lock functions to parent, no need to implemen...
[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 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;
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 # 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
597 #
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);
603
604 if (count($rows)==0) {
605 return;
606 }
607
608 # Single row case
609 if (!is_array(reset($rows))) {
610 $rows = array($rows);
611 }
612
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 (';
624 }
625 if ( is_array( $index ) ) {
626 $first2 = true;
627 foreach ( $index as $col ) {
628 if ( $first2 ) {
629 $first2 = false;
630 } else {
631 $sql .= ' AND ';
632 }
633 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
634 }
635 } else {
636 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
637 }
638 }
639 $sql .= ')';
640 $this->query( $sql, $fname );
641 }
642
643 # Now insert the row
644 $this->insert( $table, $row, $fname );
645 }
646 }
647
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' );
652 }
653
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 );
659 }
660 $sql .= ')';
661
662 $this->query( $sql, $fname );
663 }
664
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;
678 }
679 $this->freeResult( $res );
680 return $size;
681 }
682
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)";
687 }
688
689
690 function unionQueries($sqls, $all = false) {
691 $glue = ' UNION ALL ';
692 return 'SELECT * '.($all?'':'/* UNION_UNIQUE */ ').'FROM ('.implode( $glue, $sqls ).')' ;
693 }
694
695 function wasDeadlock() {
696 return $this->lastErrno() == 'OCI-00060';
697 }
698
699 function timestamp($ts = 0) {
700 return wfTimestamp(TS_ORACLE, $ts);
701 }
702
703 /**
704 * Return aggregated value function call
705 */
706 function aggregateValue ($valuedata,$valuename='value') {
707 return $valuedata;
708 }
709
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;
715
716 if ($ignore || $tempIgnore) {
717 //echo "error ignored! query = [$sql]\n";
718 wfDebug("SQL ERROR (ignored): $error\n");
719 $this->ignoreErrors( $ignore );
720 }
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);
728 }
729 }
730
731 /**
732 * @return string wikitext of a link to the server software's web site
733 */
734 function getSoftwareLink() {
735 return "[http://www.oracle.com/ Oracle]";
736 }
737
738 /**
739 * @return String: Database type for use in messages
740 */
741 function getDBtypeForMsg() {
742 return 'Oracle';
743 }
744
745 /**
746 * @return string Version information from the database
747 */
748 function getServerVersion() {
749 return oci_server_version($this->mConn);
750 }
751
752 /**
753 * Query whether a given table exists (in the given schema, or the default mw one if not given)
754 */
755 function tableExists($table) {
756 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
757 $res = $this->doQuery($SQL);
758 if ($res) {
759 $count = $res->numRows();
760 $res->free();
761 } else {
762 $count = 0;
763 }
764 return $count;
765 }
766
767 /**
768 * Query whether a given column exists in the mediawiki schema
769 * based on prebuilt table to simulate MySQL field info and keep query speed minimal
770 */
771 function fieldExists( $table, $field ) {
772 if (!isset($this->fieldInfo_stmt))
773 $this->fieldInfo_stmt = oci_parse($this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)');
774
775 oci_bind_by_name($this->fieldInfo_stmt, ':tab', trim($table, '"'));
776 oci_bind_by_name($this->fieldInfo_stmt, ':col', $field);
777
778 if (oci_execute($this->fieldInfo_stmt, OCI_DEFAULT) === false) {
779 $e = oci_error($this->fieldInfo_stmt);
780 $this->reportQueryError($e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__);
781 return false;
782 }
783 $res = new ORAResult($this,$this->fieldInfo_stmt);
784 return $res->numRows() != 0;
785 }
786
787 function fieldInfo( $table, $field ) {
788 if (!isset($this->fieldInfo_stmt))
789 $this->fieldInfo_stmt = oci_parse($this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)');
790
791 oci_bind_by_name($this->fieldInfo_stmt, ':tab', trim($table, '"'));
792 oci_bind_by_name($this->fieldInfo_stmt, ':col', $field);
793
794 if (oci_execute($this->fieldInfo_stmt, OCI_DEFAULT) === false) {
795 $e = oci_error($this->fieldInfo_stmt);
796 $this->reportQueryError($e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__);
797 return false;
798 }
799 $res = new ORAResult($this,$this->fieldInfo_stmt);
800 return new ORAField($res->fetchRow());
801 }
802
803 function begin( $fname = '' ) {
804 $this->mTrxLevel = 1;
805 }
806 function immediateCommit( $fname = '' ) {
807 return true;
808 }
809 function commit( $fname = '' ) {
810 oci_commit($this->mConn);
811 $this->mTrxLevel = 0;
812 }
813
814 /* Not even sure why this is used in the main codebase... */
815 function limitResultForUpdate($sql, $num) {
816 return $sql;
817 }
818
819 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
820 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
821 $cmd = "";
822 $done = false;
823 $dollarquote = false;
824
825 $replacements = array();
826
827 while ( ! feof( $fp ) ) {
828 if ( $lineCallback ) {
829 call_user_func( $lineCallback );
830 }
831 $line = trim( fgets( $fp, 1024 ) );
832 $sl = strlen( $line ) - 1;
833
834 if ( $sl < 0 ) { continue; }
835 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
836
837 // Allow dollar quoting for function declarations
838 if (substr($line,0,8) == '/*$mw$*/') {
839 if ($dollarquote) {
840 $dollarquote = false;
841 $done = true;
842 }
843 else {
844 $dollarquote = true;
845 }
846 }
847 else if (!$dollarquote) {
848 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
849 $done = true;
850 $line = substr( $line, 0, $sl );
851 }
852 }
853
854 if ( '' != $cmd ) { $cmd .= ' '; }
855 $cmd .= "$line\n";
856
857 if ( $done ) {
858 $cmd = str_replace(';;', ";", $cmd);
859 if (strtolower(substr($cmd, 0, 6)) == 'define' ) {
860 if (preg_match('/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines)) {
861 $replacements[$defines[2]] = $defines[1];
862 }
863 } else {
864 foreach ( $replacements as $mwVar=>$scVar ) {
865 $cmd = str_replace( '&' . $scVar . '.', '{$'.$mwVar.'}', $cmd );
866 }
867
868 $cmd = $this->replaceVars( $cmd );
869 $res = $this->query( $cmd, __METHOD__ );
870 if ( $resultCallback ) {
871 call_user_func( $resultCallback, $res, $this );
872 }
873
874 if ( false === $res ) {
875 $err = $this->lastError();
876 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
877 }
878 }
879
880 $cmd = '';
881 $done = false;
882 }
883 }
884 return true;
885 }
886
887 function setup_database() {
888 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
889
890 echo "<li>Creating DB objects</li>\n";
891 $res = $this->sourceFile( "../maintenance/ora/tables.sql" );
892
893 // Avoid the non-standard "REPLACE INTO" syntax
894 echo "<li>Populating table interwiki</li>\n";
895 $f = fopen( "../maintenance/interwiki.sql", 'r' );
896 if ($f == false ) {
897 dieout( "<li>Could not find the interwiki.sql file</li>");
898 }
899
900 //do it like the postgres :D
901 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
902 while ( ! feof( $f ) ) {
903 $line = fgets($f,1024);
904 $matches = array();
905 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
906 continue;
907 }
908 $this->query("$SQL $matches[1],$matches[2])");
909 }
910
911 echo "<li>Table interwiki successfully populated</li>\n";
912 }
913
914 function strencode($s) {
915 return str_replace("'", "''", $s);
916 }
917
918 function encodeBlob($b) {
919 return new ORABlob($b);
920 }
921 function decodeBlob($b) {
922 return $b; //return $b->load();
923 }
924
925 function addQuotes( $s ) {
926 global $wgLang;
927 if (isset($wgLang->mLoaded) && $wgLang->mLoaded)
928 $s = $wgLang->checkTitleEncoding($s);
929 return "'" . $this->strencode($s) . "'";
930 }
931
932 function quote_ident( $s ) {
933 return $s;
934 }
935
936 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
937 if (is_array($table))
938 foreach ($table as $tab)
939 $tab = $this->tableName($tab);
940 else
941 $table = $this->tableName($table);
942 return parent::selectRow($table, $vars, $conds, $fname, $options, $join_conds);
943 }
944
945 /**
946 * Returns an optional USE INDEX clause to go after the table, and a
947 * string to go at the end of the query
948 *
949 * @private
950 *
951 * @param $options Array: an associative array of options to be turned into
952 * an SQL query, valid keys are listed in the function.
953 * @return array
954 */
955 function makeSelectOptions( $options ) {
956 $preLimitTail = $postLimitTail = '';
957 $startOpts = '';
958
959 $noKeyOptions = array();
960 foreach ( $options as $key => $option ) {
961 if ( is_numeric( $key ) ) {
962 $noKeyOptions[$option] = true;
963 }
964 }
965
966 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
967 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
968
969 #if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
970 #if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
971 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
972
973 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
974 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
975 } else {
976 $useIndex = '';
977 }
978
979 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
980 }
981
982 /* redundand ... will remove after confirming bitwise operations functionality
983 public function makeList( $a, $mode = LIST_COMMA ) {
984 if ( !is_array( $a ) ) {
985 throw new DBUnexpectedError( $this, 'DatabaseOracle::makeList called with incorrect parameters' );
986 }
987 $a2 = array();
988 foreach ($a as $key => $value) {
989 if (strpos($key, ' & ') !== FALSE)
990 $a2[preg_replace('/(.*)\s&\s(.*)/', 'BITAND($1, $2)', $key)] = $value;
991 elseif (strpos($key, ' | ') !== FALSE)
992 $a2[preg_replace('/(.*)\s|\s(.*)/', 'BITOR($1, $2)', $key)] = $value;
993 elseif (!is_array($value)) {
994 if (strpos($value, ' = ') !== FALSE) {
995 if (strpos($value, ' & ') !== FALSE)
996 $a2[$key] = preg_replace('/(.*)\s&\s(.*?)\s=\s(.*)/', 'BITAND($1, $2) = $3', $value);
997 elseif (strpos($value, ' | ') !== FALSE)
998 $a2[$key] = preg_replace('/(.*)\s|\s(.*?)\s=\s(.*)/', 'BITOR($1, $2) = $3', $value);
999 else $a2[$key] = $value;
1000 }
1001 elseif (strpos($value, ' & ') !== FALSE)
1002 $a2[$key] = preg_replace('/(.*)\s&\s(.*)/', 'BITAND($1, $2)', $value);
1003 elseif (strpos($value, ' | ') !== FALSE)
1004 $a2[$key] = preg_replace('/(.*)\s|\s(.*)/', 'BITOR($1, $2)', $value);
1005 else
1006 $a2[$key] = $value;
1007 }
1008 else
1009 $a2[$key] = $value;
1010 }
1011
1012 return parent::makeList($a2, $mode);
1013 }
1014 */
1015
1016 function bitNot($field) {
1017 //expecting bit-fields smaller than 4bytes
1018 return 'BITNOT('.$bitField.')';
1019 }
1020
1021 function bitAnd($fieldLeft, $fieldRight) {
1022 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1023 }
1024
1025 function bitOr($fieldLeft, $fieldRight) {
1026 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';
1027 }
1028
1029 /**
1030 * How lagged is this slave?
1031 *
1032 * @return int
1033 */
1034 public function getLag() {
1035 # Not implemented for Oracle
1036 return 0;
1037 }
1038
1039 function setFakeSlaveLag( $lag ) {}
1040 function setFakeMaster( $enabled = true ) {}
1041
1042 function getDBname() {
1043 return $this->mDBname;
1044 }
1045
1046 function getServer() {
1047 return $this->mServer;
1048 }
1049
1050 public function replaceVars( $ins ) {
1051 $varnames = array('wgDBprefix');
1052 if ($this->mFlags & DBO_SYSDBA) {
1053 $varnames[] = 'wgDBOracleDefTS';
1054 $varnames[] = 'wgDBOracleTempTS';
1055 }
1056
1057 // Ordinary variables
1058 foreach ( $varnames as $var ) {
1059 if( isset( $GLOBALS[$var] ) ) {
1060 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1061 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1062 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1063 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1064 }
1065 }
1066
1067 return parent::replaceVars($ins);
1068 }
1069
1070 public function getSearchEngine() {
1071 return "SearchOracle";
1072 }
1073 } // end DatabaseOracle class