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() {
230 * Usually aborts on failure
232 function open( $server, $user, $password, $dbName ) {
233 if ( !function_exists( 'oci_connect' ) ) {
234 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" );
238 $this->mUser
= $user;
239 $this->mPassword
= $password;
240 // changed internal variables functions
241 // mServer now holds the TNS endpoint
242 // mDBname is schema name if different from username
244 // backward compatibillity (server used to be null and TNS was supplied in dbname)
245 $this->mServer
= $dbName;
246 $this->mDBname
= $user;
248 $this->mServer
= $server;
250 $this->mDBname
= $user;
252 $this->mDBname
= $dbName;
256 if ( !strlen( $user ) ) { # e.g. the class is being loaded
260 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
261 if ( $this->mFlags
& DBO_DEFAULT
) {
262 $this->mConn
= oci_new_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
264 $this->mConn
= oci_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
267 if ( $this->mUser
!= $this->mDBname
) {
268 //change current schema in session
269 $this->selectDB( $this->mDBname
);
272 if ( !$this->mConn
) {
273 throw new DBConnectionError( $this, $this->lastError() );
276 $this->mOpened
= true;
278 # removed putenv calls because they interfere with the system globaly
279 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
280 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
285 * Closes a database connection, if it is open
286 * Returns success, true if already closed
289 $this->mOpened
= false;
290 if ( $this->mConn
) {
291 return oci_close( $this->mConn
);
297 function execFlags() {
298 return $this->mTrxLevel ? OCI_DEFAULT
: OCI_COMMIT_ON_SUCCESS
;
301 function doQuery( $sql ) {
302 wfDebug( "SQL: [$sql]\n" );
303 if ( !mb_check_encoding( $sql ) ) {
304 throw new MWException( "SQL encoding is invalid\n$sql" );
307 // handle some oracle specifics
308 // remove AS column/table/subquery namings
309 if( !$this->getFlag( DBO_DDLMODE
) ) {
310 $sql = preg_replace( '/ as /i', ' ', $sql );
313 // Oracle has issues with UNION clause if the statement includes LOB fields
314 // So we do a UNION ALL and then filter the results array with array_unique
315 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
316 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
317 // you have to select data from plan table after explain
318 $explain_id = date( 'dmYHis' );
320 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
322 wfSuppressWarnings();
324 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
325 $e = oci_error( $this->mConn
);
326 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
330 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
331 $e = oci_error( $stmt );
332 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
333 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
340 if ( $explain_count > 0 ) {
341 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
342 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
343 return new ORAResult( $this, $stmt, $union_unique );
345 $this->mAffectedRows
= oci_num_rows( $stmt );
350 function queryIgnore( $sql, $fname = '' ) {
351 return $this->query( $sql, $fname, true );
354 function freeResult( $res ) {
355 if ( $res instanceof ResultWrapper
) {
362 function fetchObject( $res ) {
363 if ( $res instanceof ResultWrapper
) {
367 return $res->fetchObject();
370 function fetchRow( $res ) {
371 if ( $res instanceof ResultWrapper
) {
375 return $res->fetchRow();
378 function numRows( $res ) {
379 if ( $res instanceof ResultWrapper
) {
383 return $res->numRows();
386 function numFields( $res ) {
387 if ( $res instanceof ResultWrapper
) {
391 return $res->numFields();
394 function fieldName( $stmt, $n ) {
395 return oci_field_name( $stmt, $n );
399 * This must be called after nextSequenceVal
401 function insertId() {
402 return $this->mInsertId
;
405 function dataSeek( $res, $row ) {
406 if ( $res instanceof ORAResult
) {
409 $res->result
->seek( $row );
413 function lastError() {
414 if ( $this->mConn
=== false ) {
417 $e = oci_error( $this->mConn
);
419 return $e['message'];
422 function lastErrno() {
423 if ( $this->mConn
=== false ) {
426 $e = oci_error( $this->mConn
);
431 function affectedRows() {
432 return $this->mAffectedRows
;
436 * Returns information about an index
437 * If errors are explicitly ignored, returns NULL on failure
439 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
443 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
447 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
448 if ( !count( $a ) ) {
452 if ( !is_array( $options ) ) {
453 $options = array( $options );
456 if ( in_array( 'IGNORE', $options ) ) {
457 $this->ignore_DUP_VAL_ON_INDEX
= true;
460 if ( !is_array( reset( $a ) ) ) {
464 foreach ( $a as &$row ) {
465 $this->insertOneRow( $table, $row, $fname );
469 if ( in_array( 'IGNORE', $options ) ) {
470 $this->ignore_DUP_VAL_ON_INDEX
= false;
476 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
477 $col_info = $this->fieldInfoMulti( $table, $col );
478 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
481 if ( is_numeric( $col ) ) {
485 } else if ( $includeCol ) {
489 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
493 if ( $val === null ) {
494 if ( $col_info != false && $col_info->nullable() == 0 && $col_info->defaultValue() != null ) {
506 private function insertOneRow( $table, $row, $fname ) {
509 $table = $this->tableName( $table );
510 // "INSERT INTO tables (a, b, c)"
511 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
514 // for each value, append ":key"
516 foreach ( $row as $col => &$val ) {
523 $sql .= $this->fieldBindStatement( $table, $col, $val );
527 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
528 $e = oci_error( $this->mConn
);
529 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
532 foreach ( $row as $col => &$val ) {
533 $col_info = $this->fieldInfoMulti( $table, $col );
534 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
536 if ( $val === null ) {
537 // do nothing ... null was inserted in statement creation
538 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
539 if ( is_object( $val ) ) {
540 $val = $val->fetch();
543 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
544 $val = '31-12-2030 12:00:00.000000';
547 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
548 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
549 $e = oci_error( $stmt );
550 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
554 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
555 $e = oci_error( $stmt );
556 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
559 if ( is_object( $val ) ) {
560 $val = $val->fetch();
563 if ( $col_type == 'BLOB' ) {
564 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
565 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB
);
567 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
568 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
573 wfSuppressWarnings();
575 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
576 $e = oci_error( $stmt );
577 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
578 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
581 $this->mAffectedRows
= oci_num_rows( $stmt );
584 $this->mAffectedRows
= oci_num_rows( $stmt );
589 if ( isset( $lob ) ) {
590 foreach ( $lob as $lob_v ) {
595 if ( !$this->mTrxLevel
) {
596 oci_commit( $this->mConn
);
599 oci_free_statement( $stmt );
602 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
603 $insertOptions = array(), $selectOptions = array() )
605 $destTable = $this->tableName( $destTable );
606 if ( !is_array( $selectOptions ) ) {
607 $selectOptions = array( $selectOptions );
609 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
610 if ( is_array( $srcTable ) ) {
611 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
613 $srcTable = $this->tableName( $srcTable );
616 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
617 !isset( $varMap[$sequenceData['column']] ) )
619 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
622 // count-alias subselect fields to avoid abigious definition errors
624 foreach ( $varMap as &$val ) {
625 $val = $val . ' field' . ( $i++
);
628 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
629 " SELECT $startOpts " . implode( ',', $varMap ) .
630 " FROM $srcTable $useIndex ";
631 if ( $conds != '*' ) {
632 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
634 $sql .= " $tailOpts";
636 if ( in_array( 'IGNORE', $insertOptions ) ) {
637 $this->ignore_DUP_VAL_ON_INDEX
= true;
640 $retval = $this->query( $sql, $fname );
642 if ( in_array( 'IGNORE', $insertOptions ) ) {
643 $this->ignore_DUP_VAL_ON_INDEX
= false;
649 function tableName( $name ) {
650 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
652 Replace reserved words with better ones
653 Using uppercase because that's the only way Oracle can handle
661 $name = 'PAGECONTENT';
666 The rest of procedure is equal to generic Databse class
667 except for the quoting style
669 if ( $name[0] == '"' && substr( $name, - 1, 1 ) == '"' ) {
672 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
675 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
676 if ( isset( $dbDetails[1] ) ) {
677 @list
( $table, $database ) = $dbDetails;
679 @list
( $table ) = $dbDetails;
682 $prefix = $this->mTablePrefix
;
684 if ( isset( $database ) ) {
685 $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
688 if ( !isset( $database ) && isset( $wgSharedDB ) && $table[0] != '"'
689 && isset( $wgSharedTables )
690 && is_array( $wgSharedTables )
691 && in_array( $table, $wgSharedTables )
693 $database = $wgSharedDB;
694 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
697 if ( isset( $database ) ) {
698 $database = ( $database[0] == '"' ?
$database : "\"{$database}\"" );
700 $table = ( $table[0] == '"') ?
$table : "\"{$prefix}{$table}\"" ;
702 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
704 return strtoupper( $tableName );
708 * Return the next in a sequence, save the value for retrieval via insertId()
710 function nextSequenceValue( $seqName ) {
711 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
712 $row = $this->fetchRow( $res );
713 $this->mInsertId
= $row[0];
714 return $this->mInsertId
;
718 * Return sequence_name if table has a sequence
720 private function getSequenceData( $table ) {
721 if ( $this->sequenceData
== null ) {
722 $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\'' );
724 while ( ( $row = $result->fetchRow() ) !== false ) {
725 $this->sequenceData
[$this->tableName( $row[1] )] = array(
726 'sequence' => $row[0],
732 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
736 * REPLACE query wrapper
737 * Oracle simulates this with a DELETE followed by INSERT
738 * $row is the row to insert, an associative array
739 * $uniqueIndexes is an array of indexes. Each element may be either a
740 * field name or an array of field names
742 * It may be more efficient to leave off unique indexes which are unlikely to collide.
743 * However if you do this, you run the risk of encountering errors which wouldn't have
746 * @param $table String: table name
747 * @param $uniqueIndexes Array: array of indexes. Each element may be
748 * either a field name or an array of field names
749 * @param $rows Array: rows to insert to $table
750 * @param $fname String: function name, you can use __METHOD__ here
752 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
753 $table = $this->tableName( $table );
755 if ( count( $rows ) == 0 ) {
760 if ( !is_array( reset( $rows ) ) ) {
761 $rows = array( $rows );
764 $sequenceData = $this->getSequenceData( $table );
766 foreach ( $rows as $row ) {
767 # Delete rows which collide
768 if ( $uniqueIndexes ) {
769 $condsDelete = array();
770 foreach ( $uniqueIndexes as $index ) {
771 $condsDelete[$index] = $row[$index];
773 if ( count( $condsDelete ) > 0 ) {
774 $this->delete( $table, $condsDelete, $fname );
778 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
779 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
783 $this->insert( $table, $row, $fname );
787 # DELETE where the condition is a join
788 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
790 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
793 $delTable = $this->tableName( $delTable );
794 $joinTable = $this->tableName( $joinTable );
795 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
796 if ( $conds != '*' ) {
797 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
801 $this->query( $sql, $fname );
804 # Returns the size of a text field, or -1 for "unlimited"
805 function textFieldSize( $table, $field ) {
806 $fieldInfoData = $this->fieldInfo( $table, $field);
807 if ( $fieldInfoData->type() == 'varchar' ) {
808 $size = $row->size
- 4;
815 function limitResult( $sql, $limit, $offset = false ) {
816 if ( $offset === false ) {
819 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
822 function encodeBlob( $b ) {
823 return new Blob( $b );
826 function decodeBlob( $b ) {
827 if ( $b instanceof Blob
) {
833 function unionQueries( $sqls, $all ) {
834 $glue = ' UNION ALL ';
835 return 'SELECT * ' . ( $all ?
'':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
838 function wasDeadlock() {
839 return $this->lastErrno() == 'OCI-00060';
842 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
845 $temporary = $temporary ?
'TRUE' : 'FALSE';
847 $newName = trim( strtoupper( $newName ), '"');
848 $oldName = trim( strtoupper( $oldName ), '"');
850 $tabName = substr( $newName, strlen( $wgDBprefix ) );
851 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
853 return $this->doQuery( 'BEGIN DUPLICATE_TABLE(\'' . $tabName . '\', \'' . $oldPrefix . '\', \'' . strtoupper( $wgDBprefix ) . '\', ' . $temporary . '); END;' );
856 function timestamp( $ts = 0 ) {
857 return wfTimestamp( TS_ORACLE
, $ts );
861 * Return aggregated value function call
863 function aggregateValue ( $valuedata, $valuename = 'value' ) {
867 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
868 # Ignore errors during error handling to avoid infinite
870 $ignore = $this->ignoreErrors( true );
871 ++
$this->mErrorCount
;
873 if ( $ignore ||
$tempIgnore ) {
874 wfDebug( "SQL ERROR (ignored): $error\n" );
875 $this->ignoreErrors( $ignore );
877 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
882 * @return string wikitext of a link to the server software's web site
884 public static function getSoftwareLink() {
885 return '[http://www.oracle.com/ Oracle]';
889 * @return string Version information from the database
891 function getServerVersion() {
892 //better version number, fallback on driver
893 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
894 if ( !( $row = $rset->fetchRow() ) ) {
895 return oci_server_version( $this->mConn
);
897 return $row['version'];
901 * Query whether a given table exists (in the given schema, or the default mw one if not given)
903 function tableExists( $table ) {
904 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
905 $res = $this->doQuery( $SQL );
907 $count = $res->numRows();
916 * Function translates mysql_fetch_field() functionality on ORACLE.
917 * Caching is present for reducing query time.
918 * For internal calls. Use fieldInfo for normal usage.
919 * Returns false if the field doesn't exist
921 * @param $table Array
922 * @param $field String
925 private function fieldInfoMulti( $table, $field ) {
926 $field = strtoupper( $field );
927 if ( is_array( $table ) ) {
928 $table = array_map( array( &$this, 'tableName' ), $table );
929 $tableWhere = 'IN (';
930 foreach( $table as &$singleTable ) {
931 $singleTable = strtoupper( trim( $singleTable, '"' ) );
932 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
933 return $this->mFieldInfoCache
["$singleTable.$field"];
935 $tableWhere .= '\'' . $singleTable . '\',';
937 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
939 $table = strtoupper( trim( $this->tableName( $table ), '"' ) );
940 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
941 return $this->mFieldInfoCache
["$table.$field"];
943 $tableWhere = '= \''.$table.'\'';
946 $fieldInfoStmt = oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
947 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT
) === false ) {
948 $e = oci_error( $fieldInfoStmt );
949 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
952 $res = new ORAResult( $this, $fieldInfoStmt );
953 if ( $res->numRows() == 0 ) {
954 if ( is_array( $table ) ) {
955 foreach( $table as &$singleTable ) {
956 $this->mFieldInfoCache
["$singleTable.$field"] = false;
959 $this->mFieldInfoCache
["$table.$field"] = false;
961 $fieldInfoTemp = null;
963 $fieldInfoTemp = new ORAField( $res->fetchRow() );
964 $table = $fieldInfoTemp->tableName();
965 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
968 return $fieldInfoTemp;
972 * @throws DBUnexpectedError
977 function fieldInfo( $table, $field ) {
978 if ( is_array( $table ) ) {
979 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
981 return $this->fieldInfoMulti ($table, $field);
984 function begin( $fname = '' ) {
985 $this->mTrxLevel
= 1;
988 function commit( $fname = '' ) {
989 oci_commit( $this->mConn
);
990 $this->mTrxLevel
= 0;
993 /* Not even sure why this is used in the main codebase... */
994 function limitResultForUpdate( $sql, $num ) {
998 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
999 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
1002 $dollarquote = false;
1004 $replacements = array();
1006 while ( ! feof( $fp ) ) {
1007 if ( $lineCallback ) {
1008 call_user_func( $lineCallback );
1010 $line = trim( fgets( $fp, 1024 ) );
1011 $sl = strlen( $line ) - 1;
1016 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1020 // Allow dollar quoting for function declarations
1021 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1022 if ( $dollarquote ) {
1023 $dollarquote = false;
1024 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1027 $dollarquote = true;
1029 } elseif ( !$dollarquote ) {
1030 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
1032 $line = substr( $line, 0, $sl );
1042 $cmd = str_replace( ';;', ";", $cmd );
1043 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1044 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1045 $replacements[$defines[2]] = $defines[1];
1048 foreach ( $replacements as $mwVar => $scVar ) {
1049 $cmd = str_replace( '&' . $scVar . '.', '{$' . $mwVar . '}', $cmd );
1052 $cmd = $this->replaceVars( $cmd );
1053 $res = $this->doQuery( $cmd );
1054 if ( $resultCallback ) {
1055 call_user_func( $resultCallback, $res, $this );
1058 if ( false === $res ) {
1059 $err = $this->lastError();
1060 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1071 function selectDB( $db ) {
1072 if ( $db == null ||
$db == $this->mUser
) { return true; }
1073 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1074 $stmt = oci_parse( $this->mConn
, $sql );
1075 if ( !oci_execute( $stmt ) ) {
1076 $e = oci_error( $stmt );
1077 if ( $e['code'] != '1435' ) {
1078 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1085 function strencode( $s ) {
1086 return str_replace( "'", "''", $s );
1089 function addQuotes( $s ) {
1091 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1092 $s = $wgContLang->checkTitleEncoding( $s );
1094 return "'" . $this->strencode( $s ) . "'";
1097 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1101 $conds = ( $conds != null && !is_array( $conds ) ) ?
array( $conds ) : $conds;
1102 foreach ( $conds as $col => $val ) {
1103 $col_info = $this->fieldInfoMulti( $table, $col );
1104 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1105 if ( $col_type == 'CLOB' ) {
1106 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1107 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1108 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1110 $conds2[$col] = $val;
1114 return parent
::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1118 * Returns an optional USE INDEX clause to go after the table, and a
1119 * string to go at the end of the query
1123 * @param $options Array: an associative array of options to be turned into
1124 * an SQL query, valid keys are listed in the function.
1127 function makeSelectOptions( $options ) {
1128 $preLimitTail = $postLimitTail = '';
1131 $noKeyOptions = array();
1132 foreach ( $options as $key => $option ) {
1133 if ( is_numeric( $key ) ) {
1134 $noKeyOptions[$option] = true;
1138 if ( isset( $options['GROUP BY'] ) ) {
1139 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1141 if ( isset( $options['ORDER BY'] ) ) {
1142 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1145 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1146 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1147 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1148 $startOpts .= 'DISTINCT';
1151 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1152 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1157 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1160 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1163 if ( $wgContLang != null && $conds != '*' ) {
1165 $conds = ( $conds != null && !is_array( $conds ) ) ?
array( $conds ) : $conds;
1166 foreach ( $conds as $col => $val ) {
1167 $col_info = $this->fieldInfoMulti( $table, $col );
1168 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1169 if ( $col_type == 'CLOB' ) {
1170 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1172 if ( is_array( $val ) ) {
1173 $conds2[$col] = $val;
1174 foreach ( $conds2[$col] as &$val2 ) {
1175 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1178 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1183 return parent
::delete( $table, $conds2, $fname );
1185 return parent
::delete( $table, $conds, $fname );
1189 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1192 $table = $this->tableName( $table );
1193 $opts = $this->makeUpdateOptions( $options );
1194 $sql = "UPDATE $opts $table SET ";
1197 foreach ( $values as $col => &$val ) {
1198 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1201 $sqlSet = ', ' . $sqlSet;
1208 if ( $conds != '*' ) {
1209 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1212 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1213 $e = oci_error( $this->mConn
);
1214 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1217 foreach ( $values as $col => &$val ) {
1218 $col_info = $this->fieldInfoMulti( $table, $col );
1219 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1221 if ( $val === null ) {
1222 // do nothing ... null was inserted in statement creation
1223 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1224 if ( is_object( $val ) ) {
1225 $val = $val->getData();
1228 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1229 $val = '31-12-2030 12:00:00.000000';
1232 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1233 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1234 $e = oci_error( $stmt );
1235 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1239 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1240 $e = oci_error( $stmt );
1241 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1244 if ( $col_type == 'BLOB' ) {
1245 $lob[$col]->writeTemporary( $val );
1246 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
1248 $lob[$col]->writeTemporary( $val );
1249 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
1254 wfSuppressWarnings();
1256 if ( oci_execute( $stmt, OCI_DEFAULT
) === false ) {
1257 $e = oci_error( $stmt );
1258 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
1259 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1262 $this->mAffectedRows
= oci_num_rows( $stmt );
1265 $this->mAffectedRows
= oci_num_rows( $stmt );
1268 wfRestoreWarnings();
1270 if ( isset( $lob ) ) {
1271 foreach ( $lob as $lob_v ) {
1276 if ( !$this->mTrxLevel
) {
1277 oci_commit( $this->mConn
);
1280 oci_free_statement( $stmt );
1283 function bitNot( $field ) {
1284 // expecting bit-fields smaller than 4bytes
1285 return 'BITNOT(' . $field . ')';
1288 function bitAnd( $fieldLeft, $fieldRight ) {
1289 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1292 function bitOr( $fieldLeft, $fieldRight ) {
1293 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1296 function setFakeMaster( $enabled = true ) { }
1298 function getDBname() {
1299 return $this->mDBname
;
1302 function getServer() {
1303 return $this->mServer
;
1306 public function replaceVars( $ins ) {
1307 $varnames = array( 'wgDBprefix' );
1308 if ( $this->mFlags
& DBO_SYSDBA
) {
1309 $varnames[] = '_OracleDefTS';
1310 $varnames[] = '_OracleTempTS';
1313 $ins = $this->replaceGlobalVars( $ins, $varnames );
1315 return parent
::replaceVars( $ins );
1318 public function getSearchEngine() {
1319 return 'SearchOracle';
1321 } // end DatabaseOracle class