Refactoring of *Field classes:
[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 */
928 private function fieldInfoMulti( $table, $field ) {
929 $field = strtoupper( $field );
930 if ( is_array( $table ) ) {
931 $table = array_map( array( &$this, 'tableName' ), $table );
932 $tableWhere = 'IN (';
933 foreach( $table as &$singleTable ) {
934 $singleTable = strtoupper( trim( $singleTable, '"' ) );
935 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
936 return $this->mFieldInfoCache["$singleTable.$field"];
937 }
938 $tableWhere .= '\'' . $singleTable . '\',';
939 }
940 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
941 } else {
942 $table = strtoupper( trim( $this->tableName( $table ), '"' ) );
943 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
944 return $this->mFieldInfoCache["$table.$field"];
945 }
946 $tableWhere = '= \''.$table.'\'';
947 }
948
949 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
950 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT ) === false ) {
951 $e = oci_error( $fieldInfoStmt );
952 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
953 return false;
954 }
955 $res = new ORAResult( $this, $fieldInfoStmt );
956 if ( $res->numRows() == 0 ) {
957 if ( is_array( $table ) ) {
958 foreach( $table as &$singleTable ) {
959 $this->mFieldInfoCache["$singleTable.$field"] = false;
960 }
961 } else {
962 $this->mFieldInfoCache["$table.$field"] = false;
963 }
964 $fieldInfoTemp = null;
965 } else {
966 $fieldInfoTemp = new ORAField( $res->fetchRow() );
967 $table = $fieldInfoTemp->tableName();
968 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
969 }
970 $res->free();
971 return $fieldInfoTemp;
972 }
973
974 function fieldInfo( $table, $field ) {
975 if ( is_array( $table ) ) {
976 throw new DBUnexpectedError( $this, 'Database::fieldInfo called with table array!' );
977 }
978 return $this->fieldInfoMulti ($table, $field);
979 }
980
981 function begin( $fname = '' ) {
982 $this->mTrxLevel = 1;
983 }
984
985 function commit( $fname = '' ) {
986 oci_commit( $this->mConn );
987 $this->mTrxLevel = 0;
988 }
989
990 /* Not even sure why this is used in the main codebase... */
991 function limitResultForUpdate( $sql, $num ) {
992 return $sql;
993 }
994
995 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
996 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
997 $cmd = '';
998 $done = false;
999 $dollarquote = false;
1000
1001 $replacements = array();
1002
1003 while ( ! feof( $fp ) ) {
1004 if ( $lineCallback ) {
1005 call_user_func( $lineCallback );
1006 }
1007 $line = trim( fgets( $fp, 1024 ) );
1008 $sl = strlen( $line ) - 1;
1009
1010 if ( $sl < 0 ) {
1011 continue;
1012 }
1013 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1014 continue;
1015 }
1016
1017 // Allow dollar quoting for function declarations
1018 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1019 if ( $dollarquote ) {
1020 $dollarquote = false;
1021 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1022 $done = true;
1023 } else {
1024 $dollarquote = true;
1025 }
1026 } elseif ( !$dollarquote ) {
1027 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1028 $done = true;
1029 $line = substr( $line, 0, $sl );
1030 }
1031 }
1032
1033 if ( $cmd != '' ) {
1034 $cmd .= ' ';
1035 }
1036 $cmd .= "$line\n";
1037
1038 if ( $done ) {
1039 $cmd = str_replace( ';;', ";", $cmd );
1040 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1041 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1042 $replacements[$defines[2]] = $defines[1];
1043 }
1044 } else {
1045 foreach ( $replacements as $mwVar => $scVar ) {
1046 $cmd = str_replace( '&' . $scVar . '.', '{$' . $mwVar . '}', $cmd );
1047 }
1048
1049 $cmd = $this->replaceVars( $cmd );
1050 $res = $this->doQuery( $cmd );
1051 if ( $resultCallback ) {
1052 call_user_func( $resultCallback, $res, $this );
1053 }
1054
1055 if ( false === $res ) {
1056 $err = $this->lastError();
1057 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1058 }
1059 }
1060
1061 $cmd = '';
1062 $done = false;
1063 }
1064 }
1065 return true;
1066 }
1067
1068 function setup_database() {
1069 $res = $this->sourceFile( "../maintenance/oracle/tables.sql" );
1070 if ( $res === true ) {
1071 print " done.</li>\n";
1072 } else {
1073 print " <b>FAILED</b></li>\n";
1074 dieout( htmlspecialchars( $res ) );
1075 }
1076
1077 // Avoid the non-standard "REPLACE INTO" syntax
1078 echo "<li>Populating interwiki table</li>\n";
1079 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1080 if ( !$f ) {
1081 dieout( "Could not find the interwiki.sql file" );
1082 }
1083
1084 // do it like the postgres :D
1085 $SQL = "INSERT INTO " . $this->tableName( 'interwiki' ) . " (iw_prefix,iw_url,iw_local) VALUES ";
1086 while ( !feof( $f ) ) {
1087 $line = fgets( $f, 1024 );
1088 $matches = array();
1089 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) {
1090 continue;
1091 }
1092 $this->query( "$SQL $matches[1],$matches[2])" );
1093 }
1094
1095 echo "<li>Table interwiki successfully populated</li>\n";
1096 }
1097
1098 function selectDB( $db ) {
1099 if ( $db == null || $db == $this->mUser ) { return true; }
1100 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1101 $stmt = oci_parse( $this->mConn, $sql );
1102 if ( !oci_execute( $stmt ) ) {
1103 $e = oci_error( $stmt );
1104 if ( $e['code'] != '1435' ) {
1105 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1106 }
1107 return false;
1108 }
1109 return true;
1110 }
1111
1112 function strencode( $s ) {
1113 return str_replace( "'", "''", $s );
1114 }
1115
1116 function addQuotes( $s ) {
1117 global $wgContLang;
1118 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1119 $s = $wgContLang->checkTitleEncoding( $s );
1120 }
1121 return "'" . $this->strencode( $s ) . "'";
1122 }
1123
1124 function quote_ident( $s ) {
1125 return $s;
1126 }
1127
1128 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1129 global $wgContLang;
1130
1131 $conds2 = array();
1132 $conds = ( $conds != null && !is_array( $conds ) ) ? array( $conds ) : $conds;
1133 foreach ( $conds as $col => $val ) {
1134 $col_info = $this->fieldInfoMulti( $table, $col );
1135 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1136 if ( $col_type == 'CLOB' ) {
1137 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1138 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1139 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1140 } else {
1141 $conds2[$col] = $val;
1142 }
1143 }
1144
1145 return parent::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
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 != '*' ) {
1195 $conds2 = array();
1196 $conds = ( $conds != null && !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 replaceVars( $ins ) {
1338 $varnames = array( 'wgDBprefix' );
1339 if ( $this->mFlags & DBO_SYSDBA ) {
1340 $varnames[] = '_OracleDefTS';
1341 $varnames[] = '_OracleTempTS';
1342 }
1343
1344 // Ordinary variables
1345 foreach ( $varnames as $var ) {
1346 if ( isset( $GLOBALS[$var] ) ) {
1347 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1348 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1349 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1350 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1351 }
1352 }
1353
1354 return parent::replaceVars( $ins );
1355 }
1356
1357 public function getSearchEngine() {
1358 return 'SearchOracle';
1359 }
1360 } // end DatabaseOracle class