4 * This is the Oracle database abstraction layer.
10 function __construct($data) {
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.
31 function __construct(&$db, $stmt) {
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']);
44 oci_free_statement($this->stmt
);
48 $this->cursor
= min($row, $this->nrows
);
55 function numFields() {
56 return oci_num_fields($this->stmt
);
59 function fetchObject() {
60 if ($this->cursor
>= $this->nrows
)
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));
73 function fetchAssoc() {
74 if ($this->cursor
>= $this->nrows
)
77 $row = $this->rows
[$this->cursor++
];
79 foreach ($row as $k => $v) {
80 $lc = strtolower(oci_field_name($this->stmt
, $k +
1));
88 class DatabaseOracle
extends Database
{
89 var $mInsertId = NULL;
90 var $mLastResult = NULL;
91 var $numeric_version = NULL;
92 var $lastResult = null;
96 function DatabaseOracle($server = false, $user = false, $password = false, $dbName = false,
97 $failFunction = false, $flags = 0 )
101 # Can't get a reference if it hasn't been set yet
102 if ( !isset( $wgOut ) ) {
105 $this->mOut
=& $wgOut;
106 $this->mFailFunction
= $failFunction;
107 $this->mFlags
= $flags;
108 $this->open( $server, $user, $password, $dbName);
112 function cascadingDeletes() {
115 function cleanupTriggers() {
118 function strictIPs() {
121 function realTimestamps() {
124 function implicitGroupby() {
127 function searchableIPs() {
131 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
132 $failFunction = false, $flags = 0)
134 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags );
138 * Usually aborts on failure
139 * If the failFunction is set to a non-zero integer, returns success
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" );
146 # Needed for proper UTF-8 functionality
147 putenv("NLS_LANG=AMERICAN_AMERICA.AL32UTF8");
150 $this->mServer
= $server;
151 $this->mUser
= $user;
152 $this->mPassword
= $password;
153 $this->mDBname
= $dbName;
155 if (!strlen($user)) { ## e.g. the class is being loaded
159 error_reporting( E_ALL
);
160 $this->mConn
= oci_connect($user, $password, $dbName);
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");
169 $this->mOpened
= true;
174 * Closes a database connection, if it is open
175 * Returns success, true if already closed
178 $this->mOpened
= false;
179 if ( $this->mConn
) {
180 return oci_close( $this->mConn
);
186 function execFlags() {
187 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
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'], '');
197 if (oci_statement_type($stmt) == "SELECT")
198 return new ORAResult($this, $stmt);
200 $this->mAffectedRows
= oci_num_rows($stmt);
205 function queryIgnore($sql, $fname = '') {
206 return $this->query($sql, $fname, true);
209 function freeResult($res) {
213 function fetchObject($res) {
214 return $res->fetchObject();
217 function fetchRow($res) {
218 return $res->fetchAssoc();
221 function numRows($res) {
222 return $res->numRows();
225 function numFields($res) {
226 return $res->numFields();
229 function fieldName($stmt, $n) {
230 return pg_field_name($stmt, $n);
234 * This must be called after nextSequenceVal
236 function insertId() {
237 return $this->mInsertId
;
240 function dataSeek($res, $row) {
244 function lastError() {
245 if ($this->mConn
=== false)
248 $e = oci_error($this->mConn
);
249 return $e['message'];
252 function lastErrno() {
253 if ($this->mConn
=== false)
256 $e = oci_error($this->mConn
);
260 function affectedRows() {
261 return $this->mAffectedRows
;
265 * Returns information about an index
266 * If errors are explicitly ignored, returns NULL on failure
268 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
272 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
276 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
277 if (!is_array($options))
278 $options = array($options);
280 if (in_array('IGNORE', $options))
281 $oldIgnore = $this->ignoreErrors(true);
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))) {
289 foreach ($a as $row) {
290 $this->insertOneRow($table, $row, $fname);
292 //$this->ignoreErrors($oldIgnore);
295 if (in_array('IGNORE', $options))
296 $this->ignoreErrors($oldIgnore);
301 function insertOneRow($table, $row, $fname) {
302 // "INSERT INTO tables (a, b, c)"
303 $sql = "INSERT INTO " . $this->tableName($table) . " (" . join(',', array_keys($row)) . ')';
306 // for each value, append ":key"
309 foreach ($row as $col => $val) {
310 if (is_object($val)) {
311 $what = "EMPTY_BLOB()";
312 assert($returning === '');
313 $returning = " RETURNING $col INTO :bval";
324 $sql .= ") $returning";
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__
);
334 if (($bval = oci_new_descriptor($this->mConn
, OCI_D_LOB
)) === false) {
335 $e = oci_error($stmt);
336 throw new DBUnexpectedError($this, "Cannot create LOB descriptor: " . $e['message']);
339 if (strlen($returning))
340 oci_bind_by_name($stmt, ":bval", $bval, -1, SQLT_BLOB
);
342 if (oci_execute($stmt, OCI_DEFAULT
) === false) {
343 $e = oci_error($stmt);
344 $this->reportQueryError($e['message'], $e['code'], $sql, __METHOD__
);
346 if (strlen($returning)) {
347 $bval->save($row[$blobcol]->getData());
350 if (!$this->mTrxLevel
)
351 oci_commit($this->mConn
);
353 oci_free_statement($stmt);
356 function tableName( $name ) {
357 # Replace reserved words with better ones
362 return 'pagecontent';
369 * Return the next in a sequence, save the value for retrieval via insertId()
371 function nextSequenceValue($seqName) {
372 $res = $this->query("SELECT $seqName.nextval FROM dual");
373 $row = $this->fetchRow($res);
374 $this->mInsertId
= $row[0];
375 $this->freeResult($res);
376 return $this->mInsertId
;
380 * ORacle does not have a "USE INDEX" clause, so return an empty string
382 function useIndexClause($index) {
386 # REPLACE query wrapper
387 # Oracle simulates this with a DELETE followed by INSERT
388 # $row is the row to insert, an associative array
389 # $uniqueIndexes is an array of indexes. Each element may be either a
390 # field name or an array of field names
392 # It may be more efficient to leave off unique indexes which are unlikely to collide.
393 # However if you do this, you run the risk of encountering errors which wouldn't have
395 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
396 $table = $this->tableName($table);
398 if (count($rows)==0) {
403 if (!is_array(reset($rows))) {
404 $rows = array($rows);
407 foreach( $rows as $row ) {
408 # Delete rows which collide
409 if ( $uniqueIndexes ) {
410 $sql = "DELETE FROM $table WHERE ";
412 foreach ( $uniqueIndexes as $index ) {
419 if ( is_array( $index ) ) {
421 foreach ( $index as $col ) {
427 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
430 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
434 $this->query( $sql, $fname );
438 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
439 $this->makeList( $row, LIST_COMMA
) . ')';
440 $this->query($sql, $fname);
444 # DELETE where the condition is a join
445 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
447 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
450 $delTable = $this->tableName( $delTable );
451 $joinTable = $this->tableName( $joinTable );
452 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
453 if ( $conds != '*' ) {
454 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
458 $this->query( $sql, $fname );
461 # Returns the size of a text field, or -1 for "unlimited"
462 function textFieldSize( $table, $field ) {
463 $table = $this->tableName( $table );
464 $sql = "SELECT t.typname as ftype,a.atttypmod as size
465 FROM pg_class c, pg_attribute a, pg_type t
466 WHERE relname='$table' AND a.attrelid=c.oid AND
467 a.atttypid=t.oid and a.attname='$field'";
468 $res =$this->query($sql);
469 $row=$this->fetchObject($res);
470 if ($row->ftype
=="varchar") {
475 $this->freeResult( $res );
479 function lowPriorityOption() {
483 function limitResult($sql, $limit, $offset) {
484 if ($offset === false)
486 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < 1 + $limit + $offset";
490 * Returns an SQL expression for a simple conditional.
491 * Uses CASE on Oracle
493 * @param string $cond SQL expression which will result in a boolean value
494 * @param string $trueVal SQL expression to return if true
495 * @param string $falseVal SQL expression to return if false
496 * @return string SQL fragment
498 function conditional( $cond, $trueVal, $falseVal ) {
499 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
502 function wasDeadlock() {
503 return $this->lastErrno() == 'OCI-00060';
506 function timestamp($ts = 0) {
507 return wfTimestamp(TS_ORACLE
, $ts);
511 * Return aggregated value function call
513 function aggregateValue ($valuedata,$valuename='value') {
517 function reportQueryError($error, $errno, $sql, $fname, $tempIgnore = false) {
518 # Ignore errors during error handling to avoid infinite recursion
519 $ignore = $this->ignoreErrors(true);
520 ++
$this->mErrorCount
;
522 if ($ignore ||
$tempIgnore) {
523 wfDebug("SQL ERROR (ignored): $error\n");
524 $this->ignoreErrors( $ignore );
527 $message = "A database error has occurred\n" .
529 "Function: $fname\n" .
530 "Error: $errno $error\n";
531 throw new DBUnexpectedError($this, $message);
536 * @return string wikitext of a link to the server software's web site
538 function getSoftwareLink() {
539 return "[http://www.oracle.com/ Oracle]";
543 * @return string Version information from the database
545 function getServerVersion() {
546 return oci_server_version($this->mConn
);
550 * Query whether a given table exists (in the given schema, or the default mw one if not given)
552 function tableExists($table) {
553 $etable= $this->addQuotes($table);
554 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$etable'";
555 $res = $this->query($SQL);
556 $count = $res ?
oci_num_rows($res) : 0;
558 $this->freeResult($res);
563 * Query whether a given column exists in the mediawiki schema
565 function fieldExists( $table, $field ) {
569 function fieldInfo( $table, $field ) {
573 function begin( $fname = '' ) {
574 $this->mTrxLevel
= 1;
576 function immediateCommit( $fname = '' ) {
579 function commit( $fname = '' ) {
580 oci_commit($this->mConn
);
581 $this->mTrxLevel
= 0;
584 /* Not even sure why this is used in the main codebase... */
585 function limitResultForUpdate($sql, $num) {
589 function strencode($s) {
590 return str_replace("'", "''", $s);
593 function encodeBlob($b) {
594 return new ORABlob($b);
596 function decodeBlob($b) {
597 return $b; //return $b->load();
600 function addQuotes( $s ) {
601 return "'" . $this->strencode($s) . "'";
604 function quote_ident( $s ) {
608 /* For now, does nothing */
609 function selectDB( $db ) {
614 * Returns an optional USE INDEX clause to go after the table, and a
615 * string to go at the end of the query
619 * @param array $options an associative array of options to be turned into
620 * an SQL query, valid keys are listed in the function.
623 function makeSelectOptions( $options ) {
624 $preLimitTail = $postLimitTail = '';
627 $noKeyOptions = array();
628 foreach ( $options as $key => $option ) {
629 if ( is_numeric( $key ) ) {
630 $noKeyOptions[$option] = true;
634 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
635 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
637 if (isset($options['LIMIT'])) {
638 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
639 // isset($options['OFFSET']) ? $options['OFFSET']
643 #if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
644 #if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
645 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
647 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
648 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
653 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
656 public function setTimeout( $timeout ) {
661 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
666 } // end DatabaseOracle class