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