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