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