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 $bval = oci_new_descriptor($this->mConn
, OCI_D_LOB
);
335 if (strlen($returning))
336 oci_bind_by_name($stmt, ":bval", $bval, -1, SQLT_BLOB
);
338 if (oci_execute($stmt, OCI_DEFAULT
) === false) {
339 $e = oci_error($stmt);
340 $this->reportQueryError($e['message'], $e['code'], $sql, __METHOD__
);
342 if (strlen($returning)) {
343 $bval->save($row[$blobcol]->getData());
346 if (!$this->mTrxLevel
)
347 oci_commit($this->mConn
);
349 oci_free_statement($stmt);
352 function tableName( $name ) {
353 # Replace reserved words with better ones
358 return 'pagecontent';
365 * Return the next in a sequence, save the value for retrieval via insertId()
367 function nextSequenceValue($seqName) {
368 $res = $this->query("SELECT $seqName.nextval FROM dual");
369 $row = $this->fetchRow($res);
370 $this->mInsertId
= $row[0];
371 $this->freeResult($res);
372 return $this->mInsertId
;
376 * ORacle does not have a "USE INDEX" clause, so return an empty string
378 function useIndexClause($index) {
382 # REPLACE query wrapper
383 # Oracle simulates this with a DELETE followed by INSERT
384 # $row is the row to insert, an associative array
385 # $uniqueIndexes is an array of indexes. Each element may be either a
386 # field name or an array of field names
388 # It may be more efficient to leave off unique indexes which are unlikely to collide.
389 # However if you do this, you run the risk of encountering errors which wouldn't have
391 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
392 $table = $this->tableName($table);
394 if (count($rows)==0) {
399 if (!is_array(reset($rows))) {
400 $rows = array($rows);
403 foreach( $rows as $row ) {
404 # Delete rows which collide
405 if ( $uniqueIndexes ) {
406 $sql = "DELETE FROM $table WHERE ";
408 foreach ( $uniqueIndexes as $index ) {
415 if ( is_array( $index ) ) {
417 foreach ( $index as $col ) {
423 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
426 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
430 $this->query( $sql, $fname );
434 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
435 $this->makeList( $row, LIST_COMMA
) . ')';
436 $this->query($sql, $fname);
440 # DELETE where the condition is a join
441 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
443 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
446 $delTable = $this->tableName( $delTable );
447 $joinTable = $this->tableName( $joinTable );
448 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
449 if ( $conds != '*' ) {
450 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
454 $this->query( $sql, $fname );
457 # Returns the size of a text field, or -1 for "unlimited"
458 function textFieldSize( $table, $field ) {
459 $table = $this->tableName( $table );
460 $sql = "SELECT t.typname as ftype,a.atttypmod as size
461 FROM pg_class c, pg_attribute a, pg_type t
462 WHERE relname='$table' AND a.attrelid=c.oid AND
463 a.atttypid=t.oid and a.attname='$field'";
464 $res =$this->query($sql);
465 $row=$this->fetchObject($res);
466 if ($row->ftype
=="varchar") {
471 $this->freeResult( $res );
475 function lowPriorityOption() {
479 function limitResult($sql, $limit, $offset) {
480 if ($offset === false)
482 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < 1 + $limit + $offset";
486 * Returns an SQL expression for a simple conditional.
487 * Uses CASE on Oracle
489 * @param string $cond SQL expression which will result in a boolean value
490 * @param string $trueVal SQL expression to return if true
491 * @param string $falseVal SQL expression to return if false
492 * @return string SQL fragment
494 function conditional( $cond, $trueVal, $falseVal ) {
495 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
498 function wasDeadlock() {
499 return $this->lastErrno() == 'OCI-00060';
502 function timestamp($ts = 0) {
503 return wfTimestamp(TS_ORACLE
, $ts);
507 * Return aggregated value function call
509 function aggregateValue ($valuedata,$valuename='value') {
513 function reportQueryError($error, $errno, $sql, $fname, $tempIgnore = false) {
514 # Ignore errors during error handling to avoid infinite recursion
515 $ignore = $this->ignoreErrors(true);
516 ++
$this->mErrorCount
;
518 if ($ignore ||
$tempIgnore) {
519 wfDebug("SQL ERROR (ignored): $error\n");
520 $this->ignoreErrors( $ignore );
523 $message = "A database error has occurred\n" .
525 "Function: $fname\n" .
526 "Error: $errno $error\n";
527 throw new DBUnexpectedError($this, $message);
532 * @return string wikitext of a link to the server software's web site
534 function getSoftwareLink() {
535 return "[http://www.oracle.com/ Oracle]";
539 * @return string Version information from the database
541 function getServerVersion() {
542 return oci_server_version($this->mConn
);
546 * Query whether a given table exists (in the given schema, or the default mw one if not given)
548 function tableExists($table) {
549 $etable= $this->addQuotes($table);
550 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$etable'";
551 $res = $this->query($SQL);
552 $count = $res ?
oci_num_rows($res) : 0;
554 $this->freeResult($res);
559 * Query whether a given column exists in the mediawiki schema
561 function fieldExists( $table, $field ) {
565 function fieldInfo( $table, $field ) {
569 function begin( $fname = '' ) {
570 $this->mTrxLevel
= 1;
572 function immediateCommit( $fname = '' ) {
575 function commit( $fname = '' ) {
576 oci_commit($this->mConn
);
577 $this->mTrxLevel
= 0;
580 /* Not even sure why this is used in the main codebase... */
581 function limitResultForUpdate($sql, $num) {
585 function strencode($s) {
586 return str_replace("'", "''", $s);
589 function encodeBlob($b) {
590 return new ORABlob($b);
592 function decodeBlob($b) {
593 return $b; //return $b->load();
596 function addQuotes( $s ) {
597 return "'" . $this->strencode($s) . "'";
600 function quote_ident( $s ) {
604 /* For now, does nothing */
605 function selectDB( $db ) {
610 * Returns an optional USE INDEX clause to go after the table, and a
611 * string to go at the end of the query
615 * @param array $options an associative array of options to be turned into
616 * an SQL query, valid keys are listed in the function.
619 function makeSelectOptions( $options ) {
620 $preLimitTail = $postLimitTail = '';
623 $noKeyOptions = array();
624 foreach ( $options as $key => $option ) {
625 if ( is_numeric( $key ) ) {
626 $noKeyOptions[$option] = true;
630 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
631 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
633 if (isset($options['LIMIT'])) {
634 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
635 // isset($options['OFFSET']) ? $options['OFFSET']
639 #if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
640 #if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
641 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
643 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
644 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
649 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
652 public function setTimeout( $timeout ) {
657 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
662 } // end DatabaseOracle class