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 if ( !function_exists( 'oci_connect' ) ) {
139 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" );
142 # Needed for proper UTF-8 functionality
143 putenv("NLS_LANG=AMERICAN_AMERICA.AL32UTF8");
146 $this->mServer
= $server;
147 $this->mUser
= $user;
148 $this->mPassword
= $password;
149 $this->mDBname
= $dbName;
151 if (!strlen($user)) { ## e.g. the class is being loaded
155 error_reporting( E_ALL
);
156 $this->mConn
= oci_connect($user, $password, $dbName);
158 if ($this->mConn
== false) {
159 wfDebug("DB connection error\n");
160 wfDebug("Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n");
161 wfDebug($this->lastError()."\n");
165 $this->mOpened
= true;
170 * Closes a database connection, if it is open
171 * Returns success, true if already closed
174 $this->mOpened
= false;
175 if ( $this->mConn
) {
176 return oci_close( $this->mConn
);
182 function execFlags() {
183 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
186 function doQuery($sql) {
187 wfDebug("SQL: [$sql]\n");
188 $this->mLastResult
= $stmt = oci_parse($this->mConn
, $sql);
189 if (oci_execute($stmt, $this->execFlags()) == false) {
190 $e = oci_error($stmt);
191 $this->reportQueryError($sql, $e['message'], $e['code'], '');
193 if (oci_statement_type($stmt) == "SELECT")
194 return new ORAResult($this, $stmt);
196 $this->mAffectedRows
= oci_num_rows($stmt);
201 function queryIgnore($sql, $fname = '') {
202 return $this->query($sql, $fname, true);
205 function freeResult($res) {
209 function fetchObject($res) {
210 return $res->fetchObject();
213 function fetchRow($res) {
214 return $res->fetchAssoc();
217 function numRows($res) {
218 return $res->numRows();
221 function numFields($res) {
222 return $res->numFields();
225 function fieldName($stmt, $n) {
226 return pg_field_name($stmt, $n);
230 * This must be called after nextSequenceVal
232 function insertId() {
233 return $this->mInsertId
;
236 function dataSeek($res, $row) {
240 function lastError() {
241 if ($this->mConn
=== false)
244 $e = oci_error($this->mConn
);
245 return $e['message'];
248 function lastErrno() {
249 if ($this->mConn
=== false)
252 $e = oci_error($this->mConn
);
256 function affectedRows() {
257 return $this->mAffectedRows
;
261 * Returns information about an index
262 * If errors are explicitly ignored, returns NULL on failure
264 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
268 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
272 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
273 if (!is_array($options))
274 $options = array($options);
276 if (in_array('IGNORE', $options))
277 $oldIgnore = $this->ignoreErrors(true);
279 # IGNORE is performed using single-row inserts, ignoring errors in each
280 # FIXME: need some way to distiguish between key collision and other types of error
281 //$oldIgnore = $this->ignoreErrors(true);
282 if (!is_array(reset($a))) {
285 foreach ($a as $row) {
286 $this->insertOneRow($table, $row, $fname);
288 //$this->ignoreErrors($oldIgnore);
291 if (in_array('IGNORE', $options))
292 $this->ignoreErrors($oldIgnore);
297 function insertOneRow($table, $row, $fname) {
298 // "INSERT INTO tables (a, b, c)"
299 $sql = "INSERT INTO " . $this->tableName($table) . " (" . join(',', array_keys($row)) . ')';
302 // for each value, append ":key"
305 foreach ($row as $col => $val) {
306 if (is_object($val)) {
307 $what = "EMPTY_BLOB()";
308 assert($returning === '');
309 $returning = " RETURNING $col INTO :bval";
320 $sql .= ") $returning";
322 $stmt = oci_parse($this->mConn
, $sql);
323 foreach ($row as $col => $val) {
324 if (!is_object($val)) {
325 if (oci_bind_by_name($stmt, ":$col", $row[$col]) === false)
326 $this->reportQueryError($this->lastErrno(), $this->lastError(), $sql, __METHOD__
);
330 $bval = oci_new_descriptor($this->mConn
, OCI_D_LOB
);
331 if (strlen($returning))
332 oci_bind_by_name($stmt, ":bval", $bval, -1, SQLT_BLOB
);
334 if (oci_execute($stmt, OCI_DEFAULT
) === false) {
335 $e = oci_error($stmt);
336 $this->reportQueryError($e['message'], $e['code'], $sql, __METHOD__
);
338 if (strlen($returning)) {
339 $bval->save($row[$blobcol]->getData());
342 if (!$this->mTrxLevel
)
343 oci_commit($this->mConn
);
345 oci_free_statement($stmt);
348 function tableName( $name ) {
349 # Replace reserved words with better ones
354 return 'pagecontent';
361 * Return the next in a sequence, save the value for retrieval via insertId()
363 function nextSequenceValue($seqName) {
364 $res = $this->query("SELECT $seqName.nextval FROM dual");
365 $row = $this->fetchRow($res);
366 $this->mInsertId
= $row[0];
367 $this->freeResult($res);
368 return $this->mInsertId
;
372 * ORacle does not have a "USE INDEX" clause, so return an empty string
374 function useIndexClause($index) {
378 # REPLACE query wrapper
379 # Oracle simulates this with a DELETE followed by INSERT
380 # $row is the row to insert, an associative array
381 # $uniqueIndexes is an array of indexes. Each element may be either a
382 # field name or an array of field names
384 # It may be more efficient to leave off unique indexes which are unlikely to collide.
385 # However if you do this, you run the risk of encountering errors which wouldn't have
387 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
388 $table = $this->tableName($table);
390 if (count($rows)==0) {
395 if (!is_array(reset($rows))) {
396 $rows = array($rows);
399 foreach( $rows as $row ) {
400 # Delete rows which collide
401 if ( $uniqueIndexes ) {
402 $sql = "DELETE FROM $table WHERE ";
404 foreach ( $uniqueIndexes as $index ) {
411 if ( is_array( $index ) ) {
413 foreach ( $index as $col ) {
419 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
422 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
426 $this->query( $sql, $fname );
430 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
431 $this->makeList( $row, LIST_COMMA
) . ')';
432 $this->query($sql, $fname);
436 # DELETE where the condition is a join
437 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
439 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
442 $delTable = $this->tableName( $delTable );
443 $joinTable = $this->tableName( $joinTable );
444 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
445 if ( $conds != '*' ) {
446 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
450 $this->query( $sql, $fname );
453 # Returns the size of a text field, or -1 for "unlimited"
454 function textFieldSize( $table, $field ) {
455 $table = $this->tableName( $table );
456 $sql = "SELECT t.typname as ftype,a.atttypmod as size
457 FROM pg_class c, pg_attribute a, pg_type t
458 WHERE relname='$table' AND a.attrelid=c.oid AND
459 a.atttypid=t.oid and a.attname='$field'";
460 $res =$this->query($sql);
461 $row=$this->fetchObject($res);
462 if ($row->ftype
=="varchar") {
467 $this->freeResult( $res );
471 function lowPriorityOption() {
475 function limitResult($sql, $limit, $offset) {
476 if ($offset === false)
478 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < 1 + $limit + $offset";
482 * Returns an SQL expression for a simple conditional.
483 * Uses CASE on Oracle
485 * @param string $cond SQL expression which will result in a boolean value
486 * @param string $trueVal SQL expression to return if true
487 * @param string $falseVal SQL expression to return if false
488 * @return string SQL fragment
490 function conditional( $cond, $trueVal, $falseVal ) {
491 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
494 function wasDeadlock() {
495 return $this->lastErrno() == 'OCI-00060';
498 function timestamp($ts = 0) {
499 return wfTimestamp(TS_ORACLE
, $ts);
503 * Return aggregated value function call
505 function aggregateValue ($valuedata,$valuename='value') {
509 function reportQueryError($error, $errno, $sql, $fname, $tempIgnore = false) {
510 # Ignore errors during error handling to avoid infinite recursion
511 $ignore = $this->ignoreErrors(true);
512 ++
$this->mErrorCount
;
514 if ($ignore ||
$tempIgnore) {
515 wfDebug("SQL ERROR (ignored): $error\n");
516 $this->ignoreErrors( $ignore );
519 $message = "A database error has occurred\n" .
521 "Function: $fname\n" .
522 "Error: $errno $error\n";
523 throw new DBUnexpectedError($this, $message);
528 * @return string wikitext of a link to the server software's web site
530 function getSoftwareLink() {
531 return "[http://www.oracle.com/ Oracle]";
535 * @return string Version information from the database
537 function getServerVersion() {
538 return oci_server_version($this->mConn
);
542 * Query whether a given table exists (in the given schema, or the default mw one if not given)
544 function tableExists($table) {
545 $etable= $this->addQuotes($table);
546 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$etable'";
547 $res = $this->query($SQL);
548 $count = $res ?
oci_num_rows($res) : 0;
550 $this->freeResult($res);
555 * Query whether a given column exists in the mediawiki schema
557 function fieldExists( $table, $field ) {
561 function fieldInfo( $table, $field ) {
565 function begin( $fname = '' ) {
566 $this->mTrxLevel
= 1;
568 function immediateCommit( $fname = '' ) {
571 function commit( $fname = '' ) {
572 oci_commit($this->mConn
);
573 $this->mTrxLevel
= 0;
576 /* Not even sure why this is used in the main codebase... */
577 function limitResultForUpdate($sql, $num) {
581 function strencode($s) {
582 return str_replace("'", "''", $s);
585 function encodeBlob($b) {
586 return new ORABlob($b);
588 function decodeBlob($b) {
589 return $b; //return $b->load();
592 function addQuotes( $s ) {
593 return "'" . $this->strencode($s) . "'";
596 function quote_ident( $s ) {
600 /* For now, does nothing */
601 function selectDB( $db ) {
606 * Returns an optional USE INDEX clause to go after the table, and a
607 * string to go at the end of the query
611 * @param array $options an associative array of options to be turned into
612 * an SQL query, valid keys are listed in the function.
615 function makeSelectOptions( $options ) {
616 $preLimitTail = $postLimitTail = '';
619 $noKeyOptions = array();
620 foreach ( $options as $key => $option ) {
621 if ( is_numeric( $key ) ) {
622 $noKeyOptions[$option] = true;
626 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
627 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
629 if (isset($options['LIMIT'])) {
630 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
631 // isset($options['OFFSET']) ? $options['OFFSET']
635 #if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
636 #if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
637 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
639 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
640 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
645 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
648 public function setTimeout( $timeout ) {
653 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
658 } // end DatabaseOracle class