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