Abstract more methods in DatabaseBase
[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 Version information from the database
740 */
741 function getServerVersion() {
742 return oci_server_version($this->mConn);
743 }
744
745 /**
746 * Query whether a given table exists (in the given schema, or the default mw one if not given)
747 */
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;
756 }
757 return $count;
758 }
759
760 /**
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
763 */
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)');
767
768 oci_bind_by_name($this->fieldInfo_stmt, ':tab', trim($table, '"'));
769 oci_bind_by_name($this->fieldInfo_stmt, ':col', $field);
770
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;
775 }
776 $res = new ORAResult($this,$this->fieldInfo_stmt);
777 return $res->numRows() != 0;
778 }
779
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)');
783
784 oci_bind_by_name($this->fieldInfo_stmt, ':tab', trim($table, '"'));
785 oci_bind_by_name($this->fieldInfo_stmt, ':col', $field);
786
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;
791 }
792 $res = new ORAResult($this,$this->fieldInfo_stmt);
793 return new ORAField($res->fetchRow());
794 }
795
796 function begin( $fname = '' ) {
797 $this->mTrxLevel = 1;
798 }
799 function immediateCommit( $fname = '' ) {
800 return true;
801 }
802 function commit( $fname = '' ) {
803 oci_commit($this->mConn);
804 $this->mTrxLevel = 0;
805 }
806
807 /* Not even sure why this is used in the main codebase... */
808 function limitResultForUpdate($sql, $num) {
809 return $sql;
810 }
811
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;
817
818 $replacements = array();
819
820 while ( ! feof( $fp ) ) {
821 if ( $lineCallback ) {
822 call_user_func( $lineCallback );
823 }
824 $line = trim( fgets( $fp, 1024 ) );
825 $sl = strlen( $line ) - 1;
826
827 if ( $sl < 0 ) { continue; }
828 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
829
830 // Allow dollar quoting for function declarations
831 if (substr($line,0,8) == '/*$mw$*/') {
832 if ($dollarquote) {
833 $dollarquote = false;
834 $done = true;
835 }
836 else {
837 $dollarquote = true;
838 }
839 }
840 else if (!$dollarquote) {
841 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
842 $done = true;
843 $line = substr( $line, 0, $sl );
844 }
845 }
846
847 if ( '' != $cmd ) { $cmd .= ' '; }
848 $cmd .= "$line\n";
849
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];
855 }
856 } else {
857 foreach ( $replacements as $mwVar=>$scVar ) {
858 $cmd = str_replace( '&' . $scVar . '.', '{$'.$mwVar.'}', $cmd );
859 }
860
861 $cmd = $this->replaceVars( $cmd );
862 $res = $this->query( $cmd, __METHOD__ );
863 if ( $resultCallback ) {
864 call_user_func( $resultCallback, $res, $this );
865 }
866
867 if ( false === $res ) {
868 $err = $this->lastError();
869 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
870 }
871 }
872
873 $cmd = '';
874 $done = false;
875 }
876 }
877 return true;
878 }
879
880 function setup_database() {
881 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
882
883 echo "<li>Creating DB objects</li>\n";
884 $res = dbsource( "../maintenance/ora/tables.sql", $this);
885
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>");
891 }
892
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;
900 }
901 $this->query("$SQL $matches[1],$matches[2])");
902 }
903
904 echo "<li>Table interwiki successfully populated</li>\n";
905 }
906
907 function strencode($s) {
908 return str_replace("'", "''", $s);
909 }
910
911 function encodeBlob($b) {
912 return new ORABlob($b);
913 }
914 function decodeBlob($b) {
915 return $b; //return $b->load();
916 }
917
918 function addQuotes( $s ) {
919 global $wgLang;
920 if (isset($wgLang->mLoaded) && $wgLang->mLoaded)
921 $s = $wgLang->checkTitleEncoding($s);
922 return "'" . $this->strencode($s) . "'";
923 }
924
925 function quote_ident( $s ) {
926 return $s;
927 }
928
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);
936 }
937
938 /**
939 * Returns an optional USE INDEX clause to go after the table, and a
940 * string to go at the end of the query
941 *
942 * @private
943 *
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
947 */
948 function makeSelectOptions( $options ) {
949 $preLimitTail = $postLimitTail = '';
950 $startOpts = '';
951
952 $noKeyOptions = array();
953 foreach ( $options as $key => $option ) {
954 if ( is_numeric( $key ) ) {
955 $noKeyOptions[$option] = true;
956 }
957 }
958
959 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
960 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
961
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';
965
966 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
967 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
968 } else {
969 $useIndex = '';
970 }
971
972 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
973 }
974
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' );
979 }
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;
993 }
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;
1000 }
1001 else
1002 $a2[$key] = $value;
1003 }
1004
1005 return parent::makeList($a2, $mode);
1006 }
1007 */
1008
1009 function bitNot($field) {
1010 //expecting bit-fields smaller than 4bytes
1011 return 'BITNOT('.$bitField.')';
1012 }
1013
1014 function bitAnd($fieldLeft, $fieldRight) {
1015 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1016 }
1017
1018 function bitOr($fieldLeft, $fieldRight) {
1019 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';
1020 }
1021
1022 /**
1023 * How lagged is this slave?
1024 *
1025 * @return int
1026 */
1027 public function getLag() {
1028 # Not implemented for Oracle
1029 return 0;
1030 }
1031
1032 function setFakeSlaveLag( $lag ) {}
1033 function setFakeMaster( $enabled = true ) {}
1034
1035 function getDBname() {
1036 return $this->mDBname;
1037 }
1038
1039 function getServer() {
1040 return $this->mServer;
1041 }
1042
1043 public function replaceVars( $ins ) {
1044 $varnames = array('wgDBprefix');
1045 if ($this->mFlags & DBO_SYSDBA) {
1046 $varnames[] = 'wgDBOracleDefTS';
1047 $varnames[] = 'wgDBOracleTempTS';
1048 }
1049
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 );
1057 }
1058 }
1059
1060 return parent::replaceVars($ins);
1061 }
1062
1063 /**
1064 * No-op lock functions
1065 */
1066 public function lock( $lockName, $method ) {
1067 return true;
1068 }
1069 public function unlock( $lockName, $method ) {
1070 return true;
1071 }
1072
1073 public function getSearchEngine() {
1074 return "SearchOracle";
1075 }
1076
1077 /** No-op */
1078 public function setBigSelects( $value = true ) {}
1079
1080 } // end DatabaseOracle class