3 * This is the Oracle database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
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;
53 * @param $db DatabaseBase
57 function __construct( &$db, $stmt, $unique = false ) {
60 if ( ( $this->nrows
= oci_fetch_all( $stmt, $this->rows
, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM
) ) === false ) {
61 $e = oci_error( $stmt );
62 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__
);
68 $this->rows
= $this->array_unique_md( $this->rows
);
69 $this->nrows
= count( $this->rows
);
72 if ($this->nrows
> 0) {
73 foreach ( $this->rows
[0] as $k => $v ) {
74 $this->columns
[$k] = strtolower( oci_field_name( $stmt, $k +
1 ) );
79 oci_free_statement( $stmt );
82 public function free() {
86 public function seek( $row ) {
87 $this->cursor
= min( $row, $this->nrows
);
90 public function numRows() {
94 public function numFields() {
95 return count($this->columns
);
98 public function fetchObject() {
99 if ( $this->cursor
>= $this->nrows
) {
102 $row = $this->rows
[$this->cursor++
];
103 $ret = new stdClass();
104 foreach ( $row as $k => $v ) {
105 $lc = $this->columns
[$k];
112 public function fetchRow() {
113 if ( $this->cursor
>= $this->nrows
) {
117 $row = $this->rows
[$this->cursor++
];
119 foreach ( $row as $k => $v ) {
120 $lc = $this->columns
[$k];
132 class ORAField
implements Field
{
133 private $name, $tablename, $default, $max_length, $nullable,
134 $is_pk, $is_unique, $is_multiple, $is_key, $type;
136 function __construct( $info ) {
137 $this->name
= $info['column_name'];
138 $this->tablename
= $info['table_name'];
139 $this->default = $info['data_default'];
140 $this->max_length
= $info['data_length'];
141 $this->nullable
= $info['not_null'];
142 $this->is_pk
= isset( $info['prim'] ) && $info['prim'] == 1 ?
1 : 0;
143 $this->is_unique
= isset( $info['uniq'] ) && $info['uniq'] == 1 ?
1 : 0;
144 $this->is_multiple
= isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ?
1 : 0;
145 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
146 $this->type
= $info['data_type'];
153 function tableName() {
154 return $this->tablename
;
157 function defaultValue() {
158 return $this->default;
161 function maxLength() {
162 return $this->max_length
;
165 function isNullable() {
166 return $this->nullable
;
170 return $this->is_key
;
173 function isMultipleKey() {
174 return $this->is_multiple
;
185 class DatabaseOracle
extends DatabaseBase
{
186 var $mInsertId = null;
187 var $mLastResult = null;
188 var $lastResult = null;
192 var $ignore_DUP_VAL_ON_INDEX = false;
193 var $sequenceData = null;
195 var $defaultCharset = 'AL32UTF8';
197 var $mFieldInfoCache = array();
199 function __construct( $server = false, $user = false, $password = false, $dbName = false,
200 $flags = 0, $tablePrefix = 'get from global' )
203 $tablePrefix = $tablePrefix == 'get from global' ?
strtoupper( $wgDBprefix ) : strtoupper( $tablePrefix );
204 parent
::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
205 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
208 function __destruct() {
209 if ($this->mOpened
) {
210 wfSuppressWarnings();
220 function cascadingDeletes() {
223 function cleanupTriggers() {
226 function strictIPs() {
229 function realTimestamps() {
232 function implicitGroupby() {
235 function implicitOrderby() {
238 function searchableIPs() {
243 * Usually aborts on failure
244 * @return DatabaseBase|null
246 function open( $server, $user, $password, $dbName ) {
247 if ( !function_exists( 'oci_connect' ) ) {
248 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" );
252 $this->mUser
= $user;
253 $this->mPassword
= $password;
254 // changed internal variables functions
255 // mServer now holds the TNS endpoint
256 // mDBname is schema name if different from username
258 // backward compatibillity (server used to be null and TNS was supplied in dbname)
259 $this->mServer
= $dbName;
260 $this->mDBname
= $user;
262 $this->mServer
= $server;
264 $this->mDBname
= $user;
266 $this->mDBname
= $dbName;
270 if ( !strlen( $user ) ) { # e.g. the class is being loaded
274 $session_mode = $this->mFlags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
275 wfSuppressWarnings();
276 if ( $this->mFlags
& DBO_DEFAULT
) {
277 $this->mConn
= oci_new_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
279 $this->mConn
= oci_connect( $this->mUser
, $this->mPassword
, $this->mServer
, $this->defaultCharset
, $session_mode );
283 if ( $this->mUser
!= $this->mDBname
) {
284 //change current schema in session
285 $this->selectDB( $this->mDBname
);
288 if ( !$this->mConn
) {
289 throw new DBConnectionError( $this, $this->lastError() );
292 $this->mOpened
= true;
294 # removed putenv calls because they interfere with the system globaly
295 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
296 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
297 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
302 * Closes a database connection, if it is open
303 * Returns success, true if already closed
306 protected function closeConnection() {
307 return oci_close( $this->mConn
);
310 function execFlags() {
311 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
314 protected function doQuery( $sql ) {
315 wfDebug( "SQL: [$sql]\n" );
316 if ( !mb_check_encoding( $sql ) ) {
317 throw new MWException( "SQL encoding is invalid\n$sql" );
320 // handle some oracle specifics
321 // remove AS column/table/subquery namings
322 if( !$this->getFlag( DBO_DDLMODE
) ) {
323 $sql = preg_replace( '/ as /i', ' ', $sql );
326 // Oracle has issues with UNION clause if the statement includes LOB fields
327 // So we do a UNION ALL and then filter the results array with array_unique
328 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
329 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
330 // you have to select data from plan table after explain
331 $explain_id = date( 'dmYHis' );
333 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
335 wfSuppressWarnings();
337 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
338 $e = oci_error( $this->mConn
);
339 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
343 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
344 $e = oci_error( $stmt );
345 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
346 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
353 if ( $explain_count > 0 ) {
354 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
355 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
356 return new ORAResult( $this, $stmt, $union_unique );
358 $this->mAffectedRows
= oci_num_rows( $stmt );
363 function queryIgnore( $sql, $fname = '' ) {
364 return $this->query( $sql, $fname, true );
367 function freeResult( $res ) {
368 if ( $res instanceof ResultWrapper
) {
375 function fetchObject( $res ) {
376 if ( $res instanceof ResultWrapper
) {
380 return $res->fetchObject();
383 function fetchRow( $res ) {
384 if ( $res instanceof ResultWrapper
) {
388 return $res->fetchRow();
391 function numRows( $res ) {
392 if ( $res instanceof ResultWrapper
) {
396 return $res->numRows();
399 function numFields( $res ) {
400 if ( $res instanceof ResultWrapper
) {
404 return $res->numFields();
407 function fieldName( $stmt, $n ) {
408 return oci_field_name( $stmt, $n );
412 * This must be called after nextSequenceVal
415 function insertId() {
416 return $this->mInsertId
;
419 function dataSeek( $res, $row ) {
420 if ( $res instanceof ORAResult
) {
423 $res->result
->seek( $row );
427 function lastError() {
428 if ( $this->mConn
=== false ) {
431 $e = oci_error( $this->mConn
);
433 return $e['message'];
436 function lastErrno() {
437 if ( $this->mConn
=== false ) {
440 $e = oci_error( $this->mConn
);
445 function affectedRows() {
446 return $this->mAffectedRows
;
450 * Returns information about an index
451 * If errors are explicitly ignored, returns NULL on failure
454 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
458 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
462 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
463 if ( !count( $a ) ) {
467 if ( !is_array( $options ) ) {
468 $options = array( $options );
471 if ( in_array( 'IGNORE', $options ) ) {
472 $this->ignore_DUP_VAL_ON_INDEX
= true;
475 if ( !is_array( reset( $a ) ) ) {
479 foreach ( $a as &$row ) {
480 $this->insertOneRow( $table, $row, $fname );
484 if ( in_array( 'IGNORE', $options ) ) {
485 $this->ignore_DUP_VAL_ON_INDEX
= false;
491 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
492 $col_info = $this->fieldInfoMulti( $table, $col );
493 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
496 if ( is_numeric( $col ) ) {
500 } elseif ( $includeCol ) {
504 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
508 if ( $val === 'NULL' ) {
512 if ( $val === null ) {
513 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
525 private function insertOneRow( $table, $row, $fname ) {
528 $table = $this->tableName( $table );
529 // "INSERT INTO tables (a, b, c)"
530 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
533 // for each value, append ":key"
535 foreach ( $row as $col => &$val ) {
542 $sql .= $this->fieldBindStatement( $table, $col, $val );
546 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
547 $e = oci_error( $this->mConn
);
548 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
551 foreach ( $row as $col => &$val ) {
552 $col_info = $this->fieldInfoMulti( $table, $col );
553 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
555 if ( $val === null ) {
556 // do nothing ... null was inserted in statement creation
557 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
558 if ( is_object( $val ) ) {
559 $val = $val->fetch();
562 // backward compatibility
563 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
564 $val = $this->getInfinity();
567 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
568 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
569 $e = oci_error( $stmt );
570 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
574 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
575 $e = oci_error( $stmt );
576 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
579 if ( is_object( $val ) ) {
580 $val = $val->fetch();
583 if ( $col_type == 'BLOB' ) {
584 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
585 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB
);
587 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
588 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
593 wfSuppressWarnings();
595 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
596 $e = oci_error( $stmt );
597 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
598 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
601 $this->mAffectedRows
= oci_num_rows( $stmt );
604 $this->mAffectedRows
= oci_num_rows( $stmt );
609 if ( isset( $lob ) ) {
610 foreach ( $lob as $lob_v ) {
615 if ( !$this->mTrxLevel
) {
616 oci_commit( $this->mConn
);
619 oci_free_statement( $stmt );
622 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
623 $insertOptions = array(), $selectOptions = array() )
625 $destTable = $this->tableName( $destTable );
626 if ( !is_array( $selectOptions ) ) {
627 $selectOptions = array( $selectOptions );
629 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
630 if ( is_array( $srcTable ) ) {
631 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
633 $srcTable = $this->tableName( $srcTable );
636 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
637 !isset( $varMap[$sequenceData['column']] ) )
639 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
642 // count-alias subselect fields to avoid abigious definition errors
644 foreach ( $varMap as &$val ) {
645 $val = $val . ' field' . ( $i++
);
648 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
649 " SELECT $startOpts " . implode( ',', $varMap ) .
650 " FROM $srcTable $useIndex ";
651 if ( $conds != '*' ) {
652 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
654 $sql .= " $tailOpts";
656 if ( in_array( 'IGNORE', $insertOptions ) ) {
657 $this->ignore_DUP_VAL_ON_INDEX
= true;
660 $retval = $this->query( $sql, $fname );
662 if ( in_array( 'IGNORE', $insertOptions ) ) {
663 $this->ignore_DUP_VAL_ON_INDEX
= false;
669 function tableName( $name, $format = 'quoted' ) {
671 Replace reserved words with better ones
672 Using uppercase because that's the only way Oracle can handle
680 $name = 'PAGECONTENT';
684 return parent
::tableName( strtoupper( $name ), $format );
687 function tableNameInternal( $name ) {
688 $name = $this->tableName( $name );
689 return preg_replace( '/.*\.(.*)/', '$1', $name);
692 * Return the next in a sequence, save the value for retrieval via insertId()
695 function nextSequenceValue( $seqName ) {
696 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
697 $row = $this->fetchRow( $res );
698 $this->mInsertId
= $row[0];
699 return $this->mInsertId
;
703 * Return sequence_name if table has a sequence
706 private function getSequenceData( $table ) {
707 if ( $this->sequenceData
== null ) {
708 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
709 lower(atc.table_name),
710 lower(atc.column_name)
711 FROM all_sequences asq, all_tab_columns atc
712 WHERE decode(atc.table_name, '{$this->mTablePrefix}MWUSER', '{$this->mTablePrefix}USER', atc.table_name) || '_' ||
713 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
714 AND asq.sequence_owner = upper('{$this->mDBname}')
715 AND atc.owner = upper('{$this->mDBname}')" );
717 while ( ( $row = $result->fetchRow() ) !== false ) {
718 $this->sequenceData
[$row[1]] = array(
719 'sequence' => $row[0],
724 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
725 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
728 # Returns the size of a text field, or -1 for "unlimited"
729 function textFieldSize( $table, $field ) {
730 $fieldInfoData = $this->fieldInfo( $table, $field );
731 return $fieldInfoData->maxLength();
734 function limitResult( $sql, $limit, $offset = false ) {
735 if ( $offset === false ) {
738 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
741 function encodeBlob( $b ) {
742 return new Blob( $b );
745 function decodeBlob( $b ) {
746 if ( $b instanceof Blob
) {
752 function unionQueries( $sqls, $all ) {
753 $glue = ' UNION ALL ';
754 return 'SELECT * ' . ( $all ?
'':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
757 function wasDeadlock() {
758 return $this->lastErrno() == 'OCI-00060';
761 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
762 $temporary = $temporary ?
'TRUE' : 'FALSE';
764 $newName = strtoupper( $newName );
765 $oldName = strtoupper( $oldName );
767 $tabName = substr( $newName, strlen( $this->mTablePrefix
) );
768 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
769 $newPrefix = strtoupper( $this->mTablePrefix
);
771 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', '$oldPrefix', '$newPrefix', $temporary ); END;" );
774 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
776 if (!empty($prefix)) {
777 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
780 $owner = strtoupper( $this->mDBname
);
781 $result = $this->doQuery( "SELECT table_name FROM all_tables WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
783 // dirty code ... i know
785 $endArray[] = strtoupper($prefix.'MWUSER');
786 $endArray[] = strtoupper($prefix.'PAGE');
787 $endArray[] = strtoupper($prefix.'IMAGE');
788 $fixedOrderTabs = $endArray;
789 while (($row = $result->fetchRow()) !== false) {
790 if (!in_array($row['table_name'], $fixedOrderTabs))
791 $endArray[] = $row['table_name'];
797 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
798 $tableName = $this->tableName($tableName);
799 if( !$this->tableExists( $tableName ) ) {
803 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
806 function timestamp( $ts = 0 ) {
807 return wfTimestamp( TS_ORACLE
, $ts );
811 * Return aggregated value function call
813 public function aggregateValue( $valuedata, $valuename = 'value' ) {
817 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
818 # Ignore errors during error handling to avoid infinite
820 $ignore = $this->ignoreErrors( true );
821 ++
$this->mErrorCount
;
823 if ( $ignore ||
$tempIgnore ) {
824 wfDebug( "SQL ERROR (ignored): $error\n" );
825 $this->ignoreErrors( $ignore );
827 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
832 * @return string wikitext of a link to the server software's web site
834 public static function getSoftwareLink() {
835 return '[http://www.oracle.com/ Oracle]';
839 * @return string Version information from the database
841 function getServerVersion() {
842 //better version number, fallback on driver
843 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
844 if ( !( $row = $rset->fetchRow() ) ) {
845 return oci_server_version( $this->mConn
);
847 return $row['version'];
851 * Query whether a given index exists
854 function indexExists( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
855 $table = $this->tableName( $table );
856 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
857 $index = strtoupper( $index );
858 $owner = strtoupper( $this->mDBname
);
859 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
860 $res = $this->doQuery( $SQL );
862 $count = $res->numRows();
871 * Query whether a given table exists (in the given schema, or the default mw one if not given)
874 function tableExists( $table, $fname = __METHOD__
) {
875 $table = $this->tableName( $table );
876 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
877 $owner = $this->addQuotes( strtoupper( $this->mDBname
) );
878 $SQL = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
879 $res = $this->doQuery( $SQL );
881 $count = $res->numRows();
890 * Function translates mysql_fetch_field() functionality on ORACLE.
891 * Caching is present for reducing query time.
892 * For internal calls. Use fieldInfo for normal usage.
893 * Returns false if the field doesn't exist
895 * @param $table Array
896 * @param $field String
897 * @return ORAField|ORAResult
899 private function fieldInfoMulti( $table, $field ) {
900 $field = strtoupper( $field );
901 if ( is_array( $table ) ) {
902 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
903 $tableWhere = 'IN (';
904 foreach( $table as &$singleTable ) {
905 $singleTable = $this->removeIdentifierQuotes($singleTable);
906 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
907 return $this->mFieldInfoCache
["$singleTable.$field"];
909 $tableWhere .= '\'' . $singleTable . '\',';
911 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
913 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
914 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
915 return $this->mFieldInfoCache
["$table.$field"];
917 $tableWhere = '= \''.$table.'\'';
920 $fieldInfoStmt = oci_parse( $this->mConn
, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
921 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
922 $e = oci_error( $fieldInfoStmt );
923 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
926 $res = new ORAResult( $this, $fieldInfoStmt );
927 if ( $res->numRows() == 0 ) {
928 if ( is_array( $table ) ) {
929 foreach( $table as &$singleTable ) {
930 $this->mFieldInfoCache
["$singleTable.$field"] = false;
933 $this->mFieldInfoCache
["$table.$field"] = false;
935 $fieldInfoTemp = null;
937 $fieldInfoTemp = new ORAField( $res->fetchRow() );
938 $table = $fieldInfoTemp->tableName();
939 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
942 return $fieldInfoTemp;
946 * @throws DBUnexpectedError
951 function fieldInfo( $table, $field ) {
952 if ( is_array( $table ) ) {
953 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
955 return $this->fieldInfoMulti ($table, $field);
958 protected function doBegin( $fname = 'DatabaseOracle::begin' ) {
959 $this->mTrxLevel
= 1;
960 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
963 protected function doCommit( $fname = 'DatabaseOracle::commit' ) {
964 if ( $this->mTrxLevel
) {
965 $ret = oci_commit( $this->mConn
);
967 throw new DBUnexpectedError( $this, $this->lastError() );
969 $this->mTrxLevel
= 0;
970 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
974 protected function doRollback( $fname = 'DatabaseOracle::rollback' ) {
975 if ( $this->mTrxLevel
) {
976 oci_rollback( $this->mConn
);
977 $this->mTrxLevel
= 0;
978 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
982 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
983 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
984 $fname = 'DatabaseOracle::sourceStream', $inputCallback = false ) {
987 $dollarquote = false;
989 $replacements = array();
991 while ( ! feof( $fp ) ) {
992 if ( $lineCallback ) {
993 call_user_func( $lineCallback );
995 $line = trim( fgets( $fp, 1024 ) );
996 $sl = strlen( $line ) - 1;
1001 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1005 // Allow dollar quoting for function declarations
1006 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1007 if ( $dollarquote ) {
1008 $dollarquote = false;
1009 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1012 $dollarquote = true;
1014 } elseif ( !$dollarquote ) {
1015 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
1017 $line = substr( $line, 0, $sl );
1027 $cmd = str_replace( ';;', ";", $cmd );
1028 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1029 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1030 $replacements[$defines[2]] = $defines[1];
1033 foreach ( $replacements as $mwVar => $scVar ) {
1034 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1037 $cmd = $this->replaceVars( $cmd );
1038 if ( $inputCallback ) {
1039 call_user_func( $inputCallback, $cmd );
1041 $res = $this->doQuery( $cmd );
1042 if ( $resultCallback ) {
1043 call_user_func( $resultCallback, $res, $this );
1046 if ( false === $res ) {
1047 $err = $this->lastError();
1048 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1059 function selectDB( $db ) {
1060 $this->mDBname
= $db;
1061 if ( $db == null ||
$db == $this->mUser
) {
1064 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1065 $stmt = oci_parse( $this->mConn
, $sql );
1066 wfSuppressWarnings();
1067 $success = oci_execute( $stmt );
1068 wfRestoreWarnings();
1070 $e = oci_error( $stmt );
1071 if ( $e['code'] != '1435' ) {
1072 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1079 function strencode( $s ) {
1080 return str_replace( "'", "''", $s );
1083 function addQuotes( $s ) {
1085 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1086 $s = $wgContLang->checkTitleEncoding( $s );
1088 return "'" . $this->strencode( $s ) . "'";
1091 public function addIdentifierQuotes( $s ) {
1092 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1098 public function removeIdentifierQuotes( $s ) {
1099 return strpos($s, '/*Q*/') === FALSE ?
$s : substr($s, 5);
1102 public function isQuotedIdentifier( $s ) {
1103 return strpos($s, '/*Q*/') !== FALSE;
1106 private function wrapFieldForWhere( $table, &$col, &$val ) {
1109 $col_info = $this->fieldInfoMulti( $table, $col );
1110 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1111 if ( $col_type == 'CLOB' ) {
1112 $col = 'TO_CHAR(' . $col . ')';
1113 $val = $wgContLang->checkTitleEncoding( $val );
1114 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1115 $val = $wgContLang->checkTitleEncoding( $val );
1119 private function wrapConditionsForWhere ( $table, $conds, $parentCol = null ) {
1121 foreach ( $conds as $col => $val ) {
1122 if ( is_array( $val ) ) {
1123 $conds2[$col] = $this->wrapConditionsForWhere ( $table, $val, $col );
1125 if ( is_numeric( $col ) && $parentCol != null ) {
1126 $this->wrapFieldForWhere ( $table, $parentCol, $val );
1128 $this->wrapFieldForWhere ( $table, $col, $val );
1130 $conds2[$col] = $val;
1136 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1137 if ( is_array($conds) ) {
1138 $conds = $this->wrapConditionsForWhere( $table, $conds );
1140 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1144 * Returns an optional USE INDEX clause to go after the table, and a
1145 * string to go at the end of the query
1149 * @param $options Array: an associative array of options to be turned into
1150 * an SQL query, valid keys are listed in the function.
1153 function makeSelectOptions( $options ) {
1154 $preLimitTail = $postLimitTail = '';
1157 $noKeyOptions = array();
1158 foreach ( $options as $key => $option ) {
1159 if ( is_numeric( $key ) ) {
1160 $noKeyOptions[$option] = true;
1164 if ( isset( $options['GROUP BY'] ) ) {
1165 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1167 if ( isset( $options['ORDER BY'] ) ) {
1168 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1171 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1172 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1173 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1174 $startOpts .= 'DISTINCT';
1177 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1178 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1183 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1186 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1187 if ( is_array($conds) ) {
1188 $conds = $this->wrapConditionsForWhere( $table, $conds );
1190 // a hack for deleting pages, users and images (which have non-nullable FKs)
1191 // all deletions on these tables have transactions so final failure rollbacks these updates
1192 $table = $this->tableName( $table );
1193 if ( $table == $this->tableName( 'user' ) ) {
1194 $this->update( 'archive', array( 'ar_user' => 0 ), array( 'ar_user' => $conds['user_id'] ), $fname );
1195 $this->update( 'ipblocks', array( 'ipb_user' => 0 ), array( 'ipb_user' => $conds['user_id'] ), $fname );
1196 $this->update( 'image', array( 'img_user' => 0 ), array( 'img_user' => $conds['user_id'] ), $fname );
1197 $this->update( 'oldimage', array( 'oi_user' => 0 ), array( 'oi_user' => $conds['user_id'] ), $fname );
1198 $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ), array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
1199 $this->update( 'filearchive', array( 'fa_user' => 0 ), array( 'fa_user' => $conds['user_id'] ), $fname );
1200 $this->update( 'uploadstash', array( 'us_user' => 0 ), array( 'us_user' => $conds['user_id'] ), $fname );
1201 $this->update( 'recentchanges', array( 'rc_user' => 0 ), array( 'rc_user' => $conds['user_id'] ), $fname );
1202 $this->update( 'logging', array( 'log_user' => 0 ), array( 'log_user' => $conds['user_id'] ), $fname );
1203 } elseif ( $table == $this->tableName( 'image' ) ) {
1204 $this->update( 'oldimage', array( 'oi_name' => 0 ), array( 'oi_name' => $conds['img_name'] ), $fname );
1206 return parent
::delete( $table, $conds, $fname );
1209 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1212 $table = $this->tableName( $table );
1213 $opts = $this->makeUpdateOptions( $options );
1214 $sql = "UPDATE $opts $table SET ";
1217 foreach ( $values as $col => &$val ) {
1218 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1221 $sqlSet = ', ' . $sqlSet;
1228 if ( $conds !== array() && $conds !== '*' ) {
1229 $conds = $this->wrapConditionsForWhere( $table, $conds );
1230 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1233 if ( ( $this->mLastResult
= $stmt = oci_parse( $this->mConn
, $sql ) ) === false ) {
1234 $e = oci_error( $this->mConn
);
1235 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1238 foreach ( $values as $col => &$val ) {
1239 $col_info = $this->fieldInfoMulti( $table, $col );
1240 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1242 if ( $val === null ) {
1243 // do nothing ... null was inserted in statement creation
1244 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1245 if ( is_object( $val ) ) {
1246 $val = $val->getData();
1249 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1250 $val = '31-12-2030 12:00:00.000000';
1253 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1254 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1255 $e = oci_error( $stmt );
1256 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1260 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn
, OCI_D_LOB
) ) === false ) {
1261 $e = oci_error( $stmt );
1262 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1265 if ( $col_type == 'BLOB' ) {
1266 $lob[$col]->writeTemporary( $val );
1267 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB
);
1269 $lob[$col]->writeTemporary( $val );
1270 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB
);
1275 wfSuppressWarnings();
1277 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1278 $e = oci_error( $stmt );
1279 if ( !$this->ignore_DUP_VAL_ON_INDEX ||
$e['code'] != '1' ) {
1280 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1283 $this->mAffectedRows
= oci_num_rows( $stmt );
1286 $this->mAffectedRows
= oci_num_rows( $stmt );
1289 wfRestoreWarnings();
1291 if ( isset( $lob ) ) {
1292 foreach ( $lob as $lob_v ) {
1297 if ( !$this->mTrxLevel
) {
1298 oci_commit( $this->mConn
);
1301 oci_free_statement( $stmt );
1304 function bitNot( $field ) {
1305 // expecting bit-fields smaller than 4bytes
1306 return 'BITNOT(' . $field . ')';
1309 function bitAnd( $fieldLeft, $fieldRight ) {
1310 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1313 function bitOr( $fieldLeft, $fieldRight ) {
1314 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1317 function setFakeMaster( $enabled = true ) {
1320 function getDBname() {
1321 return $this->mDBname
;
1324 function getServer() {
1325 return $this->mServer
;
1328 public function getSearchEngine() {
1329 return 'SearchOracle';
1332 public function getInfinity() {
1333 return '31-12-2030 12:00:00.000000';
1336 } // end DatabaseOracle class