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