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->mCascadingDeletes
= true;
108 $this->mCleanupTriggers
= true;
109 $this->mStrictIPs
= true;
110 $this->mFlags
= $flags;
111 $this->open( $server, $user, $password, $dbName);
115 function realTimestamps() {
119 function implicitGroupby() {
123 function searchableIPs() {
127 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
128 $failFunction = false, $flags = 0)
130 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags );
134 * Usually aborts on failure
135 * If the failFunction is set to a non-zero integer, returns success
137 function open( $server, $user, $password, $dbName ) {
138 # Test for Postgres support, to avoid suppressed fatal error
139 if ( !function_exists( 'oci_connect' ) ) {
140 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 $this->mServer
= $server;
146 $this->mUser
= $user;
147 $this->mPassword
= $password;
148 $this->mDBname
= $dbName;
150 if (!strlen($user)) { ## e.g. the class is being loaded
154 error_reporting( E_ALL
);
155 $this->mConn
= oci_connect($user, $password, $dbName);
157 if ($this->mConn
== false) {
158 wfDebug("DB connection error\n");
159 wfDebug("Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n");
160 wfDebug($this->lastError()."\n");
164 $this->mOpened
= true;
169 * Closes a database connection, if it is open
170 * Returns success, true if already closed
173 $this->mOpened
= false;
174 if ( $this->mConn
) {
175 return oci_close( $this->mConn
);
181 function execFlags() {
182 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
185 function doQuery($sql) {
186 wfDebug("SQL: [$sql]\n");
187 $this->mLastResult
= $stmt = oci_parse($this->mConn
, $sql);
188 if (oci_execute($stmt, $this->execFlags()) == false) {
189 $e = oci_error($stmt);
190 $this->reportQueryError($sql, $e['message'], $e['code']);
192 if (oci_statement_type($stmt) == "SELECT")
193 return new ORAResult($this, $stmt);
195 $this->mAffectedRows
= oci_num_rows($stmt);
200 function queryIgnore($sql, $fname = '') {
201 return $this->query($sql, $fname, true);
204 function freeResult($res) {
208 function fetchObject($res) {
209 return $res->fetchObject();
212 function fetchRow($res) {
213 return $res->fetchAssoc();
216 function numRows($res) {
217 return $res->numRows();
220 function numFields($res) {
221 return $res->numFields();
224 function fieldName($stmt, $n) {
225 return pg_field_name($stmt, $n);
229 * This must be called after nextSequenceVal
231 function insertId() {
232 return $this->mInsertId
;
235 function dataSeek($res, $row) {
239 function lastError() {
240 if ($this->mConn
=== false)
243 $e = oci_error($this->mConn
);
244 return $e['message'];
247 function lastErrno() {
248 if ($this->mConn
=== false)
251 $e = oci_error($this->mConn
);
255 function affectedRows() {
256 return $this->mAffectedRows
;
260 * Returns information about an index
261 * If errors are explicitly ignored, returns NULL on failure
263 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
267 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
271 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
272 if (!is_array($options))
273 $options = array($options);
275 if (in_array('IGNORE', $options))
276 $oldIgnore = $this->ignoreErrors(true);
278 # IGNORE is performed using single-row inserts, ignoring errors in each
279 # FIXME: need some way to distiguish between key collision and other types of error
280 //$oldIgnore = $this->ignoreErrors(true);
281 if (!is_array(reset($a))) {
284 foreach ($a as $row) {
285 $this->insertOneRow($table, $row, $fname);
287 //$this->ignoreErrors($oldIgnore);
290 if (in_array('IGNORE', $options))
291 $this->ignoreErrors($oldIgnore);
296 function insertOneRow($table, $row, $fname) {
297 // "INSERT INTO tables (a, b, c)"
298 $sql = "INSERT INTO " . $this->tableName($table) . " (" . join(',', array_keys($row)) . ')';
301 // for each value, append ":key"
303 foreach ($row as $col => $val) {
305 $what = "EMPTY_BLOB()";
317 $stmt = oci_parse($this->mConn
, $sql);
318 foreach ($row as $col => $val) {
319 if (!is_object($val)) {
320 if (oci_bind_by_name($stmt, ":$col", $row[$col]) === false)
321 $this->reportQueryError($this->lastErrno(), $this->lastError(), $sql, __METHOD__
);
325 if (oci_execute($stmt, $this->execFlags()) === false) {
326 $e = oci_error($stmt);
327 $this->reportQueryError($e['message'], $e['code'], $sql, __METHOD__
);
329 oci_free_statement($stmt);
332 function tableName( $name ) {
333 # Replace reserved words with better ones
338 return 'pagecontent';
345 * Return the next in a sequence, save the value for retrieval via insertId()
347 function nextSequenceValue($seqName) {
348 $res = $this->query("SELECT $seqName.nextval FROM dual");
349 $row = $this->fetchRow($res);
350 $this->mInsertId
= $row[0];
351 $this->freeResult($res);
352 return $this->mInsertId
;
356 * ORacle does not have a "USE INDEX" clause, so return an empty string
358 function useIndexClause($index) {
362 # REPLACE query wrapper
363 # Oracle simulates this with a DELETE followed by INSERT
364 # $row is the row to insert, an associative array
365 # $uniqueIndexes is an array of indexes. Each element may be either a
366 # field name or an array of field names
368 # It may be more efficient to leave off unique indexes which are unlikely to collide.
369 # However if you do this, you run the risk of encountering errors which wouldn't have
371 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
372 $table = $this->tableName($table);
374 if (count($rows)==0) {
379 if (!is_array(reset($rows))) {
380 $rows = array($rows);
383 foreach( $rows as $row ) {
384 # Delete rows which collide
385 if ( $uniqueIndexes ) {
386 $sql = "DELETE FROM $table WHERE ";
388 foreach ( $uniqueIndexes as $index ) {
395 if ( is_array( $index ) ) {
397 foreach ( $index as $col ) {
403 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
406 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
410 $this->query( $sql, $fname );
414 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
415 $this->makeList( $row, LIST_COMMA
) . ')';
416 $this->query($sql, $fname);
420 # DELETE where the condition is a join
421 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
423 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
426 $delTable = $this->tableName( $delTable );
427 $joinTable = $this->tableName( $joinTable );
428 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
429 if ( $conds != '*' ) {
430 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
434 $this->query( $sql, $fname );
437 # Returns the size of a text field, or -1 for "unlimited"
438 function textFieldSize( $table, $field ) {
439 $table = $this->tableName( $table );
440 $sql = "SELECT t.typname as ftype,a.atttypmod as size
441 FROM pg_class c, pg_attribute a, pg_type t
442 WHERE relname='$table' AND a.attrelid=c.oid AND
443 a.atttypid=t.oid and a.attname='$field'";
444 $res =$this->query($sql);
445 $row=$this->fetchObject($res);
446 if ($row->ftype
=="varchar") {
451 $this->freeResult( $res );
455 function lowPriorityOption() {
459 function limitResult($sql, $limit, $offset) {
460 if ($offset === false)
462 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < 1 + $limit + $offset";
466 * Returns an SQL expression for a simple conditional.
467 * Uses CASE on Oracle
469 * @param string $cond SQL expression which will result in a boolean value
470 * @param string $trueVal SQL expression to return if true
471 * @param string $falseVal SQL expression to return if false
472 * @return string SQL fragment
474 function conditional( $cond, $trueVal, $falseVal ) {
475 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
478 function wasDeadlock() {
479 return $this->lastErrno() == 'OCI-00060';
482 function timestamp($ts = 0) {
483 return wfTimestamp(TS_ORACLE
, $ts);
487 * Return aggregated value function call
489 function aggregateValue ($valuedata,$valuename='value') {
493 function reportQueryError($error, $errno, $sql, $fname, $tempIgnore = false) {
494 # Ignore errors during error handling to avoid infinite recursion
495 $ignore = $this->ignoreErrors(true);
496 ++
$this->mErrorCount
;
498 if ($ignore ||
$tempIgnore) {
499 wfDebug("SQL ERROR (ignored): $error\n");
500 $this->ignoreErrors( $ignore );
503 $message = "A database error has occurred\n" .
505 "Function: $fname\n" .
506 "Error: $errno $error\n";
507 throw new DBUnexpectedError($this, $message);
512 * @return string wikitext of a link to the server software's web site
514 function getSoftwareLink() {
515 return "[http://www.oracle.com/ Oracle]";
519 * @return string Version information from the database
521 function getServerVersion() {
522 return oci_server_version($this->mConn
);
526 * Query whether a given table exists (in the given schema, or the default mw one if not given)
528 function tableExists($table) {
529 $etable= $this->addQuotes($table);
530 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$etable'";
531 $res = $this->query($SQL);
532 $count = $res ?
oci_num_rows($res) : 0;
534 $this->freeResult($res);
539 * Query whether a given column exists in the mediawiki schema
541 function fieldExists( $table, $field ) {
545 function fieldInfo( $table, $field ) {
549 function begin( $fname = '' ) {
550 $this->mTrxLevel
= 1;
552 function immediateCommit( $fname = '' ) {
555 function commit( $fname = '' ) {
556 oci_commit($this->mConn
);
557 $this->mTrxLevel
= 0;
560 /* Not even sure why this is used in the main codebase... */
561 function limitResultForUpdate($sql, $num) {
565 function strencode($s) {
566 return str_replace("'", "''", $s);
569 function encodeBlob($b) {
570 return new ORABlob($b);
572 function decodeBlob($b) {
573 return $b; //return $b->load();
576 function addQuotes( $s ) {
577 return "'" . $this->strencode($s) . "'";
580 function quote_ident( $s ) {
584 /* For now, does nothing */
585 function selectDB( $db ) {
590 * Returns an optional USE INDEX clause to go after the table, and a
591 * string to go at the end of the query
595 * @param array $options an associative array of options to be turned into
596 * an SQL query, valid keys are listed in the function.
599 function makeSelectOptions( $options ) {
603 $noKeyOptions = array();
604 foreach ( $options as $key => $option ) {
605 if ( is_numeric( $key ) ) {
606 $noKeyOptions[$option] = true;
610 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
611 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
613 if (isset($options['LIMIT'])) {
614 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
615 // isset($options['OFFSET']) ? $options['OFFSET']
619 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
620 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
621 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
623 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
624 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
629 return array( $startOpts, $useIndex, $tailOpts );
632 public function setTimeout( $timeout ) {
637 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
642 } // end DatabaseOracle class