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 die( "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 wfDebugDieBacktrace( "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 startTimer( $timeout )
285 wfDebugDieBacktrace( 'Database::startTimer() error : mysql_thread_id() not implemented for postgre' );
286 /*$tid = mysql_thread_id( $this->mConn );
287 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );*/
290 function tableName($name, $forddl = false) {
291 # First run any transformations from the parent object
292 $name = parent
::tableName( $name );
294 # Replace backticks into empty
295 # Note: "foo" and foo are not the same in Oracle!
296 $name = str_replace('`', '', $name);
298 # Now quote Oracle reserved keywords
306 return '"' . $name . '"';
309 return strtoupper($name);
313 function strencode( $s ) {
314 return str_replace("'", "''", $s);
318 * Return the next in a sequence, save the value for retrieval via insertId()
320 function nextSequenceValue( $seqName ) {
321 $r = $this->doQuery("SELECT $seqName.nextval AS val FROM dual");
322 $o = $this->fetchObject($r);
323 $this->freeResult($r);
324 return $this->mInsertId
= (int)$o->val
;
329 * PostgreSQL doesn't have them and returns ""
331 function useIndexClause( $index ) {
335 # REPLACE query wrapper
336 # PostgreSQL simulates this with a DELETE followed by INSERT
337 # $row is the row to insert, an associative array
338 # $uniqueIndexes is an array of indexes. Each element may be either a
339 # field name or an array of field names
341 # It may be more efficient to leave off unique indexes which are unlikely to collide.
342 # However if you do this, you run the risk of encountering errors which wouldn't have
344 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
345 $table = $this->tableName( $table );
347 if (count($rows)==0) {
352 if ( !is_array( reset( $rows ) ) ) {
353 $rows = array( $rows );
356 foreach( $rows as $row ) {
357 # Delete rows which collide
358 if ( $uniqueIndexes ) {
359 $sql = "DELETE FROM $table WHERE ";
361 foreach ( $uniqueIndexes as $index ) {
368 if ( is_array( $index ) ) {
370 foreach ( $index as $col ) {
376 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
379 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
383 $this->query( $sql, $fname );
387 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
388 $this->makeList( $row, LIST_COMMA
) . ')';
389 $this->query( $sql, $fname );
393 # DELETE where the condition is a join
394 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
396 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
399 $delTable = $this->tableName( $delTable );
400 $joinTable = $this->tableName( $joinTable );
401 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
402 if ( $conds != '*' ) {
403 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
407 $this->query( $sql, $fname );
410 # Returns the size of a text field, or -1 for "unlimited"
411 function textFieldSize( $table, $field ) {
412 $table = $this->tableName( $table );
413 $sql = "SELECT t.typname as ftype,a.atttypmod as size
414 FROM pg_class c, pg_attribute a, pg_type t
415 WHERE relname='$table' AND a.attrelid=c.oid AND
416 a.atttypid=t.oid and a.attname='$field'";
417 $res =$this->query($sql);
418 $row=$this->fetchObject($res);
419 if ($row->ftype
=="varchar") {
424 $this->freeResult( $res );
428 function lowPriorityOption() {
432 function limitResult($sql, $limit, $offset) {
433 $ret = "SELECT * FROM ($sql) WHERE ROWNUM < " . ((int)$limit +
(int)($offset+
1));
434 if (is_numeric($offset))
435 $ret .= " AND ROWNUM >= " . (int)$offset;
438 function limitResultForUpdate($sql, $limit) {
442 * Returns an SQL expression for a simple conditional.
443 * Uses CASE on PostgreSQL.
445 * @param string $cond SQL expression which will result in a boolean value
446 * @param string $trueVal SQL expression to return if true
447 * @param string $falseVal SQL expression to return if false
448 * @return string SQL fragment
450 function conditional( $cond, $trueVal, $falseVal ) {
451 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
454 # FIXME: actually detecting deadlocks might be nice
455 function wasDeadlock() {
459 # Return DB-style timestamp used for MySQL schema
460 function timestamp($ts = 0) {
461 return $this->strencode(wfTimestamp(TS_ORACLE
, $ts));
462 # return "TO_TIMESTAMP('" . $this->strencode(wfTimestamp(TS_DB, $ts)) . "', 'RRRR-MM-DD HH24:MI:SS')";
465 function notNullTimestamp() {
466 return "IS NOT NULL";
468 function isNullTimestamp() {
472 * Return aggregated value function call
474 function aggregateValue ($valuedata,$valuename='value') {
479 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
480 $message = "A database error has occurred\n" .
482 "Function: $fname\n" .
483 "Error: $errno $error\n";
484 wfDebugDieBacktrace($message);
488 * @return string wikitext of a link to the server software's web site
490 function getSoftwareLink() {
491 return "[http://www.oracle.com/ Oracle]";
495 * @return string Version information from the database
497 function getServerVersion() {
498 return oci_server_version($this->mConn
);
501 function setSchema($schema=false) {
502 $schemas=$this->mSchemas
;
503 if ($schema) { array_unshift($schemas,$schema); }
504 $searchpath=$this->makeList($schemas,LIST_NAMES
);
505 $this->query("SET search_path = $searchpath");
511 function immediateCommit( $fname = 'Database::immediateCommit' ) {
512 oci_commit($this->mConn
);
513 $this->mTrxLevel
= 0;
515 function rollback( $fname = 'Database::rollback' ) {
516 oci_rollback($this->mConn
);
517 $this->mTrxLevel
= 0;
522 function getStatus() {
523 $result = array('Threads_running' => 0, 'Threads_connected' => 0);
528 * Returns an optional USE INDEX clause to go after the table, and a
529 * string to go at the end of the query
533 * @param array $options an associative array of options to be turned into
534 * an SQL query, valid keys are listed in the function.
537 function makeSelectOptions($options) {
540 if (isset( $options['ORDER BY'])) {
541 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
544 return array('', $tailOpts);
547 function maxListLen() {
552 * Query whether a given table exists
554 function tableExists( $table ) {
555 $table = $this->tableName($table, true);
556 $res = $this->query( "SELECT COUNT(*) as NUM FROM user_tables WHERE table_name='"
560 $row = $this->fetchObject($res);
561 $this->freeResult($res);
562 return $row->num
>= 1;
566 * UPDATE wrapper, takes a condition array and a SET array
568 function update( $table, $values, $conds, $fname = 'Database::update' ) {
569 $table = $this->tableName( $table );
571 $sql = "UPDATE $table SET ";
573 foreach ($values as $field => $v) {
578 $sql .= "$field = :n$field ";
580 if ( $conds != '*' ) {
581 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
583 $stmt = $this->parseStatement($sql);
584 if ($stmt === false) {
585 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $stmt );
589 wfDebug("SQL: $sql\n");
591 foreach ($values as $field => $v) {
592 oci_bind_by_name($stmt, ":n$field", $values[$field]);
594 $s .= " [$field] = [$v]\n";
597 wfdebug(" PH: $s\n");
598 $ret = $this->executeStatement($stmt);
603 * INSERT wrapper, inserts an array into a table
605 * $a may be a single associative array, or an array of these with numeric keys, for
608 * Usually aborts on failure
609 * If errors are explicitly ignored, returns success
611 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
612 # No rows to insert, easy just return now
613 if ( !count( $a ) ) {
617 $table = $this->tableName( $table );
618 if (!is_array($options))
619 $options = array($options);
622 if (in_array('IGNORE', $options))
623 $oldIgnore = $this->ignoreErrors( true );
625 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
627 $keys = array_keys( $a[0] );
630 $keys = array_keys( $a );
633 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES (';
636 foreach ($a as $key => $value) {
641 if (is_object($value) && $value->isLOB()) {
642 $sql .= "EMPTY_BLOB()";
643 $return = "RETURNING $key INTO :bobj";
649 if ($this->debug()) {
650 wfDebug("SQL: $sql\n");
653 if (($stmt = $this->parseStatement($sql)) === false) {
654 $this->reportQueryError($this->lastError(), $this->lastErrno(), $sql, $fname);
655 $this->ignoreErrors($oldIgnore);
660 * If we're inserting multiple rows, parse the statement once and
661 * execute it for each set of values. Otherwise, convert it into an
667 foreach ($a as $key => $row) {
671 foreach ($row as $k => $value) {
672 if (is_object($value) && $value->isLOB()) {
673 $blob = oci_new_descriptor($this->mConn
, OCI_D_LOB
);
674 $bdata = $value->data();
675 oci_bind_by_name($stmt, ":bobj", &$blob, -1, OCI_B_BLOB
);
677 oci_bind_by_name($stmt, ":$k", $a[$key][$k], -1);
679 $s .= " [$k] = {$row[$k]}";
682 wfDebug(" PH: $s\n");
683 if (($s = $this->executeStatement($stmt)) === false) {
684 $this->reportQueryError($this->lastError(), $this->lastErrno(), $sql, $fname);
685 $this->ignoreErrors($oldIgnore);
693 $this->ignoreErrors($oldIgnore);
694 return $this->mLastResult
= $s;
701 function encodeBlob($b) {
702 return new OracleBlob($b);