Merge "Detect user rights conflicts"
[lhc/web/wiklou.git] / includes / db / DatabaseOracle.php
1 <?php
2 /**
3 * This is the Oracle database abstraction layer.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 /**
25 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
26 * other things. We use a wrapper class to handle that and other
27 * Oracle-specific bits, like converting column names back to lowercase.
28 * @ingroup Database
29 */
30 class ORAResult {
31 private $rows;
32 private $cursor;
33 private $nrows;
34
35 private $columns = array();
36
37 private function array_unique_md( $array_in ) {
38 $array_out = array();
39 $array_hashes = array();
40
41 foreach ( $array_in as $item ) {
42 $hash = md5( serialize( $item ) );
43 if ( !isset( $array_hashes[$hash] ) ) {
44 $array_hashes[$hash] = $hash;
45 $array_out[] = $item;
46 }
47 }
48
49 return $array_out;
50 }
51
52 /**
53 * @param $db DatabaseBase
54 * @param $stmt
55 * @param bool $unique
56 */
57 function __construct( &$db, $stmt, $unique = false ) {
58 $this->db =& $db;
59
60 if ( ( $this->nrows = oci_fetch_all( $stmt, $this->rows, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM ) ) === false ) {
61 $e = oci_error( $stmt );
62 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__ );
63 $this->free();
64 return;
65 }
66
67 if ( $unique ) {
68 $this->rows = $this->array_unique_md( $this->rows );
69 $this->nrows = count( $this->rows );
70 }
71
72 if ( $this->nrows > 0 ) {
73 foreach ( $this->rows[0] as $k => $v ) {
74 $this->columns[$k] = strtolower( oci_field_name( $stmt, $k + 1 ) );
75 }
76 }
77
78 $this->cursor = 0;
79 oci_free_statement( $stmt );
80 }
81
82 public function free() {
83 unset( $this->db );
84 }
85
86 public function seek( $row ) {
87 $this->cursor = min( $row, $this->nrows );
88 }
89
90 public function numRows() {
91 return $this->nrows;
92 }
93
94 public function numFields() {
95 return count( $this->columns );
96 }
97
98 public function fetchObject() {
99 if ( $this->cursor >= $this->nrows ) {
100 return false;
101 }
102 $row = $this->rows[$this->cursor++];
103 $ret = new stdClass();
104 foreach ( $row as $k => $v ) {
105 $lc = $this->columns[$k];
106 $ret->$lc = $v;
107 }
108
109 return $ret;
110 }
111
112 public function fetchRow() {
113 if ( $this->cursor >= $this->nrows ) {
114 return false;
115 }
116
117 $row = $this->rows[$this->cursor++];
118 $ret = array();
119 foreach ( $row as $k => $v ) {
120 $lc = $this->columns[$k];
121 $ret[$lc] = $v;
122 $ret[$k] = $v;
123 }
124 return $ret;
125 }
126 }
127
128 /**
129 * Utility class.
130 * @ingroup Database
131 */
132 class ORAField implements Field {
133 private $name, $tablename, $default, $max_length, $nullable,
134 $is_pk, $is_unique, $is_multiple, $is_key, $type;
135
136 function __construct( $info ) {
137 $this->name = $info['column_name'];
138 $this->tablename = $info['table_name'];
139 $this->default = $info['data_default'];
140 $this->max_length = $info['data_length'];
141 $this->nullable = $info['not_null'];
142 $this->is_pk = isset( $info['prim'] ) && $info['prim'] == 1 ? 1 : 0;
143 $this->is_unique = isset( $info['uniq'] ) && $info['uniq'] == 1 ? 1 : 0;
144 $this->is_multiple = isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ? 1 : 0;
145 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
146 $this->type = $info['data_type'];
147 }
148
149 function name() {
150 return $this->name;
151 }
152
153 function tableName() {
154 return $this->tablename;
155 }
156
157 function defaultValue() {
158 return $this->default;
159 }
160
161 function maxLength() {
162 return $this->max_length;
163 }
164
165 function isNullable() {
166 return $this->nullable;
167 }
168
169 function isKey() {
170 return $this->is_key;
171 }
172
173 function isMultipleKey() {
174 return $this->is_multiple;
175 }
176
177 function type() {
178 return $this->type;
179 }
180 }
181
182 /**
183 * @ingroup Database
184 */
185 class DatabaseOracle extends DatabaseBase {
186 var $mInsertId = null;
187 var $mLastResult = null;
188 var $lastResult = null;
189 var $cursor = 0;
190 var $mAffectedRows;
191
192 var $ignore_DUP_VAL_ON_INDEX = false;
193 var $sequenceData = null;
194
195 var $defaultCharset = 'AL32UTF8';
196
197 var $mFieldInfoCache = array();
198
199 function __construct( $server = false, $user = false, $password = false, $dbName = false,
200 $flags = 0, $tablePrefix = 'get from global' )
201 {
202 global $wgDBprefix;
203 $tablePrefix = $tablePrefix == 'get from global' ? strtoupper( $wgDBprefix ) : strtoupper( $tablePrefix );
204 parent::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
205 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
206 }
207
208 function __destruct() {
209 if ( $this->mOpened ) {
210 wfSuppressWarnings();
211 $this->close();
212 wfRestoreWarnings();
213 }
214 }
215
216 function getType() {
217 return 'oracle';
218 }
219
220 function cascadingDeletes() {
221 return true;
222 }
223 function cleanupTriggers() {
224 return true;
225 }
226 function strictIPs() {
227 return true;
228 }
229 function realTimestamps() {
230 return true;
231 }
232 function implicitGroupby() {
233 return false;
234 }
235 function implicitOrderby() {
236 return false;
237 }
238 function searchableIPs() {
239 return true;
240 }
241
242 /**
243 * Usually aborts on failure
244 * @param string $server
245 * @param string $user
246 * @param string $password
247 * @param string $dbName
248 * @throws DBConnectionError
249 * @return DatabaseBase|null
250 */
251 function open( $server, $user, $password, $dbName ) {
252 if ( !function_exists( 'oci_connect' ) ) {
253 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" );
254 }
255
256 $this->close();
257 $this->mUser = $user;
258 $this->mPassword = $password;
259 // changed internal variables functions
260 // mServer now holds the TNS endpoint
261 // mDBname is schema name if different from username
262 if ( !$server ) {
263 // backward compatibillity (server used to be null and TNS was supplied in dbname)
264 $this->mServer = $dbName;
265 $this->mDBname = $user;
266 } else {
267 $this->mServer = $server;
268 if ( !$dbName ) {
269 $this->mDBname = $user;
270 } else {
271 $this->mDBname = $dbName;
272 }
273 }
274
275 if ( !strlen( $user ) ) { # e.g. the class is being loaded
276 return;
277 }
278
279 $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
280 wfSuppressWarnings();
281 if ( $this->mFlags & DBO_DEFAULT ) {
282 $this->mConn = oci_new_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
283 } else {
284 $this->mConn = oci_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
285 }
286 wfRestoreWarnings();
287
288 if ( $this->mUser != $this->mDBname ) {
289 //change current schema in session
290 $this->selectDB( $this->mDBname );
291 }
292
293 if ( !$this->mConn ) {
294 throw new DBConnectionError( $this, $this->lastError() );
295 }
296
297 $this->mOpened = true;
298
299 # removed putenv calls because they interfere with the system globaly
300 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
301 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
302 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
303 return $this->mConn;
304 }
305
306 /**
307 * Closes a database connection, if it is open
308 * Returns success, true if already closed
309 * @return bool
310 */
311 protected function closeConnection() {
312 return oci_close( $this->mConn );
313 }
314
315 function execFlags() {
316 return $this->mTrxLevel ? OCI_NO_AUTO_COMMIT : OCI_COMMIT_ON_SUCCESS;
317 }
318
319 protected function doQuery( $sql ) {
320 wfDebug( "SQL: [$sql]\n" );
321 if ( !StringUtils::isUtf8( $sql ) ) {
322 throw new MWException( "SQL encoding is invalid\n$sql" );
323 }
324
325 // handle some oracle specifics
326 // remove AS column/table/subquery namings
327 if ( !$this->getFlag( DBO_DDLMODE ) ) {
328 $sql = preg_replace( '/ as /i', ' ', $sql );
329 }
330
331 // Oracle has issues with UNION clause if the statement includes LOB fields
332 // So we do a UNION ALL and then filter the results array with array_unique
333 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
334 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
335 // you have to select data from plan table after explain
336 $explain_id = date( 'dmYHis' );
337
338 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
339
340 wfSuppressWarnings();
341
342 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
343 $e = oci_error( $this->mConn );
344 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
345 return false;
346 }
347
348 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
349 $e = oci_error( $stmt );
350 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
351 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
352 return false;
353 }
354 }
355
356 wfRestoreWarnings();
357
358 if ( $explain_count > 0 ) {
359 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
360 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
361 return new ORAResult( $this, $stmt, $union_unique );
362 } else {
363 $this->mAffectedRows = oci_num_rows( $stmt );
364 return true;
365 }
366 }
367
368 function queryIgnore( $sql, $fname = '' ) {
369 return $this->query( $sql, $fname, true );
370 }
371
372 function freeResult( $res ) {
373 if ( $res instanceof ResultWrapper ) {
374 $res = $res->result;
375 }
376
377 $res->free();
378 }
379
380 function fetchObject( $res ) {
381 if ( $res instanceof ResultWrapper ) {
382 $res = $res->result;
383 }
384
385 return $res->fetchObject();
386 }
387
388 function fetchRow( $res ) {
389 if ( $res instanceof ResultWrapper ) {
390 $res = $res->result;
391 }
392
393 return $res->fetchRow();
394 }
395
396 function numRows( $res ) {
397 if ( $res instanceof ResultWrapper ) {
398 $res = $res->result;
399 }
400
401 return $res->numRows();
402 }
403
404 function numFields( $res ) {
405 if ( $res instanceof ResultWrapper ) {
406 $res = $res->result;
407 }
408
409 return $res->numFields();
410 }
411
412 function fieldName( $stmt, $n ) {
413 return oci_field_name( $stmt, $n );
414 }
415
416 /**
417 * This must be called after nextSequenceVal
418 * @return null
419 */
420 function insertId() {
421 return $this->mInsertId;
422 }
423
424 function dataSeek( $res, $row ) {
425 if ( $res instanceof ORAResult ) {
426 $res->seek( $row );
427 } else {
428 $res->result->seek( $row );
429 }
430 }
431
432 function lastError() {
433 if ( $this->mConn === false ) {
434 $e = oci_error();
435 } else {
436 $e = oci_error( $this->mConn );
437 }
438 return $e['message'];
439 }
440
441 function lastErrno() {
442 if ( $this->mConn === false ) {
443 $e = oci_error();
444 } else {
445 $e = oci_error( $this->mConn );
446 }
447 return $e['code'];
448 }
449
450 function affectedRows() {
451 return $this->mAffectedRows;
452 }
453
454 /**
455 * Returns information about an index
456 * If errors are explicitly ignored, returns NULL on failure
457 * @return bool
458 */
459 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
460 return false;
461 }
462
463 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
464 return false;
465 }
466
467 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
468 if ( !count( $a ) ) {
469 return true;
470 }
471
472 if ( !is_array( $options ) ) {
473 $options = array( $options );
474 }
475
476 if ( in_array( 'IGNORE', $options ) ) {
477 $this->ignore_DUP_VAL_ON_INDEX = true;
478 }
479
480 if ( !is_array( reset( $a ) ) ) {
481 $a = array( $a );
482 }
483
484 foreach ( $a as &$row ) {
485 $this->insertOneRow( $table, $row, $fname );
486 }
487 $retVal = true;
488
489 if ( in_array( 'IGNORE', $options ) ) {
490 $this->ignore_DUP_VAL_ON_INDEX = false;
491 }
492
493 return $retVal;
494 }
495
496 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
497 $col_info = $this->fieldInfoMulti( $table, $col );
498 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
499
500 $bind = '';
501 if ( is_numeric( $col ) ) {
502 $bind = $val;
503 $val = null;
504 return $bind;
505 } elseif ( $includeCol ) {
506 $bind = "$col = ";
507 }
508
509 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
510 $val = null;
511 }
512
513 if ( $val === 'NULL' ) {
514 $val = null;
515 }
516
517 if ( $val === null ) {
518 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
519 $bind .= 'DEFAULT';
520 } else {
521 $bind .= 'NULL';
522 }
523 } else {
524 $bind .= ':' . $col;
525 }
526
527 return $bind;
528 }
529
530 private function insertOneRow( $table, $row, $fname ) {
531 global $wgContLang;
532
533 $table = $this->tableName( $table );
534 // "INSERT INTO tables (a, b, c)"
535 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
536 $sql .= " VALUES (";
537
538 // for each value, append ":key"
539 $first = true;
540 foreach ( $row as $col => &$val ) {
541 if ( !$first ) {
542 $sql .= ', ';
543 } else {
544 $first = false;
545 }
546
547 $sql .= $this->fieldBindStatement( $table, $col, $val );
548 }
549 $sql .= ')';
550
551 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
552 $e = oci_error( $this->mConn );
553 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
554 return false;
555 }
556 foreach ( $row as $col => &$val ) {
557 $col_info = $this->fieldInfoMulti( $table, $col );
558 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
559
560 if ( $val === null ) {
561 // do nothing ... null was inserted in statement creation
562 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
563 if ( is_object( $val ) ) {
564 $val = $val->fetch();
565 }
566
567 // backward compatibility
568 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
569 $val = $this->getInfinity();
570 }
571
572 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
573 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR ) === false ) {
574 $e = oci_error( $stmt );
575 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
576 return false;
577 }
578 } else {
579 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
580 $e = oci_error( $stmt );
581 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
582 }
583
584 if ( is_object( $val ) ) {
585 $val = $val->fetch();
586 }
587
588 if ( $col_type == 'BLOB' ) {
589 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
590 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB );
591 } else {
592 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
593 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
594 }
595 }
596 }
597
598 wfSuppressWarnings();
599
600 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
601 $e = oci_error( $stmt );
602 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
603 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
604 return false;
605 } else {
606 $this->mAffectedRows = oci_num_rows( $stmt );
607 }
608 } else {
609 $this->mAffectedRows = oci_num_rows( $stmt );
610 }
611
612 wfRestoreWarnings();
613
614 if ( isset( $lob ) ) {
615 foreach ( $lob as $lob_v ) {
616 $lob_v->free();
617 }
618 }
619
620 if ( !$this->mTrxLevel ) {
621 oci_commit( $this->mConn );
622 }
623
624 oci_free_statement( $stmt );
625 }
626
627 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
628 $insertOptions = array(), $selectOptions = array() )
629 {
630 $destTable = $this->tableName( $destTable );
631 if ( !is_array( $selectOptions ) ) {
632 $selectOptions = array( $selectOptions );
633 }
634 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
635 if ( is_array( $srcTable ) ) {
636 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
637 } else {
638 $srcTable = $this->tableName( $srcTable );
639 }
640
641 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
642 !isset( $varMap[$sequenceData['column']] ) )
643 {
644 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
645 }
646
647 // count-alias subselect fields to avoid abigious definition errors
648 $i = 0;
649 foreach ( $varMap as &$val ) {
650 $val = $val . ' field' . ( $i++ );
651 }
652
653 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
654 " SELECT $startOpts " . implode( ',', $varMap ) .
655 " FROM $srcTable $useIndex ";
656 if ( $conds != '*' ) {
657 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
658 }
659 $sql .= " $tailOpts";
660
661 if ( in_array( 'IGNORE', $insertOptions ) ) {
662 $this->ignore_DUP_VAL_ON_INDEX = true;
663 }
664
665 $retval = $this->query( $sql, $fname );
666
667 if ( in_array( 'IGNORE', $insertOptions ) ) {
668 $this->ignore_DUP_VAL_ON_INDEX = false;
669 }
670
671 return $retval;
672 }
673
674 function tableName( $name, $format = 'quoted' ) {
675 /*
676 Replace reserved words with better ones
677 Using uppercase because that's the only way Oracle can handle
678 quoted tablenames
679 */
680 switch ( $name ) {
681 case 'user':
682 $name = 'MWUSER';
683 break;
684 case 'text':
685 $name = 'PAGECONTENT';
686 break;
687 }
688
689 return parent::tableName( strtoupper( $name ), $format );
690 }
691
692 function tableNameInternal( $name ) {
693 $name = $this->tableName( $name );
694 return preg_replace( '/.*\.(.*)/', '$1', $name );
695 }
696 /**
697 * Return the next in a sequence, save the value for retrieval via insertId()
698 * @return null
699 */
700 function nextSequenceValue( $seqName ) {
701 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
702 $row = $this->fetchRow( $res );
703 $this->mInsertId = $row[0];
704 return $this->mInsertId;
705 }
706
707 /**
708 * Return sequence_name if table has a sequence
709 * @return bool
710 */
711 private function getSequenceData( $table ) {
712 if ( $this->sequenceData == null ) {
713 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
714 lower(atc.table_name),
715 lower(atc.column_name)
716 FROM all_sequences asq, all_tab_columns atc
717 WHERE decode(atc.table_name, '{$this->mTablePrefix}MWUSER', '{$this->mTablePrefix}USER', atc.table_name) || '_' ||
718 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
719 AND asq.sequence_owner = upper('{$this->mDBname}')
720 AND atc.owner = upper('{$this->mDBname}')" );
721
722 while ( ( $row = $result->fetchRow() ) !== false ) {
723 $this->sequenceData[$row[1]] = array(
724 'sequence' => $row[0],
725 'column' => $row[2]
726 );
727 }
728 }
729 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
730 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
731 }
732
733 # Returns the size of a text field, or -1 for "unlimited"
734 function textFieldSize( $table, $field ) {
735 $fieldInfoData = $this->fieldInfo( $table, $field );
736 return $fieldInfoData->maxLength();
737 }
738
739 function limitResult( $sql, $limit, $offset = false ) {
740 if ( $offset === false ) {
741 $offset = 0;
742 }
743 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
744 }
745
746 function encodeBlob( $b ) {
747 return new Blob( $b );
748 }
749
750 function decodeBlob( $b ) {
751 if ( $b instanceof Blob ) {
752 $b = $b->fetch();
753 }
754 return $b;
755 }
756
757 function unionQueries( $sqls, $all ) {
758 $glue = ' UNION ALL ';
759 return 'SELECT * ' . ( $all ? '' : '/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')';
760 }
761
762 function wasDeadlock() {
763 return $this->lastErrno() == 'OCI-00060';
764 }
765
766 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
767 $temporary = $temporary ? 'TRUE' : 'FALSE';
768
769 $newName = strtoupper( $newName );
770 $oldName = strtoupper( $oldName );
771
772 $tabName = substr( $newName, strlen( $this->mTablePrefix ) );
773 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
774 $newPrefix = strtoupper( $this->mTablePrefix );
775
776 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', '$oldPrefix', '$newPrefix', $temporary ); END;" );
777 }
778
779 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
780 $listWhere = '';
781 if ( !empty( $prefix ) ) {
782 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
783 }
784
785 $owner = strtoupper( $this->mDBname );
786 $result = $this->doQuery( "SELECT table_name FROM all_tables WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
787
788 // dirty code ... i know
789 $endArray = array();
790 $endArray[] = strtoupper( $prefix . 'MWUSER' );
791 $endArray[] = strtoupper( $prefix . 'PAGE' );
792 $endArray[] = strtoupper( $prefix . 'IMAGE' );
793 $fixedOrderTabs = $endArray;
794 while ( ( $row = $result->fetchRow() ) !== false ) {
795 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
796 $endArray[] = $row['table_name'];
797 }
798 }
799
800 return $endArray;
801 }
802
803 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
804 $tableName = $this->tableName( $tableName );
805 if ( !$this->tableExists( $tableName ) ) {
806 return false;
807 }
808
809 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
810 }
811
812 function timestamp( $ts = 0 ) {
813 return wfTimestamp( TS_ORACLE, $ts );
814 }
815
816 /**
817 * Return aggregated value function call
818 */
819 public function aggregateValue( $valuedata, $valuename = 'value' ) {
820 return $valuedata;
821 }
822
823 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
824 # Ignore errors during error handling to avoid infinite
825 # recursion
826 $ignore = $this->ignoreErrors( true );
827 ++$this->mErrorCount;
828
829 if ( $ignore || $tempIgnore ) {
830 wfDebug( "SQL ERROR (ignored): $error\n" );
831 $this->ignoreErrors( $ignore );
832 } else {
833 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
834 }
835 }
836
837 /**
838 * @return string wikitext of a link to the server software's web site
839 */
840 public static function getSoftwareLink() {
841 return '[http://www.oracle.com/ Oracle]';
842 }
843
844 /**
845 * @return string Version information from the database
846 */
847 function getServerVersion() {
848 //better version number, fallback on driver
849 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
850 if ( !( $row = $rset->fetchRow() ) ) {
851 return oci_server_version( $this->mConn );
852 }
853 return $row['version'];
854 }
855
856 /**
857 * Query whether a given index exists
858 * @return bool
859 */
860 function indexExists( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
861 $table = $this->tableName( $table );
862 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
863 $index = strtoupper( $index );
864 $owner = strtoupper( $this->mDBname );
865 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
866 $res = $this->doQuery( $SQL );
867 if ( $res ) {
868 $count = $res->numRows();
869 $res->free();
870 } else {
871 $count = 0;
872 }
873 return $count != 0;
874 }
875
876 /**
877 * Query whether a given table exists (in the given schema, or the default mw one if not given)
878 * @return int
879 */
880 function tableExists( $table, $fname = __METHOD__ ) {
881 $table = $this->tableName( $table );
882 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
883 $owner = $this->addQuotes( strtoupper( $this->mDBname ) );
884 $SQL = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
885 $res = $this->doQuery( $SQL );
886 if ( $res ) {
887 $count = $res->numRows();
888 $res->free();
889 } else {
890 $count = 0;
891 }
892 return $count;
893 }
894
895 /**
896 * Function translates mysql_fetch_field() functionality on ORACLE.
897 * Caching is present for reducing query time.
898 * For internal calls. Use fieldInfo for normal usage.
899 * Returns false if the field doesn't exist
900 *
901 * @param $table Array
902 * @param $field String
903 * @return ORAField|ORAResult
904 */
905 private function fieldInfoMulti( $table, $field ) {
906 $field = strtoupper( $field );
907 if ( is_array( $table ) ) {
908 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
909 $tableWhere = 'IN (';
910 foreach ( $table as &$singleTable ) {
911 $singleTable = $this->removeIdentifierQuotes( $singleTable );
912 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
913 return $this->mFieldInfoCache["$singleTable.$field"];
914 }
915 $tableWhere .= '\'' . $singleTable . '\',';
916 }
917 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
918 } else {
919 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
920 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
921 return $this->mFieldInfoCache["$table.$field"];
922 }
923 $tableWhere = '= \'' . $table . '\'';
924 }
925
926 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name ' . $tableWhere . ' and column_name = \'' . $field . '\'' );
927 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
928 $e = oci_error( $fieldInfoStmt );
929 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
930 return false;
931 }
932 $res = new ORAResult( $this, $fieldInfoStmt );
933 if ( $res->numRows() == 0 ) {
934 if ( is_array( $table ) ) {
935 foreach ( $table as &$singleTable ) {
936 $this->mFieldInfoCache["$singleTable.$field"] = false;
937 }
938 } else {
939 $this->mFieldInfoCache["$table.$field"] = false;
940 }
941 $fieldInfoTemp = null;
942 } else {
943 $fieldInfoTemp = new ORAField( $res->fetchRow() );
944 $table = $fieldInfoTemp->tableName();
945 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
946 }
947 $res->free();
948 return $fieldInfoTemp;
949 }
950
951 /**
952 * @throws DBUnexpectedError
953 * @param $table
954 * @param $field
955 * @return ORAField
956 */
957 function fieldInfo( $table, $field ) {
958 if ( is_array( $table ) ) {
959 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
960 }
961 return $this->fieldInfoMulti( $table, $field );
962 }
963
964 protected function doBegin( $fname = 'DatabaseOracle::begin' ) {
965 $this->mTrxLevel = 1;
966 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
967 }
968
969 protected function doCommit( $fname = 'DatabaseOracle::commit' ) {
970 if ( $this->mTrxLevel ) {
971 $ret = oci_commit( $this->mConn );
972 if ( !$ret ) {
973 throw new DBUnexpectedError( $this, $this->lastError() );
974 }
975 $this->mTrxLevel = 0;
976 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
977 }
978 }
979
980 protected function doRollback( $fname = 'DatabaseOracle::rollback' ) {
981 if ( $this->mTrxLevel ) {
982 oci_rollback( $this->mConn );
983 $this->mTrxLevel = 0;
984 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
985 }
986 }
987
988 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
989 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
990 $fname = 'DatabaseOracle::sourceStream', $inputCallback = false ) {
991 $cmd = '';
992 $done = false;
993 $dollarquote = false;
994
995 $replacements = array();
996
997 while ( ! feof( $fp ) ) {
998 if ( $lineCallback ) {
999 call_user_func( $lineCallback );
1000 }
1001 $line = trim( fgets( $fp, 1024 ) );
1002 $sl = strlen( $line ) - 1;
1003
1004 if ( $sl < 0 ) {
1005 continue;
1006 }
1007 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1008 continue;
1009 }
1010
1011 // Allow dollar quoting for function declarations
1012 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1013 if ( $dollarquote ) {
1014 $dollarquote = false;
1015 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1016 $done = true;
1017 } else {
1018 $dollarquote = true;
1019 }
1020 } elseif ( !$dollarquote ) {
1021 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1022 $done = true;
1023 $line = substr( $line, 0, $sl );
1024 }
1025 }
1026
1027 if ( $cmd != '' ) {
1028 $cmd .= ' ';
1029 }
1030 $cmd .= "$line\n";
1031
1032 if ( $done ) {
1033 $cmd = str_replace( ';;', ";", $cmd );
1034 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1035 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1036 $replacements[$defines[2]] = $defines[1];
1037 }
1038 } else {
1039 foreach ( $replacements as $mwVar => $scVar ) {
1040 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1041 }
1042
1043 $cmd = $this->replaceVars( $cmd );
1044 if ( $inputCallback ) {
1045 call_user_func( $inputCallback, $cmd );
1046 }
1047 $res = $this->doQuery( $cmd );
1048 if ( $resultCallback ) {
1049 call_user_func( $resultCallback, $res, $this );
1050 }
1051
1052 if ( false === $res ) {
1053 $err = $this->lastError();
1054 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1055 }
1056 }
1057
1058 $cmd = '';
1059 $done = false;
1060 }
1061 }
1062 return true;
1063 }
1064
1065 function selectDB( $db ) {
1066 $this->mDBname = $db;
1067 if ( $db == null || $db == $this->mUser ) {
1068 return true;
1069 }
1070 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1071 $stmt = oci_parse( $this->mConn, $sql );
1072 wfSuppressWarnings();
1073 $success = oci_execute( $stmt );
1074 wfRestoreWarnings();
1075 if ( !$success ) {
1076 $e = oci_error( $stmt );
1077 if ( $e['code'] != '1435' ) {
1078 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1079 }
1080 return false;
1081 }
1082 return true;
1083 }
1084
1085 function strencode( $s ) {
1086 return str_replace( "'", "''", $s );
1087 }
1088
1089 function addQuotes( $s ) {
1090 global $wgContLang;
1091 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1092 $s = $wgContLang->checkTitleEncoding( $s );
1093 }
1094 return "'" . $this->strencode( $s ) . "'";
1095 }
1096
1097 public function addIdentifierQuotes( $s ) {
1098 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1099 $s = '/*Q*/' . $s;
1100 }
1101 return $s;
1102 }
1103
1104 public function removeIdentifierQuotes( $s ) {
1105 return strpos( $s, '/*Q*/' ) === false ? $s : substr( $s, 5 );
1106 }
1107
1108 public function isQuotedIdentifier( $s ) {
1109 return strpos( $s, '/*Q*/' ) !== false;
1110 }
1111
1112 private function wrapFieldForWhere( $table, &$col, &$val ) {
1113 global $wgContLang;
1114
1115 $col_info = $this->fieldInfoMulti( $table, $col );
1116 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1117 if ( $col_type == 'CLOB' ) {
1118 $col = 'TO_CHAR(' . $col . ')';
1119 $val = $wgContLang->checkTitleEncoding( $val );
1120 } elseif ( $col_type == 'VARCHAR2' ) {
1121 $val = $wgContLang->checkTitleEncoding( $val );
1122 }
1123 }
1124
1125 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1126 $conds2 = array();
1127 foreach ( $conds as $col => $val ) {
1128 if ( is_array( $val ) ) {
1129 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1130 } else {
1131 if ( is_numeric( $col ) && $parentCol != null ) {
1132 $this->wrapFieldForWhere( $table, $parentCol, $val );
1133 } else {
1134 $this->wrapFieldForWhere( $table, $col, $val );
1135 }
1136 $conds2[$col] = $val;
1137 }
1138 }
1139 return $conds2;
1140 }
1141
1142 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1143 if ( is_array( $conds ) ) {
1144 $conds = $this->wrapConditionsForWhere( $table, $conds );
1145 }
1146 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1147 }
1148
1149 /**
1150 * Returns an optional USE INDEX clause to go after the table, and a
1151 * string to go at the end of the query
1152 *
1153 * @private
1154 *
1155 * @param array $options an associative array of options to be turned into
1156 * an SQL query, valid keys are listed in the function.
1157 * @return array
1158 */
1159 function makeSelectOptions( $options ) {
1160 $preLimitTail = $postLimitTail = '';
1161 $startOpts = '';
1162
1163 $noKeyOptions = array();
1164 foreach ( $options as $key => $option ) {
1165 if ( is_numeric( $key ) ) {
1166 $noKeyOptions[$option] = true;
1167 }
1168 }
1169
1170 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1171
1172 $preLimitTail .= $this->makeOrderBy( $options );
1173
1174 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1175 $postLimitTail .= ' FOR UPDATE';
1176 }
1177
1178 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1179 $startOpts .= 'DISTINCT';
1180 }
1181
1182 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1183 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1184 } else {
1185 $useIndex = '';
1186 }
1187
1188 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1189 }
1190
1191 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1192 if ( is_array( $conds ) ) {
1193 $conds = $this->wrapConditionsForWhere( $table, $conds );
1194 }
1195 // a hack for deleting pages, users and images (which have non-nullable FKs)
1196 // all deletions on these tables have transactions so final failure rollbacks these updates
1197 $table = $this->tableName( $table );
1198 if ( $table == $this->tableName( 'user' ) ) {
1199 $this->update( 'archive', array( 'ar_user' => 0 ), array( 'ar_user' => $conds['user_id'] ), $fname );
1200 $this->update( 'ipblocks', array( 'ipb_user' => 0 ), array( 'ipb_user' => $conds['user_id'] ), $fname );
1201 $this->update( 'image', array( 'img_user' => 0 ), array( 'img_user' => $conds['user_id'] ), $fname );
1202 $this->update( 'oldimage', array( 'oi_user' => 0 ), array( 'oi_user' => $conds['user_id'] ), $fname );
1203 $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ), array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
1204 $this->update( 'filearchive', array( 'fa_user' => 0 ), array( 'fa_user' => $conds['user_id'] ), $fname );
1205 $this->update( 'uploadstash', array( 'us_user' => 0 ), array( 'us_user' => $conds['user_id'] ), $fname );
1206 $this->update( 'recentchanges', array( 'rc_user' => 0 ), array( 'rc_user' => $conds['user_id'] ), $fname );
1207 $this->update( 'logging', array( 'log_user' => 0 ), array( 'log_user' => $conds['user_id'] ), $fname );
1208 } elseif ( $table == $this->tableName( 'image' ) ) {
1209 $this->update( 'oldimage', array( 'oi_name' => 0 ), array( 'oi_name' => $conds['img_name'] ), $fname );
1210 }
1211 return parent::delete( $table, $conds, $fname );
1212 }
1213
1214 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1215 global $wgContLang;
1216
1217 $table = $this->tableName( $table );
1218 $opts = $this->makeUpdateOptions( $options );
1219 $sql = "UPDATE $opts $table SET ";
1220
1221 $first = true;
1222 foreach ( $values as $col => &$val ) {
1223 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1224
1225 if ( !$first ) {
1226 $sqlSet = ', ' . $sqlSet;
1227 } else {
1228 $first = false;
1229 }
1230 $sql .= $sqlSet;
1231 }
1232
1233 if ( $conds !== array() && $conds !== '*' ) {
1234 $conds = $this->wrapConditionsForWhere( $table, $conds );
1235 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1236 }
1237
1238 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1239 $e = oci_error( $this->mConn );
1240 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1241 return false;
1242 }
1243 foreach ( $values as $col => &$val ) {
1244 $col_info = $this->fieldInfoMulti( $table, $col );
1245 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1246
1247 if ( $val === null ) {
1248 // do nothing ... null was inserted in statement creation
1249 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1250 if ( is_object( $val ) ) {
1251 $val = $val->getData();
1252 }
1253
1254 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1255 $val = '31-12-2030 12:00:00.000000';
1256 }
1257
1258 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1259 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1260 $e = oci_error( $stmt );
1261 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1262 return false;
1263 }
1264 } else {
1265 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1266 $e = oci_error( $stmt );
1267 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1268 }
1269
1270 if ( $col_type == 'BLOB' ) {
1271 $lob[$col]->writeTemporary( $val );
1272 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1273 } else {
1274 $lob[$col]->writeTemporary( $val );
1275 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1276 }
1277 }
1278 }
1279
1280 wfSuppressWarnings();
1281
1282 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1283 $e = oci_error( $stmt );
1284 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1285 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1286 return false;
1287 } else {
1288 $this->mAffectedRows = oci_num_rows( $stmt );
1289 }
1290 } else {
1291 $this->mAffectedRows = oci_num_rows( $stmt );
1292 }
1293
1294 wfRestoreWarnings();
1295
1296 if ( isset( $lob ) ) {
1297 foreach ( $lob as $lob_v ) {
1298 $lob_v->free();
1299 }
1300 }
1301
1302 if ( !$this->mTrxLevel ) {
1303 oci_commit( $this->mConn );
1304 }
1305
1306 oci_free_statement( $stmt );
1307 }
1308
1309 function bitNot( $field ) {
1310 // expecting bit-fields smaller than 4bytes
1311 return 'BITNOT(' . $field . ')';
1312 }
1313
1314 function bitAnd( $fieldLeft, $fieldRight ) {
1315 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1316 }
1317
1318 function bitOr( $fieldLeft, $fieldRight ) {
1319 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1320 }
1321
1322 function setFakeMaster( $enabled = true ) {
1323 }
1324
1325 function getDBname() {
1326 return $this->mDBname;
1327 }
1328
1329 function getServer() {
1330 return $this->mServer;
1331 }
1332
1333 public function getSearchEngine() {
1334 return 'SearchOracle';
1335 }
1336
1337 public function getInfinity() {
1338 return '31-12-2030 12:00:00.000000';
1339 }
1340
1341 } // end DatabaseOracle class