12 require_once( 'Database.php' );
14 class OracleBlob
extends DBObject
{
27 class DatabaseOracle
extends Database
{
28 var $mInsertId = NULL;
29 var $mLastResult = NULL;
30 var $mFetchCache = array();
31 var $mFetchID = array();
32 var $mNcols = array();
33 var $mFieldNames = array(), $mFieldTypes = array();
34 var $mAffectedRows = array();
37 function DatabaseOracle($server = false, $user = false, $password = false, $dbName = false,
38 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
40 Database
::Database( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
43 /* static */ function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
44 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
46 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
50 * Usually aborts on failure
51 * If the failFunction is set to a non-zero integer, returns success
53 function open( $server, $user, $password, $dbName ) {
54 if ( !function_exists( 'oci_connect' ) ) {
55 throw new DBConnectionError( $this, "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n" );
58 $this->mServer
= $server;
60 $this->mPassword
= $password;
61 $this->mDBname
= $dbName;
66 $this->mConn
= oci_new_connect($user, $password, $dbName, "AL32UTF8");
67 if ( $this->mConn
=== false ) {
68 wfDebug( "DB connection error\n" );
69 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: "
70 . substr( $password, 0, 3 ) . "...\n" );
71 wfDebug( $this->lastError()."\n" );
73 $this->mOpened
= true;
79 * Closes a database connection, if it is open
80 * Returns success, true if already closed
83 $this->mOpened
= false;
85 return oci_close($this->mConn
);
91 function parseStatement($sql) {
92 $this->mErr
= $this->mLastResult
= false;
93 if (($stmt = oci_parse($this->mConn
, $sql)) === false) {
95 return $this->mLastResult
= false;
97 $this->mAffectedRows
[$stmt] = 0;
98 return $this->mLastResult
= $stmt;
101 function doQuery($sql) {
102 if (($stmt = $this->parseStatement($sql)) === false)
104 return $this->executeStatement($stmt);
107 function executeStatement($stmt) {
108 if (!oci_execute($stmt, OCI_DEFAULT
)) {
110 oci_free_statement($stmt);
113 $this->mAffectedRows
[$stmt] = oci_num_rows($stmt);
114 $this->mFetchCache
[$stmt] = array();
115 $this->mFetchID
[$stmt] = 0;
116 $this->mNcols
[$stmt] = oci_num_fields($stmt);
117 if ($this->mNcols
[$stmt] == 0)
118 return $this->mLastResult
;
119 for ($i = 1; $i <= $this->mNcols
[$stmt]; $i++
) {
120 $this->mFieldNames
[$stmt][$i] = oci_field_name($stmt, $i);
121 $this->mFieldTypes
[$stmt][$i] = oci_field_type($stmt, $i);
123 while (($o = oci_fetch_array($stmt)) !== false) {
124 foreach ($o as $key => $value) {
125 if (is_object($value)) {
126 $o[$key] = $value->load();
129 $this->mFetchCache
[$stmt][] = $o;
131 return $this->mLastResult
;
134 function queryIgnore( $sql, $fname = '' ) {
135 return $this->query( $sql, $fname, true );
138 function freeResult( $res ) {
139 if (!oci_free_statement($res)) {
140 throw new DBUnexpectedError( $this, "Unable to free Oracle result\n" );
142 unset($this->mFetchID
[$res]);
143 unset($this->mFetchCache
[$res]);
144 unset($this->mNcols
[$res]);
145 unset($this->mFieldNames
[$res]);
146 unset($this->mFieldTypes
[$res]);
149 function fetchAssoc($res) {
150 if ($this->mFetchID
[$res] >= count($this->mFetchCache
[$res]))
153 for ($i = 1; $i <= $this->mNcols
[$res]; $i++
) {
154 $name = $this->mFieldNames
[$res][$i];
155 $type = $this->mFieldTypes
[$res][$i];
156 if (isset($this->mFetchCache
[$res][$this->mFetchID
[$res]][$name]))
157 $value = $this->mFetchCache
[$res][$this->mFetchID
[$res]][$name];
159 $key = strtolower($name);
160 wfdebug("'$key' => '$value'\n");
163 $this->mFetchID
[$res]++
;
167 function fetchRow($res) {
168 $r = $this->fetchAssoc($res);
173 foreach ($r as $key => $value) {
174 wfdebug("ret[$i]=[$value]\n");
180 function fetchObject($res) {
181 $row = $this->fetchAssoc($res);
185 foreach ($row as $key => $value)
190 function numRows($res) {
191 return count($this->mFetchCache
[$res]);
193 function numFields( $res ) { return pg_num_fields( $res ); }
194 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
197 * This must be called after nextSequenceVal
199 function insertId() {
200 return $this->mInsertId
;
203 function dataSeek($res, $row) {
204 $this->mFetchID
[$res] = $row;
207 function lastError() {
208 if ($this->mErr
=== false) {
209 if ($this->mLastResult
!== false) $what = $this->mLastResult
;
210 else if ($this->mConn
!== false) $what = $this->mConn
;
212 $err = ($what !== false) ?
oci_error($what) : oci_error();
214 $this->mErr
= 'no error';
216 $this->mErr
= $err['message'];
218 return str_replace("\n", '<br />', $this->mErr
);
220 function lastErrno() {
224 function affectedRows() {
225 return $this->mAffectedRows
[$this->mLastResult
];
229 * Returns information about an index
230 * If errors are explicitly ignored, returns NULL on failure
232 function indexInfo ($table, $index, $fname = 'Database::indexInfo' ) {
233 $table = $this->tableName($table, true);
234 if ($index == 'PRIMARY')
235 $index = "${table}_pk";
236 $sql = "SELECT uniqueness FROM all_indexes WHERE table_name='" .
237 $table . "' AND index_name='" .
238 $this->strencode(strtoupper($index)) . "'";
239 $res = $this->query($sql, $fname);
242 if (($row = $this->fetchObject($res)) == NULL)
244 $this->freeResult($res);
245 $row->Non_unique
= !$row->uniqueness
;
249 function indexUnique ($table, $index, $fname = 'indexUnique') {
250 if (!($i = $this->indexInfo($table, $index, $fname)))
252 return $i->uniqueness
== 'UNIQUE';
255 function fieldInfo( $table, $field ) {
257 $o->multiple_key
= true; /* XXX */
261 function getColumnInformation($table, $field) {
262 $table = $this->tableName($table, true);
263 $field = strtoupper($field);
265 $res = $this->doQuery("SELECT * FROM all_tab_columns " .
266 "WHERE table_name='".$table."' " .
267 "AND column_name='".$field."'");
270 $o = $this->fetchObject($res);
271 $this->freeResult($res);
275 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
276 $column = $this->getColumnInformation($table, $field);
282 function tableName($name, $forddl = false) {
283 # First run any transformations from the parent object
284 $name = parent
::tableName( $name );
286 # Replace backticks into empty
287 # Note: "foo" and foo are not the same in Oracle!
288 $name = str_replace('`', '', $name);
290 # Now quote Oracle reserved keywords
298 return '"' . $name . '"';
301 return strtoupper($name);
305 function strencode( $s ) {
306 return str_replace("'", "''", $s);
310 * Return the next in a sequence, save the value for retrieval via insertId()
312 function nextSequenceValue( $seqName ) {
313 $r = $this->doQuery("SELECT $seqName.nextval AS val FROM dual");
314 $o = $this->fetchObject($r);
315 $this->freeResult($r);
316 return $this->mInsertId
= (int)$o->val
;
321 * PostgreSQL doesn't have them and returns ""
323 function useIndexClause( $index ) {
327 # REPLACE query wrapper
328 # PostgreSQL simulates this with a DELETE followed by INSERT
329 # $row is the row to insert, an associative array
330 # $uniqueIndexes is an array of indexes. Each element may be either a
331 # field name or an array of field names
333 # It may be more efficient to leave off unique indexes which are unlikely to collide.
334 # However if you do this, you run the risk of encountering errors which wouldn't have
336 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
337 $table = $this->tableName( $table );
339 if (count($rows)==0) {
344 if ( !is_array( reset( $rows ) ) ) {
345 $rows = array( $rows );
348 foreach( $rows as $row ) {
349 # Delete rows which collide
350 if ( $uniqueIndexes ) {
351 $sql = "DELETE FROM $table WHERE ";
353 foreach ( $uniqueIndexes as $index ) {
360 if ( is_array( $index ) ) {
362 foreach ( $index as $col ) {
368 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
371 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
375 $this->query( $sql, $fname );
379 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
380 $this->makeList( $row, LIST_COMMA
) . ')';
381 $this->query( $sql, $fname );
385 # DELETE where the condition is a join
386 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
388 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
391 $delTable = $this->tableName( $delTable );
392 $joinTable = $this->tableName( $joinTable );
393 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
394 if ( $conds != '*' ) {
395 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
399 $this->query( $sql, $fname );
402 # Returns the size of a text field, or -1 for "unlimited"
403 function textFieldSize( $table, $field ) {
404 $table = $this->tableName( $table );
405 $sql = "SELECT t.typname as ftype,a.atttypmod as size
406 FROM pg_class c, pg_attribute a, pg_type t
407 WHERE relname='$table' AND a.attrelid=c.oid AND
408 a.atttypid=t.oid and a.attname='$field'";
409 $res =$this->query($sql);
410 $row=$this->fetchObject($res);
411 if ($row->ftype
=="varchar") {
416 $this->freeResult( $res );
420 function lowPriorityOption() {
424 function limitResult($sql, $limit, $offset) {
425 $ret = "SELECT * FROM ($sql) WHERE ROWNUM < " . ((int)$limit +
(int)($offset+
1));
426 if (is_numeric($offset))
427 $ret .= " AND ROWNUM >= " . (int)$offset;
430 function limitResultForUpdate($sql, $limit) {
434 * Returns an SQL expression for a simple conditional.
435 * Uses CASE on PostgreSQL.
437 * @param string $cond SQL expression which will result in a boolean value
438 * @param string $trueVal SQL expression to return if true
439 * @param string $falseVal SQL expression to return if false
440 * @return string SQL fragment
442 function conditional( $cond, $trueVal, $falseVal ) {
443 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
446 # FIXME: actually detecting deadlocks might be nice
447 function wasDeadlock() {
451 # Return DB-style timestamp used for MySQL schema
452 function timestamp($ts = 0) {
453 return $this->strencode(wfTimestamp(TS_ORACLE
, $ts));
454 # return "TO_TIMESTAMP('" . $this->strencode(wfTimestamp(TS_DB, $ts)) . "', 'RRRR-MM-DD HH24:MI:SS')";
458 * Return aggregated value function call
460 function aggregateValue ($valuedata,$valuename='value') {
465 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
466 $message = "A database error has occurred\n" .
468 "Function: $fname\n" .
469 "Error: $errno $error\n";
470 throw new DBUnexpectedError($this, $message);
474 * @return string wikitext of a link to the server software's web site
476 function getSoftwareLink() {
477 return "[http://www.oracle.com/ Oracle]";
481 * @return string Version information from the database
483 function getServerVersion() {
484 return oci_server_version($this->mConn
);
487 function setSchema($schema=false) {
488 $schemas=$this->mSchemas
;
489 if ($schema) { array_unshift($schemas,$schema); }
490 $searchpath=$this->makeList($schemas,LIST_NAMES
);
491 $this->query("SET search_path = $searchpath");
497 function immediateCommit( $fname = 'Database::immediateCommit' ) {
498 oci_commit($this->mConn
);
499 $this->mTrxLevel
= 0;
501 function rollback( $fname = 'Database::rollback' ) {
502 oci_rollback($this->mConn
);
503 $this->mTrxLevel
= 0;
508 function getStatus($which=null) {
509 $result = array('Threads_running' => 0, 'Threads_connected' => 0);
514 * Returns an optional USE INDEX clause to go after the table, and a
515 * string to go at the end of the query
519 * @param array $options an associative array of options to be turned into
520 * an SQL query, valid keys are listed in the function.
523 function makeSelectOptions($options) {
526 if (isset( $options['ORDER BY'])) {
527 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
530 return array('', $tailOpts);
533 function maxListLen() {
538 * Query whether a given table exists
540 function tableExists( $table ) {
541 $table = $this->tableName($table, true);
542 $res = $this->query( "SELECT COUNT(*) as NUM FROM user_tables WHERE table_name='"
546 $row = $this->fetchObject($res);
547 $this->freeResult($res);
548 return $row->num
>= 1;
552 * UPDATE wrapper, takes a condition array and a SET array
554 function update( $table, $values, $conds, $fname = 'Database::update' ) {
555 $table = $this->tableName( $table );
557 $sql = "UPDATE $table SET ";
559 foreach ($values as $field => $v) {
564 $sql .= "$field = :n$field ";
566 if ( $conds != '*' ) {
567 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
569 $stmt = $this->parseStatement($sql);
570 if ($stmt === false) {
571 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $stmt );
575 wfDebug("SQL: $sql\n");
577 foreach ($values as $field => $v) {
578 oci_bind_by_name($stmt, ":n$field", $values[$field]);
580 $s .= " [$field] = [$v]\n";
583 wfdebug(" PH: $s\n");
584 $ret = $this->executeStatement($stmt);
589 * INSERT wrapper, inserts an array into a table
591 * $a may be a single associative array, or an array of these with numeric keys, for
594 * Usually aborts on failure
595 * If errors are explicitly ignored, returns success
597 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
598 # No rows to insert, easy just return now
599 if ( !count( $a ) ) {
603 $table = $this->tableName( $table );
604 if (!is_array($options))
605 $options = array($options);
608 if (in_array('IGNORE', $options))
609 $oldIgnore = $this->ignoreErrors( true );
611 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
613 $keys = array_keys( $a[0] );
616 $keys = array_keys( $a );
619 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES (';
622 foreach ($a as $key => $value) {
627 if (is_object($value) && $value->isLOB()) {
628 $sql .= "EMPTY_BLOB()";
629 $return = "RETURNING $key INTO :bobj";
635 if ($this->debug()) {
636 wfDebug("SQL: $sql\n");
639 if (($stmt = $this->parseStatement($sql)) === false) {
640 $this->reportQueryError($this->lastError(), $this->lastErrno(), $sql, $fname);
641 $this->ignoreErrors($oldIgnore);
646 * If we're inserting multiple rows, parse the statement once and
647 * execute it for each set of values. Otherwise, convert it into an
653 foreach ($a as $key => $row) {
657 foreach ($row as $k => $value) {
658 if (is_object($value) && $value->isLOB()) {
659 $blob = oci_new_descriptor($this->mConn
, OCI_D_LOB
);
660 $bdata = $value->data();
661 oci_bind_by_name($stmt, ":bobj", $blob, -1, OCI_B_BLOB
);
663 oci_bind_by_name($stmt, ":$k", $a[$key][$k], -1);
665 $s .= " [$k] = {$row[$k]}";
668 wfDebug(" PH: $s\n");
669 if (($s = $this->executeStatement($stmt)) === false) {
670 $this->reportQueryError($this->lastError(), $this->lastErrno(), $sql, $fname);
671 $this->ignoreErrors($oldIgnore);
679 $this->ignoreErrors($oldIgnore);
680 return $this->mLastResult
= $s;
687 function encodeBlob($b) {
688 return new OracleBlob($b);