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