Updated calls to Linker to call them statically and removed useless parameter to...
[lhc/web/wiklou.git] / includes / db / DatabaseOracle.php
1 <?php
2 /**
3 * This is the Oracle database abstraction layer.
4 *
5 * @file
6 * @ingroup Database
7 */
8
9 /**
10 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
11 * other things. We use a wrapper class to handle that and other
12 * Oracle-specific bits, like converting column names back to lowercase.
13 * @ingroup Database
14 */
15 class ORAResult {
16 private $rows;
17 private $cursor;
18 private $nrows;
19
20 private $columns = array();
21
22 private function array_unique_md( $array_in ) {
23 $array_out = array();
24 $array_hashes = array();
25
26 foreach ( $array_in as $item ) {
27 $hash = md5( serialize( $item ) );
28 if ( !isset( $array_hashes[$hash] ) ) {
29 $array_hashes[$hash] = $hash;
30 $array_out[] = $item;
31 }
32 }
33
34 return $array_out;
35 }
36
37 /**
38 * @param $db DatabaseBase
39 * @param $stmt
40 * @param bool $unique
41 */
42 function __construct( &$db, $stmt, $unique = false ) {
43 $this->db =& $db;
44
45 if ( ( $this->nrows = oci_fetch_all( $stmt, $this->rows, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM ) ) === false ) {
46 $e = oci_error( $stmt );
47 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__ );
48 $this->free();
49 return;
50 }
51
52 if ( $unique ) {
53 $this->rows = $this->array_unique_md( $this->rows );
54 $this->nrows = count( $this->rows );
55 }
56
57 if ($this->nrows > 0) {
58 foreach ( $this->rows[0] as $k => $v ) {
59 $this->columns[$k] = strtolower( oci_field_name( $stmt, $k + 1 ) );
60 }
61 }
62
63 $this->cursor = 0;
64 oci_free_statement( $stmt );
65 }
66
67 public function free() {
68 unset($this->db);
69 }
70
71 public function seek( $row ) {
72 $this->cursor = min( $row, $this->nrows );
73 }
74
75 public function numRows() {
76 return $this->nrows;
77 }
78
79 public function numFields() {
80 return count($this->columns);
81 }
82
83 public function fetchObject() {
84 if ( $this->cursor >= $this->nrows ) {
85 return false;
86 }
87 $row = $this->rows[$this->cursor++];
88 $ret = new stdClass();
89 foreach ( $row as $k => $v ) {
90 $lc = $this->columns[$k];
91 $ret->$lc = $v;
92 }
93
94 return $ret;
95 }
96
97 public function fetchRow() {
98 if ( $this->cursor >= $this->nrows ) {
99 return false;
100 }
101
102 $row = $this->rows[$this->cursor++];
103 $ret = array();
104 foreach ( $row as $k => $v ) {
105 $lc = $this->columns[$k];
106 $ret[$lc] = $v;
107 $ret[$k] = $v;
108 }
109 return $ret;
110 }
111 }
112
113 /**
114 * Utility class.
115 * @ingroup Database
116 */
117 class ORAField implements Field {
118 private $name, $tablename, $default, $max_length, $nullable,
119 $is_pk, $is_unique, $is_multiple, $is_key, $type;
120
121 function __construct( $info ) {
122 $this->name = $info['column_name'];
123 $this->tablename = $info['table_name'];
124 $this->default = $info['data_default'];
125 $this->max_length = $info['data_length'];
126 $this->nullable = $info['not_null'];
127 $this->is_pk = isset( $info['prim'] ) && $info['prim'] == 1 ? 1 : 0;
128 $this->is_unique = isset( $info['uniq'] ) && $info['uniq'] == 1 ? 1 : 0;
129 $this->is_multiple = isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ? 1 : 0;
130 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
131 $this->type = $info['data_type'];
132 }
133
134 function name() {
135 return $this->name;
136 }
137
138 function tableName() {
139 return $this->tablename;
140 }
141
142 function defaultValue() {
143 return $this->default;
144 }
145
146 function maxLength() {
147 return $this->max_length;
148 }
149
150 function isNullable() {
151 return $this->nullable;
152 }
153
154 function isKey() {
155 return $this->is_key;
156 }
157
158 function isMultipleKey() {
159 return $this->is_multiple;
160 }
161
162 function type() {
163 return $this->type;
164 }
165 }
166
167 /**
168 * @ingroup Database
169 */
170 class DatabaseOracle extends DatabaseBase {
171 var $mInsertId = null;
172 var $mLastResult = null;
173 var $lastResult = null;
174 var $cursor = 0;
175 var $mAffectedRows;
176
177 var $ignore_DUP_VAL_ON_INDEX = false;
178 var $sequenceData = null;
179
180 var $defaultCharset = 'AL32UTF8';
181
182 var $mFieldInfoCache = array();
183
184 function __construct( $server = false, $user = false, $password = false, $dbName = false,
185 $flags = 0, $tablePrefix = 'get from global' )
186 {
187 global $wgDBprefix;
188 $tablePrefix = $tablePrefix == 'get from global' ? strtoupper( $wgDBprefix ) : strtoupper( $tablePrefix );
189 parent::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
190 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
191 }
192
193 function __destruct() {
194 if ($this->mOpened) {
195 wfSuppressWarnings();
196 $this->close();
197 wfRestoreWarnings();
198 }
199 }
200
201 function getType() {
202 return 'oracle';
203 }
204
205 function cascadingDeletes() {
206 return true;
207 }
208 function cleanupTriggers() {
209 return true;
210 }
211 function strictIPs() {
212 return true;
213 }
214 function realTimestamps() {
215 return true;
216 }
217 function implicitGroupby() {
218 return false;
219 }
220 function implicitOrderby() {
221 return false;
222 }
223 function searchableIPs() {
224 return true;
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 wfSuppressWarnings();
260 if ( $this->mFlags & DBO_DEFAULT ) {
261 $this->mConn = oci_new_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
262 } else {
263 $this->mConn = oci_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
264 }
265 wfRestoreWarnings();
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 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
282 return $this->mConn;
283 }
284
285 /**
286 * Closes a database connection, if it is open
287 * Returns success, true if already closed
288 */
289 function close() {
290 $this->mOpened = false;
291 if ( $this->mConn ) {
292 if ( $this->mTrxLevel ) {
293 $this->commit();
294 }
295 return oci_close( $this->mConn );
296 } else {
297 return true;
298 }
299 }
300
301 function execFlags() {
302 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT : OCI_COMMIT_ON_SUCCESS;
303 }
304
305 protected function doQuery( $sql ) {
306 wfDebug( "SQL: [$sql]\n" );
307 if ( !mb_check_encoding( $sql ) ) {
308 throw new MWException( "SQL encoding is invalid\n$sql" );
309 }
310
311 // handle some oracle specifics
312 // remove AS column/table/subquery namings
313 if( !$this->getFlag( DBO_DDLMODE ) ) {
314 $sql = preg_replace( '/ as /i', ' ', $sql );
315 }
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 } elseif ( $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->isNullable() == 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, -1, SQLT_CHR ) === 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, $this->execFlags() ) === 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, $quoted = true ) {
654 /*
655 Replace reserved words with better ones
656 Using uppercase because that's the only way Oracle can handle
657 quoted tablenames
658 */
659 switch( $name ) {
660 case 'user':
661 $name = 'MWUSER';
662 break;
663 case 'text':
664 $name = 'PAGECONTENT';
665 break;
666 }
667
668 return parent::tableName( strtoupper( $name ), $quoted );
669 }
670
671 function tableNameInternal( $name ) {
672 $name = $this->tableName( $name );
673 return preg_replace( '/.*\.(.*)/', '$1', $name);
674 }
675 /**
676 * Return the next in a sequence, save the value for retrieval via insertId()
677 */
678 function nextSequenceValue( $seqName ) {
679 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
680 $row = $this->fetchRow( $res );
681 $this->mInsertId = $row[0];
682 return $this->mInsertId;
683 }
684
685 /**
686 * Return sequence_name if table has a sequence
687 */
688 private function getSequenceData( $table ) {
689 if ( $this->sequenceData == null ) {
690 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
691 lower(atc.table_name),
692 lower(atc.column_name)
693 FROM all_sequences asq, all_tab_columns atc
694 WHERE decode(atc.table_name, '{$this->mTablePrefix}MWUSER', '{$this->mTablePrefix}USER', atc.table_name) || '_' ||
695 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
696 AND asq.sequence_owner = '{$this->mDBname}'
697 AND atc.owner = '{$this->mDBname}'" );
698
699 while ( ( $row = $result->fetchRow() ) !== false ) {
700 $this->sequenceData[$this->tableName( $row[1] )] = array(
701 'sequence' => $row[0],
702 'column' => $row[2]
703 );
704 }
705 }
706 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
707 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
708 }
709
710 /**
711 * REPLACE query wrapper
712 * Oracle simulates this with a DELETE followed by INSERT
713 * $row is the row to insert, an associative array
714 * $uniqueIndexes is an array of indexes. Each element may be either a
715 * field name or an array of field names
716 *
717 * It may be more efficient to leave off unique indexes which are unlikely to collide.
718 * However if you do this, you run the risk of encountering errors which wouldn't have
719 * occurred in MySQL.
720 *
721 * @param $table String: table name
722 * @param $uniqueIndexes Array: array of indexes. Each element may be
723 * either a field name or an array of field names
724 * @param $rows Array: rows to insert to $table
725 * @param $fname String: function name, you can use __METHOD__ here
726 */
727 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
728 $table = $this->tableName( $table );
729
730 if ( count( $rows ) == 0 ) {
731 return;
732 }
733
734 # Single row case
735 if ( !is_array( reset( $rows ) ) ) {
736 $rows = array( $rows );
737 }
738
739 $sequenceData = $this->getSequenceData( $table );
740
741 foreach ( $rows as $row ) {
742 # Delete rows which collide
743 if ( $uniqueIndexes ) {
744 $deleteConds = array();
745 foreach ( $uniqueIndexes as $key=>$index ) {
746 if ( is_array( $index ) ) {
747 $deleteConds2 = array();
748 foreach ( $index as $col ) {
749 $deleteConds2[$col] = $row[$col];
750 }
751 $deleteConds[$key] = $this->makeList( $deleteConds2, LIST_AND );
752 } else {
753 $deleteConds[$index] = $row[$index];
754 }
755 }
756 $deleteConds = array( $this->makeList( $deleteConds, LIST_OR ) );
757 $this->delete( $table, $deleteConds, $fname );
758 }
759
760
761 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
762 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
763 }
764
765 # Now insert the row
766 $this->insert( $table, $row, $fname );
767 }
768 }
769
770 # Returns the size of a text field, or -1 for "unlimited"
771 function textFieldSize( $table, $field ) {
772 $fieldInfoData = $this->fieldInfo( $table, $field );
773 return $fieldInfoData->maxLength();
774 }
775
776 function limitResult( $sql, $limit, $offset = false ) {
777 if ( $offset === false ) {
778 $offset = 0;
779 }
780 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
781 }
782
783 function encodeBlob( $b ) {
784 return new Blob( $b );
785 }
786
787 function decodeBlob( $b ) {
788 if ( $b instanceof Blob ) {
789 $b = $b->fetch();
790 }
791 return $b;
792 }
793
794 function unionQueries( $sqls, $all ) {
795 $glue = ' UNION ALL ';
796 return 'SELECT * ' . ( $all ? '':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
797 }
798
799 function wasDeadlock() {
800 return $this->lastErrno() == 'OCI-00060';
801 }
802
803 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
804 $temporary = $temporary ? 'TRUE' : 'FALSE';
805
806 $newName = strtoupper( $newName );
807 $oldName = strtoupper( $oldName );
808
809 $tabName = substr( $newName, strlen( $this->mTablePrefix ) );
810 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
811 $newPrefix = strtoupper( $this->mTablePrefix );
812
813 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', '$oldPrefix', '$newPrefix', $temporary ); END;" );
814 }
815
816 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
817 $listWhere = '';
818 if (!empty($prefix)) {
819 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
820 }
821
822 $owner = strtoupper( $this->mDBname );
823 $result = $this->doQuery( "SELECT table_name FROM all_tables WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
824
825 // dirty code ... i know
826 $endArray = array();
827 $endArray[] = $prefix.'MWUSER';
828 $endArray[] = $prefix.'PAGE';
829 $endArray[] = $prefix.'IMAGE';
830 $fixedOrderTabs = $endArray;
831 while (($row = $result->fetchRow()) !== false) {
832 if (!in_array($row['table_name'], $fixedOrderTabs))
833 $endArray[] = $row['table_name'];
834 }
835
836 return $endArray;
837 }
838
839 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
840 $tableName = $this->tableName($tableName);
841 if( !$this->tableExists( $tableName ) ) {
842 return false;
843 }
844
845 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
846 }
847
848 function timestamp( $ts = 0 ) {
849 return wfTimestamp( TS_ORACLE, $ts );
850 }
851
852 /**
853 * Return aggregated value function call
854 */
855 function aggregateValue ( $valuedata, $valuename = 'value' ) {
856 return $valuedata;
857 }
858
859 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
860 # Ignore errors during error handling to avoid infinite
861 # recursion
862 $ignore = $this->ignoreErrors( true );
863 ++$this->mErrorCount;
864
865 if ( $ignore || $tempIgnore ) {
866 wfDebug( "SQL ERROR (ignored): $error\n" );
867 $this->ignoreErrors( $ignore );
868 } else {
869 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
870 }
871 }
872
873 /**
874 * @return string wikitext of a link to the server software's web site
875 */
876 public static function getSoftwareLink() {
877 return '[http://www.oracle.com/ Oracle]';
878 }
879
880 /**
881 * @return string Version information from the database
882 */
883 function getServerVersion() {
884 //better version number, fallback on driver
885 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
886 if ( !( $row = $rset->fetchRow() ) ) {
887 return oci_server_version( $this->mConn );
888 }
889 return $row['version'];
890 }
891
892 /**
893 * Query whether a given index exists
894 */
895 function indexExists( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
896 $table = $this->tableName( $table );
897 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
898 $index = strtoupper( $index );
899 $owner = strtoupper( $this->mDBname );
900 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
901 $res = $this->doQuery( $SQL );
902 if ( $res ) {
903 $count = $res->numRows();
904 $res->free();
905 } else {
906 $count = 0;
907 }
908 return $count != 0;
909 }
910
911 /**
912 * Query whether a given table exists (in the given schema, or the default mw one if not given)
913 */
914 function tableExists( $table ) {
915 $table = $this->tableName( $table );
916 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
917 $owner = $this->addQuotes( strtoupper( $this->mDBname ) );
918 $SQL = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
919 $res = $this->doQuery( $SQL );
920 if ( $res ) {
921 $count = $res->numRows();
922 $res->free();
923 } else {
924 $count = 0;
925 }
926 return $count;
927 }
928
929 /**
930 * Function translates mysql_fetch_field() functionality on ORACLE.
931 * Caching is present for reducing query time.
932 * For internal calls. Use fieldInfo for normal usage.
933 * Returns false if the field doesn't exist
934 *
935 * @param $table Array
936 * @param $field String
937 * @return ORAField|ORAResult
938 */
939 private function fieldInfoMulti( $table, $field ) {
940 $field = strtoupper( $field );
941 if ( is_array( $table ) ) {
942 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
943 $tableWhere = 'IN (';
944 foreach( $table as &$singleTable ) {
945 $singleTable = $this->removeIdentifierQuotes($singleTable);
946 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
947 return $this->mFieldInfoCache["$singleTable.$field"];
948 }
949 $tableWhere .= '\'' . $singleTable . '\',';
950 }
951 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
952 } else {
953 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
954 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
955 return $this->mFieldInfoCache["$table.$field"];
956 }
957 $tableWhere = '= \''.$table.'\'';
958 }
959
960 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
961 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
962 $e = oci_error( $fieldInfoStmt );
963 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
964 return false;
965 }
966 $res = new ORAResult( $this, $fieldInfoStmt );
967 if ( $res->numRows() == 0 ) {
968 if ( is_array( $table ) ) {
969 foreach( $table as &$singleTable ) {
970 $this->mFieldInfoCache["$singleTable.$field"] = false;
971 }
972 } else {
973 $this->mFieldInfoCache["$table.$field"] = false;
974 }
975 $fieldInfoTemp = null;
976 } else {
977 $fieldInfoTemp = new ORAField( $res->fetchRow() );
978 $table = $fieldInfoTemp->tableName();
979 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
980 }
981 $res->free();
982 return $fieldInfoTemp;
983 }
984
985 /**
986 * @throws DBUnexpectedError
987 * @param $table
988 * @param $field
989 * @return ORAField
990 */
991 function fieldInfo( $table, $field ) {
992 if ( is_array( $table ) ) {
993 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
994 }
995 return $this->fieldInfoMulti ($table, $field);
996 }
997
998 function begin( $fname = 'DatabaseOracle::begin' ) {
999 $this->mTrxLevel = 1;
1000 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
1001 }
1002
1003 function commit( $fname = 'DatabaseOracle::commit' ) {
1004 if ( $this->mTrxLevel ) {
1005 $ret = oci_commit( $this->mConn );
1006 if ( !$ret ) {
1007 throw new DBUnexpectedError( $this, $this->lastError() );
1008 }
1009 $this->mTrxLevel = 0;
1010 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1011 }
1012 }
1013
1014 function rollback( $fname = 'DatabaseOracle::rollback' ) {
1015 if ( $this->mTrxLevel ) {
1016 oci_rollback( $this->mConn );
1017 $this->mTrxLevel = 0;
1018 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
1019 }
1020 }
1021
1022 /* Not even sure why this is used in the main codebase... */
1023 function limitResultForUpdate( $sql, $num ) {
1024 return $sql;
1025 }
1026
1027 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
1028 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
1029 $cmd = '';
1030 $done = false;
1031 $dollarquote = false;
1032
1033 $replacements = array();
1034
1035 while ( ! feof( $fp ) ) {
1036 if ( $lineCallback ) {
1037 call_user_func( $lineCallback );
1038 }
1039 $line = trim( fgets( $fp, 1024 ) );
1040 $sl = strlen( $line ) - 1;
1041
1042 if ( $sl < 0 ) {
1043 continue;
1044 }
1045 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1046 continue;
1047 }
1048
1049 // Allow dollar quoting for function declarations
1050 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1051 if ( $dollarquote ) {
1052 $dollarquote = false;
1053 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1054 $done = true;
1055 } else {
1056 $dollarquote = true;
1057 }
1058 } elseif ( !$dollarquote ) {
1059 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1060 $done = true;
1061 $line = substr( $line, 0, $sl );
1062 }
1063 }
1064
1065 if ( $cmd != '' ) {
1066 $cmd .= ' ';
1067 }
1068 $cmd .= "$line\n";
1069
1070 if ( $done ) {
1071 $cmd = str_replace( ';;', ";", $cmd );
1072 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1073 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1074 $replacements[$defines[2]] = $defines[1];
1075 }
1076 } else {
1077 foreach ( $replacements as $mwVar => $scVar ) {
1078 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1079 }
1080
1081 $cmd = $this->replaceVars( $cmd );
1082 $res = $this->doQuery( $cmd );
1083 if ( $resultCallback ) {
1084 call_user_func( $resultCallback, $res, $this );
1085 }
1086
1087 if ( false === $res ) {
1088 $err = $this->lastError();
1089 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1090 }
1091 }
1092
1093 $cmd = '';
1094 $done = false;
1095 }
1096 }
1097 return true;
1098 }
1099
1100 function selectDB( $db ) {
1101 $this->mDBname = $db;
1102 if ( $db == null || $db == $this->mUser ) {
1103 return true;
1104 }
1105 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1106 $stmt = oci_parse( $this->mConn, $sql );
1107 wfSuppressWarnings();
1108 $success = oci_execute( $stmt );
1109 wfRestoreWarnings();
1110 if ( !$success ) {
1111 $e = oci_error( $stmt );
1112 if ( $e['code'] != '1435' ) {
1113 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1114 }
1115 return false;
1116 }
1117 return true;
1118 }
1119
1120 function strencode( $s ) {
1121 return str_replace( "'", "''", $s );
1122 }
1123
1124 function addQuotes( $s ) {
1125 global $wgContLang;
1126 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1127 $s = $wgContLang->checkTitleEncoding( $s );
1128 }
1129 return "'" . $this->strencode( $s ) . "'";
1130 }
1131
1132 public function addIdentifierQuotes( $s ) {
1133 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1134 $s = '/*Q*/' . $s;
1135 }
1136 return $s;
1137 }
1138
1139 public function removeIdentifierQuotes( $s ) {
1140 return strpos($s, '/*Q*/') === FALSE ? $s : substr($s, 5);
1141 }
1142
1143 public function isQuotedIdentifier( $s ) {
1144 return strpos($s, '/*Q*/') !== FALSE;
1145 }
1146
1147 private function wrapFieldForWhere( $table, &$col, &$val ) {
1148 global $wgContLang;
1149
1150 $col_info = $this->fieldInfoMulti( $table, $col );
1151 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1152 if ( $col_type == 'CLOB' ) {
1153 $col = 'TO_CHAR(' . $col . ')';
1154 $val = $wgContLang->checkTitleEncoding( $val );
1155 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1156 $val = $wgContLang->checkTitleEncoding( $val );
1157 }
1158 }
1159
1160 private function wrapConditionsForWhere ( $table, $conds, $parentCol = null ) {
1161 $conds2 = array();
1162 foreach ( $conds as $col => $val ) {
1163 if ( is_array( $val ) ) {
1164 $conds2[$col] = $this->wrapConditionsForWhere ( $table, $val, $col );
1165 } else {
1166 if ( is_numeric( $col ) && $parentCol != null ) {
1167 $this->wrapFieldForWhere ( $table, $parentCol, $val );
1168 } else {
1169 $this->wrapFieldForWhere ( $table, $col, $val );
1170 }
1171 $conds2[$col] = $val;
1172 }
1173 }
1174 return $conds2;
1175 }
1176
1177 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1178 if ( is_array($conds) ) {
1179 $conds = $this->wrapConditionsForWhere( $table, $conds );
1180 }
1181 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1182 }
1183
1184 /**
1185 * Returns an optional USE INDEX clause to go after the table, and a
1186 * string to go at the end of the query
1187 *
1188 * @private
1189 *
1190 * @param $options Array: an associative array of options to be turned into
1191 * an SQL query, valid keys are listed in the function.
1192 * @return array
1193 */
1194 function makeSelectOptions( $options ) {
1195 $preLimitTail = $postLimitTail = '';
1196 $startOpts = '';
1197
1198 $noKeyOptions = array();
1199 foreach ( $options as $key => $option ) {
1200 if ( is_numeric( $key ) ) {
1201 $noKeyOptions[$option] = true;
1202 }
1203 }
1204
1205 if ( isset( $options['GROUP BY'] ) ) {
1206 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1207 }
1208 if ( isset( $options['ORDER BY'] ) ) {
1209 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1210 }
1211
1212 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1213 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1214 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1215 $startOpts .= 'DISTINCT';
1216 }
1217
1218 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1219 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1220 } else {
1221 $useIndex = '';
1222 }
1223
1224 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1225 }
1226
1227 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1228 if ( is_array($conds) ) {
1229 $conds = $this->wrapConditionsForWhere( $table, $conds );
1230 }
1231 return parent::delete( $table, $conds, $fname );
1232 }
1233
1234 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1235 global $wgContLang;
1236
1237 $table = $this->tableName( $table );
1238 $opts = $this->makeUpdateOptions( $options );
1239 $sql = "UPDATE $opts $table SET ";
1240
1241 $first = true;
1242 foreach ( $values as $col => &$val ) {
1243 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1244
1245 if ( !$first ) {
1246 $sqlSet = ', ' . $sqlSet;
1247 } else {
1248 $first = false;
1249 }
1250 $sql .= $sqlSet;
1251 }
1252
1253 if ( $conds != '*' ) {
1254 $conds = $this->wrapConditionsForWhere( $table, $conds );
1255 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1256 }
1257
1258 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1259 $e = oci_error( $this->mConn );
1260 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1261 return false;
1262 }
1263 foreach ( $values as $col => &$val ) {
1264 $col_info = $this->fieldInfoMulti( $table, $col );
1265 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1266
1267 if ( $val === null ) {
1268 // do nothing ... null was inserted in statement creation
1269 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1270 if ( is_object( $val ) ) {
1271 $val = $val->getData();
1272 }
1273
1274 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1275 $val = '31-12-2030 12:00:00.000000';
1276 }
1277
1278 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1279 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1280 $e = oci_error( $stmt );
1281 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1282 return false;
1283 }
1284 } else {
1285 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1286 $e = oci_error( $stmt );
1287 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1288 }
1289
1290 if ( $col_type == 'BLOB' ) {
1291 $lob[$col]->writeTemporary( $val );
1292 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1293 } else {
1294 $lob[$col]->writeTemporary( $val );
1295 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1296 }
1297 }
1298 }
1299
1300 wfSuppressWarnings();
1301
1302 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1303 $e = oci_error( $stmt );
1304 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1305 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1306 return false;
1307 } else {
1308 $this->mAffectedRows = oci_num_rows( $stmt );
1309 }
1310 } else {
1311 $this->mAffectedRows = oci_num_rows( $stmt );
1312 }
1313
1314 wfRestoreWarnings();
1315
1316 if ( isset( $lob ) ) {
1317 foreach ( $lob as $lob_v ) {
1318 $lob_v->free();
1319 }
1320 }
1321
1322 if ( !$this->mTrxLevel ) {
1323 oci_commit( $this->mConn );
1324 }
1325
1326 oci_free_statement( $stmt );
1327 }
1328
1329 function bitNot( $field ) {
1330 // expecting bit-fields smaller than 4bytes
1331 return 'BITNOT(' . $field . ')';
1332 }
1333
1334 function bitAnd( $fieldLeft, $fieldRight ) {
1335 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1336 }
1337
1338 function bitOr( $fieldLeft, $fieldRight ) {
1339 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1340 }
1341
1342 function setFakeMaster( $enabled = true ) { }
1343
1344 function getDBname() {
1345 return $this->mDBname;
1346 }
1347
1348 function getServer() {
1349 return $this->mServer;
1350 }
1351
1352 public function getSearchEngine() {
1353 return 'SearchOracle';
1354 }
1355 } // end DatabaseOracle class