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'], '', __FUNCTION__
);
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 if (!mb_check_encoding($sql)) {
193 throw new MWException("SQL encoding is invalid");
196 if (($this->mLastResult
= $stmt = oci_parse($this->mConn
, $sql)) === false) {
197 $e = oci_error($this->mConn
);
198 $this->reportQueryError($e['message'], $e['code'], $sql, __FUNCTION__
);
201 if (oci_execute($stmt, $this->execFlags()) == false) {
202 $e = oci_error($stmt);
203 $this->reportQueryError($e['message'], $e['code'], $sql, __FUNCTION__
);
205 if (oci_statement_type($stmt) == "SELECT")
206 return new ORAResult($this, $stmt);
208 $this->mAffectedRows
= oci_num_rows($stmt);
213 function queryIgnore($sql, $fname = '') {
214 return $this->query($sql, $fname, true);
217 function freeResult($res) {
221 function fetchObject($res) {
222 return $res->fetchObject();
225 function fetchRow($res) {
226 return $res->fetchAssoc();
229 function numRows($res) {
230 return $res->numRows();
233 function numFields($res) {
234 return $res->numFields();
237 function fieldName($stmt, $n) {
238 return pg_field_name($stmt, $n);
242 * This must be called after nextSequenceVal
244 function insertId() {
245 return $this->mInsertId
;
248 function dataSeek($res, $row) {
252 function lastError() {
253 if ($this->mConn
=== false)
256 $e = oci_error($this->mConn
);
257 return $e['message'];
260 function lastErrno() {
261 if ($this->mConn
=== false)
264 $e = oci_error($this->mConn
);
268 function affectedRows() {
269 return $this->mAffectedRows
;
273 * Returns information about an index
274 * If errors are explicitly ignored, returns NULL on failure
276 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
280 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
284 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
285 if (!is_array($options))
286 $options = array($options);
288 #if (in_array('IGNORE', $options))
289 # $oldIgnore = $this->ignoreErrors(true);
291 # IGNORE is performed using single-row inserts, ignoring errors in each
292 # FIXME: need some way to distiguish between key collision and other types of error
293 //$oldIgnore = $this->ignoreErrors(true);
294 if (!is_array(reset($a))) {
297 foreach ($a as $row) {
298 $this->insertOneRow($table, $row, $fname);
300 //$this->ignoreErrors($oldIgnore);
303 //if (in_array('IGNORE', $options))
304 // $this->ignoreErrors($oldIgnore);
309 function insertOneRow($table, $row, $fname) {
310 // "INSERT INTO tables (a, b, c)"
311 $sql = "INSERT INTO " . $this->tableName($table) . " (" . join(',', array_keys($row)) . ')';
314 // for each value, append ":key"
317 foreach ($row as $col => $val) {
318 if (is_object($val)) {
319 $what = "EMPTY_BLOB()";
320 assert($returning === '');
321 $returning = " RETURNING $col INTO :bval";
332 $sql .= ") $returning";
334 $stmt = oci_parse($this->mConn
, $sql);
335 foreach ($row as $col => $val) {
336 if (!is_object($val)) {
337 if (oci_bind_by_name($stmt, ":$col", $row[$col]) === false)
338 $this->reportQueryError($this->lastErrno(), $this->lastError(), $sql, __METHOD__
);
342 if (($bval = oci_new_descriptor($this->mConn
, OCI_D_LOB
)) === false) {
343 $e = oci_error($stmt);
344 throw new DBUnexpectedError($this, "Cannot create LOB descriptor: " . $e['message']);
347 if (strlen($returning))
348 oci_bind_by_name($stmt, ":bval", $bval, -1, SQLT_BLOB
);
350 if (oci_execute($stmt, OCI_DEFAULT
) === false) {
351 $e = oci_error($stmt);
352 $this->reportQueryError($e['message'], $e['code'], $sql, __METHOD__
);
354 if (strlen($returning)) {
355 $bval->save($row[$blobcol]->getData());
358 if (!$this->mTrxLevel
)
359 oci_commit($this->mConn
);
361 oci_free_statement($stmt);
364 function tableName( $name ) {
365 # Replace reserved words with better ones
370 return 'pagecontent';
377 * Return the next in a sequence, save the value for retrieval via insertId()
379 function nextSequenceValue($seqName) {
380 $res = $this->query("SELECT $seqName.nextval FROM dual");
381 $row = $this->fetchRow($res);
382 $this->mInsertId
= $row[0];
383 $this->freeResult($res);
384 return $this->mInsertId
;
388 * ORacle does not have a "USE INDEX" clause, so return an empty string
390 function useIndexClause($index) {
394 # REPLACE query wrapper
395 # Oracle simulates this with a DELETE followed by INSERT
396 # $row is the row to insert, an associative array
397 # $uniqueIndexes is an array of indexes. Each element may be either a
398 # field name or an array of field names
400 # It may be more efficient to leave off unique indexes which are unlikely to collide.
401 # However if you do this, you run the risk of encountering errors which wouldn't have
403 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
404 $table = $this->tableName($table);
406 if (count($rows)==0) {
411 if (!is_array(reset($rows))) {
412 $rows = array($rows);
415 foreach( $rows as $row ) {
416 # Delete rows which collide
417 if ( $uniqueIndexes ) {
418 $sql = "DELETE FROM $table WHERE ";
420 foreach ( $uniqueIndexes as $index ) {
427 if ( is_array( $index ) ) {
429 foreach ( $index as $col ) {
435 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
438 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
442 $this->query( $sql, $fname );
446 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
447 $this->makeList( $row, LIST_COMMA
) . ')';
448 $this->query($sql, $fname);
452 # DELETE where the condition is a join
453 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
455 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
458 $delTable = $this->tableName( $delTable );
459 $joinTable = $this->tableName( $joinTable );
460 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
461 if ( $conds != '*' ) {
462 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
466 $this->query( $sql, $fname );
469 # Returns the size of a text field, or -1 for "unlimited"
470 function textFieldSize( $table, $field ) {
471 $table = $this->tableName( $table );
472 $sql = "SELECT t.typname as ftype,a.atttypmod as size
473 FROM pg_class c, pg_attribute a, pg_type t
474 WHERE relname='$table' AND a.attrelid=c.oid AND
475 a.atttypid=t.oid and a.attname='$field'";
476 $res =$this->query($sql);
477 $row=$this->fetchObject($res);
478 if ($row->ftype
=="varchar") {
483 $this->freeResult( $res );
487 function lowPriorityOption() {
491 function limitResult($sql, $limit, $offset) {
492 if ($offset === false)
494 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < 1 + $limit + $offset";
498 * Returns an SQL expression for a simple conditional.
499 * Uses CASE on Oracle
501 * @param string $cond SQL expression which will result in a boolean value
502 * @param string $trueVal SQL expression to return if true
503 * @param string $falseVal SQL expression to return if false
504 * @return string SQL fragment
506 function conditional( $cond, $trueVal, $falseVal ) {
507 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
510 function wasDeadlock() {
511 return $this->lastErrno() == 'OCI-00060';
514 function timestamp($ts = 0) {
515 return wfTimestamp(TS_ORACLE
, $ts);
519 * Return aggregated value function call
521 function aggregateValue ($valuedata,$valuename='value') {
525 function reportQueryError($error, $errno, $sql, $fname, $tempIgnore = false) {
526 # Ignore errors during error handling to avoid infinite
528 $ignore = $this->ignoreErrors(true);
529 ++
$this->mErrorCount
;
531 if ($ignore ||
$tempIgnore) {
532 echo "error ignored! query = [$sql]\n";
533 wfDebug("SQL ERROR (ignored): $error\n");
534 $this->ignoreErrors( $ignore );
538 $message = "A database error has occurred\n" .
540 "Function: $fname\n" .
541 "Error: $errno $error\n";
542 throw new DBUnexpectedError($this, $message);
547 * @return string wikitext of a link to the server software's web site
549 function getSoftwareLink() {
550 return "[http://www.oracle.com/ Oracle]";
554 * @return string Version information from the database
556 function getServerVersion() {
557 return oci_server_version($this->mConn
);
561 * Query whether a given table exists (in the given schema, or the default mw one if not given)
563 function tableExists($table) {
564 $etable= $this->addQuotes($table);
565 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$etable'";
566 $res = $this->query($SQL);
567 $count = $res ?
oci_num_rows($res) : 0;
569 $this->freeResult($res);
574 * Query whether a given column exists in the mediawiki schema
576 function fieldExists( $table, $field ) {
580 function fieldInfo( $table, $field ) {
584 function begin( $fname = '' ) {
585 $this->mTrxLevel
= 1;
587 function immediateCommit( $fname = '' ) {
590 function commit( $fname = '' ) {
591 oci_commit($this->mConn
);
592 $this->mTrxLevel
= 0;
595 /* Not even sure why this is used in the main codebase... */
596 function limitResultForUpdate($sql, $num) {
600 function strencode($s) {
601 return str_replace("'", "''", $s);
604 function encodeBlob($b) {
605 return new ORABlob($b);
607 function decodeBlob($b) {
608 return $b; //return $b->load();
611 function addQuotes( $s ) {
613 $s = $wgLang->checkTitleEncoding($s);
614 return "'" . $this->strencode($s) . "'";
617 function quote_ident( $s ) {
621 /* For now, does nothing */
622 function selectDB( $db ) {
627 * Returns an optional USE INDEX clause to go after the table, and a
628 * string to go at the end of the query
632 * @param array $options an associative array of options to be turned into
633 * an SQL query, valid keys are listed in the function.
636 function makeSelectOptions( $options ) {
637 $preLimitTail = $postLimitTail = '';
640 $noKeyOptions = array();
641 foreach ( $options as $key => $option ) {
642 if ( is_numeric( $key ) ) {
643 $noKeyOptions[$option] = true;
647 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
648 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
650 if (isset($options['LIMIT'])) {
651 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
652 // isset($options['OFFSET']) ? $options['OFFSET']
656 #if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
657 #if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
658 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
660 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
661 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
666 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
669 public function setTimeout( $timeout ) {
674 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
679 } // end DatabaseOracle class