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