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