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