3 * This is the Oracle database abstraction layer.
15 function __construct( $data ) {
25 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
26 * other things. We use a wrapper class to handle that and other
27 * Oracle-specific bits, like converting column names back to lowercase.
35 private $columns = array();
37 private function array_unique_md( $array_in ) {
39 $array_hashes = array();
41 foreach ( $array_in as $item ) {
42 $hash = md5( serialize( $item ) );
43 if ( !isset( $array_hashes[$hash] ) ) {
44 $array_hashes[$hash] = $hash;
52 function __construct( &$db, $stmt, $unique = false ) {
55 if ( ( $this->nrows
= oci_fetch_all( $stmt, $this->rows
, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM
) ) === false ) {
56 $e = oci_error( $stmt );
57 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__
);
63 $this->rows
= $this->array_unique_md( $this->rows
);
64 $this->nrows
= count( $this->rows
);
67 if ($this->nrows
> 0) {
68 foreach ( $this->rows
[0] as $k => $v ) {
69 $this->columns
[$k] = strtolower( oci_field_name( $stmt, $k +
1 ) );
74 oci_free_statement( $stmt );
77 public function free() {
81 public function seek( $row ) {
82 $this->cursor
= min( $row, $this->nrows
);
85 public function numRows() {
89 public function numFields() {
90 return count($this->columns
);
93 public function fetchObject() {
94 if ( $this->cursor
>= $this->nrows
) {
97 $row = $this->rows
[$this->cursor++
];
98 $ret = new stdClass();
99 foreach ( $row as $k => $v ) {
100 $lc = $this->columns
[$k];
107 public function fetchRow() {
108 if ( $this->cursor
>= $this->nrows
) {
112 $row = $this->rows
[$this->cursor++
];
114 foreach ( $row as $k => $v ) {
115 $lc = $this->columns
[$k];
127 class ORAField
implements Field
{
128 private $name, $tablename, $default, $max_length, $nullable,
129 $is_pk, $is_unique, $is_multiple, $is_key, $type;
131 function __construct( $info ) {
132 $this->name
= $info['column_name'];
133 $this->tablename
= $info['table_name'];
134 $this->default = $info['data_default'];
135 $this->max_length
= $info['data_length'];
136 $this->nullable
= $info['not_null'];
137 $this->is_pk
= isset( $info['prim'] ) && $info['prim'] == 1 ?
1 : 0;
138 $this->is_unique
= isset( $info['uniq'] ) && $info['uniq'] == 1 ?
1 : 0;
139 $this->is_multiple
= isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ?
1 : 0;
140 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
141 $this->type
= $info['data_type'];
148 function tableName() {
149 return $this->tablename
;
152 function defaultValue() {
153 return $this->default;
156 function maxLength() {
157 return $this->max_length
;
160 function isNullable() {
161 return $this->nullable
;
165 return $this->is_key
;
168 function isMultipleKey() {
169 return $this->is_multiple
;
180 class DatabaseOracle
extends DatabaseBase
{
181 var $mInsertId = null;
182 var $mLastResult = null;
183 var $numeric_version = null;
184 var $lastResult = null;
188 var $ignore_DUP_VAL_ON_INDEX = false;
189 var $sequenceData = null;
191 var $defaultCharset = 'AL32UTF8';
193 var $mFieldInfoCache = array();
195 function __construct( $server = false, $user = false, $password = false, $dbName = false,
196 $flags = 0, $tablePrefix = 'get from global' )
198 $tablePrefix = $tablePrefix == 'get from global' ?
$tablePrefix : strtoupper( $tablePrefix );
199 parent
::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
200 wfRunHooks( 'DatabaseOraclePostInit', array( &$this ) );
207 function cascadingDeletes() {
210 function cleanupTriggers() {
213 function strictIPs() {
216 function realTimestamps() {
219 function implicitGroupby() {
222 function implicitOrderby() {
225 function searchableIPs() {
229 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 )
231 return new DatabaseOracle( $server, $user, $password, $dbName, $flags );
235 * Usually aborts on failure
237 function open( $server, $user, $password, $dbName ) {
238 if ( !function_exists( 'oci_connect' ) ) {
239 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" );
243 $this->mUser
= $user;
244 $this->mPassword
= $password;
245 // changed internal variables functions
246 // mServer now holds the TNS endpoint
247 // mDBname is schema name if different from username
249 // backward compatibillity (server used to be null and TNS was supplied in dbname)
250 $this->mServer
= $dbName;
251 $this->mDBname
= $user;
253 $this->mServer
= $server;
255 $this->mDBname
= $user;
257 $this->mDBname
= $dbName;
261 if ( !strlen( $user ) ) { # e.g. the class is being loaded
265 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
266 if ( $this->mFlags
& DBO_DEFAULT
) {
267 $this->mConn
= oci_new_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
269 $this->mConn
= oci_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
272 if ( $this->mUser
!= $this->mDBname
) {
273 //change current schema in session
274 $this->selectDB( $this->mDBname
);
277 if ( !$this->mConn
) {
278 throw new DBConnectionError( $this, $this->lastError() );
281 $this->mOpened
= true;
283 # removed putenv calls because they interfere with the system globaly
284 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
285 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
290 * Closes a database connection, if it is open
291 * Returns success, true if already closed
294 $this->mOpened
= false;
295 if ( $this->mConn
) {
296 return oci_close( $this->mConn
);
302 function execFlags() {
303 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
306 function doQuery( $sql ) {
307 wfDebug( "SQL: [$sql]\n" );
308 if ( !mb_check_encoding( $sql ) ) {
309 throw new MWException( "SQL encoding is invalid\n$sql" );
312 // handle some oracle specifics
313 // remove AS column/table/subquery namings
314 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
315 $sql = preg_replace( '/ as /i', ' ', $sql );
317 // Oracle has issues with UNION clause if the statement includes LOB fields
318 // So we do a UNION ALL and then filter the results array with array_unique
319 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
320 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
321 // you have to select data from plan table after explain
322 $explain_id = date( 'dmYHis' );
324 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
326 wfSuppressWarnings();
328 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
329 $e = oci_error( $this->mConn
);
330 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
334 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
335 $e = oci_error( $stmt );
336 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
337 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
344 if ( $explain_count > 0 ) {
345 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
346 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
347 return new ORAResult( $this, $stmt, $union_unique );
349 $this->mAffectedRows
= oci_num_rows( $stmt );
354 function queryIgnore( $sql, $fname = '' ) {
355 return $this->query( $sql, $fname, true );
358 function freeResult( $res ) {
359 if ( $res instanceof ResultWrapper
) {
366 function fetchObject( $res ) {
367 if ( $res instanceof ResultWrapper
) {
371 return $res->fetchObject();
374 function fetchRow( $res ) {
375 if ( $res instanceof ResultWrapper
) {
379 return $res->fetchRow();
382 function numRows( $res ) {
383 if ( $res instanceof ResultWrapper
) {
387 return $res->numRows();
390 function numFields( $res ) {
391 if ( $res instanceof ResultWrapper
) {
395 return $res->numFields();
398 function fieldName( $stmt, $n ) {
399 return oci_field_name( $stmt, $n );
403 * This must be called after nextSequenceVal
405 function insertId() {
406 return $this->mInsertId
;
409 function dataSeek( $res, $row ) {
410 if ( $res instanceof ORAResult
) {
413 $res->result
->seek( $row );
417 function lastError() {
418 if ( $this->mConn
=== false ) {
421 $e = oci_error( $this->mConn
);
423 return $e['message'];
426 function lastErrno() {
427 if ( $this->mConn
=== false ) {
430 $e = oci_error( $this->mConn
);
435 function affectedRows() {
436 return $this->mAffectedRows
;
440 * Returns information about an index
441 * If errors are explicitly ignored, returns NULL on failure
443 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
447 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
451 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
452 if ( !count( $a ) ) {
456 if ( !is_array( $options ) ) {
457 $options = array( $options );
460 if ( in_array( 'IGNORE', $options ) ) {
461 $this->ignore_DUP_VAL_ON_INDEX
= true;
464 if ( !is_array( reset( $a ) ) ) {
468 foreach ( $a as &$row ) {
469 $this->insertOneRow( $table, $row, $fname );
473 if ( in_array( 'IGNORE', $options ) ) {
474 $this->ignore_DUP_VAL_ON_INDEX
= false;
480 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
481 $col_info = $this->fieldInfoMulti( $table, $col );
482 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
485 if ( is_numeric( $col ) ) {
489 } else if ( $includeCol ) {
493 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
497 if ( $val === null ) {
498 if ( $col_info != false && $col_info->nullable() == 0 && $col_info->defaultValue() != null ) {
510 private function insertOneRow( $table, $row, $fname ) {
513 $table = $this->tableName( $table );
514 // "INSERT INTO tables (a, b, c)"
515 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
518 // for each value, append ":key"
520 foreach ( $row as $col => &$val ) {
527 $sql .= $this->fieldBindStatement( $table, $col, $val );
531 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
532 $e = oci_error( $this->mConn
);
533 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
536 foreach ( $row as $col => &$val ) {
537 $col_info = $this->fieldInfoMulti( $table, $col );
538 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
540 if ( $val === null ) {
541 // do nothing ... null was inserted in statement creation
542 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
543 if ( is_object( $val ) ) {
544 $val = $val->fetch();
547 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
548 $val = '31-12-2030 12:00:00.000000';
551 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
552 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
553 $e = oci_error( $stmt );
554 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
558 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
559 $e = oci_error( $stmt );
560 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
563 if ( is_object( $val ) ) {
564 $val = $val->fetch();
567 if ( $col_type == 'BLOB' ) {
568 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
569 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB
);
571 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
572 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
577 wfSuppressWarnings();
579 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
580 $e = oci_error( $stmt );
581 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
582 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
585 $this->mAffectedRows
= oci_num_rows( $stmt );
588 $this->mAffectedRows
= oci_num_rows( $stmt );
593 if ( isset( $lob ) ) {
594 foreach ( $lob as $lob_v ) {
599 if ( !$this->mTrxLevel
) {
600 oci_commit( $this->mConn
);
603 oci_free_statement( $stmt );
606 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
607 $insertOptions = array(), $selectOptions = array() )
609 $destTable = $this->tableName( $destTable );
610 if ( !is_array( $selectOptions ) ) {
611 $selectOptions = array( $selectOptions );
613 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
614 if ( is_array( $srcTable ) ) {
615 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
617 $srcTable = $this->tableName( $srcTable );
620 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
621 !isset( $varMap[$sequenceData['column']] ) )
623 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
626 // count-alias subselect fields to avoid abigious definition errors
628 foreach ( $varMap as &$val ) {
629 $val = $val . ' field' . ( $i++
);
632 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
633 " SELECT $startOpts " . implode( ',', $varMap ) .
634 " FROM $srcTable $useIndex ";
635 if ( $conds != '*' ) {
636 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
638 $sql .= " $tailOpts";
640 if ( in_array( 'IGNORE', $insertOptions ) ) {
641 $this->ignore_DUP_VAL_ON_INDEX
= true;
644 $retval = $this->query( $sql, $fname );
646 if ( in_array( 'IGNORE', $insertOptions ) ) {
647 $this->ignore_DUP_VAL_ON_INDEX
= false;
653 function tableName( $name ) {
654 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
656 Replace reserved words with better ones
657 Using uppercase because that's the only way Oracle can handle
665 $name = 'PAGECONTENT';
670 The rest of procedure is equal to generic Databse class
671 except for the quoting style
673 if ( $name[0] == '"' && substr( $name, - 1, 1 ) == '"' ) {
676 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
679 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
680 if ( isset( $dbDetails[1] ) ) {
681 @list
( $table, $database ) = $dbDetails;
683 @list
( $table ) = $dbDetails;
686 $prefix = $this->mTablePrefix
;
688 if ( isset( $database ) ) {
689 $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
692 if ( !isset( $database ) && isset( $wgSharedDB ) && $table[0] != '"'
693 && isset( $wgSharedTables )
694 && is_array( $wgSharedTables )
695 && in_array( $table, $wgSharedTables )
697 $database = $wgSharedDB;
698 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
701 if ( isset( $database ) ) {
702 $database = ( $database[0] == '"' ?
$database : "\"{$database}\"" );
704 $table = ( $table[0] == '"') ?
$table : "\"{$prefix}{$table}\"" ;
706 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
708 return strtoupper( $tableName );
712 * Return the next in a sequence, save the value for retrieval via insertId()
714 function nextSequenceValue( $seqName ) {
715 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
716 $row = $this->fetchRow( $res );
717 $this->mInsertId
= $row[0];
718 return $this->mInsertId
;
722 * Return sequence_name if table has a sequence
724 private function getSequenceData( $table ) {
725 if ( $this->sequenceData
== null ) {
726 $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\'' );
728 while ( ( $row = $result->fetchRow() ) !== false ) {
729 $this->sequenceData
[$this->tableName( $row[1] )] = array(
730 'sequence' => $row[0],
736 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
740 * REPLACE query wrapper
741 * Oracle simulates this with a DELETE followed by INSERT
742 * $row is the row to insert, an associative array
743 * $uniqueIndexes is an array of indexes. Each element may be either a
744 * field name or an array of field names
746 * It may be more efficient to leave off unique indexes which are unlikely to collide.
747 * However if you do this, you run the risk of encountering errors which wouldn't have
750 * @param $table String: table name
751 * @param $uniqueIndexes Array: array of indexes. Each element may be
752 * either a field name or an array of field names
753 * @param $rows Array: rows to insert to $table
754 * @param $fname String: function name, you can use __METHOD__ here
756 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
757 $table = $this->tableName( $table );
759 if ( count( $rows ) == 0 ) {
764 if ( !is_array( reset( $rows ) ) ) {
765 $rows = array( $rows );
768 $sequenceData = $this->getSequenceData( $table );
770 foreach ( $rows as $row ) {
771 # Delete rows which collide
772 if ( $uniqueIndexes ) {
773 $condsDelete = array();
774 foreach ( $uniqueIndexes as $index ) {
775 $condsDelete[$index] = $row[$index];
777 if ( count( $condsDelete ) > 0 ) {
778 $this->delete( $table, $condsDelete, $fname );
782 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
783 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
787 $this->insert( $table, $row, $fname );
791 # DELETE where the condition is a join
792 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
794 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
797 $delTable = $this->tableName( $delTable );
798 $joinTable = $this->tableName( $joinTable );
799 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
800 if ( $conds != '*' ) {
801 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
805 $this->query( $sql, $fname );
808 # Returns the size of a text field, or -1 for "unlimited"
809 function textFieldSize( $table, $field ) {
810 $fieldInfoData = $this->fieldInfo( $table, $field);
811 if ( $fieldInfoData->type() == 'varchar' ) {
812 $size = $row->size
- 4;
819 function limitResult( $sql, $limit, $offset = false ) {
820 if ( $offset === false ) {
823 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
826 function encodeBlob( $b ) {
827 return new Blob( $b );
830 function decodeBlob( $b ) {
831 if ( $b instanceof Blob
) {
837 function unionQueries( $sqls, $all ) {
838 $glue = ' UNION ALL ';
839 return 'SELECT * ' . ( $all ?
'':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
842 function wasDeadlock() {
843 return $this->lastErrno() == 'OCI-00060';
846 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
849 $temporary = $temporary ?
'TRUE' : 'FALSE';
851 $newName = trim( strtoupper( $newName ), '"');
852 $oldName = trim( strtoupper( $oldName ), '"');
854 $tabName = substr( $newName, strlen( $wgDBprefix ) );
855 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
857 return $this->doQuery( 'BEGIN DUPLICATE_TABLE(\'' . $tabName . '\', \'' . $oldPrefix . '\', \'' . strtoupper( $wgDBprefix ) . '\', ' . $temporary . '); END;' );
860 function timestamp( $ts = 0 ) {
861 return wfTimestamp( TS_ORACLE
, $ts );
865 * Return aggregated value function call
867 function aggregateValue ( $valuedata, $valuename = 'value' ) {
871 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
872 # Ignore errors during error handling to avoid infinite
874 $ignore = $this->ignoreErrors( true );
875 ++
$this->mErrorCount
;
877 if ( $ignore ||
$tempIgnore ) {
878 wfDebug( "SQL ERROR (ignored): $error\n" );
879 $this->ignoreErrors( $ignore );
881 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
886 * @return string wikitext of a link to the server software's web site
888 public static function getSoftwareLink() {
889 return '[http://www.oracle.com/ Oracle]';
893 * @return string Version information from the database
895 function getServerVersion() {
896 //better version number, fallback on driver
897 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
898 if ( !( $row = $rset->fetchRow() ) ) {
899 return oci_server_version( $this->mConn
);
901 return $row['version'];
905 * Query whether a given table exists (in the given schema, or the default mw one if not given)
907 function tableExists( $table ) {
908 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
909 $res = $this->doQuery( $SQL );
911 $count = $res->numRows();
920 * Function translates mysql_fetch_field() functionality on ORACLE.
921 * Caching is present for reducing query time.
922 * For internal calls. Use fieldInfo for normal usage.
923 * Returns false if the field doesn't exist
925 * @param $table Array
926 * @param $field String
929 private function fieldInfoMulti( $table, $field ) {
930 $field = strtoupper( $field );
931 if ( is_array( $table ) ) {
932 $table = array_map( array( &$this, 'tableName' ), $table );
933 $tableWhere = 'IN (';
934 foreach( $table as &$singleTable ) {
935 $singleTable = strtoupper( trim( $singleTable, '"' ) );
936 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
937 return $this->mFieldInfoCache
["$singleTable.$field"];
939 $tableWhere .= '\'' . $singleTable . '\',';
941 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
943 $table = strtoupper( trim( $this->tableName( $table ), '"' ) );
944 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
945 return $this->mFieldInfoCache
["$table.$field"];
947 $tableWhere = '= \''.$table.'\'';
950 $fieldInfoStmt = oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
951 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT
) === false ) {
952 $e = oci_error( $fieldInfoStmt );
953 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
956 $res = new ORAResult( $this, $fieldInfoStmt );
957 if ( $res->numRows() == 0 ) {
958 if ( is_array( $table ) ) {
959 foreach( $table as &$singleTable ) {
960 $this->mFieldInfoCache
["$singleTable.$field"] = false;
963 $this->mFieldInfoCache
["$table.$field"] = false;
965 $fieldInfoTemp = null;
967 $fieldInfoTemp = new ORAField( $res->fetchRow() );
968 $table = $fieldInfoTemp->tableName();
969 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
972 return $fieldInfoTemp;
976 * @throws DBUnexpectedError
981 function fieldInfo( $table, $field ) {
982 if ( is_array( $table ) ) {
983 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
985 return $this->fieldInfoMulti ($table, $field);
988 function begin( $fname = '' ) {
989 $this->mTrxLevel
= 1;
992 function commit( $fname = '' ) {
993 oci_commit( $this->mConn
);
994 $this->mTrxLevel
= 0;
997 /* Not even sure why this is used in the main codebase... */
998 function limitResultForUpdate( $sql, $num ) {
1002 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
1003 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
1006 $dollarquote = false;
1008 $replacements = array();
1010 while ( ! feof( $fp ) ) {
1011 if ( $lineCallback ) {
1012 call_user_func( $lineCallback );
1014 $line = trim( fgets( $fp, 1024 ) );
1015 $sl = strlen( $line ) - 1;
1020 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1024 // Allow dollar quoting for function declarations
1025 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1026 if ( $dollarquote ) {
1027 $dollarquote = false;
1028 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1031 $dollarquote = true;
1033 } elseif ( !$dollarquote ) {
1034 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
1036 $line = substr( $line, 0, $sl );
1046 $cmd = str_replace( ';;', ";", $cmd );
1047 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1048 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1049 $replacements[$defines[2]] = $defines[1];
1052 foreach ( $replacements as $mwVar => $scVar ) {
1053 $cmd = str_replace( '&' . $scVar . '.', '{$' . $mwVar . '}', $cmd );
1056 $cmd = $this->replaceVars( $cmd );
1057 $res = $this->doQuery( $cmd );
1058 if ( $resultCallback ) {
1059 call_user_func( $resultCallback, $res, $this );
1062 if ( false === $res ) {
1063 $err = $this->lastError();
1064 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1075 function selectDB( $db ) {
1076 if ( $db == null ||
$db == $this->mUser
) { return true; }
1077 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1078 $stmt = oci_parse( $this->mConn
, $sql );
1079 if ( !oci_execute( $stmt ) ) {
1080 $e = oci_error( $stmt );
1081 if ( $e['code'] != '1435' ) {
1082 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1089 function strencode( $s ) {
1090 return str_replace( "'", "''", $s );
1093 function addQuotes( $s ) {
1095 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1096 $s = $wgContLang->checkTitleEncoding( $s );
1098 return "'" . $this->strencode( $s ) . "'";
1101 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1105 $conds = ( $conds != null && !is_array( $conds ) ) ?
array( $conds ) : $conds;
1106 foreach ( $conds as $col => $val ) {
1107 $col_info = $this->fieldInfoMulti( $table, $col );
1108 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1109 if ( $col_type == 'CLOB' ) {
1110 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1111 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1112 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1114 $conds2[$col] = $val;
1118 return parent
::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1122 * Returns an optional USE INDEX clause to go after the table, and a
1123 * string to go at the end of the query
1127 * @param $options Array: an associative array of options to be turned into
1128 * an SQL query, valid keys are listed in the function.
1131 function makeSelectOptions( $options ) {
1132 $preLimitTail = $postLimitTail = '';
1135 $noKeyOptions = array();
1136 foreach ( $options as $key => $option ) {
1137 if ( is_numeric( $key ) ) {
1138 $noKeyOptions[$option] = true;
1142 if ( isset( $options['GROUP BY'] ) ) {
1143 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1145 if ( isset( $options['ORDER BY'] ) ) {
1146 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1149 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1150 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1151 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1152 $startOpts .= 'DISTINCT';
1155 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1156 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1161 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1164 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1167 if ( $wgContLang != null && $conds != '*' ) {
1169 $conds = ( $conds != null && !is_array( $conds ) ) ?
array( $conds ) : $conds;
1170 foreach ( $conds as $col => $val ) {
1171 $col_info = $this->fieldInfoMulti( $table, $col );
1172 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1173 if ( $col_type == 'CLOB' ) {
1174 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1176 if ( is_array( $val ) ) {
1177 $conds2[$col] = $val;
1178 foreach ( $conds2[$col] as &$val2 ) {
1179 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1182 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1187 return parent
::delete( $table, $conds2, $fname );
1189 return parent
::delete( $table, $conds, $fname );
1193 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1196 $table = $this->tableName( $table );
1197 $opts = $this->makeUpdateOptions( $options );
1198 $sql = "UPDATE $opts $table SET ";
1201 foreach ( $values as $col => &$val ) {
1202 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1205 $sqlSet = ', ' . $sqlSet;
1212 if ( $conds != '*' ) {
1213 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1216 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1217 $e = oci_error( $this->mConn
);
1218 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1221 foreach ( $values as $col => &$val ) {
1222 $col_info = $this->fieldInfoMulti( $table, $col );
1223 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1225 if ( $val === null ) {
1226 // do nothing ... null was inserted in statement creation
1227 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1228 if ( is_object( $val ) ) {
1229 $val = $val->getData();
1232 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1233 $val = '31-12-2030 12:00:00.000000';
1236 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1237 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1238 $e = oci_error( $stmt );
1239 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1243 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1244 $e = oci_error( $stmt );
1245 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1248 if ( $col_type == 'BLOB' ) {
1249 $lob[$col]->writeTemporary( $val );
1250 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
1252 $lob[$col]->writeTemporary( $val );
1253 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
1258 wfSuppressWarnings();
1260 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
1261 $e = oci_error( $stmt );
1262 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
1263 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1266 $this->mAffectedRows
= oci_num_rows( $stmt );
1269 $this->mAffectedRows
= oci_num_rows( $stmt );
1272 wfRestoreWarnings();
1274 if ( isset( $lob ) ) {
1275 foreach ( $lob as $lob_v ) {
1280 if ( !$this->mTrxLevel
) {
1281 oci_commit( $this->mConn
);
1284 oci_free_statement( $stmt );
1287 function bitNot( $field ) {
1288 // expecting bit-fields smaller than 4bytes
1289 return 'BITNOT(' . $field . ')';
1292 function bitAnd( $fieldLeft, $fieldRight ) {
1293 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1296 function bitOr( $fieldLeft, $fieldRight ) {
1297 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1300 function setFakeMaster( $enabled = true ) { }
1302 function getDBname() {
1303 return $this->mDBname
;
1306 function getServer() {
1307 return $this->mServer
;
1310 public function replaceVars( $ins ) {
1311 $varnames = array( 'wgDBprefix' );
1312 if ( $this->mFlags
& DBO_SYSDBA
) {
1313 $varnames[] = '_OracleDefTS';
1314 $varnames[] = '_OracleTempTS';
1317 $ins = $this->replaceGlobalVars( $ins, $varnames );
1319 return parent
::replaceVars( $ins );
1322 public function getSearchEngine() {
1323 return 'SearchOracle';
1325 } // end DatabaseOracle class