* updated listTables function to also take in account possible user-dbname difference
[lhc/web/wiklou.git] / includes / db / DatabaseOracle.php
1 <?php
2 /**
3 * This is the Oracle database abstraction layer.
4 *
5 * @file
6 * @ingroup Database
7 */
8
9 /**
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.
13 * @ingroup Database
14 */
15 class ORAResult {
16 private $rows;
17 private $cursor;
18 private $nrows;
19
20 private $columns = array();
21
22 private function array_unique_md( $array_in ) {
23 $array_out = array();
24 $array_hashes = array();
25
26 foreach ( $array_in as $item ) {
27 $hash = md5( serialize( $item ) );
28 if ( !isset( $array_hashes[$hash] ) ) {
29 $array_hashes[$hash] = $hash;
30 $array_out[] = $item;
31 }
32 }
33
34 return $array_out;
35 }
36
37 /**
38 * @param $db DatabaseBase
39 * @param $stmt
40 * @param bool $unique
41 */
42 function __construct( &$db, $stmt, $unique = false ) {
43 $this->db =& $db;
44
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__ );
48 $this->free();
49 return;
50 }
51
52 if ( $unique ) {
53 $this->rows = $this->array_unique_md( $this->rows );
54 $this->nrows = count( $this->rows );
55 }
56
57 if ($this->nrows > 0) {
58 foreach ( $this->rows[0] as $k => $v ) {
59 $this->columns[$k] = strtolower( oci_field_name( $stmt, $k + 1 ) );
60 }
61 }
62
63 $this->cursor = 0;
64 oci_free_statement( $stmt );
65 }
66
67 public function free() {
68 unset($this->db);
69 }
70
71 public function seek( $row ) {
72 $this->cursor = min( $row, $this->nrows );
73 }
74
75 public function numRows() {
76 return $this->nrows;
77 }
78
79 public function numFields() {
80 return count($this->columns);
81 }
82
83 public function fetchObject() {
84 if ( $this->cursor >= $this->nrows ) {
85 return false;
86 }
87 $row = $this->rows[$this->cursor++];
88 $ret = new stdClass();
89 foreach ( $row as $k => $v ) {
90 $lc = $this->columns[$k];
91 $ret->$lc = $v;
92 }
93
94 return $ret;
95 }
96
97 public function fetchRow() {
98 if ( $this->cursor >= $this->nrows ) {
99 return false;
100 }
101
102 $row = $this->rows[$this->cursor++];
103 $ret = array();
104 foreach ( $row as $k => $v ) {
105 $lc = $this->columns[$k];
106 $ret[$lc] = $v;
107 $ret[$k] = $v;
108 }
109 return $ret;
110 }
111 }
112
113 /**
114 * Utility class.
115 * @ingroup Database
116 */
117 class ORAField implements Field {
118 private $name, $tablename, $default, $max_length, $nullable,
119 $is_pk, $is_unique, $is_multiple, $is_key, $type;
120
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'];
132 }
133
134 function name() {
135 return $this->name;
136 }
137
138 function tableName() {
139 return $this->tablename;
140 }
141
142 function defaultValue() {
143 return $this->default;
144 }
145
146 function maxLength() {
147 return $this->max_length;
148 }
149
150 function isNullable() {
151 return $this->nullable;
152 }
153
154 function isKey() {
155 return $this->is_key;
156 }
157
158 function isMultipleKey() {
159 return $this->is_multiple;
160 }
161
162 function type() {
163 return $this->type;
164 }
165 }
166
167 /**
168 * @ingroup Database
169 */
170 class DatabaseOracle extends DatabaseBase {
171 var $mInsertId = null;
172 var $mLastResult = null;
173 var $lastResult = null;
174 var $cursor = 0;
175 var $mAffectedRows;
176
177 var $ignore_DUP_VAL_ON_INDEX = false;
178 var $sequenceData = null;
179
180 var $defaultCharset = 'AL32UTF8';
181
182 var $mFieldInfoCache = array();
183
184 function __construct( $server = false, $user = false, $password = false, $dbName = false,
185 $flags = 0, $tablePrefix = 'get from global' )
186 {
187 global $wgDBprefix;
188 $tablePrefix = $tablePrefix == 'get from global' ? strtoupper( $wgDBprefix ) : strtoupper( $tablePrefix );
189 parent::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
190 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
191 }
192
193 function __destruct() {
194 if ($this->mOpened) {
195 wfSuppressWarnings();
196 $this->close();
197 wfRestoreWarnings();
198 }
199 }
200
201 function getType() {
202 return 'oracle';
203 }
204
205 function cascadingDeletes() {
206 return true;
207 }
208 function cleanupTriggers() {
209 return true;
210 }
211 function strictIPs() {
212 return true;
213 }
214 function realTimestamps() {
215 return true;
216 }
217 function implicitGroupby() {
218 return false;
219 }
220 function implicitOrderby() {
221 return false;
222 }
223 function searchableIPs() {
224 return true;
225 }
226
227 /**
228 * Usually aborts on failure
229 */
230 function open( $server, $user, $password, $dbName ) {
231 if ( !function_exists( 'oci_connect' ) ) {
232 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" );
233 }
234
235 $this->close();
236 $this->mUser = $user;
237 $this->mPassword = $password;
238 // changed internal variables functions
239 // mServer now holds the TNS endpoint
240 // mDBname is schema name if different from username
241 if ( !$server ) {
242 // backward compatibillity (server used to be null and TNS was supplied in dbname)
243 $this->mServer = $dbName;
244 $this->mDBname = $user;
245 } else {
246 $this->mServer = $server;
247 if ( !$dbName ) {
248 $this->mDBname = $user;
249 } else {
250 $this->mDBname = $dbName;
251 }
252 }
253
254 if ( !strlen( $user ) ) { # e.g. the class is being loaded
255 return;
256 }
257
258 $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
259 wfSuppressWarnings();
260 if ( $this->mFlags & DBO_DEFAULT ) {
261 $this->mConn = oci_new_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
262 } else {
263 $this->mConn = oci_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
264 }
265 wfRestoreWarnings();
266
267 if ( $this->mUser != $this->mDBname ) {
268 //change current schema in session
269 $this->selectDB( $this->mDBname );
270 }
271
272 if ( !$this->mConn ) {
273 throw new DBConnectionError( $this, $this->lastError() );
274 }
275
276 $this->mOpened = true;
277
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\'' );
281 return $this->mConn;
282 }
283
284 /**
285 * Closes a database connection, if it is open
286 * Returns success, true if already closed
287 */
288 function close() {
289 $this->mOpened = false;
290 if ( $this->mConn ) {
291 if ( $this->mTrxLevel ) {
292 $this->commit();
293 }
294 return oci_close( $this->mConn );
295 } else {
296 return true;
297 }
298 }
299
300 function execFlags() {
301 return $this->mTrxLevel ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
302 }
303
304 function doQuery( $sql ) {
305 wfDebug( "SQL: [$sql]\n" );
306 if ( !mb_check_encoding( $sql ) ) {
307 throw new MWException( "SQL encoding is invalid\n$sql" );
308 }
309
310 // handle some oracle specifics
311 // remove AS column/table/subquery namings
312 if( !$this->getFlag( DBO_DDLMODE ) ) {
313 $sql = preg_replace( '/ as /i', ' ', $sql );
314 }
315
316 // Oracle has issues with UNION clause if the statement includes LOB fields
317 // So we do a UNION ALL and then filter the results array with array_unique
318 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
319 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
320 // you have to select data from plan table after explain
321 $explain_id = date( 'dmYHis' );
322
323 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
324
325 wfSuppressWarnings();
326
327 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
328 $e = oci_error( $this->mConn );
329 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
330 return false;
331 }
332
333 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
334 $e = oci_error( $stmt );
335 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
336 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
337 return false;
338 }
339 }
340
341 wfRestoreWarnings();
342
343 if ( $explain_count > 0 ) {
344 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
345 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
346 return new ORAResult( $this, $stmt, $union_unique );
347 } else {
348 $this->mAffectedRows = oci_num_rows( $stmt );
349 return true;
350 }
351 }
352
353 function queryIgnore( $sql, $fname = '' ) {
354 return $this->query( $sql, $fname, true );
355 }
356
357 function freeResult( $res ) {
358 if ( $res instanceof ResultWrapper ) {
359 $res = $res->result;
360 }
361
362 $res->free();
363 }
364
365 function fetchObject( $res ) {
366 if ( $res instanceof ResultWrapper ) {
367 $res = $res->result;
368 }
369
370 return $res->fetchObject();
371 }
372
373 function fetchRow( $res ) {
374 if ( $res instanceof ResultWrapper ) {
375 $res = $res->result;
376 }
377
378 return $res->fetchRow();
379 }
380
381 function numRows( $res ) {
382 if ( $res instanceof ResultWrapper ) {
383 $res = $res->result;
384 }
385
386 return $res->numRows();
387 }
388
389 function numFields( $res ) {
390 if ( $res instanceof ResultWrapper ) {
391 $res = $res->result;
392 }
393
394 return $res->numFields();
395 }
396
397 function fieldName( $stmt, $n ) {
398 return oci_field_name( $stmt, $n );
399 }
400
401 /**
402 * This must be called after nextSequenceVal
403 */
404 function insertId() {
405 return $this->mInsertId;
406 }
407
408 function dataSeek( $res, $row ) {
409 if ( $res instanceof ORAResult ) {
410 $res->seek( $row );
411 } else {
412 $res->result->seek( $row );
413 }
414 }
415
416 function lastError() {
417 if ( $this->mConn === false ) {
418 $e = oci_error();
419 } else {
420 $e = oci_error( $this->mConn );
421 }
422 return $e['message'];
423 }
424
425 function lastErrno() {
426 if ( $this->mConn === false ) {
427 $e = oci_error();
428 } else {
429 $e = oci_error( $this->mConn );
430 }
431 return $e['code'];
432 }
433
434 function affectedRows() {
435 return $this->mAffectedRows;
436 }
437
438 /**
439 * Returns information about an index
440 * If errors are explicitly ignored, returns NULL on failure
441 */
442 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
443 return false;
444 }
445
446 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
447 return false;
448 }
449
450 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
451 if ( !count( $a ) ) {
452 return true;
453 }
454
455 if ( !is_array( $options ) ) {
456 $options = array( $options );
457 }
458
459 if ( in_array( 'IGNORE', $options ) ) {
460 $this->ignore_DUP_VAL_ON_INDEX = true;
461 }
462
463 if ( !is_array( reset( $a ) ) ) {
464 $a = array( $a );
465 }
466
467 foreach ( $a as &$row ) {
468 $this->insertOneRow( $table, $row, $fname );
469 }
470 $retVal = true;
471
472 if ( in_array( 'IGNORE', $options ) ) {
473 $this->ignore_DUP_VAL_ON_INDEX = false;
474 }
475
476 return $retVal;
477 }
478
479 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
480 $col_info = $this->fieldInfoMulti( $table, $col );
481 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
482
483 $bind = '';
484 if ( is_numeric( $col ) ) {
485 $bind = $val;
486 $val = null;
487 return $bind;
488 } else if ( $includeCol ) {
489 $bind = "$col = ";
490 }
491
492 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
493 $val = null;
494 }
495
496 if ( $val === null ) {
497 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
498 $bind .= 'DEFAULT';
499 } else {
500 $bind .= 'NULL';
501 }
502 } else {
503 $bind .= ':' . $col;
504 }
505
506 return $bind;
507 }
508
509 private function insertOneRow( $table, $row, $fname ) {
510 global $wgContLang;
511
512 $table = $this->tableName( $table );
513 // "INSERT INTO tables (a, b, c)"
514 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
515 $sql .= " VALUES (";
516
517 // for each value, append ":key"
518 $first = true;
519 foreach ( $row as $col => &$val ) {
520 if ( !$first ) {
521 $sql .= ', ';
522 } else {
523 $first = false;
524 }
525
526 $sql .= $this->fieldBindStatement( $table, $col, $val );
527 }
528 $sql .= ')';
529
530 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
531 $e = oci_error( $this->mConn );
532 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
533 return false;
534 }
535 foreach ( $row as $col => &$val ) {
536 $col_info = $this->fieldInfoMulti( $table, $col );
537 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
538
539 if ( $val === null ) {
540 // do nothing ... null was inserted in statement creation
541 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
542 if ( is_object( $val ) ) {
543 $val = $val->fetch();
544 }
545
546 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
547 $val = '31-12-2030 12:00:00.000000';
548 }
549
550 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
551 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
552 $e = oci_error( $stmt );
553 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
554 return false;
555 }
556 } else {
557 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
558 $e = oci_error( $stmt );
559 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
560 }
561
562 if ( is_object( $val ) ) {
563 $val = $val->fetch();
564 }
565
566 if ( $col_type == 'BLOB' ) {
567 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
568 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB );
569 } else {
570 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
571 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
572 }
573 }
574 }
575
576 wfSuppressWarnings();
577
578 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
579 $e = oci_error( $stmt );
580 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
581 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
582 return false;
583 } else {
584 $this->mAffectedRows = oci_num_rows( $stmt );
585 }
586 } else {
587 $this->mAffectedRows = oci_num_rows( $stmt );
588 }
589
590 wfRestoreWarnings();
591
592 if ( isset( $lob ) ) {
593 foreach ( $lob as $lob_v ) {
594 $lob_v->free();
595 }
596 }
597
598 if ( !$this->mTrxLevel ) {
599 oci_commit( $this->mConn );
600 }
601
602 oci_free_statement( $stmt );
603 }
604
605 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
606 $insertOptions = array(), $selectOptions = array() )
607 {
608 $destTable = $this->tableName( $destTable );
609 if ( !is_array( $selectOptions ) ) {
610 $selectOptions = array( $selectOptions );
611 }
612 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
613 if ( is_array( $srcTable ) ) {
614 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
615 } else {
616 $srcTable = $this->tableName( $srcTable );
617 }
618
619 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
620 !isset( $varMap[$sequenceData['column']] ) )
621 {
622 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
623 }
624
625 // count-alias subselect fields to avoid abigious definition errors
626 $i = 0;
627 foreach ( $varMap as &$val ) {
628 $val = $val . ' field' . ( $i++ );
629 }
630
631 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
632 " SELECT $startOpts " . implode( ',', $varMap ) .
633 " FROM $srcTable $useIndex ";
634 if ( $conds != '*' ) {
635 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
636 }
637 $sql .= " $tailOpts";
638
639 if ( in_array( 'IGNORE', $insertOptions ) ) {
640 $this->ignore_DUP_VAL_ON_INDEX = true;
641 }
642
643 $retval = $this->query( $sql, $fname );
644
645 if ( in_array( 'IGNORE', $insertOptions ) ) {
646 $this->ignore_DUP_VAL_ON_INDEX = false;
647 }
648
649 return $retval;
650 }
651
652 function tableName( $name, $quoted = true ) {
653 /*
654 Replace reserved words with better ones
655 Using uppercase because that's the only way Oracle can handle
656 quoted tablenames
657 */
658 switch( $name ) {
659 case 'user':
660 $name = 'MWUSER';
661 break;
662 case 'text':
663 $name = 'PAGECONTENT';
664 break;
665 }
666
667 return parent::tableName( strtoupper( $name ), $quoted );
668 }
669
670 function tableNameInternal( $name ) {
671 $name = $this->tableName( $name );
672 return preg_replace( '/.*\.(.*)/', '$1', $name);
673 }
674 /**
675 * Return the next in a sequence, save the value for retrieval via insertId()
676 */
677 function nextSequenceValue( $seqName ) {
678 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
679 $row = $this->fetchRow( $res );
680 $this->mInsertId = $row[0];
681 return $this->mInsertId;
682 }
683
684 /**
685 * Return sequence_name if table has a sequence
686 */
687 private function getSequenceData( $table ) {
688 if ( $this->sequenceData == null ) {
689 $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\'' );
690
691 while ( ( $row = $result->fetchRow() ) !== false ) {
692 $this->sequenceData[$this->tableName( $row[1] )] = array(
693 'sequence' => $row[0],
694 'column' => $row[2]
695 );
696 }
697 }
698
699 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
700 }
701
702 /**
703 * REPLACE query wrapper
704 * Oracle simulates this with a DELETE followed by INSERT
705 * $row is the row to insert, an associative array
706 * $uniqueIndexes is an array of indexes. Each element may be either a
707 * field name or an array of field names
708 *
709 * It may be more efficient to leave off unique indexes which are unlikely to collide.
710 * However if you do this, you run the risk of encountering errors which wouldn't have
711 * occurred in MySQL.
712 *
713 * @param $table String: table name
714 * @param $uniqueIndexes Array: array of indexes. Each element may be
715 * either a field name or an array of field names
716 * @param $rows Array: rows to insert to $table
717 * @param $fname String: function name, you can use __METHOD__ here
718 */
719 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
720 $table = $this->tableName( $table );
721
722 if ( count( $rows ) == 0 ) {
723 return;
724 }
725
726 # Single row case
727 if ( !is_array( reset( $rows ) ) ) {
728 $rows = array( $rows );
729 }
730
731 $sequenceData = $this->getSequenceData( $table );
732
733 foreach ( $rows as $row ) {
734 # Delete rows which collide
735 if ( $uniqueIndexes ) {
736 $condsDelete = array();
737 foreach ( $uniqueIndexes as $index ) {
738 $condsDelete[$index] = $row[$index];
739 }
740 if ( count( $condsDelete ) > 0 ) {
741 $this->delete( $table, $condsDelete, $fname );
742 }
743 }
744
745 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
746 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
747 }
748
749 # Now insert the row
750 $this->insert( $table, $row, $fname );
751 }
752 }
753
754 # DELETE where the condition is a join
755 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
756 if ( !$conds ) {
757 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
758 }
759
760 $delTable = $this->tableName( $delTable );
761 $joinTable = $this->tableName( $joinTable );
762 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
763 if ( $conds != '*' ) {
764 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
765 }
766 $sql .= ')';
767
768 $this->query( $sql, $fname );
769 }
770
771 # Returns the size of a text field, or -1 for "unlimited"
772 function textFieldSize( $table, $field ) {
773 $fieldInfoData = $this->fieldInfo( $table, $field );
774 return $fieldInfoData->maxLength();
775 }
776
777 function limitResult( $sql, $limit, $offset = false ) {
778 if ( $offset === false ) {
779 $offset = 0;
780 }
781 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
782 }
783
784 function encodeBlob( $b ) {
785 return new Blob( $b );
786 }
787
788 function decodeBlob( $b ) {
789 if ( $b instanceof Blob ) {
790 $b = $b->fetch();
791 }
792 return $b;
793 }
794
795 function unionQueries( $sqls, $all ) {
796 $glue = ' UNION ALL ';
797 return 'SELECT * ' . ( $all ? '':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
798 }
799
800 function wasDeadlock() {
801 return $this->lastErrno() == 'OCI-00060';
802 }
803
804 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
805 global $wgDBprefix;
806 $this->setFlag( DBO_DDLMODE );
807
808 $temporary = $temporary ? 'TRUE' : 'FALSE';
809
810 $newName = strtoupper( $newName );
811 $oldName = strtoupper( $oldName );
812
813 $tabName = $this->addIdentifierQuotes( substr( $newName, strlen( $wgDBprefix ) ) );
814 $oldPrefix = $this->addIdentifierQuotes( substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) ) );
815 $newPrefix = $this->addIdentifierQuotes( $wgDBprefix );
816
817 $this->clearFlag( DBO_DDLMODE );
818 return $this->doQuery( "BEGIN DUPLICATE_TABLE( $tabName, $oldPrefix, $newPrefix, $temporary ); END;" );
819 }
820
821 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
822 $listWhere = '';
823 if (!empty($prefix)) {
824 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
825 }
826
827 $owner = strtoupper( $this->mDBname );
828 $result = $this->doQuery( "SELECT table_name FROM all_tables WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX$_' ESCAPE '!' $listWhere" );
829
830 // dirty code ... i know
831 $endArray = array();
832 $endArray[] = $prefix.'MWUSER';
833 $endArray[] = $prefix.'PAGE';
834 $endArray[] = $prefix.'IMAGE';
835 $fixedOrderTabs = $endArray;
836 while (($row = $result->fetchRow()) !== false) {
837 if (!in_array($row['table_name'], $fixedOrderTabs))
838 $endArray[] = $row['table_name'];
839 }
840
841 return $endArray;
842 }
843
844 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
845 $tableName = $this->tableName($tableName);
846 if( !$this->tableExists( $tableName ) ) {
847 return false;
848 }
849
850 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
851 }
852
853 function timestamp( $ts = 0 ) {
854 return wfTimestamp( TS_ORACLE, $ts );
855 }
856
857 /**
858 * Return aggregated value function call
859 */
860 function aggregateValue ( $valuedata, $valuename = 'value' ) {
861 return $valuedata;
862 }
863
864 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
865 # Ignore errors during error handling to avoid infinite
866 # recursion
867 $ignore = $this->ignoreErrors( true );
868 ++$this->mErrorCount;
869
870 if ( $ignore || $tempIgnore ) {
871 wfDebug( "SQL ERROR (ignored): $error\n" );
872 $this->ignoreErrors( $ignore );
873 } else {
874 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
875 }
876 }
877
878 /**
879 * @return string wikitext of a link to the server software's web site
880 */
881 public static function getSoftwareLink() {
882 return '[http://www.oracle.com/ Oracle]';
883 }
884
885 /**
886 * @return string Version information from the database
887 */
888 function getServerVersion() {
889 //better version number, fallback on driver
890 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
891 if ( !( $row = $rset->fetchRow() ) ) {
892 return oci_server_version( $this->mConn );
893 }
894 return $row['version'];
895 }
896
897 /**
898 * Query whether a given index exists
899 */
900 function indexExists( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
901 $table = $this->tableName( $table );
902 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
903 $index = strtoupper( $index );
904 $owner = strtoupper( $this->mDBname );
905 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
906 $res = $this->doQuery( $SQL );
907 if ( $res ) {
908 $count = $res->numRows();
909 $res->free();
910 } else {
911 $count = 0;
912 }
913 return $count != 0;
914 }
915
916 /**
917 * Query whether a given table exists (in the given schema, or the default mw one if not given)
918 */
919 function tableExists( $table ) {
920 $table = $this->tableName( $table );
921 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
922 $owner = strtoupper( $this->mDBname );
923 $SQL = "SELECT 1 FROM all_tables WHERE owner='$owner' AND table_name='$table'";
924 $res = $this->doQuery( $SQL );
925 if ( $res ) {
926 $count = $res->numRows();
927 $res->free();
928 } else {
929 $count = 0;
930 }
931 return $count != 0;
932 }
933
934 /**
935 * Function translates mysql_fetch_field() functionality on ORACLE.
936 * Caching is present for reducing query time.
937 * For internal calls. Use fieldInfo for normal usage.
938 * Returns false if the field doesn't exist
939 *
940 * @param $table Array
941 * @param $field String
942 * @return ORAField|ORAResult
943 */
944 private function fieldInfoMulti( $table, $field ) {
945 $field = strtoupper( $field );
946 if ( is_array( $table ) ) {
947 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
948 $tableWhere = 'IN (';
949 foreach( $table as &$singleTable ) {
950 $singleTable = $this->removeIdentifierQuotes($singleTable);
951 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
952 return $this->mFieldInfoCache["$singleTable.$field"];
953 }
954 $tableWhere .= '\'' . $singleTable . '\',';
955 }
956 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
957 } else {
958 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
959 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
960 return $this->mFieldInfoCache["$table.$field"];
961 }
962 $tableWhere = '= \''.$table.'\'';
963 }
964
965 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
966 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
967 $e = oci_error( $fieldInfoStmt );
968 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
969 return false;
970 }
971 $res = new ORAResult( $this, $fieldInfoStmt );
972 if ( $res->numRows() == 0 ) {
973 if ( is_array( $table ) ) {
974 foreach( $table as &$singleTable ) {
975 $this->mFieldInfoCache["$singleTable.$field"] = false;
976 }
977 } else {
978 $this->mFieldInfoCache["$table.$field"] = false;
979 }
980 $fieldInfoTemp = null;
981 } else {
982 $fieldInfoTemp = new ORAField( $res->fetchRow() );
983 $table = $fieldInfoTemp->tableName();
984 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
985 }
986 $res->free();
987 return $fieldInfoTemp;
988 }
989
990 /**
991 * @throws DBUnexpectedError
992 * @param $table
993 * @param $field
994 * @return ORAField
995 */
996 function fieldInfo( $table, $field ) {
997 if ( is_array( $table ) ) {
998 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
999 }
1000 return $this->fieldInfoMulti ($table, $field);
1001 }
1002
1003 function begin( $fname = 'DatabaseOracle::begin' ) {
1004 $this->mTrxLevel = 1;
1005 }
1006
1007 function commit( $fname = 'DatabaseOracle::commit' ) {
1008 if ( $this->mTrxLevel ) {
1009 oci_commit( $this->mConn );
1010 $this->mTrxLevel = 0;
1011 }
1012 }
1013
1014 function rollback( $fname = 'DatabaseOracle::rollback' ) {
1015 if ( $this->mTrxLevel ) {
1016 oci_rollback( $this->mConn );
1017 $this->mTrxLevel = 0;
1018 }
1019 }
1020
1021 /* Not even sure why this is used in the main codebase... */
1022 function limitResultForUpdate( $sql, $num ) {
1023 return $sql;
1024 }
1025
1026 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
1027 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
1028 $cmd = '';
1029 $done = false;
1030 $dollarquote = false;
1031
1032 $replacements = array();
1033
1034 while ( ! feof( $fp ) ) {
1035 if ( $lineCallback ) {
1036 call_user_func( $lineCallback );
1037 }
1038 $line = trim( fgets( $fp, 1024 ) );
1039 $sl = strlen( $line ) - 1;
1040
1041 if ( $sl < 0 ) {
1042 continue;
1043 }
1044 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1045 continue;
1046 }
1047
1048 // Allow dollar quoting for function declarations
1049 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1050 if ( $dollarquote ) {
1051 $dollarquote = false;
1052 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1053 $done = true;
1054 } else {
1055 $dollarquote = true;
1056 }
1057 } elseif ( !$dollarquote ) {
1058 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1059 $done = true;
1060 $line = substr( $line, 0, $sl );
1061 }
1062 }
1063
1064 if ( $cmd != '' ) {
1065 $cmd .= ' ';
1066 }
1067 $cmd .= "$line\n";
1068
1069 if ( $done ) {
1070 $cmd = str_replace( ';;', ";", $cmd );
1071 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1072 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1073 $replacements[$defines[2]] = $defines[1];
1074 }
1075 } else {
1076 foreach ( $replacements as $mwVar => $scVar ) {
1077 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1078 }
1079
1080 $cmd = $this->replaceVars( $cmd );
1081 $res = $this->doQuery( $cmd );
1082 if ( $resultCallback ) {
1083 call_user_func( $resultCallback, $res, $this );
1084 }
1085
1086 if ( false === $res ) {
1087 $err = $this->lastError();
1088 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1089 }
1090 }
1091
1092 $cmd = '';
1093 $done = false;
1094 }
1095 }
1096 return true;
1097 }
1098
1099 function selectDB( $db ) {
1100 $this->mDBname = $db;
1101 if ( $db == null || $db == $this->mUser ) {
1102 return true;
1103 }
1104 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1105 $stmt = oci_parse( $this->mConn, $sql );
1106 wfSuppressWarnings();
1107 $success = oci_execute( $stmt );
1108 wfRestoreWarnings();
1109 if ( !$success ) {
1110 $e = oci_error( $stmt );
1111 if ( $e['code'] != '1435' ) {
1112 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1113 }
1114 return false;
1115 }
1116 return true;
1117 }
1118
1119 function strencode( $s ) {
1120 return str_replace( "'", "''", $s );
1121 }
1122
1123 function addQuotes( $s ) {
1124 global $wgContLang;
1125 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1126 $s = $wgContLang->checkTitleEncoding( $s );
1127 }
1128 return "'" . $this->strencode( $s ) . "'";
1129 }
1130
1131 public function addIdentifierQuotes( $s ) {
1132 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1133 $s = '/*Q*/' . $s;
1134 }
1135 return $s;
1136 }
1137
1138 public function removeIdentifierQuotes( $s ) {
1139 return strpos($s, '/*Q*/') === FALSE ? $s : substr($s, 5);
1140 }
1141
1142 public function isQuotedIdentifier( $s ) {
1143 return strpos($s, '/*Q*/') !== FALSE;
1144 }
1145
1146 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1147 global $wgContLang;
1148
1149 if ($conds != null) {
1150 $conds2 = array();
1151 $conds = ( !is_array( $conds ) ) ? array( $conds ) : $conds;
1152 foreach ( $conds as $col => $val ) {
1153 $col_info = $this->fieldInfoMulti( $table, $col );
1154 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1155 if ( $col_type == 'CLOB' ) {
1156 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1157 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1158 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1159 } else {
1160 $conds2[$col] = $val;
1161 }
1162 }
1163
1164 return parent::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1165 } else {
1166 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1167 }
1168 }
1169
1170 /**
1171 * Returns an optional USE INDEX clause to go after the table, and a
1172 * string to go at the end of the query
1173 *
1174 * @private
1175 *
1176 * @param $options Array: an associative array of options to be turned into
1177 * an SQL query, valid keys are listed in the function.
1178 * @return array
1179 */
1180 function makeSelectOptions( $options ) {
1181 $preLimitTail = $postLimitTail = '';
1182 $startOpts = '';
1183
1184 $noKeyOptions = array();
1185 foreach ( $options as $key => $option ) {
1186 if ( is_numeric( $key ) ) {
1187 $noKeyOptions[$option] = true;
1188 }
1189 }
1190
1191 if ( isset( $options['GROUP BY'] ) ) {
1192 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1193 }
1194 if ( isset( $options['ORDER BY'] ) ) {
1195 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1196 }
1197
1198 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1199 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1200 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1201 $startOpts .= 'DISTINCT';
1202 }
1203
1204 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1205 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1206 } else {
1207 $useIndex = '';
1208 }
1209
1210 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1211 }
1212
1213 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1214 global $wgContLang;
1215
1216 if ( $wgContLang != null && $conds != null && $conds != '*' ) {
1217 $conds2 = array();
1218 $conds = ( !is_array( $conds ) ) ? array( $conds ) : $conds;
1219 foreach ( $conds as $col => $val ) {
1220 $col_info = $this->fieldInfoMulti( $table, $col );
1221 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1222 if ( $col_type == 'CLOB' ) {
1223 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1224 } else {
1225 if ( is_array( $val ) ) {
1226 $conds2[$col] = $val;
1227 foreach ( $conds2[$col] as &$val2 ) {
1228 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1229 }
1230 } else {
1231 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1232 }
1233 }
1234 }
1235
1236 return parent::delete( $table, $conds2, $fname );
1237 } else {
1238 return parent::delete( $table, $conds, $fname );
1239 }
1240 }
1241
1242 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1243 global $wgContLang;
1244
1245 $table = $this->tableName( $table );
1246 $opts = $this->makeUpdateOptions( $options );
1247 $sql = "UPDATE $opts $table SET ";
1248
1249 $first = true;
1250 foreach ( $values as $col => &$val ) {
1251 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1252
1253 if ( !$first ) {
1254 $sqlSet = ', ' . $sqlSet;
1255 } else {
1256 $first = false;
1257 }
1258 $sql .= $sqlSet;
1259 }
1260
1261 if ( $conds != '*' ) {
1262 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1263 }
1264
1265 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1266 $e = oci_error( $this->mConn );
1267 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1268 return false;
1269 }
1270 foreach ( $values as $col => &$val ) {
1271 $col_info = $this->fieldInfoMulti( $table, $col );
1272 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1273
1274 if ( $val === null ) {
1275 // do nothing ... null was inserted in statement creation
1276 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1277 if ( is_object( $val ) ) {
1278 $val = $val->getData();
1279 }
1280
1281 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1282 $val = '31-12-2030 12:00:00.000000';
1283 }
1284
1285 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1286 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1287 $e = oci_error( $stmt );
1288 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1289 return false;
1290 }
1291 } else {
1292 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1293 $e = oci_error( $stmt );
1294 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1295 }
1296
1297 if ( $col_type == 'BLOB' ) {
1298 $lob[$col]->writeTemporary( $val );
1299 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1300 } else {
1301 $lob[$col]->writeTemporary( $val );
1302 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1303 }
1304 }
1305 }
1306
1307 wfSuppressWarnings();
1308
1309 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1310 $e = oci_error( $stmt );
1311 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1312 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1313 return false;
1314 } else {
1315 $this->mAffectedRows = oci_num_rows( $stmt );
1316 }
1317 } else {
1318 $this->mAffectedRows = oci_num_rows( $stmt );
1319 }
1320
1321 wfRestoreWarnings();
1322
1323 if ( isset( $lob ) ) {
1324 foreach ( $lob as $lob_v ) {
1325 $lob_v->free();
1326 }
1327 }
1328
1329 if ( !$this->mTrxLevel ) {
1330 oci_commit( $this->mConn );
1331 }
1332
1333 oci_free_statement( $stmt );
1334 }
1335
1336 function bitNot( $field ) {
1337 // expecting bit-fields smaller than 4bytes
1338 return 'BITNOT(' . $field . ')';
1339 }
1340
1341 function bitAnd( $fieldLeft, $fieldRight ) {
1342 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1343 }
1344
1345 function bitOr( $fieldLeft, $fieldRight ) {
1346 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1347 }
1348
1349 function setFakeMaster( $enabled = true ) { }
1350
1351 function getDBname() {
1352 return $this->mDBname;
1353 }
1354
1355 function getServer() {
1356 return $this->mServer;
1357 }
1358
1359 public function getSearchEngine() {
1360 return 'SearchOracle';
1361 }
1362 } // end DatabaseOracle class