Fixed some Oracle-specific installer and Strict Standards issues
[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 private function array_unique_md($array_in) {
37 $array_out = array();
38 $array_hashes = array();
39
40 foreach($array_in as $key => $item) {
41 $hash = md5(serialize($item));
42 if (!isset($array_hashes[$hash])) {
43 $array_hashes[$hash] = $hash;
44 $array_out[] = $item;
45 }
46 }
47
48 return $array_out;
49 }
50
51 function __construct(&$db, $stmt, $unique = false) {
52 $this->db =& $db;
53
54 if (($this->nrows = oci_fetch_all($stmt, $this->rows, 0, -1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM)) === false) {
55 $e = oci_error($stmt);
56 $db->reportQueryError($e['message'], $e['code'], '', __FUNCTION__);
57 return;
58 }
59
60 if ($unique) {
61 $this->rows = $this->array_unique_md($this->rows);
62 $this->nrows = count($this->rows);
63 }
64
65 $this->cursor = 0;
66 $this->stmt = $stmt;
67 }
68
69 public function free() {
70 oci_free_statement($this->stmt);
71 }
72
73 public function seek($row) {
74 $this->cursor = min($row, $this->nrows);
75 }
76
77 public function numRows() {
78 return $this->nrows;
79 }
80
81 public function numFields() {
82 return oci_num_fields($this->stmt);
83 }
84
85 public function fetchObject() {
86 if ($this->cursor >= $this->nrows)
87 return false;
88 $row = $this->rows[$this->cursor++];
89 $ret = new stdClass();
90 foreach ($row as $k => $v) {
91 $lc = strtolower(oci_field_name($this->stmt, $k + 1));
92 $ret->$lc = $v;
93 }
94
95 return $ret;
96 }
97
98 public function fetchRow() {
99 if ($this->cursor >= $this->nrows)
100 return false;
101
102 $row = $this->rows[$this->cursor++];
103 $ret = array();
104 foreach ($row as $k => $v) {
105 $lc = strtolower(oci_field_name($this->stmt, $k + 1));
106 $ret[$lc] = $v;
107 $ret[$k] = $v;
108 }
109 return $ret;
110 }
111 }
112
113 /**
114 * Utility class.
115 * @ingroup Database
116 */
117 class ORAField {
118 private $name, $tablename, $default, $max_length, $nullable,
119 $is_pk, $is_unique, $is_multiple, $is_key, $type;
120
121 function __construct($info) {
122 $this->name = $info['column_name'];
123 $this->tablename = $info['table_name'];
124 $this->default = $info['data_default'];
125 $this->max_length = $info['data_length'];
126 $this->nullable = $info['not_null'];
127 $this->is_pk = isset($info['prim']) && $info['prim'] == 1 ? 1 : 0;
128 $this->is_unique = isset($info['uniq']) && $info['uniq'] == 1 ? 1 : 0;
129 $this->is_multiple = isset($info['nonuniq']) && $info['nonuniq'] == 1 ? 1 : 0;
130 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
131 $this->type = $info['data_type'];
132 }
133
134 function name() {
135 return $this->name;
136 }
137
138 function tableName() {
139 return $this->tablename;
140 }
141
142 function defaultValue() {
143 return $this->default;
144 }
145
146 function maxLength() {
147 return $this->max_length;
148 }
149
150 function nullable() {
151 return $this->nullable;
152 }
153
154 function isKey() {
155 return $this->is_key;
156 }
157
158 function isMultipleKey() {
159 return $this->is_multiple;
160 }
161
162 function type() {
163 return $this->type;
164 }
165 }
166
167 /**
168 * @ingroup Database
169 */
170 class DatabaseOracle extends DatabaseBase {
171 var $mInsertId = NULL;
172 var $mLastResult = NULL;
173 var $numeric_version = NULL;
174 var $lastResult = null;
175 var $cursor = 0;
176 var $mAffectedRows;
177
178 var $ignore_DUP_VAL_ON_INDEX = false;
179 var $sequenceData = null;
180
181 function DatabaseOracle($server = false, $user = false, $password = false, $dbName = false,
182 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
183 {
184 $tablePrefix = $tablePrefix == 'get from global' ? $tablePrefix : strtoupper($tablePrefix);
185 parent::__construct($server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix);
186 wfRunHooks( 'DatabaseOraclePostInit', array(&$this));
187 }
188
189 function cascadingDeletes() {
190 return true;
191 }
192 function cleanupTriggers() {
193 return true;
194 }
195 function strictIPs() {
196 return true;
197 }
198 function realTimestamps() {
199 return true;
200 }
201 function implicitGroupby() {
202 return false;
203 }
204 function implicitOrderby() {
205 return false;
206 }
207 function searchableIPs() {
208 return true;
209 }
210
211 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
212 {
213 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags );
214 }
215
216 /**
217 * Usually aborts on failure
218 * If the failFunction is set to a non-zero integer, returns success
219 */
220 function open( $server, $user, $password, $dbName ) {
221 if ( !function_exists( 'oci_connect' ) ) {
222 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" );
223 }
224
225 putenv("NLS_LANG=AMERICAN_AMERICA.AL32UTF8");
226
227 $this->close();
228 $this->mServer = $server;
229 $this->mUser = $user;
230 $this->mPassword = $password;
231 $this->mDBname = $dbName;
232
233 if (!strlen($user)) { ## e.g. the class is being loaded
234 return;
235 }
236
237 //error_reporting( E_ALL ); //whoever had this bright idea
238 $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
239 if ( $this->mFlags & DBO_DEFAULT )
240 $this->mConn = oci_new_connect($user, $password, $dbName, null, $session_mode);
241 else
242 $this->mConn = oci_connect($user, $password, $dbName, null, $session_mode);
243
244 if ($this->mConn == false) {
245 wfDebug("DB connection error\n");
246 wfDebug("Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n");
247 wfDebug($this->lastError()."\n");
248 return false;
249 }
250
251 $this->mOpened = true;
252
253 #removed putenv calls because they interfere with the system globaly
254 $this->doQuery('ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'');
255 $this->doQuery('ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'');
256
257 return $this->mConn;
258 }
259
260 /**
261 * Closes a database connection, if it is open
262 * Returns success, true if already closed
263 */
264 function close() {
265 $this->mOpened = false;
266 if ( $this->mConn ) {
267 return oci_close( $this->mConn );
268 } else {
269 return true;
270 }
271 }
272
273 function execFlags() {
274 return $this->mTrxLevel ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
275 }
276
277 function doQuery($sql) {
278 wfDebug("SQL: [$sql]\n");
279 if (!mb_check_encoding($sql)) {
280 throw new MWException("SQL encoding is invalid");
281 }
282
283 //handle some oracle specifics
284 //remove AS column/table/subquery namings
285 $sql = preg_replace('/ as /i', ' ', $sql);
286 // Oracle has issues with UNION clause if the statement includes LOB fields
287 // So we do a UNION ALL and then filter the results array with array_unique
288 $union_unique = (preg_match('/\/\* UNION_UNIQUE \*\/ /', $sql) != 0);
289 //EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
290 //you have to select data from plan table after explain
291 $olderr = error_reporting(E_ERROR);
292 $explain_id = date('dmYHis');
293 error_reporting($olderr);
294 $sql = preg_replace('/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \''.$explain_id.'\' FOR', $sql, 1, $explain_count);
295
296
297 if (($this->mLastResult = $stmt = oci_parse($this->mConn, $sql)) === false) {
298 $e = oci_error($this->mConn);
299 $this->reportQueryError($e['message'], $e['code'], $sql, __FUNCTION__);
300 }
301
302 $olderr = error_reporting(E_ERROR);
303 if (oci_execute($stmt, $this->execFlags()) == false) {
304 $e = oci_error($stmt);
305 if (!$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1')
306 $this->reportQueryError($e['message'], $e['code'], $sql, __FUNCTION__);
307 }
308 error_reporting($olderr);
309
310 if ($explain_count > 0) {
311 return $this->doQuery('SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \''.$explain_id.'\'');
312 } elseif (oci_statement_type($stmt) == "SELECT") {
313 return new ORAResult($this, $stmt, $union_unique);
314 } else {
315 $this->mAffectedRows = oci_num_rows($stmt);
316 return true;
317 }
318 }
319
320 function queryIgnore($sql, $fname = '') {
321 return $this->query($sql, $fname, true);
322 }
323
324 function freeResult($res) {
325 if ( $res instanceof ORAResult ) {
326 $res->free();
327 } else {
328 $res->result->free();
329 }
330 }
331
332 function fetchObject($res) {
333 if ( $res instanceof ORAResult ) {
334 return $res->numRows();
335 } else {
336 return $res->result->fetchObject();
337 }
338 }
339
340 function fetchRow($res) {
341 if ( $res instanceof ORAResult ) {
342 return $res->fetchRow();
343 } else {
344 return $res->result->fetchRow();
345 }
346 }
347
348 function numRows($res) {
349 if ( $res instanceof ORAResult ) {
350 return $res->numRows();
351 } else {
352 return $res->result->numRows();
353 }
354 }
355
356 function numFields($res) {
357 if ( $res instanceof ORAResult ) {
358 return $res->numFields();
359 } else {
360 return $res->result->numFields();
361 }
362 }
363
364 function fieldName($stmt, $n) {
365 return oci_field_name($stmt, $n);
366 }
367
368 /**
369 * This must be called after nextSequenceVal
370 */
371 function insertId() {
372 return $this->mInsertId;
373 }
374
375 function dataSeek($res, $row) {
376 if ( $res instanceof ORAResult ) {
377 $res->seek($row);
378 } else {
379 $res->result->seek($row);
380 }
381 }
382
383 function lastError() {
384 if ($this->mConn === false)
385 $e = oci_error();
386 else
387 $e = oci_error($this->mConn);
388 return $e['message'];
389 }
390
391 function lastErrno() {
392 if ($this->mConn === false)
393 $e = oci_error();
394 else
395 $e = oci_error($this->mConn);
396 return $e['code'];
397 }
398
399 function affectedRows() {
400 return $this->mAffectedRows;
401 }
402
403 /**
404 * Returns information about an index
405 * If errors are explicitly ignored, returns NULL on failure
406 */
407 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
408 return false;
409 }
410
411 function indexUnique ($table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
412 return false;
413 }
414
415 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
416 if ( !count( $a ) )
417 return true;
418
419 if (!is_array($options))
420 $options = array($options);
421
422 if (in_array('IGNORE', $options))
423 $this->ignore_DUP_VAL_ON_INDEX = true;
424
425 if (!is_array(reset($a))) {
426 $a = array($a);
427 }
428 foreach ($a as $row) {
429 $this->insertOneRow($table, $row, $fname);
430 }
431 $retVal = true;
432
433 if (in_array('IGNORE', $options))
434 $this->ignore_DUP_VAL_ON_INDEX = false;
435
436 return $retVal;
437 }
438
439 function insertOneRow($table, $row, $fname) {
440 global $wgLang;
441
442 // "INSERT INTO tables (a, b, c)"
443 $sql = "INSERT INTO " . $this->tableName($table) . " (" . join(',', array_keys($row)) . ')';
444 $sql .= " VALUES (";
445
446 // for each value, append ":key"
447 $first = true;
448 foreach ($row as $col => $val) {
449 if ($first)
450 $sql .= $val !== NULL ? ':'.$col : 'NULL';
451 else
452 $sql .= $val !== NULL ? ', :'.$col : ', NULL';
453
454 $first = false;
455 }
456 $sql .= ')';
457
458
459 $stmt = oci_parse($this->mConn, $sql);
460 foreach ($row as $col => &$val) {
461 $col_type=$this->fieldInfo($this->tableName($table), $col)->type();
462
463 if ($val === NULL) {
464 // do nothing ... null was inserted in statement creation
465 } elseif ($col_type != 'BLOB' && $col_type != 'CLOB') {
466 if (is_object($val))
467 $val = $val->getData();
468
469 if (preg_match('/^timestamp.*/i', $col_type) == 1 && strtolower($val) == 'infinity')
470 $val = '31-12-2030 12:00:00.000000';
471
472 $val = $wgLang->checkTitleEncoding($val);
473 if (oci_bind_by_name($stmt, ":$col", $val) === false)
474 $this->reportQueryError($this->lastErrno(), $this->lastError(), $sql, __METHOD__);
475 } else {
476 if (($lob[$col] = oci_new_descriptor($this->mConn, OCI_D_LOB)) === false) {
477 $e = oci_error($stmt);
478 throw new DBUnexpectedError($this, "Cannot create LOB descriptor: " . $e['message']);
479 }
480
481 if (is_object($val)) {
482 $lob[$col]->writeTemporary($val->getData());
483 oci_bind_by_name($stmt, ":$col", $lob[$col], -1, SQLT_BLOB);
484 } else {
485 $lob[$col]->writeTemporary($val);
486 oci_bind_by_name($stmt, ":$col", $lob[$col], -1, OCI_B_CLOB);
487 }
488 }
489 }
490
491 $olderr = error_reporting(E_ERROR);
492 if (oci_execute($stmt, OCI_DEFAULT) === false) {
493 $e = oci_error($stmt);
494
495 if (!$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1')
496 $this->reportQueryError($e['message'], $e['code'], $sql, __METHOD__);
497 else
498 $this->mAffectedRows = oci_num_rows($stmt);
499 } else
500 $this->mAffectedRows = oci_num_rows($stmt);
501 error_reporting($olderr);
502
503 if (isset($lob)){
504 foreach ($lob as $lob_i => $lob_v) {
505 $lob_v->free();
506 }
507 }
508
509 if (!$this->mTrxLevel)
510 oci_commit($this->mConn);
511
512 oci_free_statement($stmt);
513 }
514
515 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
516 $insertOptions = array(), $selectOptions = array() )
517 {
518 $destTable = $this->tableName( $destTable );
519 if( !is_array( $selectOptions ) ) {
520 $selectOptions = array( $selectOptions );
521 }
522 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
523 if( is_array( $srcTable ) ) {
524 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
525 } else {
526 $srcTable = $this->tableName( $srcTable );
527 }
528
529 if (($sequenceData = $this->getSequenceData($destTable)) !== false &&
530 !isset($varMap[$sequenceData['column']]))
531 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\''.$sequenceData['sequence'].'\')';
532
533 // count-alias subselect fields to avoid abigious definition errors
534 $i=0;
535 foreach($varMap as $key=>&$val)
536 $val=$val.' field'.($i++);
537
538 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
539 " SELECT $startOpts " . implode( ',', $varMap ) .
540 " FROM $srcTable $useIndex ";
541 if ( $conds != '*' ) {
542 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
543 }
544 $sql .= " $tailOpts";
545
546 if (in_array('IGNORE', $insertOptions))
547 $this->ignore_DUP_VAL_ON_INDEX = true;
548
549 $retval = $this->query( $sql, $fname );
550
551 if (in_array('IGNORE', $insertOptions))
552 $this->ignore_DUP_VAL_ON_INDEX = false;
553
554 return $retval;
555 }
556
557 function tableName( $name ) {
558 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
559 /*
560 Replace reserved words with better ones
561 Useing uppercase, because that's the only way oracle can handle
562 quoted tablenames
563 */
564 switch( $name ) {
565 case 'user':
566 $name = 'MWUSER'; break;
567 case 'text':
568 $name = 'PAGECONTENT'; break;
569 }
570
571 /*
572 The rest of procedure is equal to generic Databse class
573 except for the quoting style
574 */
575 if ( $name[0] == '"' && substr( $name, -1, 1 ) == '"' ) return $name;
576
577 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
578 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
579 if( isset( $dbDetails[1] ) ) @list( $table, $database ) = $dbDetails;
580 else @list( $table ) = $dbDetails;
581
582 $prefix = $this->mTablePrefix;
583
584 if( isset($database) ) $table = ( $table[0] == '`' ? $table : "`{$table}`" );
585
586 if( !isset( $database )
587 && isset( $wgSharedDB )
588 && $table[0] != '"'
589 && isset( $wgSharedTables )
590 && is_array( $wgSharedTables )
591 && in_array( $table, $wgSharedTables ) ) {
592 $database = $wgSharedDB;
593 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
594 }
595
596 if( isset($database) ) $database = ( $database[0] == '"' ? $database : "\"{$database}\"" );
597 $table = ( $table[0] == '"' ? $table : "\"{$prefix}{$table}\"" );
598
599 $tableName = ( isset($database) ? "{$database}.{$table}" : "{$table}" );
600
601 return strtoupper($tableName);
602 }
603
604 /**
605 * Return the next in a sequence, save the value for retrieval via insertId()
606 */
607 function nextSequenceValue($seqName) {
608 $res = $this->query("SELECT $seqName.nextval FROM dual");
609 $row = $this->fetchRow($res);
610 $this->mInsertId = $row[0];
611 $this->freeResult($res);
612 return $this->mInsertId;
613 }
614
615 /**
616 * Return sequence_name if table has a sequence
617 */
618 function getSequenceData($table) {
619 if ($this->sequenceData == NULL) {
620 $result = $this->query("SELECT lower(us.sequence_name), lower(utc.table_name), lower(utc.column_name) from user_sequences us, user_tab_columns utc where us.sequence_name = utc.table_name||'_'||utc.column_name||'_SEQ'");
621
622 while(($row = $result->fetchRow()) !== false)
623 $this->sequenceData[$this->tableName($row[1])] = array('sequence' => $row[0], 'column' => $row[2]);
624 }
625
626 return (isset($this->sequenceData[$table])) ? $this->sequenceData[$table] : false;
627 }
628
629
630 # REPLACE query wrapper
631 # Oracle simulates this with a DELETE followed by INSERT
632 # $row is the row to insert, an associative array
633 # $uniqueIndexes is an array of indexes. Each element may be either a
634 # field name or an array of field names
635 #
636 # It may be more efficient to leave off unique indexes which are unlikely to collide.
637 # However if you do this, you run the risk of encountering errors which wouldn't have
638 # occurred in MySQL
639 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
640 $table = $this->tableName($table);
641
642 if (count($rows)==0) {
643 return;
644 }
645
646 # Single row case
647 if (!is_array(reset($rows))) {
648 $rows = array($rows);
649 }
650
651 foreach( $rows as $row ) {
652 # Delete rows which collide
653 if ( $uniqueIndexes ) {
654 $sql = "DELETE FROM $table WHERE ";
655 $first = true;
656 foreach ( $uniqueIndexes as $index ) {
657 if ( $first ) {
658 $first = false;
659 $sql .= "(";
660 } else {
661 $sql .= ') OR (';
662 }
663 if ( is_array( $index ) ) {
664 $first2 = true;
665 foreach ( $index as $col ) {
666 if ( $first2 ) {
667 $first2 = false;
668 } else {
669 $sql .= ' AND ';
670 }
671 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
672 }
673 } else {
674 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
675 }
676 }
677 $sql .= ')';
678 $this->query( $sql, $fname );
679 }
680
681 # Now insert the row
682 $this->insert( $table, $row, $fname );
683 }
684 }
685
686 # DELETE where the condition is a join
687 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseOracle::deleteJoin" ) {
688 if ( !$conds ) {
689 throw new DBUnexpectedError($this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
690 }
691
692 $delTable = $this->tableName( $delTable );
693 $joinTable = $this->tableName( $joinTable );
694 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
695 if ( $conds != '*' ) {
696 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
697 }
698 $sql .= ')';
699
700 $this->query( $sql, $fname );
701 }
702
703 # Returns the size of a text field, or -1 for "unlimited"
704 function textFieldSize( $table, $field ) {
705 $table = $this->tableName( $table );
706 $sql = "SELECT t.typname as ftype,a.atttypmod as size
707 FROM pg_class c, pg_attribute a, pg_type t
708 WHERE relname='$table' AND a.attrelid=c.oid AND
709 a.atttypid=t.oid and a.attname='$field'";
710 $res =$this->query($sql);
711 $row=$this->fetchObject($res);
712 if ($row->ftype=="varchar") {
713 $size=$row->size-4;
714 } else {
715 $size=$row->size;
716 }
717 $this->freeResult( $res );
718 return $size;
719 }
720
721 function limitResult( $sql, $limit, $offset=false ) {
722 if ($offset === false)
723 $offset = 0;
724 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
725 }
726
727
728 function unionQueries($sqls, $all) {
729 $glue = ' UNION ALL ';
730 return 'SELECT * '.($all?'':'/* UNION_UNIQUE */ ').'FROM ('.implode( $glue, $sqls ).')' ;
731 }
732
733 function wasDeadlock() {
734 return $this->lastErrno() == 'OCI-00060';
735 }
736
737 function timestamp($ts = 0) {
738 return wfTimestamp(TS_ORACLE, $ts);
739 }
740
741 /**
742 * Return aggregated value function call
743 */
744 function aggregateValue ($valuedata,$valuename='value') {
745 return $valuedata;
746 }
747
748 function reportQueryError($error, $errno, $sql, $fname, $tempIgnore = false) {
749 # Ignore errors during error handling to avoid infinite
750 # recursion
751 $ignore = $this->ignoreErrors(true);
752 ++$this->mErrorCount;
753
754 if ($ignore || $tempIgnore) {
755 //echo "error ignored! query = [$sql]\n";
756 wfDebug("SQL ERROR (ignored): $error\n");
757 $this->ignoreErrors( $ignore );
758 }
759 else {
760 //echo "error!\n";
761 $message = "A database error has occurred\n" .
762 "Query: $sql\n" .
763 "Function: $fname\n" .
764 "Error: $errno $error\n";
765 throw new DBUnexpectedError($this, $message);
766 }
767 }
768
769 /**
770 * @return string wikitext of a link to the server software's web site
771 */
772 function getSoftwareLink() {
773 return "[http://www.oracle.com/ Oracle]";
774 }
775
776 /**
777 * @return string Version information from the database
778 */
779 function getServerVersion() {
780 return oci_server_version($this->mConn);
781 }
782
783 /**
784 * Query whether a given table exists (in the given schema, or the default mw one if not given)
785 */
786 function tableExists($table) {
787 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
788 $res = $this->doQuery($SQL);
789 if ($res) {
790 $count = $res->numRows();
791 $res->free();
792 } else {
793 $count = 0;
794 }
795 return $count;
796 }
797
798 /**
799 * Query whether a given column exists in the mediawiki schema
800 * based on prebuilt table to simulate MySQL field info and keep query speed minimal
801 */
802 function fieldExists( $table, $field, $fname = 'DatabaseOracle::fieldExists' ) {
803 if (!isset($this->fieldInfo_stmt))
804 $this->fieldInfo_stmt = oci_parse($this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)');
805
806 oci_bind_by_name($this->fieldInfo_stmt, ':tab', trim($table, '"'));
807 oci_bind_by_name($this->fieldInfo_stmt, ':col', $field);
808
809 if (oci_execute($this->fieldInfo_stmt, OCI_DEFAULT) === false) {
810 $e = oci_error($this->fieldInfo_stmt);
811 $this->reportQueryError($e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__);
812 return false;
813 }
814 $res = new ORAResult($this,$this->fieldInfo_stmt);
815 return $res->numRows() != 0;
816 }
817
818 function fieldInfo( $table, $field ) {
819 if (!isset($this->fieldInfo_stmt))
820 $this->fieldInfo_stmt = oci_parse($this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name = upper(:tab) and column_name = UPPER(:col)');
821
822 $table = trim($table, '"');
823 oci_bind_by_name($this->fieldInfo_stmt, ':tab', $table);
824 oci_bind_by_name($this->fieldInfo_stmt, ':col', $field);
825
826 if (oci_execute($this->fieldInfo_stmt, OCI_DEFAULT) === false) {
827 $e = oci_error($this->fieldInfo_stmt);
828 $this->reportQueryError($e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__);
829 return false;
830 }
831 $res = new ORAResult($this,$this->fieldInfo_stmt);
832 return new ORAField($res->fetchRow());
833 }
834
835 function begin( $fname = '' ) {
836 $this->mTrxLevel = 1;
837 }
838 function immediateCommit( $fname = '' ) {
839 return true;
840 }
841 function commit( $fname = '' ) {
842 oci_commit($this->mConn);
843 $this->mTrxLevel = 0;
844 }
845
846 /* Not even sure why this is used in the main codebase... */
847 function limitResultForUpdate($sql, $num) {
848 return $sql;
849 }
850
851 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
852 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
853 $cmd = "";
854 $done = false;
855 $dollarquote = false;
856
857 $replacements = array();
858
859 while ( ! feof( $fp ) ) {
860 if ( $lineCallback ) {
861 call_user_func( $lineCallback );
862 }
863 $line = trim( fgets( $fp, 1024 ) );
864 $sl = strlen( $line ) - 1;
865
866 if ( $sl < 0 ) { continue; }
867 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
868
869 // Allow dollar quoting for function declarations
870 if (substr($line,0,8) == '/*$mw$*/') {
871 if ($dollarquote) {
872 $dollarquote = false;
873 $done = true;
874 }
875 else {
876 $dollarquote = true;
877 }
878 }
879 else if (!$dollarquote) {
880 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
881 $done = true;
882 $line = substr( $line, 0, $sl );
883 }
884 }
885
886 if ( '' != $cmd ) { $cmd .= ' '; }
887 $cmd .= "$line\n";
888
889 if ( $done ) {
890 $cmd = str_replace(';;', ";", $cmd);
891 if (strtolower(substr($cmd, 0, 6)) == 'define' ) {
892 if (preg_match('/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines)) {
893 $replacements[$defines[2]] = $defines[1];
894 }
895 } else {
896 foreach ( $replacements as $mwVar=>$scVar ) {
897 $cmd = str_replace( '&' . $scVar . '.', '{$'.$mwVar.'}', $cmd );
898 }
899
900 $cmd = $this->replaceVars( $cmd );
901 $res = $this->query( $cmd, __METHOD__ );
902 if ( $resultCallback ) {
903 call_user_func( $resultCallback, $res, $this );
904 }
905
906 if ( false === $res ) {
907 $err = $this->lastError();
908 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
909 }
910 }
911
912 $cmd = '';
913 $done = false;
914 }
915 }
916 return true;
917 }
918
919 function setup_database() {
920 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
921
922 echo "<li>Creating DB objects</li>\n";
923 $res = $this->sourceFile( "../maintenance/ora/tables.sql" );
924
925 // Avoid the non-standard "REPLACE INTO" syntax
926 echo "<li>Populating table interwiki</li>\n";
927 $f = fopen( "../maintenance/interwiki.sql", 'r' );
928 if ($f == false ) {
929 dieout( "<li>Could not find the interwiki.sql file</li>");
930 }
931
932 //do it like the postgres :D
933 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
934 while ( ! feof( $f ) ) {
935 $line = fgets($f,1024);
936 $matches = array();
937 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
938 continue;
939 }
940 $this->query("$SQL $matches[1],$matches[2])");
941 }
942
943 echo "<li>Table interwiki successfully populated</li>\n";
944 }
945
946 function strencode($s) {
947 return str_replace("'", "''", $s);
948 }
949
950 function encodeBlob($b) {
951 return new ORABlob($b);
952 }
953 function decodeBlob($b) {
954 return $b; //return $b->load();
955 }
956
957 function addQuotes( $s ) {
958 global $wgLang;
959 if (isset($wgLang->mLoaded) && $wgLang->mLoaded)
960 $s = $wgLang->checkTitleEncoding($s);
961 return "'" . $this->strencode($s) . "'";
962 }
963
964 function quote_ident( $s ) {
965 return $s;
966 }
967
968 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
969 if (is_array($table))
970 foreach ($table as $tab)
971 $tab = $this->tableName($tab);
972 else
973 $table = $this->tableName($table);
974 return parent::selectRow($table, $vars, $conds, $fname, $options, $join_conds);
975 }
976
977 /**
978 * Returns an optional USE INDEX clause to go after the table, and a
979 * string to go at the end of the query
980 *
981 * @private
982 *
983 * @param $options Array: an associative array of options to be turned into
984 * an SQL query, valid keys are listed in the function.
985 * @return array
986 */
987 function makeSelectOptions( $options ) {
988 $preLimitTail = $postLimitTail = '';
989 $startOpts = '';
990
991 $noKeyOptions = array();
992 foreach ( $options as $key => $option ) {
993 if ( is_numeric( $key ) ) {
994 $noKeyOptions[$option] = true;
995 }
996 }
997
998 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
999 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1000
1001 #if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1002 #if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1003 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1004
1005 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1006 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1007 } else {
1008 $useIndex = '';
1009 }
1010
1011 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1012 }
1013
1014 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1015
1016 $conds2 = array();
1017 foreach($conds as $col=>$val) {
1018 $col_type=$this->fieldInfo($this->tableName($table), $col)->type();
1019 if ($col_type == 'CLOB')
1020 $conds2['TO_CHAR('.$col.')'] = $val;
1021 else
1022 $conds2[$col] = $val;
1023 }
1024
1025 return parent::delete( $table, $conds2, $fname );
1026 }
1027
1028 function bitNot($field) {
1029 //expecting bit-fields smaller than 4bytes
1030 return 'BITNOT('.$bitField.')';
1031 }
1032
1033 function bitAnd($fieldLeft, $fieldRight) {
1034 return 'BITAND('.$fieldLeft.', '.$fieldRight.')';
1035 }
1036
1037 function bitOr($fieldLeft, $fieldRight) {
1038 return 'BITOR('.$fieldLeft.', '.$fieldRight.')';
1039 }
1040
1041 /**
1042 * How lagged is this slave?
1043 *
1044 * @return int
1045 */
1046 public function getLag() {
1047 # Not implemented for Oracle
1048 return 0;
1049 }
1050
1051 function setFakeSlaveLag( $lag ) {}
1052 function setFakeMaster( $enabled = true ) {}
1053
1054 function getDBname() {
1055 return $this->mDBname;
1056 }
1057
1058 function getServer() {
1059 return $this->mServer;
1060 }
1061
1062 public function replaceVars( $ins ) {
1063 $varnames = array('wgDBprefix');
1064 if ($this->mFlags & DBO_SYSDBA) {
1065 $varnames[] = 'wgDBOracleDefTS';
1066 $varnames[] = 'wgDBOracleTempTS';
1067 }
1068
1069 // Ordinary variables
1070 foreach ( $varnames as $var ) {
1071 if( isset( $GLOBALS[$var] ) ) {
1072 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1073 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1074 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1075 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1076 }
1077 }
1078
1079 return parent::replaceVars($ins);
1080 }
1081
1082 public function getSearchEngine() {
1083 return "SearchOracle";
1084 }
1085 } // end DatabaseOracle class