* DatabaseOracle.php binds variables, so using $val = 'NULL' breaks certain maint...
[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 $val = null;
499 }
500
501 if ( $val === null ) {
502 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
503 $bind .= 'DEFAULT';
504 } else {
505 $bind .= 'NULL';
506 }
507 } else {
508 $bind .= ':' . $col;
509 }
510
511 return $bind;
512 }
513
514 private function insertOneRow( $table, $row, $fname ) {
515 global $wgContLang;
516
517 $table = $this->tableName( $table );
518 // "INSERT INTO tables (a, b, c)"
519 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
520 $sql .= " VALUES (";
521
522 // for each value, append ":key"
523 $first = true;
524 foreach ( $row as $col => &$val ) {
525 if ( !$first ) {
526 $sql .= ', ';
527 } else {
528 $first = false;
529 }
530
531 $sql .= $this->fieldBindStatement( $table, $col, $val );
532 }
533 $sql .= ')';
534
535 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
536 $e = oci_error( $this->mConn );
537 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
538 return false;
539 }
540 foreach ( $row as $col => &$val ) {
541 $col_info = $this->fieldInfoMulti( $table, $col );
542 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
543
544 if ( $val === null ) {
545 // do nothing ... null was inserted in statement creation
546 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
547 if ( is_object( $val ) ) {
548 $val = $val->fetch();
549 }
550
551 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
552 $val = '31-12-2030 12:00:00.000000';
553 }
554
555 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
556 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR ) === false ) {
557 $e = oci_error( $stmt );
558 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
559 return false;
560 }
561 } else {
562 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
563 $e = oci_error( $stmt );
564 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
565 }
566
567 if ( is_object( $val ) ) {
568 $val = $val->fetch();
569 }
570
571 if ( $col_type == 'BLOB' ) {
572 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
573 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB );
574 } else {
575 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
576 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
577 }
578 }
579 }
580
581 wfSuppressWarnings();
582
583 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
584 $e = oci_error( $stmt );
585 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
586 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
587 return false;
588 } else {
589 $this->mAffectedRows = oci_num_rows( $stmt );
590 }
591 } else {
592 $this->mAffectedRows = oci_num_rows( $stmt );
593 }
594
595 wfRestoreWarnings();
596
597 if ( isset( $lob ) ) {
598 foreach ( $lob as $lob_v ) {
599 $lob_v->free();
600 }
601 }
602
603 if ( !$this->mTrxLevel ) {
604 oci_commit( $this->mConn );
605 }
606
607 oci_free_statement( $stmt );
608 }
609
610 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
611 $insertOptions = array(), $selectOptions = array() )
612 {
613 $destTable = $this->tableName( $destTable );
614 if ( !is_array( $selectOptions ) ) {
615 $selectOptions = array( $selectOptions );
616 }
617 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
618 if ( is_array( $srcTable ) ) {
619 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
620 } else {
621 $srcTable = $this->tableName( $srcTable );
622 }
623
624 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
625 !isset( $varMap[$sequenceData['column']] ) )
626 {
627 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
628 }
629
630 // count-alias subselect fields to avoid abigious definition errors
631 $i = 0;
632 foreach ( $varMap as &$val ) {
633 $val = $val . ' field' . ( $i++ );
634 }
635
636 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
637 " SELECT $startOpts " . implode( ',', $varMap ) .
638 " FROM $srcTable $useIndex ";
639 if ( $conds != '*' ) {
640 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
641 }
642 $sql .= " $tailOpts";
643
644 if ( in_array( 'IGNORE', $insertOptions ) ) {
645 $this->ignore_DUP_VAL_ON_INDEX = true;
646 }
647
648 $retval = $this->query( $sql, $fname );
649
650 if ( in_array( 'IGNORE', $insertOptions ) ) {
651 $this->ignore_DUP_VAL_ON_INDEX = false;
652 }
653
654 return $retval;
655 }
656
657 function tableName( $name, $quoted = true ) {
658 /*
659 Replace reserved words with better ones
660 Using uppercase because that's the only way Oracle can handle
661 quoted tablenames
662 */
663 switch( $name ) {
664 case 'user':
665 $name = 'MWUSER';
666 break;
667 case 'text':
668 $name = 'PAGECONTENT';
669 break;
670 }
671
672 return parent::tableName( strtoupper( $name ), $quoted );
673 }
674
675 function tableNameInternal( $name ) {
676 $name = $this->tableName( $name );
677 return preg_replace( '/.*\.(.*)/', '$1', $name);
678 }
679 /**
680 * Return the next in a sequence, save the value for retrieval via insertId()
681 */
682 function nextSequenceValue( $seqName ) {
683 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
684 $row = $this->fetchRow( $res );
685 $this->mInsertId = $row[0];
686 return $this->mInsertId;
687 }
688
689 /**
690 * Return sequence_name if table has a sequence
691 */
692 private function getSequenceData( $table ) {
693 if ( $this->sequenceData == null ) {
694 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
695 lower(atc.table_name),
696 lower(atc.column_name)
697 FROM all_sequences asq, all_tab_columns atc
698 WHERE decode(atc.table_name, '{$this->mTablePrefix}MWUSER', '{$this->mTablePrefix}USER', atc.table_name) || '_' ||
699 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
700 AND asq.sequence_owner = '{$this->mDBname}'
701 AND atc.owner = '{$this->mDBname}'" );
702
703 while ( ( $row = $result->fetchRow() ) !== false ) {
704 $this->sequenceData[$this->tableName( $row[1] )] = array(
705 'sequence' => $row[0],
706 'column' => $row[2]
707 );
708 }
709 }
710 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
711 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
712 }
713
714 # Returns the size of a text field, or -1 for "unlimited"
715 function textFieldSize( $table, $field ) {
716 $fieldInfoData = $this->fieldInfo( $table, $field );
717 return $fieldInfoData->maxLength();
718 }
719
720 function limitResult( $sql, $limit, $offset = false ) {
721 if ( $offset === false ) {
722 $offset = 0;
723 }
724 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
725 }
726
727 function encodeBlob( $b ) {
728 return new Blob( $b );
729 }
730
731 function decodeBlob( $b ) {
732 if ( $b instanceof Blob ) {
733 $b = $b->fetch();
734 }
735 return $b;
736 }
737
738 function unionQueries( $sqls, $all ) {
739 $glue = ' UNION ALL ';
740 return 'SELECT * ' . ( $all ? '':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
741 }
742
743 function wasDeadlock() {
744 return $this->lastErrno() == 'OCI-00060';
745 }
746
747 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
748 $temporary = $temporary ? 'TRUE' : 'FALSE';
749
750 $newName = strtoupper( $newName );
751 $oldName = strtoupper( $oldName );
752
753 $tabName = substr( $newName, strlen( $this->mTablePrefix ) );
754 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
755 $newPrefix = strtoupper( $this->mTablePrefix );
756
757 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', '$oldPrefix', '$newPrefix', $temporary ); END;" );
758 }
759
760 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
761 $listWhere = '';
762 if (!empty($prefix)) {
763 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
764 }
765
766 $owner = strtoupper( $this->mDBname );
767 $result = $this->doQuery( "SELECT table_name FROM all_tables WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
768
769 // dirty code ... i know
770 $endArray = array();
771 $endArray[] = $prefix.'MWUSER';
772 $endArray[] = $prefix.'PAGE';
773 $endArray[] = $prefix.'IMAGE';
774 $fixedOrderTabs = $endArray;
775 while (($row = $result->fetchRow()) !== false) {
776 if (!in_array($row['table_name'], $fixedOrderTabs))
777 $endArray[] = $row['table_name'];
778 }
779
780 return $endArray;
781 }
782
783 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
784 $tableName = $this->tableName($tableName);
785 if( !$this->tableExists( $tableName ) ) {
786 return false;
787 }
788
789 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
790 }
791
792 function timestamp( $ts = 0 ) {
793 return wfTimestamp( TS_ORACLE, $ts );
794 }
795
796 /**
797 * Return aggregated value function call
798 */
799 function aggregateValue ( $valuedata, $valuename = 'value' ) {
800 return $valuedata;
801 }
802
803 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
804 # Ignore errors during error handling to avoid infinite
805 # recursion
806 $ignore = $this->ignoreErrors( true );
807 ++$this->mErrorCount;
808
809 if ( $ignore || $tempIgnore ) {
810 wfDebug( "SQL ERROR (ignored): $error\n" );
811 $this->ignoreErrors( $ignore );
812 } else {
813 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
814 }
815 }
816
817 /**
818 * @return string wikitext of a link to the server software's web site
819 */
820 public static function getSoftwareLink() {
821 return '[http://www.oracle.com/ Oracle]';
822 }
823
824 /**
825 * @return string Version information from the database
826 */
827 function getServerVersion() {
828 //better version number, fallback on driver
829 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
830 if ( !( $row = $rset->fetchRow() ) ) {
831 return oci_server_version( $this->mConn );
832 }
833 return $row['version'];
834 }
835
836 /**
837 * Query whether a given index exists
838 */
839 function indexExists( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
840 $table = $this->tableName( $table );
841 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
842 $index = strtoupper( $index );
843 $owner = strtoupper( $this->mDBname );
844 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
845 $res = $this->doQuery( $SQL );
846 if ( $res ) {
847 $count = $res->numRows();
848 $res->free();
849 } else {
850 $count = 0;
851 }
852 return $count != 0;
853 }
854
855 /**
856 * Query whether a given table exists (in the given schema, or the default mw one if not given)
857 */
858 function tableExists( $table ) {
859 $table = $this->tableName( $table );
860 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
861 $owner = $this->addQuotes( strtoupper( $this->mDBname ) );
862 $SQL = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
863 $res = $this->doQuery( $SQL );
864 if ( $res ) {
865 $count = $res->numRows();
866 $res->free();
867 } else {
868 $count = 0;
869 }
870 return $count;
871 }
872
873 /**
874 * Function translates mysql_fetch_field() functionality on ORACLE.
875 * Caching is present for reducing query time.
876 * For internal calls. Use fieldInfo for normal usage.
877 * Returns false if the field doesn't exist
878 *
879 * @param $table Array
880 * @param $field String
881 * @return ORAField|ORAResult
882 */
883 private function fieldInfoMulti( $table, $field ) {
884 $field = strtoupper( $field );
885 if ( is_array( $table ) ) {
886 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
887 $tableWhere = 'IN (';
888 foreach( $table as &$singleTable ) {
889 $singleTable = $this->removeIdentifierQuotes($singleTable);
890 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
891 return $this->mFieldInfoCache["$singleTable.$field"];
892 }
893 $tableWhere .= '\'' . $singleTable . '\',';
894 }
895 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
896 } else {
897 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
898 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
899 return $this->mFieldInfoCache["$table.$field"];
900 }
901 $tableWhere = '= \''.$table.'\'';
902 }
903
904 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
905 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
906 $e = oci_error( $fieldInfoStmt );
907 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
908 return false;
909 }
910 $res = new ORAResult( $this, $fieldInfoStmt );
911 if ( $res->numRows() == 0 ) {
912 if ( is_array( $table ) ) {
913 foreach( $table as &$singleTable ) {
914 $this->mFieldInfoCache["$singleTable.$field"] = false;
915 }
916 } else {
917 $this->mFieldInfoCache["$table.$field"] = false;
918 }
919 $fieldInfoTemp = null;
920 } else {
921 $fieldInfoTemp = new ORAField( $res->fetchRow() );
922 $table = $fieldInfoTemp->tableName();
923 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
924 }
925 $res->free();
926 return $fieldInfoTemp;
927 }
928
929 /**
930 * @throws DBUnexpectedError
931 * @param $table
932 * @param $field
933 * @return ORAField
934 */
935 function fieldInfo( $table, $field ) {
936 if ( is_array( $table ) ) {
937 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
938 }
939 return $this->fieldInfoMulti ($table, $field);
940 }
941
942 function begin( $fname = 'DatabaseOracle::begin' ) {
943 $this->mTrxLevel = 1;
944 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
945 }
946
947 function commit( $fname = 'DatabaseOracle::commit' ) {
948 if ( $this->mTrxLevel ) {
949 $ret = oci_commit( $this->mConn );
950 if ( !$ret ) {
951 throw new DBUnexpectedError( $this, $this->lastError() );
952 }
953 $this->mTrxLevel = 0;
954 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
955 }
956 }
957
958 function rollback( $fname = 'DatabaseOracle::rollback' ) {
959 if ( $this->mTrxLevel ) {
960 oci_rollback( $this->mConn );
961 $this->mTrxLevel = 0;
962 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
963 }
964 }
965
966 /* Not even sure why this is used in the main codebase... */
967 function limitResultForUpdate( $sql, $num ) {
968 return $sql;
969 }
970
971 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
972 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
973 $cmd = '';
974 $done = false;
975 $dollarquote = false;
976
977 $replacements = array();
978
979 while ( ! feof( $fp ) ) {
980 if ( $lineCallback ) {
981 call_user_func( $lineCallback );
982 }
983 $line = trim( fgets( $fp, 1024 ) );
984 $sl = strlen( $line ) - 1;
985
986 if ( $sl < 0 ) {
987 continue;
988 }
989 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
990 continue;
991 }
992
993 // Allow dollar quoting for function declarations
994 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
995 if ( $dollarquote ) {
996 $dollarquote = false;
997 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
998 $done = true;
999 } else {
1000 $dollarquote = true;
1001 }
1002 } elseif ( !$dollarquote ) {
1003 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1004 $done = true;
1005 $line = substr( $line, 0, $sl );
1006 }
1007 }
1008
1009 if ( $cmd != '' ) {
1010 $cmd .= ' ';
1011 }
1012 $cmd .= "$line\n";
1013
1014 if ( $done ) {
1015 $cmd = str_replace( ';;', ";", $cmd );
1016 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1017 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1018 $replacements[$defines[2]] = $defines[1];
1019 }
1020 } else {
1021 foreach ( $replacements as $mwVar => $scVar ) {
1022 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1023 }
1024
1025 $cmd = $this->replaceVars( $cmd );
1026 $res = $this->doQuery( $cmd );
1027 if ( $resultCallback ) {
1028 call_user_func( $resultCallback, $res, $this );
1029 }
1030
1031 if ( false === $res ) {
1032 $err = $this->lastError();
1033 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1034 }
1035 }
1036
1037 $cmd = '';
1038 $done = false;
1039 }
1040 }
1041 return true;
1042 }
1043
1044 function selectDB( $db ) {
1045 $this->mDBname = $db;
1046 if ( $db == null || $db == $this->mUser ) {
1047 return true;
1048 }
1049 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1050 $stmt = oci_parse( $this->mConn, $sql );
1051 wfSuppressWarnings();
1052 $success = oci_execute( $stmt );
1053 wfRestoreWarnings();
1054 if ( !$success ) {
1055 $e = oci_error( $stmt );
1056 if ( $e['code'] != '1435' ) {
1057 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1058 }
1059 return false;
1060 }
1061 return true;
1062 }
1063
1064 function strencode( $s ) {
1065 return str_replace( "'", "''", $s );
1066 }
1067
1068 function addQuotes( $s ) {
1069 global $wgContLang;
1070 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1071 $s = $wgContLang->checkTitleEncoding( $s );
1072 }
1073 return "'" . $this->strencode( $s ) . "'";
1074 }
1075
1076 public function addIdentifierQuotes( $s ) {
1077 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1078 $s = '/*Q*/' . $s;
1079 }
1080 return $s;
1081 }
1082
1083 public function removeIdentifierQuotes( $s ) {
1084 return strpos($s, '/*Q*/') === FALSE ? $s : substr($s, 5);
1085 }
1086
1087 public function isQuotedIdentifier( $s ) {
1088 return strpos($s, '/*Q*/') !== FALSE;
1089 }
1090
1091 private function wrapFieldForWhere( $table, &$col, &$val ) {
1092 global $wgContLang;
1093
1094 $col_info = $this->fieldInfoMulti( $table, $col );
1095 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1096 if ( $col_type == 'CLOB' ) {
1097 $col = 'TO_CHAR(' . $col . ')';
1098 $val = $wgContLang->checkTitleEncoding( $val );
1099 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1100 $val = $wgContLang->checkTitleEncoding( $val );
1101 }
1102 }
1103
1104 private function wrapConditionsForWhere ( $table, $conds, $parentCol = null ) {
1105 $conds2 = array();
1106 foreach ( $conds as $col => $val ) {
1107 if ( is_array( $val ) ) {
1108 $conds2[$col] = $this->wrapConditionsForWhere ( $table, $val, $col );
1109 } else {
1110 if ( is_numeric( $col ) && $parentCol != null ) {
1111 $this->wrapFieldForWhere ( $table, $parentCol, $val );
1112 } else {
1113 $this->wrapFieldForWhere ( $table, $col, $val );
1114 }
1115 $conds2[$col] = $val;
1116 }
1117 }
1118 return $conds2;
1119 }
1120
1121 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1122 if ( is_array($conds) ) {
1123 $conds = $this->wrapConditionsForWhere( $table, $conds );
1124 }
1125 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1126 }
1127
1128 /**
1129 * Returns an optional USE INDEX clause to go after the table, and a
1130 * string to go at the end of the query
1131 *
1132 * @private
1133 *
1134 * @param $options Array: an associative array of options to be turned into
1135 * an SQL query, valid keys are listed in the function.
1136 * @return array
1137 */
1138 function makeSelectOptions( $options ) {
1139 $preLimitTail = $postLimitTail = '';
1140 $startOpts = '';
1141
1142 $noKeyOptions = array();
1143 foreach ( $options as $key => $option ) {
1144 if ( is_numeric( $key ) ) {
1145 $noKeyOptions[$option] = true;
1146 }
1147 }
1148
1149 if ( isset( $options['GROUP BY'] ) ) {
1150 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1151 }
1152 if ( isset( $options['ORDER BY'] ) ) {
1153 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1154 }
1155
1156 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1157 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1158 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1159 $startOpts .= 'DISTINCT';
1160 }
1161
1162 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1163 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1164 } else {
1165 $useIndex = '';
1166 }
1167
1168 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1169 }
1170
1171 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1172 if ( is_array($conds) ) {
1173 $conds = $this->wrapConditionsForWhere( $table, $conds );
1174 }
1175 return parent::delete( $table, $conds, $fname );
1176 }
1177
1178 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1179 global $wgContLang;
1180
1181 $table = $this->tableName( $table );
1182 $opts = $this->makeUpdateOptions( $options );
1183 $sql = "UPDATE $opts $table SET ";
1184
1185 $first = true;
1186 foreach ( $values as $col => &$val ) {
1187 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1188
1189 if ( !$first ) {
1190 $sqlSet = ', ' . $sqlSet;
1191 } else {
1192 $first = false;
1193 }
1194 $sql .= $sqlSet;
1195 }
1196
1197 if ( $conds != '*' ) {
1198 $conds = $this->wrapConditionsForWhere( $table, $conds );
1199 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1200 }
1201
1202 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1203 $e = oci_error( $this->mConn );
1204 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1205 return false;
1206 }
1207 foreach ( $values as $col => &$val ) {
1208 $col_info = $this->fieldInfoMulti( $table, $col );
1209 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1210
1211 if ( $val === null ) {
1212 // do nothing ... null was inserted in statement creation
1213 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1214 if ( is_object( $val ) ) {
1215 $val = $val->getData();
1216 }
1217
1218 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1219 $val = '31-12-2030 12:00:00.000000';
1220 }
1221
1222 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1223 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1224 $e = oci_error( $stmt );
1225 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1226 return false;
1227 }
1228 } else {
1229 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1230 $e = oci_error( $stmt );
1231 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1232 }
1233
1234 if ( $col_type == 'BLOB' ) {
1235 $lob[$col]->writeTemporary( $val );
1236 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1237 } else {
1238 $lob[$col]->writeTemporary( $val );
1239 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1240 }
1241 }
1242 }
1243
1244 wfSuppressWarnings();
1245
1246 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1247 $e = oci_error( $stmt );
1248 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1249 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1250 return false;
1251 } else {
1252 $this->mAffectedRows = oci_num_rows( $stmt );
1253 }
1254 } else {
1255 $this->mAffectedRows = oci_num_rows( $stmt );
1256 }
1257
1258 wfRestoreWarnings();
1259
1260 if ( isset( $lob ) ) {
1261 foreach ( $lob as $lob_v ) {
1262 $lob_v->free();
1263 }
1264 }
1265
1266 if ( !$this->mTrxLevel ) {
1267 oci_commit( $this->mConn );
1268 }
1269
1270 oci_free_statement( $stmt );
1271 }
1272
1273 function bitNot( $field ) {
1274 // expecting bit-fields smaller than 4bytes
1275 return 'BITNOT(' . $field . ')';
1276 }
1277
1278 function bitAnd( $fieldLeft, $fieldRight ) {
1279 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1280 }
1281
1282 function bitOr( $fieldLeft, $fieldRight ) {
1283 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1284 }
1285
1286 function setFakeMaster( $enabled = true ) { }
1287
1288 function getDBname() {
1289 return $this->mDBname;
1290 }
1291
1292 function getServer() {
1293 return $this->mServer;
1294 }
1295
1296 public function getSearchEngine() {
1297 return 'SearchOracle';
1298 }
1299 } // end DatabaseOracle class