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