4 * This is the Oracle database abstraction layer.
9 function __construct($data) {
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.
30 function __construct(&$db, $stmt) {
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']);
43 oci_free_statement($this->stmt
);
47 $this->cursor
= min($row, $this->nrows
);
54 function numFields() {
55 return oci_num_fields($this->stmt
);
58 function fetchObject() {
59 if ($this->cursor
>= $this->nrows
)
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));
72 function fetchAssoc() {
73 if ($this->cursor
>= $this->nrows
)
76 $row = $this->rows
[$this->cursor++
];
78 foreach ($row as $k => $v) {
79 $lc = strtolower(oci_field_name($this->stmt
, $k +
1));
87 class DatabaseOracle
extends Database
{
88 var $mInsertId = NULL;
89 var $mLastResult = NULL;
90 var $numeric_version = NULL;
91 var $lastResult = null;
95 function DatabaseOracle($server = false, $user = false, $password = false, $dbName = false,
96 $failFunction = false, $flags = 0 )
100 # Can't get a reference if it hasn't been set yet
101 if ( !isset( $wgOut ) ) {
104 $this->mOut
=& $wgOut;
105 $this->mFailFunction
= $failFunction;
106 $this->mFlags
= $flags;
107 $this->open( $server, $user, $password, $dbName);
111 function cascadingDeletes() {
114 function cleanupTriggers() {
117 function strictIPs() {
120 function realTimestamps() {
123 function implicitGroupby() {
126 function searchableIPs() {
130 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
131 $failFunction = false, $flags = 0)
133 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags );
137 * Usually aborts on failure
138 * If the failFunction is set to a non-zero integer, returns success
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" );
145 # Needed for proper UTF-8 functionality
146 putenv("NLS_LANG=AMERICAN_AMERICA.AL32UTF8");
149 $this->mServer
= $server;
150 $this->mUser
= $user;
151 $this->mPassword
= $password;
152 $this->mDBname
= $dbName;
154 if (!strlen($user)) { ## e.g. the class is being loaded
158 error_reporting( E_ALL
);
159 $this->mConn
= oci_connect($user, $password, $dbName);
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");
168 $this->mOpened
= true;
173 * Closes a database connection, if it is open
174 * Returns success, true if already closed
177 $this->mOpened
= false;
178 if ( $this->mConn
) {
179 return oci_close( $this->mConn
);
185 function execFlags() {
186 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
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'], '');
196 if (oci_statement_type($stmt) == "SELECT")
197 return new ORAResult($this, $stmt);
199 $this->mAffectedRows
= oci_num_rows($stmt);
204 function queryIgnore($sql, $fname = '') {
205 return $this->query($sql, $fname, true);
208 function freeResult($res) {
212 function fetchObject($res) {
213 return $res->fetchObject();
216 function fetchRow($res) {
217 return $res->fetchAssoc();
220 function numRows($res) {
221 return $res->numRows();
224 function numFields($res) {
225 return $res->numFields();
228 function fieldName($stmt, $n) {
229 return pg_field_name($stmt, $n);
233 * This must be called after nextSequenceVal
235 function insertId() {
236 return $this->mInsertId
;
239 function dataSeek($res, $row) {
243 function lastError() {
244 if ($this->mConn
=== false)
247 $e = oci_error($this->mConn
);
248 return $e['message'];
251 function lastErrno() {
252 if ($this->mConn
=== false)
255 $e = oci_error($this->mConn
);
259 function affectedRows() {
260 return $this->mAffectedRows
;
264 * Returns information about an index
265 * If errors are explicitly ignored, returns NULL on failure
267 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
271 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
275 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
276 if (!is_array($options))
277 $options = array($options);
279 if (in_array('IGNORE', $options))
280 $oldIgnore = $this->ignoreErrors(true);
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))) {
288 foreach ($a as $row) {
289 $this->insertOneRow($table, $row, $fname);
291 //$this->ignoreErrors($oldIgnore);
294 if (in_array('IGNORE', $options))
295 $this->ignoreErrors($oldIgnore);
300 function insertOneRow($table, $row, $fname) {
301 // "INSERT INTO tables (a, b, c)"
302 $sql = "INSERT INTO " . $this->tableName($table) . " (" . join(',', array_keys($row)) . ')';
305 // for each value, append ":key"
308 foreach ($row as $col => $val) {
309 if (is_object($val)) {
310 $what = "EMPTY_BLOB()";
311 assert($returning === '');
312 $returning = " RETURNING $col INTO :bval";
323 $sql .= ") $returning";
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__
);
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
);
337 if (oci_execute($stmt, OCI_DEFAULT
) === false) {
338 $e = oci_error($stmt);
339 $this->reportQueryError($e['message'], $e['code'], $sql, __METHOD__
);
341 if (strlen($returning)) {
342 $bval->save($row[$blobcol]->getData());
345 if (!$this->mTrxLevel
)
346 oci_commit($this->mConn
);
348 oci_free_statement($stmt);
351 function tableName( $name ) {
352 # Replace reserved words with better ones
357 return 'pagecontent';
364 * Return the next in a sequence, save the value for retrieval via insertId()
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
;
375 * ORacle does not have a "USE INDEX" clause, so return an empty string
377 function useIndexClause($index) {
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
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
390 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
391 $table = $this->tableName($table);
393 if (count($rows)==0) {
398 if (!is_array(reset($rows))) {
399 $rows = array($rows);
402 foreach( $rows as $row ) {
403 # Delete rows which collide
404 if ( $uniqueIndexes ) {
405 $sql = "DELETE FROM $table WHERE ";
407 foreach ( $uniqueIndexes as $index ) {
414 if ( is_array( $index ) ) {
416 foreach ( $index as $col ) {
422 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
425 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
429 $this->query( $sql, $fname );
433 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
434 $this->makeList( $row, LIST_COMMA
) . ')';
435 $this->query($sql, $fname);
439 # DELETE where the condition is a join
440 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
442 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
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
);
453 $this->query( $sql, $fname );
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") {
470 $this->freeResult( $res );
474 function lowPriorityOption() {
478 function limitResult($sql, $limit, $offset) {
479 if ($offset === false)
481 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < 1 + $limit + $offset";
485 * Returns an SQL expression for a simple conditional.
486 * Uses CASE on Oracle
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
493 function conditional( $cond, $trueVal, $falseVal ) {
494 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
497 function wasDeadlock() {
498 return $this->lastErrno() == 'OCI-00060';
501 function timestamp($ts = 0) {
502 return wfTimestamp(TS_ORACLE
, $ts);
506 * Return aggregated value function call
508 function aggregateValue ($valuedata,$valuename='value') {
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
;
517 if ($ignore ||
$tempIgnore) {
518 wfDebug("SQL ERROR (ignored): $error\n");
519 $this->ignoreErrors( $ignore );
522 $message = "A database error has occurred\n" .
524 "Function: $fname\n" .
525 "Error: $errno $error\n";
526 throw new DBUnexpectedError($this, $message);
531 * @return string wikitext of a link to the server software's web site
533 function getSoftwareLink() {
534 return "[http://www.oracle.com/ Oracle]";
538 * @return string Version information from the database
540 function getServerVersion() {
541 return oci_server_version($this->mConn
);
545 * Query whether a given table exists (in the given schema, or the default mw one if not given)
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;
553 $this->freeResult($res);
558 * Query whether a given column exists in the mediawiki schema
560 function fieldExists( $table, $field ) {
564 function fieldInfo( $table, $field ) {
568 function begin( $fname = '' ) {
569 $this->mTrxLevel
= 1;
571 function immediateCommit( $fname = '' ) {
574 function commit( $fname = '' ) {
575 oci_commit($this->mConn
);
576 $this->mTrxLevel
= 0;
579 /* Not even sure why this is used in the main codebase... */
580 function limitResultForUpdate($sql, $num) {
584 function strencode($s) {
585 return str_replace("'", "''", $s);
588 function encodeBlob($b) {
589 return new ORABlob($b);
591 function decodeBlob($b) {
592 return $b; //return $b->load();
595 function addQuotes( $s ) {
596 return "'" . $this->strencode($s) . "'";
599 function quote_ident( $s ) {
603 /* For now, does nothing */
604 function selectDB( $db ) {
609 * Returns an optional USE INDEX clause to go after the table, and a
610 * string to go at the end of the query
614 * @param array $options an associative array of options to be turned into
615 * an SQL query, valid keys are listed in the function.
618 function makeSelectOptions( $options ) {
619 $preLimitTail = $postLimitTail = '';
622 $noKeyOptions = array();
623 foreach ( $options as $key => $option ) {
624 if ( is_numeric( $key ) ) {
625 $noKeyOptions[$option] = true;
629 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
630 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
632 if (isset($options['LIMIT'])) {
633 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
634 // isset($options['OFFSET']) ? $options['OFFSET']
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';
642 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
643 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
648 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
651 public function setTimeout( $timeout ) {
656 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
661 } // end DatabaseOracle class