Remove variables when we can simply override accessors instead.
[lhc/web/wiklou.git] / includes / DatabaseOracle.php
1 <?php
2
3 /**
4 * This is the Oracle database abstraction layer.
5 */
6
7 class ORABlob {
8 var $mData;
9
10 function __construct($data) {
11 $this->mData = $data;
12 }
13
14 function getData() {
15 return $this->mData;
16 }
17 };
18
19 /*
20 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
21 * other things. We use a wrapper class to handle that and other
22 * Oracle-specific bits, like converting column names back to lowercase.
23 */
24 class ORAResult {
25 private $rows;
26 private $cursor;
27 private $stmt;
28 private $nrows;
29 private $db;
30
31 function __construct(&$db, $stmt) {
32 $this->db =& $db;
33 if (($this->nrows = oci_fetch_all($stmt, $this->rows, 0, -1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM)) === false) {
34 $e = oci_error($stmt);
35 $db->reportQueryError('', $e['message'], $e['code']);
36 return;
37 }
38
39 $this->cursor = 0;
40 $this->stmt = $stmt;
41 }
42
43 function free() {
44 oci_free_statement($this->stmt);
45 }
46
47 function seek($row) {
48 $this->cursor = min($row, $this->nrows);
49 }
50
51 function numRows() {
52 return $this->nrows;
53 }
54
55 function numFields() {
56 return oci_num_fields($this->stmt);
57 }
58
59 function fetchObject() {
60 if ($this->cursor >= $this->nrows)
61 return false;
62
63 $row = $this->rows[$this->cursor++];
64 $ret = new stdClass();
65 foreach ($row as $k => $v) {
66 $lc = strtolower(oci_field_name($this->stmt, $k + 1));
67 $ret->$lc = $v;
68 }
69
70 return $ret;
71 }
72
73 function fetchAssoc() {
74 if ($this->cursor >= $this->nrows)
75 return false;
76
77 $row = $this->rows[$this->cursor++];
78 $ret = array();
79 foreach ($row as $k => $v) {
80 $lc = strtolower(oci_field_name($this->stmt, $k + 1));
81 $ret[$lc] = $v;
82 $ret[$k] = $v;
83 }
84 return $ret;
85 }
86 };
87
88 class DatabaseOracle extends Database {
89 var $mInsertId = NULL;
90 var $mLastResult = NULL;
91 var $numeric_version = NULL;
92 var $lastResult = null;
93 var $cursor = 0;
94 var $mAffectedRows;
95
96 function DatabaseOracle($server = false, $user = false, $password = false, $dbName = false,
97 $failFunction = false, $flags = 0 )
98 {
99
100 global $wgOut;
101 # Can't get a reference if it hasn't been set yet
102 if ( !isset( $wgOut ) ) {
103 $wgOut = NULL;
104 }
105 $this->mOut =& $wgOut;
106 $this->mFailFunction = $failFunction;
107 $this->mFlags = $flags;
108 $this->open( $server, $user, $password, $dbName);
109
110 }
111
112 function cascadingDeletes() {
113 return true;
114 }
115 function cleanupTriggers() {
116 return true;
117 }
118 function strictIPs() {
119 return true;
120 }
121 function realTimestamps() {
122 return true;
123 }
124 function implicitGroupby() {
125 return false;
126 }
127 function searchableIPs() {
128 return true;
129 }
130
131 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
132 $failFunction = false, $flags = 0)
133 {
134 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags );
135 }
136
137 /**
138 * Usually aborts on failure
139 * If the failFunction is set to a non-zero integer, returns success
140 */
141 function open( $server, $user, $password, $dbName ) {
142 if ( !function_exists( 'oci_connect' ) ) {
143 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" );
144 }
145
146 # Needed for proper UTF-8 functionality
147 putenv("NLS_LANG=AMERICAN_AMERICA.AL32UTF8");
148
149 $this->close();
150 $this->mServer = $server;
151 $this->mUser = $user;
152 $this->mPassword = $password;
153 $this->mDBname = $dbName;
154
155 if (!strlen($user)) { ## e.g. the class is being loaded
156 return;
157 }
158
159 error_reporting( E_ALL );
160 $this->mConn = oci_connect($user, $password, $dbName);
161
162 if ($this->mConn == false) {
163 wfDebug("DB connection error\n");
164 wfDebug("Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n");
165 wfDebug($this->lastError()."\n");
166 return false;
167 }
168
169 $this->mOpened = true;
170 return $this->mConn;
171 }
172
173 /**
174 * Closes a database connection, if it is open
175 * Returns success, true if already closed
176 */
177 function close() {
178 $this->mOpened = false;
179 if ( $this->mConn ) {
180 return oci_close( $this->mConn );
181 } else {
182 return true;
183 }
184 }
185
186 function execFlags() {
187 return $this->mTrxLevel ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
188 }
189
190 function doQuery($sql) {
191 wfDebug("SQL: [$sql]\n");
192 $this->mLastResult = $stmt = oci_parse($this->mConn, $sql);
193 if (oci_execute($stmt, $this->execFlags()) == false) {
194 $e = oci_error($stmt);
195 $this->reportQueryError($sql, $e['message'], $e['code'], '');
196 }
197 if (oci_statement_type($stmt) == "SELECT")
198 return new ORAResult($this, $stmt);
199 else {
200 $this->mAffectedRows = oci_num_rows($stmt);
201 return true;
202 }
203 }
204
205 function queryIgnore($sql, $fname = '') {
206 return $this->query($sql, $fname, true);
207 }
208
209 function freeResult($res) {
210 $res->free();
211 }
212
213 function fetchObject($res) {
214 return $res->fetchObject();
215 }
216
217 function fetchRow($res) {
218 return $res->fetchAssoc();
219 }
220
221 function numRows($res) {
222 return $res->numRows();
223 }
224
225 function numFields($res) {
226 return $res->numFields();
227 }
228
229 function fieldName($stmt, $n) {
230 return pg_field_name($stmt, $n);
231 }
232
233 /**
234 * This must be called after nextSequenceVal
235 */
236 function insertId() {
237 return $this->mInsertId;
238 }
239
240 function dataSeek($res, $row) {
241 $res->seek($row);
242 }
243
244 function lastError() {
245 if ($this->mConn === false)
246 $e = oci_error();
247 else
248 $e = oci_error($this->mConn);
249 return $e['message'];
250 }
251
252 function lastErrno() {
253 if ($this->mConn === false)
254 $e = oci_error();
255 else
256 $e = oci_error($this->mConn);
257 return $e['code'];
258 }
259
260 function affectedRows() {
261 return $this->mAffectedRows;
262 }
263
264 /**
265 * Returns information about an index
266 * If errors are explicitly ignored, returns NULL on failure
267 */
268 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
269 return false;
270 }
271
272 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
273 return false;
274 }
275
276 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
277 if (!is_array($options))
278 $options = array($options);
279
280 if (in_array('IGNORE', $options))
281 $oldIgnore = $this->ignoreErrors(true);
282
283 # IGNORE is performed using single-row inserts, ignoring errors in each
284 # FIXME: need some way to distiguish between key collision and other types of error
285 //$oldIgnore = $this->ignoreErrors(true);
286 if (!is_array(reset($a))) {
287 $a = array($a);
288 }
289 foreach ($a as $row) {
290 $this->insertOneRow($table, $row, $fname);
291 }
292 //$this->ignoreErrors($oldIgnore);
293 $retVal = true;
294
295 if (in_array('IGNORE', $options))
296 $this->ignoreErrors($oldIgnore);
297
298 return $retVal;
299 }
300
301 function insertOneRow($table, $row, $fname) {
302 // "INSERT INTO tables (a, b, c)"
303 $sql = "INSERT INTO " . $this->tableName($table) . " (" . join(',', array_keys($row)) . ')';
304 $sql .= " VALUES (";
305
306 // for each value, append ":key"
307 $first = true;
308 $returning = '';
309 foreach ($row as $col => $val) {
310 if (is_object($val)) {
311 $what = "EMPTY_BLOB()";
312 assert($returning === '');
313 $returning = " RETURNING $col INTO :bval";
314 $blobcol = $col;
315 } else
316 $what = ":$col";
317
318 if ($first)
319 $sql .= "$what";
320 else
321 $sql.= ", $what";
322 $first = false;
323 }
324 $sql .= ") $returning";
325
326 $stmt = oci_parse($this->mConn, $sql);
327 foreach ($row as $col => $val) {
328 if (!is_object($val)) {
329 if (oci_bind_by_name($stmt, ":$col", $row[$col]) === false)
330 $this->reportQueryError($this->lastErrno(), $this->lastError(), $sql, __METHOD__);
331 }
332 }
333
334 $bval = oci_new_descriptor($this->mConn, OCI_D_LOB);
335 if (strlen($returning))
336 oci_bind_by_name($stmt, ":bval", $bval, -1, SQLT_BLOB);
337
338 if (oci_execute($stmt, OCI_DEFAULT) === false) {
339 $e = oci_error($stmt);
340 $this->reportQueryError($e['message'], $e['code'], $sql, __METHOD__);
341 }
342 if (strlen($returning)) {
343 $bval->save($row[$blobcol]->getData());
344 $bval->free();
345 }
346 if (!$this->mTrxLevel)
347 oci_commit($this->mConn);
348
349 oci_free_statement($stmt);
350 }
351
352 function tableName( $name ) {
353 # Replace reserved words with better ones
354 switch( $name ) {
355 case 'user':
356 return 'mwuser';
357 case 'text':
358 return 'pagecontent';
359 default:
360 return $name;
361 }
362 }
363
364 /**
365 * Return the next in a sequence, save the value for retrieval via insertId()
366 */
367 function nextSequenceValue($seqName) {
368 $res = $this->query("SELECT $seqName.nextval FROM dual");
369 $row = $this->fetchRow($res);
370 $this->mInsertId = $row[0];
371 $this->freeResult($res);
372 return $this->mInsertId;
373 }
374
375 /**
376 * ORacle does not have a "USE INDEX" clause, so return an empty string
377 */
378 function useIndexClause($index) {
379 return '';
380 }
381
382 # REPLACE query wrapper
383 # Oracle simulates this with a DELETE followed by INSERT
384 # $row is the row to insert, an associative array
385 # $uniqueIndexes is an array of indexes. Each element may be either a
386 # field name or an array of field names
387 #
388 # It may be more efficient to leave off unique indexes which are unlikely to collide.
389 # However if you do this, you run the risk of encountering errors which wouldn't have
390 # occurred in MySQL
391 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
392 $table = $this->tableName($table);
393
394 if (count($rows)==0) {
395 return;
396 }
397
398 # Single row case
399 if (!is_array(reset($rows))) {
400 $rows = array($rows);
401 }
402
403 foreach( $rows as $row ) {
404 # Delete rows which collide
405 if ( $uniqueIndexes ) {
406 $sql = "DELETE FROM $table WHERE ";
407 $first = true;
408 foreach ( $uniqueIndexes as $index ) {
409 if ( $first ) {
410 $first = false;
411 $sql .= "(";
412 } else {
413 $sql .= ') OR (';
414 }
415 if ( is_array( $index ) ) {
416 $first2 = true;
417 foreach ( $index as $col ) {
418 if ( $first2 ) {
419 $first2 = false;
420 } else {
421 $sql .= ' AND ';
422 }
423 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
424 }
425 } else {
426 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
427 }
428 }
429 $sql .= ')';
430 $this->query( $sql, $fname );
431 }
432
433 # Now insert the row
434 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
435 $this->makeList( $row, LIST_COMMA ) . ')';
436 $this->query($sql, $fname);
437 }
438 }
439
440 # DELETE where the condition is a join
441 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
442 if ( !$conds ) {
443 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
444 }
445
446 $delTable = $this->tableName( $delTable );
447 $joinTable = $this->tableName( $joinTable );
448 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
449 if ( $conds != '*' ) {
450 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
451 }
452 $sql .= ')';
453
454 $this->query( $sql, $fname );
455 }
456
457 # Returns the size of a text field, or -1 for "unlimited"
458 function textFieldSize( $table, $field ) {
459 $table = $this->tableName( $table );
460 $sql = "SELECT t.typname as ftype,a.atttypmod as size
461 FROM pg_class c, pg_attribute a, pg_type t
462 WHERE relname='$table' AND a.attrelid=c.oid AND
463 a.atttypid=t.oid and a.attname='$field'";
464 $res =$this->query($sql);
465 $row=$this->fetchObject($res);
466 if ($row->ftype=="varchar") {
467 $size=$row->size-4;
468 } else {
469 $size=$row->size;
470 }
471 $this->freeResult( $res );
472 return $size;
473 }
474
475 function lowPriorityOption() {
476 return '';
477 }
478
479 function limitResult($sql, $limit, $offset) {
480 if ($offset === false)
481 $offset = 0;
482 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < 1 + $limit + $offset";
483 }
484
485 /**
486 * Returns an SQL expression for a simple conditional.
487 * Uses CASE on Oracle
488 *
489 * @param string $cond SQL expression which will result in a boolean value
490 * @param string $trueVal SQL expression to return if true
491 * @param string $falseVal SQL expression to return if false
492 * @return string SQL fragment
493 */
494 function conditional( $cond, $trueVal, $falseVal ) {
495 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
496 }
497
498 function wasDeadlock() {
499 return $this->lastErrno() == 'OCI-00060';
500 }
501
502 function timestamp($ts = 0) {
503 return wfTimestamp(TS_ORACLE, $ts);
504 }
505
506 /**
507 * Return aggregated value function call
508 */
509 function aggregateValue ($valuedata,$valuename='value') {
510 return $valuedata;
511 }
512
513 function reportQueryError($error, $errno, $sql, $fname, $tempIgnore = false) {
514 # Ignore errors during error handling to avoid infinite recursion
515 $ignore = $this->ignoreErrors(true);
516 ++$this->mErrorCount;
517
518 if ($ignore || $tempIgnore) {
519 wfDebug("SQL ERROR (ignored): $error\n");
520 $this->ignoreErrors( $ignore );
521 }
522 else {
523 $message = "A database error has occurred\n" .
524 "Query: $sql\n" .
525 "Function: $fname\n" .
526 "Error: $errno $error\n";
527 throw new DBUnexpectedError($this, $message);
528 }
529 }
530
531 /**
532 * @return string wikitext of a link to the server software's web site
533 */
534 function getSoftwareLink() {
535 return "[http://www.oracle.com/ Oracle]";
536 }
537
538 /**
539 * @return string Version information from the database
540 */
541 function getServerVersion() {
542 return oci_server_version($this->mConn);
543 }
544
545 /**
546 * Query whether a given table exists (in the given schema, or the default mw one if not given)
547 */
548 function tableExists($table) {
549 $etable= $this->addQuotes($table);
550 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$etable'";
551 $res = $this->query($SQL);
552 $count = $res ? oci_num_rows($res) : 0;
553 if ($res)
554 $this->freeResult($res);
555 return $count;
556 }
557
558 /**
559 * Query whether a given column exists in the mediawiki schema
560 */
561 function fieldExists( $table, $field ) {
562 return true; // XXX
563 }
564
565 function fieldInfo( $table, $field ) {
566 return false; // XXX
567 }
568
569 function begin( $fname = '' ) {
570 $this->mTrxLevel = 1;
571 }
572 function immediateCommit( $fname = '' ) {
573 return true;
574 }
575 function commit( $fname = '' ) {
576 oci_commit($this->mConn);
577 $this->mTrxLevel = 0;
578 }
579
580 /* Not even sure why this is used in the main codebase... */
581 function limitResultForUpdate($sql, $num) {
582 return $sql;
583 }
584
585 function strencode($s) {
586 return str_replace("'", "''", $s);
587 }
588
589 function encodeBlob($b) {
590 return new ORABlob($b);
591 }
592 function decodeBlob($b) {
593 return $b; //return $b->load();
594 }
595
596 function addQuotes( $s ) {
597 return "'" . $this->strencode($s) . "'";
598 }
599
600 function quote_ident( $s ) {
601 return $s;
602 }
603
604 /* For now, does nothing */
605 function selectDB( $db ) {
606 return true;
607 }
608
609 /**
610 * Returns an optional USE INDEX clause to go after the table, and a
611 * string to go at the end of the query
612 *
613 * @private
614 *
615 * @param array $options an associative array of options to be turned into
616 * an SQL query, valid keys are listed in the function.
617 * @return array
618 */
619 function makeSelectOptions( $options ) {
620 $preLimitTail = $postLimitTail = '';
621 $startOpts = '';
622
623 $noKeyOptions = array();
624 foreach ( $options as $key => $option ) {
625 if ( is_numeric( $key ) ) {
626 $noKeyOptions[$option] = true;
627 }
628 }
629
630 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
631 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
632
633 if (isset($options['LIMIT'])) {
634 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
635 // isset($options['OFFSET']) ? $options['OFFSET']
636 // : false);
637 }
638
639 #if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
640 #if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
641 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
642
643 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
644 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
645 } else {
646 $useIndex = '';
647 }
648
649 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
650 }
651
652 public function setTimeout( $timeout ) {
653 /// @fixme no-op
654 }
655
656 function ping() {
657 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
658 return true;
659 }
660
661
662 } // end DatabaseOracle class
663
664 ?>