3 * This is the Oracle database abstraction layer.
10 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
11 * other things. We use a wrapper class to handle that and other
12 * Oracle-specific bits, like converting column names back to lowercase.
20 private $columns = array();
22 private function array_unique_md( $array_in ) {
24 $array_hashes = array();
26 foreach ( $array_in as $item ) {
27 $hash = md5( serialize( $item ) );
28 if ( !isset( $array_hashes[$hash] ) ) {
29 $array_hashes[$hash] = $hash;
37 function __construct( &$db, $stmt, $unique = false ) {
40 if ( ( $this->nrows
= oci_fetch_all( $stmt, $this->rows
, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM
) ) === false ) {
41 $e = oci_error( $stmt );
42 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__
);
48 $this->rows
= $this->array_unique_md( $this->rows
);
49 $this->nrows
= count( $this->rows
);
52 if ($this->nrows
> 0) {
53 foreach ( $this->rows
[0] as $k => $v ) {
54 $this->columns
[$k] = strtolower( oci_field_name( $stmt, $k +
1 ) );
59 oci_free_statement( $stmt );
62 public function free() {
66 public function seek( $row ) {
67 $this->cursor
= min( $row, $this->nrows
);
70 public function numRows() {
74 public function numFields() {
75 return count($this->columns
);
78 public function fetchObject() {
79 if ( $this->cursor
>= $this->nrows
) {
82 $row = $this->rows
[$this->cursor++
];
83 $ret = new stdClass();
84 foreach ( $row as $k => $v ) {
85 $lc = $this->columns
[$k];
92 public function fetchRow() {
93 if ( $this->cursor
>= $this->nrows
) {
97 $row = $this->rows
[$this->cursor++
];
99 foreach ( $row as $k => $v ) {
100 $lc = $this->columns
[$k];
112 class ORAField
implements Field
{
113 private $name, $tablename, $default, $max_length, $nullable,
114 $is_pk, $is_unique, $is_multiple, $is_key, $type;
116 function __construct( $info ) {
117 $this->name
= $info['column_name'];
118 $this->tablename
= $info['table_name'];
119 $this->default = $info['data_default'];
120 $this->max_length
= $info['data_length'];
121 $this->nullable
= $info['not_null'];
122 $this->is_pk
= isset( $info['prim'] ) && $info['prim'] == 1 ?
1 : 0;
123 $this->is_unique
= isset( $info['uniq'] ) && $info['uniq'] == 1 ?
1 : 0;
124 $this->is_multiple
= isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ?
1 : 0;
125 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
126 $this->type
= $info['data_type'];
133 function tableName() {
134 return $this->tablename
;
137 function defaultValue() {
138 return $this->default;
141 function maxLength() {
142 return $this->max_length
;
145 function isNullable() {
146 return $this->nullable
;
150 return $this->is_key
;
153 function isMultipleKey() {
154 return $this->is_multiple
;
165 class DatabaseOracle
extends DatabaseBase
{
166 var $mInsertId = null;
167 var $mLastResult = null;
168 var $lastResult = null;
172 var $ignore_DUP_VAL_ON_INDEX = false;
173 var $sequenceData = null;
175 var $defaultCharset = 'AL32UTF8';
177 var $mFieldInfoCache = array();
179 function __construct( $server = false, $user = false, $password = false, $dbName = false,
180 $flags = 0, $tablePrefix = 'get from global' )
183 $tablePrefix = $tablePrefix == 'get from global' ?
strtoupper( $wgDBprefix ) : strtoupper( $tablePrefix );
184 parent
::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
185 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
188 function __destruct() {
189 if ($this->mOpened
) {
190 wfSuppressWarnings();
200 function cascadingDeletes() {
203 function cleanupTriggers() {
206 function strictIPs() {
209 function realTimestamps() {
212 function implicitGroupby() {
215 function implicitOrderby() {
218 function searchableIPs() {
223 * Usually aborts on failure
225 function open( $server, $user, $password, $dbName ) {
226 if ( !function_exists( 'oci_connect' ) ) {
227 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" );
231 $this->mUser
= $user;
232 $this->mPassword
= $password;
233 // changed internal variables functions
234 // mServer now holds the TNS endpoint
235 // mDBname is schema name if different from username
237 // backward compatibillity (server used to be null and TNS was supplied in dbname)
238 $this->mServer
= $dbName;
239 $this->mDBname
= $user;
241 $this->mServer
= $server;
243 $this->mDBname
= $user;
245 $this->mDBname
= $dbName;
249 if ( !strlen( $user ) ) { # e.g. the class is being loaded
253 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
254 wfSuppressWarnings();
255 if ( $this->mFlags
& DBO_DEFAULT
) {
256 $this->mConn
= oci_new_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
258 $this->mConn
= oci_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
262 if ( $this->mUser
!= $this->mDBname
) {
263 //change current schema in session
264 $this->selectDB( $this->mDBname
);
267 if ( !$this->mConn
) {
268 throw new DBConnectionError( $this, $this->lastError() );
271 $this->mOpened
= true;
273 # removed putenv calls because they interfere with the system globaly
274 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
275 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
280 * Closes a database connection, if it is open
281 * Returns success, true if already closed
284 $this->mOpened
= false;
285 if ( $this->mConn
) {
286 if ( $this->mTrxLevel
) {
289 return oci_close( $this->mConn
);
295 function execFlags() {
296 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
299 function doQuery( $sql ) {
300 wfDebug( "SQL: [$sql]\n" );
301 if ( !mb_check_encoding( $sql ) ) {
302 throw new MWException( "SQL encoding is invalid\n$sql" );
305 // handle some oracle specifics
306 // remove AS column/table/subquery namings
307 if( !$this->getFlag( DBO_DDLMODE
) ) {
308 $sql = preg_replace( '/ as /i', ' ', $sql );
311 // Oracle has issues with UNION clause if the statement includes LOB fields
312 // So we do a UNION ALL and then filter the results array with array_unique
313 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
314 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
315 // you have to select data from plan table after explain
316 $explain_id = date( 'dmYHis' );
318 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
320 wfSuppressWarnings();
322 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
323 $e = oci_error( $this->mConn
);
324 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
328 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
329 $e = oci_error( $stmt );
330 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
331 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
338 if ( $explain_count > 0 ) {
339 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
340 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
341 return new ORAResult( $this, $stmt, $union_unique );
343 $this->mAffectedRows
= oci_num_rows( $stmt );
348 function queryIgnore( $sql, $fname = '' ) {
349 return $this->query( $sql, $fname, true );
352 function freeResult( $res ) {
353 if ( $res instanceof ResultWrapper
) {
360 function fetchObject( $res ) {
361 if ( $res instanceof ResultWrapper
) {
365 return $res->fetchObject();
368 function fetchRow( $res ) {
369 if ( $res instanceof ResultWrapper
) {
373 return $res->fetchRow();
376 function numRows( $res ) {
377 if ( $res instanceof ResultWrapper
) {
381 return $res->numRows();
384 function numFields( $res ) {
385 if ( $res instanceof ResultWrapper
) {
389 return $res->numFields();
392 function fieldName( $stmt, $n ) {
393 return oci_field_name( $stmt, $n );
397 * This must be called after nextSequenceVal
399 function insertId() {
400 return $this->mInsertId
;
403 function dataSeek( $res, $row ) {
404 if ( $res instanceof ORAResult
) {
407 $res->result
->seek( $row );
411 function lastError() {
412 if ( $this->mConn
=== false ) {
415 $e = oci_error( $this->mConn
);
417 return $e['message'];
420 function lastErrno() {
421 if ( $this->mConn
=== false ) {
424 $e = oci_error( $this->mConn
);
429 function affectedRows() {
430 return $this->mAffectedRows
;
434 * Returns information about an index
435 * If errors are explicitly ignored, returns NULL on failure
437 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
441 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
445 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
446 if ( !count( $a ) ) {
450 if ( !is_array( $options ) ) {
451 $options = array( $options );
454 if ( in_array( 'IGNORE', $options ) ) {
455 $this->ignore_DUP_VAL_ON_INDEX
= true;
458 if ( !is_array( reset( $a ) ) ) {
462 foreach ( $a as &$row ) {
463 $this->insertOneRow( $table, $row, $fname );
467 if ( in_array( 'IGNORE', $options ) ) {
468 $this->ignore_DUP_VAL_ON_INDEX
= false;
474 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
475 $col_info = $this->fieldInfoMulti( $table, $col );
476 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
479 if ( is_numeric( $col ) ) {
483 } else if ( $includeCol ) {
487 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
491 if ( $val === null ) {
492 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
504 private function insertOneRow( $table, $row, $fname ) {
507 $table = $this->tableName( $table );
508 // "INSERT INTO tables (a, b, c)"
509 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
512 // for each value, append ":key"
514 foreach ( $row as $col => &$val ) {
521 $sql .= $this->fieldBindStatement( $table, $col, $val );
525 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
526 $e = oci_error( $this->mConn
);
527 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
530 foreach ( $row as $col => &$val ) {
531 $col_info = $this->fieldInfoMulti( $table, $col );
532 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
534 if ( $val === null ) {
535 // do nothing ... null was inserted in statement creation
536 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
537 if ( is_object( $val ) ) {
538 $val = $val->fetch();
541 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
542 $val = '31-12-2030 12:00:00.000000';
545 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
546 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
547 $e = oci_error( $stmt );
548 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
552 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
553 $e = oci_error( $stmt );
554 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
557 if ( is_object( $val ) ) {
558 $val = $val->fetch();
561 if ( $col_type == 'BLOB' ) {
562 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
563 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB
);
565 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
566 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
571 wfSuppressWarnings();
573 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
574 $e = oci_error( $stmt );
575 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
576 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
579 $this->mAffectedRows
= oci_num_rows( $stmt );
582 $this->mAffectedRows
= oci_num_rows( $stmt );
587 if ( isset( $lob ) ) {
588 foreach ( $lob as $lob_v ) {
593 if ( !$this->mTrxLevel
) {
594 oci_commit( $this->mConn
);
597 oci_free_statement( $stmt );
600 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
601 $insertOptions = array(), $selectOptions = array() )
603 $destTable = $this->tableName( $destTable );
604 if ( !is_array( $selectOptions ) ) {
605 $selectOptions = array( $selectOptions );
607 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
608 if ( is_array( $srcTable ) ) {
609 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
611 $srcTable = $this->tableName( $srcTable );
614 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
615 !isset( $varMap[$sequenceData['column']] ) )
617 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
620 // count-alias subselect fields to avoid abigious definition errors
622 foreach ( $varMap as &$val ) {
623 $val = $val . ' field' . ( $i++
);
626 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
627 " SELECT $startOpts " . implode( ',', $varMap ) .
628 " FROM $srcTable $useIndex ";
629 if ( $conds != '*' ) {
630 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
632 $sql .= " $tailOpts";
634 if ( in_array( 'IGNORE', $insertOptions ) ) {
635 $this->ignore_DUP_VAL_ON_INDEX
= true;
638 $retval = $this->query( $sql, $fname );
640 if ( in_array( 'IGNORE', $insertOptions ) ) {
641 $this->ignore_DUP_VAL_ON_INDEX
= false;
647 function tableName( $name, $quoted = true ) {
649 Replace reserved words with better ones
650 Using uppercase because that's the only way Oracle can handle
658 $name = 'PAGECONTENT';
662 return parent
::tableName( strtoupper( $name ), $quoted );
665 function tableNameInternal( $name ) {
666 $name = $this->tableName( $name );
667 return preg_replace( '/.*\.(.*)/', '$1', $name);
670 * Return the next in a sequence, save the value for retrieval via insertId()
672 function nextSequenceValue( $seqName ) {
673 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
674 $row = $this->fetchRow( $res );
675 $this->mInsertId
= $row[0];
676 return $this->mInsertId
;
680 * Return sequence_name if table has a sequence
682 private function getSequenceData( $table ) {
683 if ( $this->sequenceData
== null ) {
684 $result = $this->doQuery( 'SELECT lower(us.sequence_name), lower(utc.table_name), lower(utc.column_name) from user_sequences us, user_tab_columns utc where us.sequence_name = utc.table_name||\'_\'||utc.column_name||\'_SEQ\'' );
686 while ( ( $row = $result->fetchRow() ) !== false ) {
687 $this->sequenceData
[$this->tableName( $row[1] )] = array(
688 'sequence' => $row[0],
694 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
698 * REPLACE query wrapper
699 * Oracle simulates this with a DELETE followed by INSERT
700 * $row is the row to insert, an associative array
701 * $uniqueIndexes is an array of indexes. Each element may be either a
702 * field name or an array of field names
704 * It may be more efficient to leave off unique indexes which are unlikely to collide.
705 * However if you do this, you run the risk of encountering errors which wouldn't have
708 * @param $table String: table name
709 * @param $uniqueIndexes Array: array of indexes. Each element may be
710 * either a field name or an array of field names
711 * @param $rows Array: rows to insert to $table
712 * @param $fname String: function name, you can use __METHOD__ here
714 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
715 $table = $this->tableName( $table );
717 if ( count( $rows ) == 0 ) {
722 if ( !is_array( reset( $rows ) ) ) {
723 $rows = array( $rows );
726 $sequenceData = $this->getSequenceData( $table );
728 foreach ( $rows as $row ) {
729 # Delete rows which collide
730 if ( $uniqueIndexes ) {
731 $condsDelete = array();
732 foreach ( $uniqueIndexes as $index ) {
733 $condsDelete[$index] = $row[$index];
735 if ( count( $condsDelete ) > 0 ) {
736 $this->delete( $table, $condsDelete, $fname );
740 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
741 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
745 $this->insert( $table, $row, $fname );
749 # DELETE where the condition is a join
750 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
752 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
755 $delTable = $this->tableName( $delTable );
756 $joinTable = $this->tableName( $joinTable );
757 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
758 if ( $conds != '*' ) {
759 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
763 $this->query( $sql, $fname );
766 # Returns the size of a text field, or -1 for "unlimited"
767 function textFieldSize( $table, $field ) {
768 $fieldInfoData = $this->fieldInfo( $table, $field );
769 return $fieldInfoData->maxLength();
772 function limitResult( $sql, $limit, $offset = false ) {
773 if ( $offset === false ) {
776 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
779 function encodeBlob( $b ) {
780 return new Blob( $b );
783 function decodeBlob( $b ) {
784 if ( $b instanceof Blob
) {
790 function unionQueries( $sqls, $all ) {
791 $glue = ' UNION ALL ';
792 return 'SELECT * ' . ( $all ?
'':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
795 function wasDeadlock() {
796 return $this->lastErrno() == 'OCI-00060';
799 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
801 $this->setFlag( DBO_DDLMODE
);
803 $temporary = $temporary ?
'TRUE' : 'FALSE';
805 $newName = strtoupper( $newName );
806 $oldName = strtoupper( $oldName );
808 $tabName = $this->addIdentifierQuotes( substr( $newName, strlen( $wgDBprefix ) ) );
809 $oldPrefix = $this->addIdentifierQuotes( substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) ) );
810 $newPrefix = $this->addIdentifierQuotes( $wgDBprefix );
812 $this->clearFlag( DBO_DDLMODE
);
813 return $this->doQuery( "BEGIN DUPLICATE_TABLE( $tabName, $oldPrefix, $newPrefix, $temporary ); END;" );
816 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
818 if (!empty($prefix)) {
819 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
822 $result = $this->doQuery( "SELECT table_name FROM user_tables WHERE table_name NOT LIKE '%!_IDX$_' ESCAPE '!' $listWhere" );
824 // dirty code ... i know
826 $endArray[] = $prefix.'MWUSER';
827 $endArray[] = $prefix.'PAGE';
828 $endArray[] = $prefix.'IMAGE';
829 $fixedOrderTabs = $endArray;
830 while (($row = $result->fetchRow()) !== false) {
831 if (!in_array($row['table_name'], $fixedOrderTabs))
832 $endArray[] = $row['table_name'];
838 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
839 $tableName = $this->tableName($tableName);
840 if( !$this->tableExists( $tableName ) ) {
844 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
847 function timestamp( $ts = 0 ) {
848 return wfTimestamp( TS_ORACLE
, $ts );
852 * Return aggregated value function call
854 function aggregateValue ( $valuedata, $valuename = 'value' ) {
858 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
859 # Ignore errors during error handling to avoid infinite
861 $ignore = $this->ignoreErrors( true );
862 ++
$this->mErrorCount
;
864 if ( $ignore ||
$tempIgnore ) {
865 wfDebug( "SQL ERROR (ignored): $error\n" );
866 $this->ignoreErrors( $ignore );
868 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
873 * @return string wikitext of a link to the server software's web site
875 public static function getSoftwareLink() {
876 return '[http://www.oracle.com/ Oracle]';
880 * @return string Version information from the database
882 function getServerVersion() {
883 //better version number, fallback on driver
884 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
885 if ( !( $row = $rset->fetchRow() ) ) {
886 return oci_server_version( $this->mConn
);
888 return $row['version'];
892 * Query whether a given table exists (in the given schema, or the default mw one if not given)
894 function tableExists( $table ) {
895 $table = $this->removeIdentifierQuotes($table);
896 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
897 $res = $this->doQuery( $SQL );
899 $count = $res->numRows();
908 * Function translates mysql_fetch_field() functionality on ORACLE.
909 * Caching is present for reducing query time.
910 * For internal calls. Use fieldInfo for normal usage.
911 * Returns false if the field doesn't exist
913 * @param $table Array
914 * @param $field String
917 private function fieldInfoMulti( $table, $field ) {
918 $field = strtoupper( $field );
919 if ( is_array( $table ) ) {
920 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
921 $tableWhere = 'IN (';
922 foreach( $table as &$singleTable ) {
923 $singleTable = $this->removeIdentifierQuotes($singleTable);
924 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
925 return $this->mFieldInfoCache
["$singleTable.$field"];
927 $tableWhere .= '\'' . $singleTable . '\',';
929 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
931 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
932 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
933 return $this->mFieldInfoCache
["$table.$field"];
935 $tableWhere = '= \''.$table.'\'';
938 $fieldInfoStmt = oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
939 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
940 $e = oci_error( $fieldInfoStmt );
941 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
944 $res = new ORAResult( $this, $fieldInfoStmt );
945 if ( $res->numRows() == 0 ) {
946 if ( is_array( $table ) ) {
947 foreach( $table as &$singleTable ) {
948 $this->mFieldInfoCache
["$singleTable.$field"] = false;
951 $this->mFieldInfoCache
["$table.$field"] = false;
953 $fieldInfoTemp = null;
955 $fieldInfoTemp = new ORAField( $res->fetchRow() );
956 $table = $fieldInfoTemp->tableName();
957 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
960 return $fieldInfoTemp;
964 * @throws DBUnexpectedError
969 function fieldInfo( $table, $field ) {
970 if ( is_array( $table ) ) {
971 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
973 return $this->fieldInfoMulti ($table, $field);
976 function begin( $fname = 'DatabaseOracle::begin' ) {
977 $this->mTrxLevel
= 1;
980 function commit( $fname = 'DatabaseOracle::commit' ) {
981 if ( $this->mTrxLevel
) {
982 oci_commit( $this->mConn
);
983 $this->mTrxLevel
= 0;
987 function rollback( $fname = 'DatabaseOracle::rollback' ) {
988 if ( $this->mTrxLevel
) {
989 oci_rollback( $this->mConn
);
990 $this->mTrxLevel
= 0;
994 /* Not even sure why this is used in the main codebase... */
995 function limitResultForUpdate( $sql, $num ) {
999 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
1000 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
1003 $dollarquote = false;
1005 $replacements = array();
1007 while ( ! feof( $fp ) ) {
1008 if ( $lineCallback ) {
1009 call_user_func( $lineCallback );
1011 $line = trim( fgets( $fp, 1024 ) );
1012 $sl = strlen( $line ) - 1;
1017 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1021 // Allow dollar quoting for function declarations
1022 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1023 if ( $dollarquote ) {
1024 $dollarquote = false;
1025 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1028 $dollarquote = true;
1030 } elseif ( !$dollarquote ) {
1031 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
1033 $line = substr( $line, 0, $sl );
1043 $cmd = str_replace( ';;', ";", $cmd );
1044 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1045 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1046 $replacements[$defines[2]] = $defines[1];
1049 foreach ( $replacements as $mwVar => $scVar ) {
1050 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1053 $cmd = $this->replaceVars( $cmd );
1054 $res = $this->doQuery( $cmd );
1055 if ( $resultCallback ) {
1056 call_user_func( $resultCallback, $res, $this );
1059 if ( false === $res ) {
1060 $err = $this->lastError();
1061 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1072 function selectDB( $db ) {
1073 $this->mDBname
= $db;
1074 if ( $db == null ||
$db == $this->mUser
) {
1077 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1078 $stmt = oci_parse( $this->mConn
, $sql );
1079 wfSuppressWarnings();
1080 $success = oci_execute( $stmt );
1081 wfRestoreWarnings();
1083 $e = oci_error( $stmt );
1084 if ( $e['code'] != '1435' ) {
1085 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1092 function strencode( $s ) {
1093 return str_replace( "'", "''", $s );
1096 function addQuotes( $s ) {
1098 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1099 $s = $wgContLang->checkTitleEncoding( $s );
1101 return "'" . $this->strencode( $s ) . "'";
1104 public function addIdentifierQuotes( $s ) {
1105 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1111 public function removeIdentifierQuotes( $s ) {
1112 return strpos($s, '/*Q*/') === FALSE ?
$s : substr($s, 5);
1115 public function isQuotedIdentifier( $s ) {
1116 return strpos($s, '/*Q*/') !== FALSE;
1119 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1122 if ($conds != null) {
1124 $conds = ( !is_array( $conds ) ) ?
array( $conds ) : $conds;
1125 foreach ( $conds as $col => $val ) {
1126 $col_info = $this->fieldInfoMulti( $table, $col );
1127 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1128 if ( $col_type == 'CLOB' ) {
1129 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1130 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1131 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1133 $conds2[$col] = $val;
1137 return parent
::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1139 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1144 * Returns an optional USE INDEX clause to go after the table, and a
1145 * string to go at the end of the query
1149 * @param $options Array: an associative array of options to be turned into
1150 * an SQL query, valid keys are listed in the function.
1153 function makeSelectOptions( $options ) {
1154 $preLimitTail = $postLimitTail = '';
1157 $noKeyOptions = array();
1158 foreach ( $options as $key => $option ) {
1159 if ( is_numeric( $key ) ) {
1160 $noKeyOptions[$option] = true;
1164 if ( isset( $options['GROUP BY'] ) ) {
1165 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1167 if ( isset( $options['ORDER BY'] ) ) {
1168 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1171 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1172 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1173 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1174 $startOpts .= 'DISTINCT';
1177 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1178 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1183 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1186 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1189 if ( $wgContLang != null && $conds != null && $conds != '*' ) {
1191 $conds = ( !is_array( $conds ) ) ?
array( $conds ) : $conds;
1192 foreach ( $conds as $col => $val ) {
1193 $col_info = $this->fieldInfoMulti( $table, $col );
1194 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1195 if ( $col_type == 'CLOB' ) {
1196 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1198 if ( is_array( $val ) ) {
1199 $conds2[$col] = $val;
1200 foreach ( $conds2[$col] as &$val2 ) {
1201 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1204 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1209 return parent
::delete( $table, $conds2, $fname );
1211 return parent
::delete( $table, $conds, $fname );
1215 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1218 $table = $this->tableName( $table );
1219 $opts = $this->makeUpdateOptions( $options );
1220 $sql = "UPDATE $opts $table SET ";
1223 foreach ( $values as $col => &$val ) {
1224 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1227 $sqlSet = ', ' . $sqlSet;
1234 if ( $conds != '*' ) {
1235 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1238 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1239 $e = oci_error( $this->mConn
);
1240 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1243 foreach ( $values as $col => &$val ) {
1244 $col_info = $this->fieldInfoMulti( $table, $col );
1245 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1247 if ( $val === null ) {
1248 // do nothing ... null was inserted in statement creation
1249 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1250 if ( is_object( $val ) ) {
1251 $val = $val->getData();
1254 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1255 $val = '31-12-2030 12:00:00.000000';
1258 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1259 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1260 $e = oci_error( $stmt );
1261 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1265 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1266 $e = oci_error( $stmt );
1267 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1270 if ( $col_type == 'BLOB' ) {
1271 $lob[$col]->writeTemporary( $val );
1272 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
1274 $lob[$col]->writeTemporary( $val );
1275 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
1280 wfSuppressWarnings();
1282 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1283 $e = oci_error( $stmt );
1284 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
1285 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1288 $this->mAffectedRows
= oci_num_rows( $stmt );
1291 $this->mAffectedRows
= oci_num_rows( $stmt );
1294 wfRestoreWarnings();
1296 if ( isset( $lob ) ) {
1297 foreach ( $lob as $lob_v ) {
1302 if ( !$this->mTrxLevel
) {
1303 oci_commit( $this->mConn
);
1306 oci_free_statement( $stmt );
1309 function bitNot( $field ) {
1310 // expecting bit-fields smaller than 4bytes
1311 return 'BITNOT(' . $field . ')';
1314 function bitAnd( $fieldLeft, $fieldRight ) {
1315 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1318 function bitOr( $fieldLeft, $fieldRight ) {
1319 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1322 function setFakeMaster( $enabled = true ) { }
1324 function getDBname() {
1325 return $this->mDBname
;
1328 function getServer() {
1329 return $this->mServer
;
1332 public function getSearchEngine() {
1333 return 'SearchOracle';
1335 } // end DatabaseOracle class