Follow-up r112565: fix code duplication
[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 * @return DatabaseBase|null
230 */
231 function open( $server, $user, $password, $dbName ) {
232 if ( !function_exists( 'oci_connect' ) ) {
233 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" );
234 }
235
236 $this->close();
237 $this->mUser = $user;
238 $this->mPassword = $password;
239 // changed internal variables functions
240 // mServer now holds the TNS endpoint
241 // mDBname is schema name if different from username
242 if ( !$server ) {
243 // backward compatibillity (server used to be null and TNS was supplied in dbname)
244 $this->mServer = $dbName;
245 $this->mDBname = $user;
246 } else {
247 $this->mServer = $server;
248 if ( !$dbName ) {
249 $this->mDBname = $user;
250 } else {
251 $this->mDBname = $dbName;
252 }
253 }
254
255 if ( !strlen( $user ) ) { # e.g. the class is being loaded
256 return;
257 }
258
259 $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
260 wfSuppressWarnings();
261 if ( $this->mFlags & DBO_DEFAULT ) {
262 $this->mConn = oci_new_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
263 } else {
264 $this->mConn = oci_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
265 }
266 wfRestoreWarnings();
267
268 if ( $this->mUser != $this->mDBname ) {
269 //change current schema in session
270 $this->selectDB( $this->mDBname );
271 }
272
273 if ( !$this->mConn ) {
274 throw new DBConnectionError( $this, $this->lastError() );
275 }
276
277 $this->mOpened = true;
278
279 # removed putenv calls because they interfere with the system globaly
280 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
281 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
282 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
283 return $this->mConn;
284 }
285
286 /**
287 * Closes a database connection, if it is open
288 * Returns success, true if already closed
289 * @return bool
290 */
291 protected function closeConnection() {
292 return oci_close( $this->mConn );
293 }
294
295 function execFlags() {
296 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT : OCI_COMMIT_ON_SUCCESS;
297 }
298
299 protected function doQuery( $sql ) {
300 wfDebug( "SQL: [$sql]\n" );
301 if ( !mb_check_encoding( $sql ) ) {
302 throw new MWException( "SQL encoding is invalid\n$sql" );
303 }
304
305 // handle some oracle specifics
306 // remove AS column/table/subquery namings
307 if( !$this->getFlag( DBO_DDLMODE ) ) {
308 $sql = preg_replace( '/ as /i', ' ', $sql );
309 }
310
311 // Oracle has issues with UNION clause if the statement includes LOB fields
312 // So we do a UNION ALL and then filter the results array with array_unique
313 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
314 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
315 // you have to select data from plan table after explain
316 $explain_id = date( 'dmYHis' );
317
318 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
319
320 wfSuppressWarnings();
321
322 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
323 $e = oci_error( $this->mConn );
324 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
325 return false;
326 }
327
328 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
329 $e = oci_error( $stmt );
330 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
331 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
332 return false;
333 }
334 }
335
336 wfRestoreWarnings();
337
338 if ( $explain_count > 0 ) {
339 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
340 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
341 return new ORAResult( $this, $stmt, $union_unique );
342 } else {
343 $this->mAffectedRows = oci_num_rows( $stmt );
344 return true;
345 }
346 }
347
348 function queryIgnore( $sql, $fname = '' ) {
349 return $this->query( $sql, $fname, true );
350 }
351
352 function freeResult( $res ) {
353 if ( $res instanceof ResultWrapper ) {
354 $res = $res->result;
355 }
356
357 $res->free();
358 }
359
360 function fetchObject( $res ) {
361 if ( $res instanceof ResultWrapper ) {
362 $res = $res->result;
363 }
364
365 return $res->fetchObject();
366 }
367
368 function fetchRow( $res ) {
369 if ( $res instanceof ResultWrapper ) {
370 $res = $res->result;
371 }
372
373 return $res->fetchRow();
374 }
375
376 function numRows( $res ) {
377 if ( $res instanceof ResultWrapper ) {
378 $res = $res->result;
379 }
380
381 return $res->numRows();
382 }
383
384 function numFields( $res ) {
385 if ( $res instanceof ResultWrapper ) {
386 $res = $res->result;
387 }
388
389 return $res->numFields();
390 }
391
392 function fieldName( $stmt, $n ) {
393 return oci_field_name( $stmt, $n );
394 }
395
396 /**
397 * This must be called after nextSequenceVal
398 * @return null
399 */
400 function insertId() {
401 return $this->mInsertId;
402 }
403
404 function dataSeek( $res, $row ) {
405 if ( $res instanceof ORAResult ) {
406 $res->seek( $row );
407 } else {
408 $res->result->seek( $row );
409 }
410 }
411
412 function lastError() {
413 if ( $this->mConn === false ) {
414 $e = oci_error();
415 } else {
416 $e = oci_error( $this->mConn );
417 }
418 return $e['message'];
419 }
420
421 function lastErrno() {
422 if ( $this->mConn === false ) {
423 $e = oci_error();
424 } else {
425 $e = oci_error( $this->mConn );
426 }
427 return $e['code'];
428 }
429
430 function affectedRows() {
431 return $this->mAffectedRows;
432 }
433
434 /**
435 * Returns information about an index
436 * If errors are explicitly ignored, returns NULL on failure
437 * @return bool
438 */
439 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
440 return false;
441 }
442
443 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
444 return false;
445 }
446
447 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
448 if ( !count( $a ) ) {
449 return true;
450 }
451
452 if ( !is_array( $options ) ) {
453 $options = array( $options );
454 }
455
456 if ( in_array( 'IGNORE', $options ) ) {
457 $this->ignore_DUP_VAL_ON_INDEX = true;
458 }
459
460 if ( !is_array( reset( $a ) ) ) {
461 $a = array( $a );
462 }
463
464 foreach ( $a as &$row ) {
465 $this->insertOneRow( $table, $row, $fname );
466 }
467 $retVal = true;
468
469 if ( in_array( 'IGNORE', $options ) ) {
470 $this->ignore_DUP_VAL_ON_INDEX = false;
471 }
472
473 return $retVal;
474 }
475
476 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
477 $col_info = $this->fieldInfoMulti( $table, $col );
478 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
479
480 $bind = '';
481 if ( is_numeric( $col ) ) {
482 $bind = $val;
483 $val = null;
484 return $bind;
485 } elseif ( $includeCol ) {
486 $bind = "$col = ";
487 }
488
489 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
490 $val = null;
491 }
492
493 if ( $val === 'NULL' ) {
494 $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 // backward compatibility
548 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
549 $val = $this->getInfinity();
550 }
551
552 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
553 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR ) === false ) {
554 $e = oci_error( $stmt );
555 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
556 return false;
557 }
558 } else {
559 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
560 $e = oci_error( $stmt );
561 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
562 }
563
564 if ( is_object( $val ) ) {
565 $val = $val->fetch();
566 }
567
568 if ( $col_type == 'BLOB' ) {
569 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
570 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB );
571 } else {
572 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
573 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
574 }
575 }
576 }
577
578 wfSuppressWarnings();
579
580 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
581 $e = oci_error( $stmt );
582 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
583 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
584 return false;
585 } else {
586 $this->mAffectedRows = oci_num_rows( $stmt );
587 }
588 } else {
589 $this->mAffectedRows = oci_num_rows( $stmt );
590 }
591
592 wfRestoreWarnings();
593
594 if ( isset( $lob ) ) {
595 foreach ( $lob as $lob_v ) {
596 $lob_v->free();
597 }
598 }
599
600 if ( !$this->mTrxLevel ) {
601 oci_commit( $this->mConn );
602 }
603
604 oci_free_statement( $stmt );
605 }
606
607 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
608 $insertOptions = array(), $selectOptions = array() )
609 {
610 $destTable = $this->tableName( $destTable );
611 if ( !is_array( $selectOptions ) ) {
612 $selectOptions = array( $selectOptions );
613 }
614 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
615 if ( is_array( $srcTable ) ) {
616 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
617 } else {
618 $srcTable = $this->tableName( $srcTable );
619 }
620
621 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
622 !isset( $varMap[$sequenceData['column']] ) )
623 {
624 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
625 }
626
627 // count-alias subselect fields to avoid abigious definition errors
628 $i = 0;
629 foreach ( $varMap as &$val ) {
630 $val = $val . ' field' . ( $i++ );
631 }
632
633 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
634 " SELECT $startOpts " . implode( ',', $varMap ) .
635 " FROM $srcTable $useIndex ";
636 if ( $conds != '*' ) {
637 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
638 }
639 $sql .= " $tailOpts";
640
641 if ( in_array( 'IGNORE', $insertOptions ) ) {
642 $this->ignore_DUP_VAL_ON_INDEX = true;
643 }
644
645 $retval = $this->query( $sql, $fname );
646
647 if ( in_array( 'IGNORE', $insertOptions ) ) {
648 $this->ignore_DUP_VAL_ON_INDEX = false;
649 }
650
651 return $retval;
652 }
653
654 function tableName( $name, $format = 'quoted' ) {
655 /*
656 Replace reserved words with better ones
657 Using uppercase because that's the only way Oracle can handle
658 quoted tablenames
659 */
660 switch( $name ) {
661 case 'user':
662 $name = 'MWUSER';
663 break;
664 case 'text':
665 $name = 'PAGECONTENT';
666 break;
667 }
668
669 return parent::tableName( strtoupper( $name ), $format );
670 }
671
672 function tableNameInternal( $name ) {
673 $name = $this->tableName( $name );
674 return preg_replace( '/.*\.(.*)/', '$1', $name);
675 }
676 /**
677 * Return the next in a sequence, save the value for retrieval via insertId()
678 * @return null
679 */
680 function nextSequenceValue( $seqName ) {
681 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
682 $row = $this->fetchRow( $res );
683 $this->mInsertId = $row[0];
684 return $this->mInsertId;
685 }
686
687 /**
688 * Return sequence_name if table has a sequence
689 * @return bool
690 */
691 private function getSequenceData( $table ) {
692 if ( $this->sequenceData == null ) {
693 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
694 lower(atc.table_name),
695 lower(atc.column_name)
696 FROM all_sequences asq, all_tab_columns atc
697 WHERE decode(atc.table_name, '{$this->mTablePrefix}MWUSER', '{$this->mTablePrefix}USER', atc.table_name) || '_' ||
698 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
699 AND asq.sequence_owner = upper('{$this->mDBname}')
700 AND atc.owner = upper('{$this->mDBname}')" );
701
702 while ( ( $row = $result->fetchRow() ) !== false ) {
703 $this->sequenceData[$row[1]] = array(
704 'sequence' => $row[0],
705 'column' => $row[2]
706 );
707 }
708 }
709 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
710 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
711 }
712
713 # Returns the size of a text field, or -1 for "unlimited"
714 function textFieldSize( $table, $field ) {
715 $fieldInfoData = $this->fieldInfo( $table, $field );
716 return $fieldInfoData->maxLength();
717 }
718
719 function limitResult( $sql, $limit, $offset = false ) {
720 if ( $offset === false ) {
721 $offset = 0;
722 }
723 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
724 }
725
726 function encodeBlob( $b ) {
727 return new Blob( $b );
728 }
729
730 function decodeBlob( $b ) {
731 if ( $b instanceof Blob ) {
732 $b = $b->fetch();
733 }
734 return $b;
735 }
736
737 function unionQueries( $sqls, $all ) {
738 $glue = ' UNION ALL ';
739 return 'SELECT * ' . ( $all ? '':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
740 }
741
742 function wasDeadlock() {
743 return $this->lastErrno() == 'OCI-00060';
744 }
745
746 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
747 $temporary = $temporary ? 'TRUE' : 'FALSE';
748
749 $newName = strtoupper( $newName );
750 $oldName = strtoupper( $oldName );
751
752 $tabName = substr( $newName, strlen( $this->mTablePrefix ) );
753 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
754 $newPrefix = strtoupper( $this->mTablePrefix );
755
756 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', '$oldPrefix', '$newPrefix', $temporary ); END;" );
757 }
758
759 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
760 $listWhere = '';
761 if (!empty($prefix)) {
762 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
763 }
764
765 $owner = strtoupper( $this->mDBname );
766 $result = $this->doQuery( "SELECT table_name FROM all_tables WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
767
768 // dirty code ... i know
769 $endArray = array();
770 $endArray[] = strtoupper($prefix.'MWUSER');
771 $endArray[] = strtoupper($prefix.'PAGE');
772 $endArray[] = strtoupper($prefix.'IMAGE');
773 $fixedOrderTabs = $endArray;
774 while (($row = $result->fetchRow()) !== false) {
775 if (!in_array($row['table_name'], $fixedOrderTabs))
776 $endArray[] = $row['table_name'];
777 }
778
779 return $endArray;
780 }
781
782 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
783 $tableName = $this->tableName($tableName);
784 if( !$this->tableExists( $tableName ) ) {
785 return false;
786 }
787
788 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
789 }
790
791 function timestamp( $ts = 0 ) {
792 return wfTimestamp( TS_ORACLE, $ts );
793 }
794
795 /**
796 * Return aggregated value function call
797 */
798 function aggregateValue ( $valuedata, $valuename = 'value' ) {
799 return $valuedata;
800 }
801
802 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
803 # Ignore errors during error handling to avoid infinite
804 # recursion
805 $ignore = $this->ignoreErrors( true );
806 ++$this->mErrorCount;
807
808 if ( $ignore || $tempIgnore ) {
809 wfDebug( "SQL ERROR (ignored): $error\n" );
810 $this->ignoreErrors( $ignore );
811 } else {
812 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
813 }
814 }
815
816 /**
817 * @return string wikitext of a link to the server software's web site
818 */
819 public static function getSoftwareLink() {
820 return '[http://www.oracle.com/ Oracle]';
821 }
822
823 /**
824 * @return string Version information from the database
825 */
826 function getServerVersion() {
827 //better version number, fallback on driver
828 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
829 if ( !( $row = $rset->fetchRow() ) ) {
830 return oci_server_version( $this->mConn );
831 }
832 return $row['version'];
833 }
834
835 /**
836 * Query whether a given index exists
837 * @return bool
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 * @return int
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,
974 $fname = 'DatabaseOracle::sourceStream', $inputCallback = false ) {
975 $cmd = '';
976 $done = false;
977 $dollarquote = false;
978
979 $replacements = array();
980
981 while ( ! feof( $fp ) ) {
982 if ( $lineCallback ) {
983 call_user_func( $lineCallback );
984 }
985 $line = trim( fgets( $fp, 1024 ) );
986 $sl = strlen( $line ) - 1;
987
988 if ( $sl < 0 ) {
989 continue;
990 }
991 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
992 continue;
993 }
994
995 // Allow dollar quoting for function declarations
996 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
997 if ( $dollarquote ) {
998 $dollarquote = false;
999 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1000 $done = true;
1001 } else {
1002 $dollarquote = true;
1003 }
1004 } elseif ( !$dollarquote ) {
1005 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1006 $done = true;
1007 $line = substr( $line, 0, $sl );
1008 }
1009 }
1010
1011 if ( $cmd != '' ) {
1012 $cmd .= ' ';
1013 }
1014 $cmd .= "$line\n";
1015
1016 if ( $done ) {
1017 $cmd = str_replace( ';;', ";", $cmd );
1018 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1019 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1020 $replacements[$defines[2]] = $defines[1];
1021 }
1022 } else {
1023 foreach ( $replacements as $mwVar => $scVar ) {
1024 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1025 }
1026
1027 $cmd = $this->replaceVars( $cmd );
1028 if ( $inputCallback ) {
1029 call_user_func( $inputCallback, $cmd );
1030 }
1031 $res = $this->doQuery( $cmd );
1032 if ( $resultCallback ) {
1033 call_user_func( $resultCallback, $res, $this );
1034 }
1035
1036 if ( false === $res ) {
1037 $err = $this->lastError();
1038 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1039 }
1040 }
1041
1042 $cmd = '';
1043 $done = false;
1044 }
1045 }
1046 return true;
1047 }
1048
1049 function selectDB( $db ) {
1050 $this->mDBname = $db;
1051 if ( $db == null || $db == $this->mUser ) {
1052 return true;
1053 }
1054 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1055 $stmt = oci_parse( $this->mConn, $sql );
1056 wfSuppressWarnings();
1057 $success = oci_execute( $stmt );
1058 wfRestoreWarnings();
1059 if ( !$success ) {
1060 $e = oci_error( $stmt );
1061 if ( $e['code'] != '1435' ) {
1062 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1063 }
1064 return false;
1065 }
1066 return true;
1067 }
1068
1069 function strencode( $s ) {
1070 return str_replace( "'", "''", $s );
1071 }
1072
1073 function addQuotes( $s ) {
1074 global $wgContLang;
1075 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1076 $s = $wgContLang->checkTitleEncoding( $s );
1077 }
1078 return "'" . $this->strencode( $s ) . "'";
1079 }
1080
1081 public function addIdentifierQuotes( $s ) {
1082 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1083 $s = '/*Q*/' . $s;
1084 }
1085 return $s;
1086 }
1087
1088 public function removeIdentifierQuotes( $s ) {
1089 return strpos($s, '/*Q*/') === FALSE ? $s : substr($s, 5);
1090 }
1091
1092 public function isQuotedIdentifier( $s ) {
1093 return strpos($s, '/*Q*/') !== FALSE;
1094 }
1095
1096 private function wrapFieldForWhere( $table, &$col, &$val ) {
1097 global $wgContLang;
1098
1099 $col_info = $this->fieldInfoMulti( $table, $col );
1100 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1101 if ( $col_type == 'CLOB' ) {
1102 $col = 'TO_CHAR(' . $col . ')';
1103 $val = $wgContLang->checkTitleEncoding( $val );
1104 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1105 $val = $wgContLang->checkTitleEncoding( $val );
1106 }
1107 }
1108
1109 private function wrapConditionsForWhere ( $table, $conds, $parentCol = null ) {
1110 $conds2 = array();
1111 foreach ( $conds as $col => $val ) {
1112 if ( is_array( $val ) ) {
1113 $conds2[$col] = $this->wrapConditionsForWhere ( $table, $val, $col );
1114 } else {
1115 if ( is_numeric( $col ) && $parentCol != null ) {
1116 $this->wrapFieldForWhere ( $table, $parentCol, $val );
1117 } else {
1118 $this->wrapFieldForWhere ( $table, $col, $val );
1119 }
1120 $conds2[$col] = $val;
1121 }
1122 }
1123 return $conds2;
1124 }
1125
1126 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1127 if ( is_array($conds) ) {
1128 $conds = $this->wrapConditionsForWhere( $table, $conds );
1129 }
1130 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1131 }
1132
1133 /**
1134 * Returns an optional USE INDEX clause to go after the table, and a
1135 * string to go at the end of the query
1136 *
1137 * @private
1138 *
1139 * @param $options Array: an associative array of options to be turned into
1140 * an SQL query, valid keys are listed in the function.
1141 * @return array
1142 */
1143 function makeSelectOptions( $options ) {
1144 $preLimitTail = $postLimitTail = '';
1145 $startOpts = '';
1146
1147 $noKeyOptions = array();
1148 foreach ( $options as $key => $option ) {
1149 if ( is_numeric( $key ) ) {
1150 $noKeyOptions[$option] = true;
1151 }
1152 }
1153
1154 if ( isset( $options['GROUP BY'] ) ) {
1155 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1156 }
1157 if ( isset( $options['ORDER BY'] ) ) {
1158 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1159 }
1160
1161 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1162 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1163 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1164 $startOpts .= 'DISTINCT';
1165 }
1166
1167 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1168 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1169 } else {
1170 $useIndex = '';
1171 }
1172
1173 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1174 }
1175
1176 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1177 if ( is_array($conds) ) {
1178 $conds = $this->wrapConditionsForWhere( $table, $conds );
1179 }
1180 // a hack for deleting pages, users and images (which have non-nullable FKs)
1181 // all deletions on these tables have transactions so final failure rollbacks these updates
1182 $table = $this->tableName( $table );
1183 if ( $table == $this->tableName( 'user' ) ) {
1184 $this->update( 'archive', array( 'ar_user' => 0 ), array( 'ar_user' => $conds['user_id'] ), $fname );
1185 $this->update( 'ipblocks', array( 'ipb_user' => 0 ), array( 'ipb_user' => $conds['user_id'] ), $fname );
1186 $this->update( 'image', array( 'img_user' => 0 ), array( 'img_user' => $conds['user_id'] ), $fname );
1187 $this->update( 'oldimage', array( 'oi_user' => 0 ), array( 'oi_user' => $conds['user_id'] ), $fname );
1188 $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ), array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
1189 $this->update( 'filearchive', array( 'fa_user' => 0 ), array( 'fa_user' => $conds['user_id'] ), $fname );
1190 $this->update( 'uploadstash', array( 'us_user' => 0 ), array( 'us_user' => $conds['user_id'] ), $fname );
1191 $this->update( 'recentchanges', array( 'rc_user' => 0 ), array( 'rc_user' => $conds['user_id'] ), $fname );
1192 $this->update( 'logging', array( 'log_user' => 0 ), array( 'log_user' => $conds['user_id'] ), $fname );
1193 } elseif ( $table == $this->tableName( 'image' ) ) {
1194 $this->update( 'oldimage', array( 'oi_name' => 0 ), array( 'oi_name' => $conds['img_name'] ), $fname );
1195 }
1196 return parent::delete( $table, $conds, $fname );
1197 }
1198
1199 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1200 global $wgContLang;
1201
1202 $table = $this->tableName( $table );
1203 $opts = $this->makeUpdateOptions( $options );
1204 $sql = "UPDATE $opts $table SET ";
1205
1206 $first = true;
1207 foreach ( $values as $col => &$val ) {
1208 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1209
1210 if ( !$first ) {
1211 $sqlSet = ', ' . $sqlSet;
1212 } else {
1213 $first = false;
1214 }
1215 $sql .= $sqlSet;
1216 }
1217
1218 if ( $conds !== array() && $conds !== '*' ) {
1219 $conds = $this->wrapConditionsForWhere( $table, $conds );
1220 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1221 }
1222
1223 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1224 $e = oci_error( $this->mConn );
1225 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1226 return false;
1227 }
1228 foreach ( $values as $col => &$val ) {
1229 $col_info = $this->fieldInfoMulti( $table, $col );
1230 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1231
1232 if ( $val === null ) {
1233 // do nothing ... null was inserted in statement creation
1234 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1235 if ( is_object( $val ) ) {
1236 $val = $val->getData();
1237 }
1238
1239 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1240 $val = '31-12-2030 12:00:00.000000';
1241 }
1242
1243 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1244 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1245 $e = oci_error( $stmt );
1246 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1247 return false;
1248 }
1249 } else {
1250 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1251 $e = oci_error( $stmt );
1252 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1253 }
1254
1255 if ( $col_type == 'BLOB' ) {
1256 $lob[$col]->writeTemporary( $val );
1257 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1258 } else {
1259 $lob[$col]->writeTemporary( $val );
1260 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1261 }
1262 }
1263 }
1264
1265 wfSuppressWarnings();
1266
1267 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1268 $e = oci_error( $stmt );
1269 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1270 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1271 return false;
1272 } else {
1273 $this->mAffectedRows = oci_num_rows( $stmt );
1274 }
1275 } else {
1276 $this->mAffectedRows = oci_num_rows( $stmt );
1277 }
1278
1279 wfRestoreWarnings();
1280
1281 if ( isset( $lob ) ) {
1282 foreach ( $lob as $lob_v ) {
1283 $lob_v->free();
1284 }
1285 }
1286
1287 if ( !$this->mTrxLevel ) {
1288 oci_commit( $this->mConn );
1289 }
1290
1291 oci_free_statement( $stmt );
1292 }
1293
1294 function bitNot( $field ) {
1295 // expecting bit-fields smaller than 4bytes
1296 return 'BITNOT(' . $field . ')';
1297 }
1298
1299 function bitAnd( $fieldLeft, $fieldRight ) {
1300 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1301 }
1302
1303 function bitOr( $fieldLeft, $fieldRight ) {
1304 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1305 }
1306
1307 function setFakeMaster( $enabled = true ) {
1308 }
1309
1310 function getDBname() {
1311 return $this->mDBname;
1312 }
1313
1314 function getServer() {
1315 return $this->mServer;
1316 }
1317
1318 public function getSearchEngine() {
1319 return 'SearchOracle';
1320 }
1321
1322 public function getInfinity() {
1323 return '31-12-2030 12:00:00.000000';
1324 }
1325
1326 } // end DatabaseOracle class