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