* fixed table duplication for phpunit testing
[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 $deleteConds = array();
737 foreach ( $uniqueIndexes as $key=>$index ) {
738 if ( is_array( $index ) ) {
739 $deleteConds2 = array();
740 foreach ( $index as $col ) {
741 $deleteConds2[$col] = $row[$col];
742 }
743 $deleteConds[$key] = $this->makeList( $deleteConds2, LIST_AND );
744 } else {
745 $deleteConds[$index] = $row[$index];
746 }
747 }
748 $deleteConds = array( $this->makeList( $deleteConds, LIST_OR ) );
749 $this->delete( $table, $deleteConds, $fname );
750 }
751
752
753 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
754 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
755 }
756
757 # Now insert the row
758 $this->insert( $table, $row, $fname );
759 }
760 }
761
762 # DELETE where the condition is a join
763 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
764 if ( !$conds ) {
765 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
766 }
767
768 $delTable = $this->tableName( $delTable );
769 $joinTable = $this->tableName( $joinTable );
770 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
771 if ( $conds != '*' ) {
772 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
773 }
774 $sql .= ')';
775
776 $this->query( $sql, $fname );
777 }
778
779 # Returns the size of a text field, or -1 for "unlimited"
780 function textFieldSize( $table, $field ) {
781 $fieldInfoData = $this->fieldInfo( $table, $field );
782 return $fieldInfoData->maxLength();
783 }
784
785 function limitResult( $sql, $limit, $offset = false ) {
786 if ( $offset === false ) {
787 $offset = 0;
788 }
789 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
790 }
791
792 function encodeBlob( $b ) {
793 return new Blob( $b );
794 }
795
796 function decodeBlob( $b ) {
797 if ( $b instanceof Blob ) {
798 $b = $b->fetch();
799 }
800 return $b;
801 }
802
803 function unionQueries( $sqls, $all ) {
804 $glue = ' UNION ALL ';
805 return 'SELECT * ' . ( $all ? '':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
806 }
807
808 function wasDeadlock() {
809 return $this->lastErrno() == 'OCI-00060';
810 }
811
812 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
813 global $wgDBprefix;
814 $this->setFlag( DBO_DDLMODE );
815
816 $temporary = $temporary ? 'TRUE' : 'FALSE';
817
818 $newName = strtoupper( $newName );
819 $oldName = strtoupper( $oldName );
820
821 $tabName = substr( $newName, strlen( $wgDBprefix ) );
822 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
823 $newPrefix = strtoupper( $wgDBprefix );
824
825 $this->clearFlag( DBO_DDLMODE );
826 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', '$oldPrefix', '$newPrefix', $temporary ); END;" );
827 }
828
829 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
830 $listWhere = '';
831 if (!empty($prefix)) {
832 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
833 }
834
835 $owner = strtoupper( $this->mDBname );
836 $result = $this->doQuery( "SELECT table_name FROM all_tables WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
837
838 // dirty code ... i know
839 $endArray = array();
840 $endArray[] = $prefix.'MWUSER';
841 $endArray[] = $prefix.'PAGE';
842 $endArray[] = $prefix.'IMAGE';
843 $fixedOrderTabs = $endArray;
844 while (($row = $result->fetchRow()) !== false) {
845 if (!in_array($row['table_name'], $fixedOrderTabs))
846 $endArray[] = $row['table_name'];
847 }
848
849 return $endArray;
850 }
851
852 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
853 $tableName = $this->tableName($tableName);
854 if( !$this->tableExists( $tableName ) ) {
855 return false;
856 }
857
858 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
859 }
860
861 function timestamp( $ts = 0 ) {
862 return wfTimestamp( TS_ORACLE, $ts );
863 }
864
865 /**
866 * Return aggregated value function call
867 */
868 function aggregateValue ( $valuedata, $valuename = 'value' ) {
869 return $valuedata;
870 }
871
872 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
873 # Ignore errors during error handling to avoid infinite
874 # recursion
875 $ignore = $this->ignoreErrors( true );
876 ++$this->mErrorCount;
877
878 if ( $ignore || $tempIgnore ) {
879 wfDebug( "SQL ERROR (ignored): $error\n" );
880 $this->ignoreErrors( $ignore );
881 } else {
882 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
883 }
884 }
885
886 /**
887 * @return string wikitext of a link to the server software's web site
888 */
889 public static function getSoftwareLink() {
890 return '[http://www.oracle.com/ Oracle]';
891 }
892
893 /**
894 * @return string Version information from the database
895 */
896 function getServerVersion() {
897 //better version number, fallback on driver
898 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
899 if ( !( $row = $rset->fetchRow() ) ) {
900 return oci_server_version( $this->mConn );
901 }
902 return $row['version'];
903 }
904
905 /**
906 * Query whether a given index exists
907 */
908 function indexExists( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
909 $table = $this->tableName( $table );
910 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
911 $index = strtoupper( $index );
912 $owner = strtoupper( $this->mDBname );
913 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
914 $res = $this->doQuery( $SQL );
915 if ( $res ) {
916 $count = $res->numRows();
917 $res->free();
918 } else {
919 $count = 0;
920 }
921 return $count != 0;
922 }
923
924 /**
925 * Query whether a given table exists (in the given schema, or the default mw one if not given)
926 */
927 function tableExists( $table ) {
928 $table = $this->tableName( $table );
929 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
930 $owner = strtoupper( $this->mDBname );
931 $SQL = "SELECT 1 FROM all_tables WHERE owner='$owner' AND table_name='$table'";
932 $res = $this->doQuery( $SQL );
933 if ( $res ) {
934 $count = $res->numRows();
935 $res->free();
936 } else {
937 $count = 0;
938 }
939 return $count != 0;
940 }
941
942 /**
943 * Function translates mysql_fetch_field() functionality on ORACLE.
944 * Caching is present for reducing query time.
945 * For internal calls. Use fieldInfo for normal usage.
946 * Returns false if the field doesn't exist
947 *
948 * @param $table Array
949 * @param $field String
950 * @return ORAField|ORAResult
951 */
952 private function fieldInfoMulti( $table, $field ) {
953 $field = strtoupper( $field );
954 if ( is_array( $table ) ) {
955 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
956 $tableWhere = 'IN (';
957 foreach( $table as &$singleTable ) {
958 $singleTable = $this->removeIdentifierQuotes($singleTable);
959 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
960 return $this->mFieldInfoCache["$singleTable.$field"];
961 }
962 $tableWhere .= '\'' . $singleTable . '\',';
963 }
964 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
965 } else {
966 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
967 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
968 return $this->mFieldInfoCache["$table.$field"];
969 }
970 $tableWhere = '= \''.$table.'\'';
971 }
972
973 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
974 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
975 $e = oci_error( $fieldInfoStmt );
976 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
977 return false;
978 }
979 $res = new ORAResult( $this, $fieldInfoStmt );
980 if ( $res->numRows() == 0 ) {
981 if ( is_array( $table ) ) {
982 foreach( $table as &$singleTable ) {
983 $this->mFieldInfoCache["$singleTable.$field"] = false;
984 }
985 } else {
986 $this->mFieldInfoCache["$table.$field"] = false;
987 }
988 $fieldInfoTemp = null;
989 } else {
990 $fieldInfoTemp = new ORAField( $res->fetchRow() );
991 $table = $fieldInfoTemp->tableName();
992 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
993 }
994 $res->free();
995 return $fieldInfoTemp;
996 }
997
998 /**
999 * @throws DBUnexpectedError
1000 * @param $table
1001 * @param $field
1002 * @return ORAField
1003 */
1004 function fieldInfo( $table, $field ) {
1005 if ( is_array( $table ) ) {
1006 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
1007 }
1008 return $this->fieldInfoMulti ($table, $field);
1009 }
1010
1011 function begin( $fname = 'DatabaseOracle::begin' ) {
1012 $this->mTrxLevel = 1;
1013 }
1014
1015 function commit( $fname = 'DatabaseOracle::commit' ) {
1016 if ( $this->mTrxLevel ) {
1017 oci_commit( $this->mConn );
1018 $this->mTrxLevel = 0;
1019 }
1020 }
1021
1022 function rollback( $fname = 'DatabaseOracle::rollback' ) {
1023 if ( $this->mTrxLevel ) {
1024 oci_rollback( $this->mConn );
1025 $this->mTrxLevel = 0;
1026 }
1027 }
1028
1029 /* Not even sure why this is used in the main codebase... */
1030 function limitResultForUpdate( $sql, $num ) {
1031 return $sql;
1032 }
1033
1034 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
1035 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
1036 $cmd = '';
1037 $done = false;
1038 $dollarquote = false;
1039
1040 $replacements = array();
1041
1042 while ( ! feof( $fp ) ) {
1043 if ( $lineCallback ) {
1044 call_user_func( $lineCallback );
1045 }
1046 $line = trim( fgets( $fp, 1024 ) );
1047 $sl = strlen( $line ) - 1;
1048
1049 if ( $sl < 0 ) {
1050 continue;
1051 }
1052 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1053 continue;
1054 }
1055
1056 // Allow dollar quoting for function declarations
1057 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1058 if ( $dollarquote ) {
1059 $dollarquote = false;
1060 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1061 $done = true;
1062 } else {
1063 $dollarquote = true;
1064 }
1065 } elseif ( !$dollarquote ) {
1066 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1067 $done = true;
1068 $line = substr( $line, 0, $sl );
1069 }
1070 }
1071
1072 if ( $cmd != '' ) {
1073 $cmd .= ' ';
1074 }
1075 $cmd .= "$line\n";
1076
1077 if ( $done ) {
1078 $cmd = str_replace( ';;', ";", $cmd );
1079 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1080 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1081 $replacements[$defines[2]] = $defines[1];
1082 }
1083 } else {
1084 foreach ( $replacements as $mwVar => $scVar ) {
1085 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1086 }
1087
1088 $cmd = $this->replaceVars( $cmd );
1089 $res = $this->doQuery( $cmd );
1090 if ( $resultCallback ) {
1091 call_user_func( $resultCallback, $res, $this );
1092 }
1093
1094 if ( false === $res ) {
1095 $err = $this->lastError();
1096 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1097 }
1098 }
1099
1100 $cmd = '';
1101 $done = false;
1102 }
1103 }
1104 return true;
1105 }
1106
1107 function selectDB( $db ) {
1108 $this->mDBname = $db;
1109 if ( $db == null || $db == $this->mUser ) {
1110 return true;
1111 }
1112 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1113 $stmt = oci_parse( $this->mConn, $sql );
1114 wfSuppressWarnings();
1115 $success = oci_execute( $stmt );
1116 wfRestoreWarnings();
1117 if ( !$success ) {
1118 $e = oci_error( $stmt );
1119 if ( $e['code'] != '1435' ) {
1120 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1121 }
1122 return false;
1123 }
1124 return true;
1125 }
1126
1127 function strencode( $s ) {
1128 return str_replace( "'", "''", $s );
1129 }
1130
1131 function addQuotes( $s ) {
1132 global $wgContLang;
1133 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1134 $s = $wgContLang->checkTitleEncoding( $s );
1135 }
1136 return "'" . $this->strencode( $s ) . "'";
1137 }
1138
1139 public function addIdentifierQuotes( $s ) {
1140 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1141 $s = '/*Q*/' . $s;
1142 }
1143 return $s;
1144 }
1145
1146 public function removeIdentifierQuotes( $s ) {
1147 return strpos($s, '/*Q*/') === FALSE ? $s : substr($s, 5);
1148 }
1149
1150 public function isQuotedIdentifier( $s ) {
1151 return strpos($s, '/*Q*/') !== FALSE;
1152 }
1153
1154 private function wrapFieldForWhere( $table, &$col, &$val ) {
1155 global $wgContLang;
1156
1157 $col_info = $this->fieldInfoMulti( $table, $col );
1158 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1159 if ( $col_type == 'CLOB' ) {
1160 $col = 'TO_CHAR(' . $col . ')';
1161 $val = $wgContLang->checkTitleEncoding( $val );
1162 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1163 $val = $wgContLang->checkTitleEncoding( $val );
1164 }
1165 }
1166
1167 private function wrapConditionsForWhere ( $table, $conds, $parentCol = null ) {
1168 $conds2 = array();
1169 foreach ( $conds as $col => $val ) {
1170 if ( is_array( $val ) ) {
1171 $conds2[$col] = $this->wrapConditionsForWhere ( $table, $val, $col );
1172 } else {
1173 if ( is_numeric( $col ) && $parentCol != null ) {
1174 $this->wrapFieldForWhere ( $table, $parentCol, $val );
1175 } else {
1176 $this->wrapFieldForWhere ( $table, $col, $val );
1177 }
1178 $conds2[$col] = $val;
1179 }
1180 }
1181 return $conds2;
1182 }
1183
1184 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1185 if ( is_array($conds) ) {
1186 $conds = $this->wrapConditionsForWhere( $table, $conds );
1187 }
1188 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1189 }
1190
1191 /**
1192 * Returns an optional USE INDEX clause to go after the table, and a
1193 * string to go at the end of the query
1194 *
1195 * @private
1196 *
1197 * @param $options Array: an associative array of options to be turned into
1198 * an SQL query, valid keys are listed in the function.
1199 * @return array
1200 */
1201 function makeSelectOptions( $options ) {
1202 $preLimitTail = $postLimitTail = '';
1203 $startOpts = '';
1204
1205 $noKeyOptions = array();
1206 foreach ( $options as $key => $option ) {
1207 if ( is_numeric( $key ) ) {
1208 $noKeyOptions[$option] = true;
1209 }
1210 }
1211
1212 if ( isset( $options['GROUP BY'] ) ) {
1213 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1214 }
1215 if ( isset( $options['ORDER BY'] ) ) {
1216 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1217 }
1218
1219 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1220 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1221 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1222 $startOpts .= 'DISTINCT';
1223 }
1224
1225 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1226 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1227 } else {
1228 $useIndex = '';
1229 }
1230
1231 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1232 }
1233
1234 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1235 if ( is_array($conds) ) {
1236 $conds = $this->wrapConditionsForWhere( $table, $conds );
1237 }
1238 return parent::delete( $table, $conds, $fname );
1239 }
1240
1241 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1242 global $wgContLang;
1243
1244 $table = $this->tableName( $table );
1245 $opts = $this->makeUpdateOptions( $options );
1246 $sql = "UPDATE $opts $table SET ";
1247
1248 $first = true;
1249 foreach ( $values as $col => &$val ) {
1250 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1251
1252 if ( !$first ) {
1253 $sqlSet = ', ' . $sqlSet;
1254 } else {
1255 $first = false;
1256 }
1257 $sql .= $sqlSet;
1258 }
1259
1260 if ( $conds != '*' ) {
1261 $conds = $this->wrapConditionsForWhere( $table, $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