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;
38 * @param $db DatabaseBase
42 function __construct( &$db, $stmt, $unique = false ) {
45 if ( ( $this->nrows
= oci_fetch_all( $stmt, $this->rows
, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM
) ) === false ) {
46 $e = oci_error( $stmt );
47 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__
);
53 $this->rows
= $this->array_unique_md( $this->rows
);
54 $this->nrows
= count( $this->rows
);
57 if ($this->nrows
> 0) {
58 foreach ( $this->rows
[0] as $k => $v ) {
59 $this->columns
[$k] = strtolower( oci_field_name( $stmt, $k +
1 ) );
64 oci_free_statement( $stmt );
67 public function free() {
71 public function seek( $row ) {
72 $this->cursor
= min( $row, $this->nrows
);
75 public function numRows() {
79 public function numFields() {
80 return count($this->columns
);
83 public function fetchObject() {
84 if ( $this->cursor
>= $this->nrows
) {
87 $row = $this->rows
[$this->cursor++
];
88 $ret = new stdClass();
89 foreach ( $row as $k => $v ) {
90 $lc = $this->columns
[$k];
97 public function fetchRow() {
98 if ( $this->cursor
>= $this->nrows
) {
102 $row = $this->rows
[$this->cursor++
];
104 foreach ( $row as $k => $v ) {
105 $lc = $this->columns
[$k];
117 class ORAField
implements Field
{
118 private $name, $tablename, $default, $max_length, $nullable,
119 $is_pk, $is_unique, $is_multiple, $is_key, $type;
121 function __construct( $info ) {
122 $this->name
= $info['column_name'];
123 $this->tablename
= $info['table_name'];
124 $this->default = $info['data_default'];
125 $this->max_length
= $info['data_length'];
126 $this->nullable
= $info['not_null'];
127 $this->is_pk
= isset( $info['prim'] ) && $info['prim'] == 1 ?
1 : 0;
128 $this->is_unique
= isset( $info['uniq'] ) && $info['uniq'] == 1 ?
1 : 0;
129 $this->is_multiple
= isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ?
1 : 0;
130 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
131 $this->type
= $info['data_type'];
138 function tableName() {
139 return $this->tablename
;
142 function defaultValue() {
143 return $this->default;
146 function maxLength() {
147 return $this->max_length
;
150 function isNullable() {
151 return $this->nullable
;
155 return $this->is_key
;
158 function isMultipleKey() {
159 return $this->is_multiple
;
170 class DatabaseOracle
extends DatabaseBase
{
171 var $mInsertId = null;
172 var $mLastResult = null;
173 var $lastResult = null;
177 var $ignore_DUP_VAL_ON_INDEX = false;
178 var $sequenceData = null;
180 var $defaultCharset = 'AL32UTF8';
182 var $mFieldInfoCache = array();
184 function __construct( $server = false, $user = false, $password = false, $dbName = false,
185 $flags = 0, $tablePrefix = 'get from global' )
188 $tablePrefix = $tablePrefix == 'get from global' ?
strtoupper( $wgDBprefix ) : strtoupper( $tablePrefix );
189 parent
::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
190 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
193 function __destruct() {
194 if ($this->mOpened
) {
195 wfSuppressWarnings();
205 function cascadingDeletes() {
208 function cleanupTriggers() {
211 function strictIPs() {
214 function realTimestamps() {
217 function implicitGroupby() {
220 function implicitOrderby() {
223 function searchableIPs() {
228 * Usually aborts on failure
229 * @return DatabaseBase|null
231 function open( $server, $user, $password, $dbName ) {
232 if ( !function_exists( 'oci_connect' ) ) {
233 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" );
237 $this->mUser
= $user;
238 $this->mPassword
= $password;
239 // changed internal variables functions
240 // mServer now holds the TNS endpoint
241 // mDBname is schema name if different from username
243 // backward compatibillity (server used to be null and TNS was supplied in dbname)
244 $this->mServer
= $dbName;
245 $this->mDBname
= $user;
247 $this->mServer
= $server;
249 $this->mDBname
= $user;
251 $this->mDBname
= $dbName;
255 if ( !strlen( $user ) ) { # e.g. the class is being loaded
259 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
260 wfSuppressWarnings();
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 );
268 if ( $this->mUser
!= $this->mDBname
) {
269 //change current schema in session
270 $this->selectDB( $this->mDBname
);
273 if ( !$this->mConn
) {
274 throw new DBConnectionError( $this, $this->lastError() );
277 $this->mOpened
= true;
279 # removed putenv calls because they interfere with the system globaly
280 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
281 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
282 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
287 * Closes a database connection, if it is open
288 * Returns success, true if already closed
292 $this->mOpened
= false;
293 if ( $this->mConn
) {
294 if ( $this->mTrxLevel
) {
295 $this->commit( __METHOD__
);
297 return oci_close( $this->mConn
);
303 function execFlags() {
304 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
307 protected function doQuery( $sql ) {
308 wfDebug( "SQL: [$sql]\n" );
309 if ( !mb_check_encoding( $sql ) ) {
310 throw new MWException( "SQL encoding is invalid\n$sql" );
313 // handle some oracle specifics
314 // remove AS column/table/subquery namings
315 if( !$this->getFlag( DBO_DDLMODE
) ) {
316 $sql = preg_replace( '/ as /i', ' ', $sql );
319 // Oracle has issues with UNION clause if the statement includes LOB fields
320 // So we do a UNION ALL and then filter the results array with array_unique
321 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
322 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
323 // you have to select data from plan table after explain
324 $explain_id = date( 'dmYHis' );
326 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
328 wfSuppressWarnings();
330 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
331 $e = oci_error( $this->mConn
);
332 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
336 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
337 $e = oci_error( $stmt );
338 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
339 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
346 if ( $explain_count > 0 ) {
347 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
348 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
349 return new ORAResult( $this, $stmt, $union_unique );
351 $this->mAffectedRows
= oci_num_rows( $stmt );
356 function queryIgnore( $sql, $fname = '' ) {
357 return $this->query( $sql, $fname, true );
360 function freeResult( $res ) {
361 if ( $res instanceof ResultWrapper
) {
368 function fetchObject( $res ) {
369 if ( $res instanceof ResultWrapper
) {
373 return $res->fetchObject();
376 function fetchRow( $res ) {
377 if ( $res instanceof ResultWrapper
) {
381 return $res->fetchRow();
384 function numRows( $res ) {
385 if ( $res instanceof ResultWrapper
) {
389 return $res->numRows();
392 function numFields( $res ) {
393 if ( $res instanceof ResultWrapper
) {
397 return $res->numFields();
400 function fieldName( $stmt, $n ) {
401 return oci_field_name( $stmt, $n );
405 * This must be called after nextSequenceVal
408 function insertId() {
409 return $this->mInsertId
;
412 function dataSeek( $res, $row ) {
413 if ( $res instanceof ORAResult
) {
416 $res->result
->seek( $row );
420 function lastError() {
421 if ( $this->mConn
=== false ) {
424 $e = oci_error( $this->mConn
);
426 return $e['message'];
429 function lastErrno() {
430 if ( $this->mConn
=== false ) {
433 $e = oci_error( $this->mConn
);
438 function affectedRows() {
439 return $this->mAffectedRows
;
443 * Returns information about an index
444 * If errors are explicitly ignored, returns NULL on failure
447 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
451 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
455 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
456 if ( !count( $a ) ) {
460 if ( !is_array( $options ) ) {
461 $options = array( $options );
464 if ( in_array( 'IGNORE', $options ) ) {
465 $this->ignore_DUP_VAL_ON_INDEX
= true;
468 if ( !is_array( reset( $a ) ) ) {
472 foreach ( $a as &$row ) {
473 $this->insertOneRow( $table, $row, $fname );
477 if ( in_array( 'IGNORE', $options ) ) {
478 $this->ignore_DUP_VAL_ON_INDEX
= false;
484 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
485 $col_info = $this->fieldInfoMulti( $table, $col );
486 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
489 if ( is_numeric( $col ) ) {
493 } elseif ( $includeCol ) {
497 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
501 if ( $val === 'NULL' ) {
505 if ( $val === null ) {
506 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
518 private function insertOneRow( $table, $row, $fname ) {
521 $table = $this->tableName( $table );
522 // "INSERT INTO tables (a, b, c)"
523 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
526 // for each value, append ":key"
528 foreach ( $row as $col => &$val ) {
535 $sql .= $this->fieldBindStatement( $table, $col, $val );
539 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
540 $e = oci_error( $this->mConn
);
541 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
544 foreach ( $row as $col => &$val ) {
545 $col_info = $this->fieldInfoMulti( $table, $col );
546 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
548 if ( $val === null ) {
549 // do nothing ... null was inserted in statement creation
550 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
551 if ( is_object( $val ) ) {
552 $val = $val->fetch();
555 // backward compatibility
556 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
557 $val = $this->getInfinity();
560 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
561 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
562 $e = oci_error( $stmt );
563 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
567 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
568 $e = oci_error( $stmt );
569 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
572 if ( is_object( $val ) ) {
573 $val = $val->fetch();
576 if ( $col_type == 'BLOB' ) {
577 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
578 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB
);
580 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
581 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
586 wfSuppressWarnings();
588 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
589 $e = oci_error( $stmt );
590 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
591 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
594 $this->mAffectedRows
= oci_num_rows( $stmt );
597 $this->mAffectedRows
= oci_num_rows( $stmt );
602 if ( isset( $lob ) ) {
603 foreach ( $lob as $lob_v ) {
608 if ( !$this->mTrxLevel
) {
609 oci_commit( $this->mConn
);
612 oci_free_statement( $stmt );
615 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
616 $insertOptions = array(), $selectOptions = array() )
618 $destTable = $this->tableName( $destTable );
619 if ( !is_array( $selectOptions ) ) {
620 $selectOptions = array( $selectOptions );
622 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
623 if ( is_array( $srcTable ) ) {
624 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
626 $srcTable = $this->tableName( $srcTable );
629 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
630 !isset( $varMap[$sequenceData['column']] ) )
632 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
635 // count-alias subselect fields to avoid abigious definition errors
637 foreach ( $varMap as &$val ) {
638 $val = $val . ' field' . ( $i++
);
641 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
642 " SELECT $startOpts " . implode( ',', $varMap ) .
643 " FROM $srcTable $useIndex ";
644 if ( $conds != '*' ) {
645 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
647 $sql .= " $tailOpts";
649 if ( in_array( 'IGNORE', $insertOptions ) ) {
650 $this->ignore_DUP_VAL_ON_INDEX
= true;
653 $retval = $this->query( $sql, $fname );
655 if ( in_array( 'IGNORE', $insertOptions ) ) {
656 $this->ignore_DUP_VAL_ON_INDEX
= false;
662 function tableName( $name, $format = 'quoted' ) {
664 Replace reserved words with better ones
665 Using uppercase because that's the only way Oracle can handle
673 $name = 'PAGECONTENT';
677 return parent
::tableName( strtoupper( $name ), $format );
680 function tableNameInternal( $name ) {
681 $name = $this->tableName( $name );
682 return preg_replace( '/.*\.(.*)/', '$1', $name);
685 * Return the next in a sequence, save the value for retrieval via insertId()
688 function nextSequenceValue( $seqName ) {
689 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
690 $row = $this->fetchRow( $res );
691 $this->mInsertId
= $row[0];
692 return $this->mInsertId
;
696 * Return sequence_name if table has a sequence
699 private function getSequenceData( $table ) {
700 if ( $this->sequenceData
== null ) {
701 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
702 lower(atc.table_name),
703 lower(atc.column_name)
704 FROM all_sequences asq, all_tab_columns atc
705 WHERE decode(atc.table_name, '{$this->mTablePrefix}MWUSER', '{$this->mTablePrefix}USER', atc.table_name) || '_' ||
706 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
707 AND asq.sequence_owner = upper('{$this->mDBname}')
708 AND atc.owner = upper('{$this->mDBname}')" );
710 while ( ( $row = $result->fetchRow() ) !== false ) {
711 $this->sequenceData
[$row[1]] = array(
712 'sequence' => $row[0],
717 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
718 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
721 # Returns the size of a text field, or -1 for "unlimited"
722 function textFieldSize( $table, $field ) {
723 $fieldInfoData = $this->fieldInfo( $table, $field );
724 return $fieldInfoData->maxLength();
727 function limitResult( $sql, $limit, $offset = false ) {
728 if ( $offset === false ) {
731 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
734 function encodeBlob( $b ) {
735 return new Blob( $b );
738 function decodeBlob( $b ) {
739 if ( $b instanceof Blob
) {
745 function unionQueries( $sqls, $all ) {
746 $glue = ' UNION ALL ';
747 return 'SELECT * ' . ( $all ?
'':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
750 function wasDeadlock() {
751 return $this->lastErrno() == 'OCI-00060';
754 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
755 $temporary = $temporary ?
'TRUE' : 'FALSE';
757 $newName = strtoupper( $newName );
758 $oldName = strtoupper( $oldName );
760 $tabName = substr( $newName, strlen( $this->mTablePrefix
) );
761 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
762 $newPrefix = strtoupper( $this->mTablePrefix
);
764 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', '$oldPrefix', '$newPrefix', $temporary ); END;" );
767 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
769 if (!empty($prefix)) {
770 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
773 $owner = strtoupper( $this->mDBname
);
774 $result = $this->doQuery( "SELECT table_name FROM all_tables WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
776 // dirty code ... i know
778 $endArray[] = strtoupper($prefix.'MWUSER');
779 $endArray[] = strtoupper($prefix.'PAGE');
780 $endArray[] = strtoupper($prefix.'IMAGE');
781 $fixedOrderTabs = $endArray;
782 while (($row = $result->fetchRow()) !== false) {
783 if (!in_array($row['table_name'], $fixedOrderTabs))
784 $endArray[] = $row['table_name'];
790 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
791 $tableName = $this->tableName($tableName);
792 if( !$this->tableExists( $tableName ) ) {
796 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
799 function timestamp( $ts = 0 ) {
800 return wfTimestamp( TS_ORACLE
, $ts );
804 * Return aggregated value function call
806 function aggregateValue ( $valuedata, $valuename = 'value' ) {
810 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
811 # Ignore errors during error handling to avoid infinite
813 $ignore = $this->ignoreErrors( true );
814 ++
$this->mErrorCount
;
816 if ( $ignore ||
$tempIgnore ) {
817 wfDebug( "SQL ERROR (ignored): $error\n" );
818 $this->ignoreErrors( $ignore );
820 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
825 * @return string wikitext of a link to the server software's web site
827 public static function getSoftwareLink() {
828 return '[http://www.oracle.com/ Oracle]';
832 * @return string Version information from the database
834 function getServerVersion() {
835 //better version number, fallback on driver
836 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
837 if ( !( $row = $rset->fetchRow() ) ) {
838 return oci_server_version( $this->mConn
);
840 return $row['version'];
844 * Query whether a given index exists
847 function indexExists( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
848 $table = $this->tableName( $table );
849 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
850 $index = strtoupper( $index );
851 $owner = strtoupper( $this->mDBname
);
852 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
853 $res = $this->doQuery( $SQL );
855 $count = $res->numRows();
864 * Query whether a given table exists (in the given schema, or the default mw one if not given)
867 function tableExists( $table, $fname = __METHOD__
) {
868 $table = $this->tableName( $table );
869 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
870 $owner = $this->addQuotes( strtoupper( $this->mDBname
) );
871 $SQL = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
872 $res = $this->doQuery( $SQL );
874 $count = $res->numRows();
883 * Function translates mysql_fetch_field() functionality on ORACLE.
884 * Caching is present for reducing query time.
885 * For internal calls. Use fieldInfo for normal usage.
886 * Returns false if the field doesn't exist
888 * @param $table Array
889 * @param $field String
890 * @return ORAField|ORAResult
892 private function fieldInfoMulti( $table, $field ) {
893 $field = strtoupper( $field );
894 if ( is_array( $table ) ) {
895 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
896 $tableWhere = 'IN (';
897 foreach( $table as &$singleTable ) {
898 $singleTable = $this->removeIdentifierQuotes($singleTable);
899 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
900 return $this->mFieldInfoCache
["$singleTable.$field"];
902 $tableWhere .= '\'' . $singleTable . '\',';
904 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
906 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
907 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
908 return $this->mFieldInfoCache
["$table.$field"];
910 $tableWhere = '= \''.$table.'\'';
913 $fieldInfoStmt = oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
914 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
915 $e = oci_error( $fieldInfoStmt );
916 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
919 $res = new ORAResult( $this, $fieldInfoStmt );
920 if ( $res->numRows() == 0 ) {
921 if ( is_array( $table ) ) {
922 foreach( $table as &$singleTable ) {
923 $this->mFieldInfoCache
["$singleTable.$field"] = false;
926 $this->mFieldInfoCache
["$table.$field"] = false;
928 $fieldInfoTemp = null;
930 $fieldInfoTemp = new ORAField( $res->fetchRow() );
931 $table = $fieldInfoTemp->tableName();
932 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
935 return $fieldInfoTemp;
939 * @throws DBUnexpectedError
944 function fieldInfo( $table, $field ) {
945 if ( is_array( $table ) ) {
946 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
948 return $this->fieldInfoMulti ($table, $field);
951 function begin( $fname = 'DatabaseOracle::begin' ) {
952 $this->mTrxLevel
= 1;
953 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
956 function commit( $fname = 'DatabaseOracle::commit' ) {
957 if ( $this->mTrxLevel
) {
958 $ret = oci_commit( $this->mConn
);
960 throw new DBUnexpectedError( $this, $this->lastError() );
962 $this->mTrxLevel
= 0;
963 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
967 function rollback( $fname = 'DatabaseOracle::rollback' ) {
968 if ( $this->mTrxLevel
) {
969 oci_rollback( $this->mConn
);
970 $this->mTrxLevel
= 0;
971 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
975 /* Not even sure why this is used in the main codebase... */
976 function limitResultForUpdate( $sql, $num ) {
980 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
981 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
982 $fname = 'DatabaseOracle::sourceStream', $inputCallback = false ) {
985 $dollarquote = false;
987 $replacements = array();
989 while ( ! feof( $fp ) ) {
990 if ( $lineCallback ) {
991 call_user_func( $lineCallback );
993 $line = trim( fgets( $fp, 1024 ) );
994 $sl = strlen( $line ) - 1;
999 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1003 // Allow dollar quoting for function declarations
1004 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1005 if ( $dollarquote ) {
1006 $dollarquote = false;
1007 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1010 $dollarquote = true;
1012 } elseif ( !$dollarquote ) {
1013 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
1015 $line = substr( $line, 0, $sl );
1025 $cmd = str_replace( ';;', ";", $cmd );
1026 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1027 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1028 $replacements[$defines[2]] = $defines[1];
1031 foreach ( $replacements as $mwVar => $scVar ) {
1032 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1035 $cmd = $this->replaceVars( $cmd );
1036 if ( $inputCallback ) {
1037 call_user_func( $inputCallback, $cmd );
1039 $res = $this->doQuery( $cmd );
1040 if ( $resultCallback ) {
1041 call_user_func( $resultCallback, $res, $this );
1044 if ( false === $res ) {
1045 $err = $this->lastError();
1046 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1057 function selectDB( $db ) {
1058 $this->mDBname
= $db;
1059 if ( $db == null ||
$db == $this->mUser
) {
1062 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1063 $stmt = oci_parse( $this->mConn
, $sql );
1064 wfSuppressWarnings();
1065 $success = oci_execute( $stmt );
1066 wfRestoreWarnings();
1068 $e = oci_error( $stmt );
1069 if ( $e['code'] != '1435' ) {
1070 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1077 function strencode( $s ) {
1078 return str_replace( "'", "''", $s );
1081 function addQuotes( $s ) {
1083 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1084 $s = $wgContLang->checkTitleEncoding( $s );
1086 return "'" . $this->strencode( $s ) . "'";
1089 public function addIdentifierQuotes( $s ) {
1090 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1096 public function removeIdentifierQuotes( $s ) {
1097 return strpos($s, '/*Q*/') === FALSE ?
$s : substr($s, 5);
1100 public function isQuotedIdentifier( $s ) {
1101 return strpos($s, '/*Q*/') !== FALSE;
1104 private function wrapFieldForWhere( $table, &$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 $col = 'TO_CHAR(' . $col . ')';
1111 $val = $wgContLang->checkTitleEncoding( $val );
1112 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1113 $val = $wgContLang->checkTitleEncoding( $val );
1117 private function wrapConditionsForWhere ( $table, $conds, $parentCol = null ) {
1119 foreach ( $conds as $col => $val ) {
1120 if ( is_array( $val ) ) {
1121 $conds2[$col] = $this->wrapConditionsForWhere ( $table, $val, $col );
1123 if ( is_numeric( $col ) && $parentCol != null ) {
1124 $this->wrapFieldForWhere ( $table, $parentCol, $val );
1126 $this->wrapFieldForWhere ( $table, $col, $val );
1128 $conds2[$col] = $val;
1134 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1135 if ( is_array($conds) ) {
1136 $conds = $this->wrapConditionsForWhere( $table, $conds );
1138 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1142 * Returns an optional USE INDEX clause to go after the table, and a
1143 * string to go at the end of the query
1147 * @param $options Array: an associative array of options to be turned into
1148 * an SQL query, valid keys are listed in the function.
1151 function makeSelectOptions( $options ) {
1152 $preLimitTail = $postLimitTail = '';
1155 $noKeyOptions = array();
1156 foreach ( $options as $key => $option ) {
1157 if ( is_numeric( $key ) ) {
1158 $noKeyOptions[$option] = true;
1162 if ( isset( $options['GROUP BY'] ) ) {
1163 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1165 if ( isset( $options['ORDER BY'] ) ) {
1166 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1169 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1170 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1171 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1172 $startOpts .= 'DISTINCT';
1175 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1176 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1181 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1184 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1185 if ( is_array($conds) ) {
1186 $conds = $this->wrapConditionsForWhere( $table, $conds );
1188 // a hack for deleting pages, users and images (which have non-nullable FKs)
1189 // all deletions on these tables have transactions so final failure rollbacks these updates
1190 $table = $this->tableName( $table );
1191 if ( $table == $this->tableName( 'user' ) ) {
1192 $this->update( 'archive', array( 'ar_user' => 0 ), array( 'ar_user' => $conds['user_id'] ), $fname );
1193 $this->update( 'ipblocks', array( 'ipb_user' => 0 ), array( 'ipb_user' => $conds['user_id'] ), $fname );
1194 $this->update( 'image', array( 'img_user' => 0 ), array( 'img_user' => $conds['user_id'] ), $fname );
1195 $this->update( 'oldimage', array( 'oi_user' => 0 ), array( 'oi_user' => $conds['user_id'] ), $fname );
1196 $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ), array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
1197 $this->update( 'filearchive', array( 'fa_user' => 0 ), array( 'fa_user' => $conds['user_id'] ), $fname );
1198 $this->update( 'uploadstash', array( 'us_user' => 0 ), array( 'us_user' => $conds['user_id'] ), $fname );
1199 $this->update( 'recentchanges', array( 'rc_user' => 0 ), array( 'rc_user' => $conds['user_id'] ), $fname );
1200 $this->update( 'logging', array( 'log_user' => 0 ), array( 'log_user' => $conds['user_id'] ), $fname );
1201 } elseif ( $table == $this->tableName( 'image' ) ) {
1202 $this->update( 'oldimage', array( 'oi_name' => 0 ), array( 'oi_name' => $conds['img_name'] ), $fname );
1204 return parent
::delete( $table, $conds, $fname );
1207 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1210 $table = $this->tableName( $table );
1211 $opts = $this->makeUpdateOptions( $options );
1212 $sql = "UPDATE $opts $table SET ";
1215 foreach ( $values as $col => &$val ) {
1216 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1219 $sqlSet = ', ' . $sqlSet;
1226 if ( $conds !== array() && $conds !== '*' ) {
1227 $conds = $this->wrapConditionsForWhere( $table, $conds );
1228 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1231 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1232 $e = oci_error( $this->mConn
);
1233 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1236 foreach ( $values as $col => &$val ) {
1237 $col_info = $this->fieldInfoMulti( $table, $col );
1238 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1240 if ( $val === null ) {
1241 // do nothing ... null was inserted in statement creation
1242 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1243 if ( is_object( $val ) ) {
1244 $val = $val->getData();
1247 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1248 $val = '31-12-2030 12:00:00.000000';
1251 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1252 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1253 $e = oci_error( $stmt );
1254 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1258 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1259 $e = oci_error( $stmt );
1260 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1263 if ( $col_type == 'BLOB' ) {
1264 $lob[$col]->writeTemporary( $val );
1265 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
1267 $lob[$col]->writeTemporary( $val );
1268 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
1273 wfSuppressWarnings();
1275 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1276 $e = oci_error( $stmt );
1277 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
1278 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1281 $this->mAffectedRows
= oci_num_rows( $stmt );
1284 $this->mAffectedRows
= oci_num_rows( $stmt );
1287 wfRestoreWarnings();
1289 if ( isset( $lob ) ) {
1290 foreach ( $lob as $lob_v ) {
1295 if ( !$this->mTrxLevel
) {
1296 oci_commit( $this->mConn
);
1299 oci_free_statement( $stmt );
1302 function bitNot( $field ) {
1303 // expecting bit-fields smaller than 4bytes
1304 return 'BITNOT(' . $field . ')';
1307 function bitAnd( $fieldLeft, $fieldRight ) {
1308 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1311 function bitOr( $fieldLeft, $fieldRight ) {
1312 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1315 function setFakeMaster( $enabled = true ) {
1318 function getDBname() {
1319 return $this->mDBname
;
1322 function getServer() {
1323 return $this->mServer
;
1326 public function getSearchEngine() {
1327 return 'SearchOracle';
1330 public function getInfinity() {
1331 return '31-12-2030 12:00:00.000000';
1334 } // end DatabaseOracle class