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