* Use call_user_func( $func ) rather than $func(), like wgHooks and parser hooks
[lhc/web/wiklou.git] / includes / DatabaseOracle.php
1 <?php
2
3 /**
4 * Oracle.
5 *
6 * @package MediaWiki
7 */
8
9 /**
10 * Depends on database
11 */
12 require_once( 'Database.php' );
13
14 class OracleBlob extends DBObject {
15 function isLOB() {
16 return true;
17 }
18 function data() {
19 return $this->mData;
20 }
21 };
22
23 /**
24 *
25 * @package MediaWiki
26 */
27 class DatabaseOracle extends Database {
28 var $mInsertId = NULL;
29 var $mLastResult = NULL;
30 var $mFetchCache = array();
31 var $mFetchID = array();
32 var $mNcols = array();
33 var $mFieldNames = array(), $mFieldTypes = array();
34 var $mAffectedRows = array();
35 var $mErr;
36
37 function DatabaseOracle($server = false, $user = false, $password = false, $dbName = false,
38 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
39 {
40 Database::Database( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
41 }
42
43 /* static */ function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
44 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
45 {
46 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
47 }
48
49 /**
50 * Usually aborts on failure
51 * If the failFunction is set to a non-zero integer, returns success
52 */
53 function open( $server, $user, $password, $dbName ) {
54 if ( !function_exists( 'oci_connect' ) ) {
55 die( "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n" );
56 }
57 $this->close();
58 $this->mServer = $server;
59 $this->mUser = $user;
60 $this->mPassword = $password;
61 $this->mDBname = $dbName;
62
63 $success = false;
64
65 $hstring="";
66 $this->mConn = oci_new_connect($user, $password, $dbName, "AL32UTF8");
67 if ( $this->mConn === false ) {
68 wfDebug( "DB connection error\n" );
69 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: "
70 . substr( $password, 0, 3 ) . "...\n" );
71 wfDebug( $this->lastError()."\n" );
72 } else {
73 $this->mOpened = true;
74 }
75 return $this->mConn;
76 }
77
78 /**
79 * Closes a database connection, if it is open
80 * Returns success, true if already closed
81 */
82 function close() {
83 $this->mOpened = false;
84 if ($this->mConn) {
85 return oci_close($this->mConn);
86 } else {
87 return true;
88 }
89 }
90
91 function parseStatement($sql) {
92 $this->mErr = $this->mLastResult = false;
93 if (($stmt = oci_parse($this->mConn, $sql)) === false) {
94 $this->lastError();
95 return $this->mLastResult = false;
96 }
97 $this->mAffectedRows[$stmt] = 0;
98 return $this->mLastResult = $stmt;
99 }
100
101 function doQuery($sql) {
102 if (($stmt = $this->parseStatement($sql)) === false)
103 return false;
104 return $this->executeStatement($stmt);
105 }
106
107 function executeStatement($stmt) {
108 if (!oci_execute($stmt, OCI_DEFAULT)) {
109 $this->lastError();
110 oci_free_statement($stmt);
111 return false;
112 }
113 $this->mAffectedRows[$stmt] = oci_num_rows($stmt);
114 $this->mFetchCache[$stmt] = array();
115 $this->mFetchID[$stmt] = 0;
116 $this->mNcols[$stmt] = oci_num_fields($stmt);
117 if ($this->mNcols[$stmt] == 0)
118 return $this->mLastResult;
119 for ($i = 1; $i <= $this->mNcols[$stmt]; $i++) {
120 $this->mFieldNames[$stmt][$i] = oci_field_name($stmt, $i);
121 $this->mFieldTypes[$stmt][$i] = oci_field_type($stmt, $i);
122 }
123 while (($o = oci_fetch_array($stmt)) !== false) {
124 foreach ($o as $key => $value) {
125 if (is_object($value)) {
126 $o[$key] = $value->load();
127 }
128 }
129 $this->mFetchCache[$stmt][] = $o;
130 }
131 return $this->mLastResult;
132 }
133
134 function queryIgnore( $sql, $fname = '' ) {
135 return $this->query( $sql, $fname, true );
136 }
137
138 function freeResult( $res ) {
139 if (!oci_free_statement($res)) {
140 wfDebugDieBacktrace( "Unable to free Oracle result\n" );
141 }
142 unset($this->mFetchID[$res]);
143 unset($this->mFetchCache[$res]);
144 unset($this->mNcols[$res]);
145 unset($this->mFieldNames[$res]);
146 unset($this->mFieldTypes[$res]);
147 }
148
149 function fetchAssoc($res) {
150 if ($this->mFetchID[$res] >= count($this->mFetchCache[$res]))
151 return false;
152
153 for ($i = 1; $i <= $this->mNcols[$res]; $i++) {
154 $name = $this->mFieldNames[$res][$i];
155 $type = $this->mFieldTypes[$res][$i];
156 if (isset($this->mFetchCache[$res][$this->mFetchID[$res]][$name]))
157 $value = $this->mFetchCache[$res][$this->mFetchID[$res]][$name];
158 else $value = NULL;
159 $key = strtolower($name);
160 wfdebug("'$key' => '$value'\n");
161 $ret[$key] = $value;
162 }
163 $this->mFetchID[$res]++;
164 return $ret;
165 }
166
167 function fetchRow($res) {
168 $r = $this->fetchAssoc($res);
169 if (!$r)
170 return false;
171 $i = 0;
172 $ret = array();
173 foreach ($r as $key => $value) {
174 wfdebug("ret[$i]=[$value]\n");
175 $ret[$i++] = $value;
176 }
177 return $ret;
178 }
179
180 function fetchObject($res) {
181 $row = $this->fetchAssoc($res);
182 if (!$row)
183 return false;
184 $ret = new stdClass;
185 foreach ($row as $key => $value)
186 $ret->$key = $value;
187 return $ret;
188 }
189
190 function numRows($res) {
191 return count($this->mFetchCache[$res]);
192 }
193 function numFields( $res ) { return pg_num_fields( $res ); }
194 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
195
196 /**
197 * This must be called after nextSequenceVal
198 */
199 function insertId() {
200 return $this->mInsertId;
201 }
202
203 function dataSeek($res, $row) {
204 $this->mFetchID[$res] = $row;
205 }
206
207 function lastError() {
208 if ($this->mErr === false) {
209 if ($this->mLastResult !== false) $what = $this->mLastResult;
210 else if ($this->mConn !== false) $what = $this->mConn;
211 else $what = false;
212 $err = ($what !== false) ? oci_error($what) : oci_error();
213 if ($err === false)
214 $this->mErr = 'no error';
215 else
216 $this->mErr = $err['message'];
217 }
218 return str_replace("\n", '<br />', $this->mErr);
219 }
220 function lastErrno() {
221 return 0;
222 }
223
224 function affectedRows() {
225 return $this->mAffectedRows[$this->mLastResult];
226 }
227
228 /**
229 * Returns information about an index
230 * If errors are explicitly ignored, returns NULL on failure
231 */
232 function indexInfo ($table, $index, $fname = 'Database::indexInfo' ) {
233 $table = $this->tableName($table, true);
234 if ($index == 'PRIMARY')
235 $index = "${table}_pk";
236 $sql = "SELECT uniqueness FROM all_indexes WHERE table_name='" .
237 $table . "' AND index_name='" .
238 $this->strencode(strtoupper($index)) . "'";
239 $res = $this->query($sql, $fname);
240 if (!$res)
241 return NULL;
242 if (($row = $this->fetchObject($res)) == NULL)
243 return false;
244 $this->freeResult($res);
245 $row->Non_unique = !$row->uniqueness;
246 return $row;
247 }
248
249 function indexUnique ($table, $index, $fname = 'indexUnique') {
250 if (!($i = $this->indexInfo($table, $index, $fname)))
251 return $i;
252 return $i->uniqueness == 'UNIQUE';
253 }
254
255 function fieldInfo( $table, $field ) {
256 $o = new stdClass;
257 $o->multiple_key = true; /* XXX */
258 return $o;
259 }
260
261 function getColumnInformation($table, $field) {
262 $table = $this->tableName($table, true);
263 $field = strtoupper($field);
264
265 $res = $this->doQuery("SELECT * FROM all_tab_columns " .
266 "WHERE table_name='".$table."' " .
267 "AND column_name='".$field."'");
268 if (!$res)
269 return false;
270 $o = $this->fetchObject($res);
271 $this->freeResult($res);
272 return $o;
273 }
274
275 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
276 $column = $this->getColumnInformation($table, $field);
277 if (!$column)
278 return false;
279 return true;
280 }
281
282 /** @todo FIXME */
283 function startTimer( $timeout ) {
284 wfDebugDieBacktrace( 'Database::startTimer() error : mysql_thread_id() not implemented for postgre' );
285 /*$tid = mysql_thread_id( $this->mConn );
286 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );*/
287 }
288
289 /** */
290 function tableName($name, $forddl = false) {
291 # First run any transformations from the parent object
292 $name = parent::tableName( $name );
293
294 # Replace backticks into empty
295 # Note: "foo" and foo are not the same in Oracle!
296 $name = str_replace('`', '', $name);
297
298 # Now quote Oracle reserved keywords
299 switch( $name ) {
300 case 'user':
301 case 'group':
302 case 'validate':
303 if ($forddl)
304 return $name;
305 else
306 return '"' . $name . '"';
307
308 default:
309 return strtoupper($name);
310 }
311 }
312
313 function strencode( $s ) {
314 return str_replace("'", "''", $s);
315 }
316
317 /**
318 * Return the next in a sequence, save the value for retrieval via insertId()
319 */
320 function nextSequenceValue( $seqName ) {
321 $r = $this->doQuery("SELECT $seqName.nextval AS val FROM dual");
322 $o = $this->fetchObject($r);
323 $this->freeResult($r);
324 return $this->mInsertId = (int)$o->val;
325 }
326
327 /**
328 * USE INDEX clause
329 * PostgreSQL doesn't have them and returns ""
330 */
331 function useIndexClause( $index ) {
332 return '';
333 }
334
335 # REPLACE query wrapper
336 # PostgreSQL simulates this with a DELETE followed by INSERT
337 # $row is the row to insert, an associative array
338 # $uniqueIndexes is an array of indexes. Each element may be either a
339 # field name or an array of field names
340 #
341 # It may be more efficient to leave off unique indexes which are unlikely to collide.
342 # However if you do this, you run the risk of encountering errors which wouldn't have
343 # occurred in MySQL
344 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
345 $table = $this->tableName( $table );
346
347 if (count($rows)==0) {
348 return;
349 }
350
351 # Single row case
352 if ( !is_array( reset( $rows ) ) ) {
353 $rows = array( $rows );
354 }
355
356 foreach( $rows as $row ) {
357 # Delete rows which collide
358 if ( $uniqueIndexes ) {
359 $sql = "DELETE FROM $table WHERE ";
360 $first = true;
361 foreach ( $uniqueIndexes as $index ) {
362 if ( $first ) {
363 $first = false;
364 $sql .= "(";
365 } else {
366 $sql .= ') OR (';
367 }
368 if ( is_array( $index ) ) {
369 $first2 = true;
370 foreach ( $index as $col ) {
371 if ( $first2 ) {
372 $first2 = false;
373 } else {
374 $sql .= ' AND ';
375 }
376 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
377 }
378 } else {
379 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
380 }
381 }
382 $sql .= ')';
383 $this->query( $sql, $fname );
384 }
385
386 # Now insert the row
387 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
388 $this->makeList( $row, LIST_COMMA ) . ')';
389 $this->query( $sql, $fname );
390 }
391 }
392
393 # DELETE where the condition is a join
394 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
395 if ( !$conds ) {
396 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
397 }
398
399 $delTable = $this->tableName( $delTable );
400 $joinTable = $this->tableName( $joinTable );
401 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
402 if ( $conds != '*' ) {
403 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
404 }
405 $sql .= ')';
406
407 $this->query( $sql, $fname );
408 }
409
410 # Returns the size of a text field, or -1 for "unlimited"
411 function textFieldSize( $table, $field ) {
412 $table = $this->tableName( $table );
413 $sql = "SELECT t.typname as ftype,a.atttypmod as size
414 FROM pg_class c, pg_attribute a, pg_type t
415 WHERE relname='$table' AND a.attrelid=c.oid AND
416 a.atttypid=t.oid and a.attname='$field'";
417 $res =$this->query($sql);
418 $row=$this->fetchObject($res);
419 if ($row->ftype=="varchar") {
420 $size=$row->size-4;
421 } else {
422 $size=$row->size;
423 }
424 $this->freeResult( $res );
425 return $size;
426 }
427
428 function lowPriorityOption() {
429 return '';
430 }
431
432 function limitResult($sql, $limit, $offset) {
433 $ret = "SELECT * FROM ($sql) WHERE ROWNUM < " . ((int)$limit + (int)($offset+1));
434 if (is_numeric($offset))
435 $ret .= " AND ROWNUM >= " . (int)$offset;
436 return $ret;
437 }
438 function limitResultForUpdate($sql, $limit) {
439 return $sql;
440 }
441 /**
442 * Returns an SQL expression for a simple conditional.
443 * Uses CASE on PostgreSQL.
444 *
445 * @param string $cond SQL expression which will result in a boolean value
446 * @param string $trueVal SQL expression to return if true
447 * @param string $falseVal SQL expression to return if false
448 * @return string SQL fragment
449 */
450 function conditional( $cond, $trueVal, $falseVal ) {
451 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
452 }
453
454 # FIXME: actually detecting deadlocks might be nice
455 function wasDeadlock() {
456 return false;
457 }
458
459 # Return DB-style timestamp used for MySQL schema
460 function timestamp($ts = 0) {
461 return $this->strencode(wfTimestamp(TS_ORACLE, $ts));
462 # return "TO_TIMESTAMP('" . $this->strencode(wfTimestamp(TS_DB, $ts)) . "', 'RRRR-MM-DD HH24:MI:SS')";
463 }
464
465 /**
466 * Return aggregated value function call
467 */
468 function aggregateValue ($valuedata,$valuename='value') {
469 return $valuedata;
470 }
471
472
473 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
474 $message = "A database error has occurred\n" .
475 "Query: $sql\n" .
476 "Function: $fname\n" .
477 "Error: $errno $error\n";
478 wfDebugDieBacktrace($message);
479 }
480
481 /**
482 * @return string wikitext of a link to the server software's web site
483 */
484 function getSoftwareLink() {
485 return "[http://www.oracle.com/ Oracle]";
486 }
487
488 /**
489 * @return string Version information from the database
490 */
491 function getServerVersion() {
492 return oci_server_version($this->mConn);
493 }
494
495 function setSchema($schema=false) {
496 $schemas=$this->mSchemas;
497 if ($schema) { array_unshift($schemas,$schema); }
498 $searchpath=$this->makeList($schemas,LIST_NAMES);
499 $this->query("SET search_path = $searchpath");
500 }
501
502 function begin() {
503 }
504
505 function immediateCommit( $fname = 'Database::immediateCommit' ) {
506 oci_commit($this->mConn);
507 $this->mTrxLevel = 0;
508 }
509 function rollback( $fname = 'Database::rollback' ) {
510 oci_rollback($this->mConn);
511 $this->mTrxLevel = 0;
512 }
513 function getLag() {
514 return false;
515 }
516 function getStatus() {
517 $result = array('Threads_running' => 0, 'Threads_connected' => 0);
518 return $result;
519 }
520
521 /**
522 * Returns an optional USE INDEX clause to go after the table, and a
523 * string to go at the end of the query
524 *
525 * @access private
526 *
527 * @param array $options an associative array of options to be turned into
528 * an SQL query, valid keys are listed in the function.
529 * @return array
530 */
531 function makeSelectOptions($options) {
532 $tailOpts = '';
533
534 if (isset( $options['ORDER BY'])) {
535 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
536 }
537
538 return array('', $tailOpts);
539 }
540
541 function maxListLen() {
542 return 1000;
543 }
544
545 /**
546 * Query whether a given table exists
547 */
548 function tableExists( $table ) {
549 $table = $this->tableName($table, true);
550 $res = $this->query( "SELECT COUNT(*) as NUM FROM user_tables WHERE table_name='"
551 . $table . "'" );
552 if (!$res)
553 return false;
554 $row = $this->fetchObject($res);
555 $this->freeResult($res);
556 return $row->num >= 1;
557 }
558
559 /**
560 * UPDATE wrapper, takes a condition array and a SET array
561 */
562 function update( $table, $values, $conds, $fname = 'Database::update' ) {
563 $table = $this->tableName( $table );
564
565 $sql = "UPDATE $table SET ";
566 $first = true;
567 foreach ($values as $field => $v) {
568 if ($first)
569 $first = false;
570 else
571 $sql .= ", ";
572 $sql .= "$field = :n$field ";
573 }
574 if ( $conds != '*' ) {
575 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
576 }
577 $stmt = $this->parseStatement($sql);
578 if ($stmt === false) {
579 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $stmt );
580 return false;
581 }
582 if ($this->debug())
583 wfDebug("SQL: $sql\n");
584 $s = '';
585 foreach ($values as $field => $v) {
586 oci_bind_by_name($stmt, ":n$field", $values[$field]);
587 if ($this->debug())
588 $s .= " [$field] = [$v]\n";
589 }
590 if ($this->debug())
591 wfdebug(" PH: $s\n");
592 $ret = $this->executeStatement($stmt);
593 return $ret;
594 }
595
596 /**
597 * INSERT wrapper, inserts an array into a table
598 *
599 * $a may be a single associative array, or an array of these with numeric keys, for
600 * multi-row insert.
601 *
602 * Usually aborts on failure
603 * If errors are explicitly ignored, returns success
604 */
605 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
606 # No rows to insert, easy just return now
607 if ( !count( $a ) ) {
608 return true;
609 }
610
611 $table = $this->tableName( $table );
612 if (!is_array($options))
613 $options = array($options);
614
615 $oldIgnore = false;
616 if (in_array('IGNORE', $options))
617 $oldIgnore = $this->ignoreErrors( true );
618
619 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
620 $multi = true;
621 $keys = array_keys( $a[0] );
622 } else {
623 $multi = false;
624 $keys = array_keys( $a );
625 }
626
627 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES (';
628 $return = '';
629 $first = true;
630 foreach ($a as $key => $value) {
631 if ($first)
632 $first = false;
633 else
634 $sql .= ", ";
635 if (is_object($value) && $value->isLOB()) {
636 $sql .= "EMPTY_BLOB()";
637 $return = "RETURNING $key INTO :bobj";
638 } else
639 $sql .= ":$key";
640 }
641 $sql .= ") $return";
642
643 if ($this->debug()) {
644 wfDebug("SQL: $sql\n");
645 }
646
647 if (($stmt = $this->parseStatement($sql)) === false) {
648 $this->reportQueryError($this->lastError(), $this->lastErrno(), $sql, $fname);
649 $this->ignoreErrors($oldIgnore);
650 return false;
651 }
652
653 /*
654 * If we're inserting multiple rows, parse the statement once and
655 * execute it for each set of values. Otherwise, convert it into an
656 * array and pretend.
657 */
658 if (!$multi)
659 $a = array($a);
660
661 foreach ($a as $key => $row) {
662 $blob = false;
663 $bdata = false;
664 $s = '';
665 foreach ($row as $k => $value) {
666 if (is_object($value) && $value->isLOB()) {
667 $blob = oci_new_descriptor($this->mConn, OCI_D_LOB);
668 $bdata = $value->data();
669 oci_bind_by_name($stmt, ":bobj", &$blob, -1, OCI_B_BLOB);
670 } else
671 oci_bind_by_name($stmt, ":$k", $a[$key][$k], -1);
672 if ($this->debug())
673 $s .= " [$k] = {$row[$k]}";
674 }
675 if ($this->debug())
676 wfDebug(" PH: $s\n");
677 if (($s = $this->executeStatement($stmt)) === false) {
678 $this->reportQueryError($this->lastError(), $this->lastErrno(), $sql, $fname);
679 $this->ignoreErrors($oldIgnore);
680 return false;
681 }
682
683 if ($blob) {
684 $blob->save($bdata);
685 }
686 }
687 $this->ignoreErrors($oldIgnore);
688 return $this->mLastResult = $s;
689 }
690
691 function ping() {
692 return true;
693 }
694
695 function encodeBlob($b) {
696 return new OracleBlob($b);
697 }
698 }
699
700 ?>