Merge "Follow-up I5f7f6da0 (cefb9ef): pass the User parameter to more LogEventsList...
[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 return $endArray;
800 }
801
802 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
803 $tableName = $this->tableName($tableName);
804 if( !$this->tableExists( $tableName ) ) {
805 return false;
806 }
807
808 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
809 }
810
811 function timestamp( $ts = 0 ) {
812 return wfTimestamp( TS_ORACLE, $ts );
813 }
814
815 /**
816 * Return aggregated value function call
817 */
818 public function aggregateValue( $valuedata, $valuename = 'value' ) {
819 return $valuedata;
820 }
821
822 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
823 # Ignore errors during error handling to avoid infinite
824 # recursion
825 $ignore = $this->ignoreErrors( true );
826 ++$this->mErrorCount;
827
828 if ( $ignore || $tempIgnore ) {
829 wfDebug( "SQL ERROR (ignored): $error\n" );
830 $this->ignoreErrors( $ignore );
831 } else {
832 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
833 }
834 }
835
836 /**
837 * @return string wikitext of a link to the server software's web site
838 */
839 public static function getSoftwareLink() {
840 return '[http://www.oracle.com/ Oracle]';
841 }
842
843 /**
844 * @return string Version information from the database
845 */
846 function getServerVersion() {
847 //better version number, fallback on driver
848 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
849 if ( !( $row = $rset->fetchRow() ) ) {
850 return oci_server_version( $this->mConn );
851 }
852 return $row['version'];
853 }
854
855 /**
856 * Query whether a given index exists
857 * @return bool
858 */
859 function indexExists( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
860 $table = $this->tableName( $table );
861 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
862 $index = strtoupper( $index );
863 $owner = strtoupper( $this->mDBname );
864 $SQL = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
865 $res = $this->doQuery( $SQL );
866 if ( $res ) {
867 $count = $res->numRows();
868 $res->free();
869 } else {
870 $count = 0;
871 }
872 return $count != 0;
873 }
874
875 /**
876 * Query whether a given table exists (in the given schema, or the default mw one if not given)
877 * @return int
878 */
879 function tableExists( $table, $fname = __METHOD__ ) {
880 $table = $this->tableName( $table );
881 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
882 $owner = $this->addQuotes( strtoupper( $this->mDBname ) );
883 $SQL = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
884 $res = $this->doQuery( $SQL );
885 if ( $res ) {
886 $count = $res->numRows();
887 $res->free();
888 } else {
889 $count = 0;
890 }
891 return $count;
892 }
893
894 /**
895 * Function translates mysql_fetch_field() functionality on ORACLE.
896 * Caching is present for reducing query time.
897 * For internal calls. Use fieldInfo for normal usage.
898 * Returns false if the field doesn't exist
899 *
900 * @param $table Array
901 * @param $field String
902 * @return ORAField|ORAResult
903 */
904 private function fieldInfoMulti( $table, $field ) {
905 $field = strtoupper( $field );
906 if ( is_array( $table ) ) {
907 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
908 $tableWhere = 'IN (';
909 foreach( $table as &$singleTable ) {
910 $singleTable = $this->removeIdentifierQuotes($singleTable);
911 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
912 return $this->mFieldInfoCache["$singleTable.$field"];
913 }
914 $tableWhere .= '\'' . $singleTable . '\',';
915 }
916 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
917 } else {
918 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
919 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
920 return $this->mFieldInfoCache["$table.$field"];
921 }
922 $tableWhere = '= \''.$table.'\'';
923 }
924
925 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
926 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
927 $e = oci_error( $fieldInfoStmt );
928 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
929 return false;
930 }
931 $res = new ORAResult( $this, $fieldInfoStmt );
932 if ( $res->numRows() == 0 ) {
933 if ( is_array( $table ) ) {
934 foreach( $table as &$singleTable ) {
935 $this->mFieldInfoCache["$singleTable.$field"] = false;
936 }
937 } else {
938 $this->mFieldInfoCache["$table.$field"] = false;
939 }
940 $fieldInfoTemp = null;
941 } else {
942 $fieldInfoTemp = new ORAField( $res->fetchRow() );
943 $table = $fieldInfoTemp->tableName();
944 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
945 }
946 $res->free();
947 return $fieldInfoTemp;
948 }
949
950 /**
951 * @throws DBUnexpectedError
952 * @param $table
953 * @param $field
954 * @return ORAField
955 */
956 function fieldInfo( $table, $field ) {
957 if ( is_array( $table ) ) {
958 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
959 }
960 return $this->fieldInfoMulti ($table, $field);
961 }
962
963 protected function doBegin( $fname = 'DatabaseOracle::begin' ) {
964 $this->mTrxLevel = 1;
965 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
966 }
967
968 protected function doCommit( $fname = 'DatabaseOracle::commit' ) {
969 if ( $this->mTrxLevel ) {
970 $ret = oci_commit( $this->mConn );
971 if ( !$ret ) {
972 throw new DBUnexpectedError( $this, $this->lastError() );
973 }
974 $this->mTrxLevel = 0;
975 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
976 }
977 }
978
979 protected function doRollback( $fname = 'DatabaseOracle::rollback' ) {
980 if ( $this->mTrxLevel ) {
981 oci_rollback( $this->mConn );
982 $this->mTrxLevel = 0;
983 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
984 }
985 }
986
987 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
988 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
989 $fname = 'DatabaseOracle::sourceStream', $inputCallback = false ) {
990 $cmd = '';
991 $done = false;
992 $dollarquote = false;
993
994 $replacements = array();
995
996 while ( ! feof( $fp ) ) {
997 if ( $lineCallback ) {
998 call_user_func( $lineCallback );
999 }
1000 $line = trim( fgets( $fp, 1024 ) );
1001 $sl = strlen( $line ) - 1;
1002
1003 if ( $sl < 0 ) {
1004 continue;
1005 }
1006 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1007 continue;
1008 }
1009
1010 // Allow dollar quoting for function declarations
1011 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1012 if ( $dollarquote ) {
1013 $dollarquote = false;
1014 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1015 $done = true;
1016 } else {
1017 $dollarquote = true;
1018 }
1019 } elseif ( !$dollarquote ) {
1020 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1021 $done = true;
1022 $line = substr( $line, 0, $sl );
1023 }
1024 }
1025
1026 if ( $cmd != '' ) {
1027 $cmd .= ' ';
1028 }
1029 $cmd .= "$line\n";
1030
1031 if ( $done ) {
1032 $cmd = str_replace( ';;', ";", $cmd );
1033 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1034 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1035 $replacements[$defines[2]] = $defines[1];
1036 }
1037 } else {
1038 foreach ( $replacements as $mwVar => $scVar ) {
1039 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1040 }
1041
1042 $cmd = $this->replaceVars( $cmd );
1043 if ( $inputCallback ) {
1044 call_user_func( $inputCallback, $cmd );
1045 }
1046 $res = $this->doQuery( $cmd );
1047 if ( $resultCallback ) {
1048 call_user_func( $resultCallback, $res, $this );
1049 }
1050
1051 if ( false === $res ) {
1052 $err = $this->lastError();
1053 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1054 }
1055 }
1056
1057 $cmd = '';
1058 $done = false;
1059 }
1060 }
1061 return true;
1062 }
1063
1064 function selectDB( $db ) {
1065 $this->mDBname = $db;
1066 if ( $db == null || $db == $this->mUser ) {
1067 return true;
1068 }
1069 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1070 $stmt = oci_parse( $this->mConn, $sql );
1071 wfSuppressWarnings();
1072 $success = oci_execute( $stmt );
1073 wfRestoreWarnings();
1074 if ( !$success ) {
1075 $e = oci_error( $stmt );
1076 if ( $e['code'] != '1435' ) {
1077 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1078 }
1079 return false;
1080 }
1081 return true;
1082 }
1083
1084 function strencode( $s ) {
1085 return str_replace( "'", "''", $s );
1086 }
1087
1088 function addQuotes( $s ) {
1089 global $wgContLang;
1090 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1091 $s = $wgContLang->checkTitleEncoding( $s );
1092 }
1093 return "'" . $this->strencode( $s ) . "'";
1094 }
1095
1096 public function addIdentifierQuotes( $s ) {
1097 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1098 $s = '/*Q*/' . $s;
1099 }
1100 return $s;
1101 }
1102
1103 public function removeIdentifierQuotes( $s ) {
1104 return strpos($s, '/*Q*/') === FALSE ? $s : substr($s, 5);
1105 }
1106
1107 public function isQuotedIdentifier( $s ) {
1108 return strpos($s, '/*Q*/') !== FALSE;
1109 }
1110
1111 private function wrapFieldForWhere( $table, &$col, &$val ) {
1112 global $wgContLang;
1113
1114 $col_info = $this->fieldInfoMulti( $table, $col );
1115 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1116 if ( $col_type == 'CLOB' ) {
1117 $col = 'TO_CHAR(' . $col . ')';
1118 $val = $wgContLang->checkTitleEncoding( $val );
1119 } elseif ( $col_type == 'VARCHAR2' ) {
1120 $val = $wgContLang->checkTitleEncoding( $val );
1121 }
1122 }
1123
1124 private function wrapConditionsForWhere ( $table, $conds, $parentCol = null ) {
1125 $conds2 = array();
1126 foreach ( $conds as $col => $val ) {
1127 if ( is_array( $val ) ) {
1128 $conds2[$col] = $this->wrapConditionsForWhere ( $table, $val, $col );
1129 } else {
1130 if ( is_numeric( $col ) && $parentCol != null ) {
1131 $this->wrapFieldForWhere ( $table, $parentCol, $val );
1132 } else {
1133 $this->wrapFieldForWhere ( $table, $col, $val );
1134 }
1135 $conds2[$col] = $val;
1136 }
1137 }
1138 return $conds2;
1139 }
1140
1141 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1142 if ( is_array($conds) ) {
1143 $conds = $this->wrapConditionsForWhere( $table, $conds );
1144 }
1145 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1146 }
1147
1148 /**
1149 * Returns an optional USE INDEX clause to go after the table, and a
1150 * string to go at the end of the query
1151 *
1152 * @private
1153 *
1154 * @param $options Array: an associative array of options to be turned into
1155 * an SQL query, valid keys are listed in the function.
1156 * @return array
1157 */
1158 function makeSelectOptions( $options ) {
1159 $preLimitTail = $postLimitTail = '';
1160 $startOpts = '';
1161
1162 $noKeyOptions = array();
1163 foreach ( $options as $key => $option ) {
1164 if ( is_numeric( $key ) ) {
1165 $noKeyOptions[$option] = true;
1166 }
1167 }
1168
1169 if ( isset( $options['GROUP BY'] ) ) {
1170 $gb = is_array( $options['GROUP BY'] )
1171 ? implode( ',', $options['GROUP BY'] )
1172 : $options['GROUP BY'];
1173 $preLimitTail .= " GROUP BY {$gb}";
1174 }
1175
1176 if ( isset( $options['HAVING'] ) ) {
1177 $having = is_array( $options['HAVING'] )
1178 ? $this->makeList( $options['HAVING'], LIST_AND )
1179 : $options['HAVING'];
1180 $preLimitTail .= " HAVING {$having}";
1181 }
1182
1183 if ( isset( $options['ORDER BY'] ) ) {
1184 $ob = is_array( $options['ORDER BY'] )
1185 ? implode( ',', $options['ORDER BY'] )
1186 : $options['ORDER BY'];
1187 $preLimitTail .= " ORDER BY {$ob}";
1188 }
1189
1190 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1191 $postLimitTail .= ' FOR UPDATE';
1192 }
1193
1194 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1195 $startOpts .= 'DISTINCT';
1196 }
1197
1198 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1199 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1200 } else {
1201 $useIndex = '';
1202 }
1203
1204 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1205 }
1206
1207 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1208 if ( is_array($conds) ) {
1209 $conds = $this->wrapConditionsForWhere( $table, $conds );
1210 }
1211 // a hack for deleting pages, users and images (which have non-nullable FKs)
1212 // all deletions on these tables have transactions so final failure rollbacks these updates
1213 $table = $this->tableName( $table );
1214 if ( $table == $this->tableName( 'user' ) ) {
1215 $this->update( 'archive', array( 'ar_user' => 0 ), array( 'ar_user' => $conds['user_id'] ), $fname );
1216 $this->update( 'ipblocks', array( 'ipb_user' => 0 ), array( 'ipb_user' => $conds['user_id'] ), $fname );
1217 $this->update( 'image', array( 'img_user' => 0 ), array( 'img_user' => $conds['user_id'] ), $fname );
1218 $this->update( 'oldimage', array( 'oi_user' => 0 ), array( 'oi_user' => $conds['user_id'] ), $fname );
1219 $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ), array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
1220 $this->update( 'filearchive', array( 'fa_user' => 0 ), array( 'fa_user' => $conds['user_id'] ), $fname );
1221 $this->update( 'uploadstash', array( 'us_user' => 0 ), array( 'us_user' => $conds['user_id'] ), $fname );
1222 $this->update( 'recentchanges', array( 'rc_user' => 0 ), array( 'rc_user' => $conds['user_id'] ), $fname );
1223 $this->update( 'logging', array( 'log_user' => 0 ), array( 'log_user' => $conds['user_id'] ), $fname );
1224 } elseif ( $table == $this->tableName( 'image' ) ) {
1225 $this->update( 'oldimage', array( 'oi_name' => 0 ), array( 'oi_name' => $conds['img_name'] ), $fname );
1226 }
1227 return parent::delete( $table, $conds, $fname );
1228 }
1229
1230 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1231 global $wgContLang;
1232
1233 $table = $this->tableName( $table );
1234 $opts = $this->makeUpdateOptions( $options );
1235 $sql = "UPDATE $opts $table SET ";
1236
1237 $first = true;
1238 foreach ( $values as $col => &$val ) {
1239 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1240
1241 if ( !$first ) {
1242 $sqlSet = ', ' . $sqlSet;
1243 } else {
1244 $first = false;
1245 }
1246 $sql .= $sqlSet;
1247 }
1248
1249 if ( $conds !== array() && $conds !== '*' ) {
1250 $conds = $this->wrapConditionsForWhere( $table, $conds );
1251 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1252 }
1253
1254 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1255 $e = oci_error( $this->mConn );
1256 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1257 return false;
1258 }
1259 foreach ( $values as $col => &$val ) {
1260 $col_info = $this->fieldInfoMulti( $table, $col );
1261 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1262
1263 if ( $val === null ) {
1264 // do nothing ... null was inserted in statement creation
1265 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1266 if ( is_object( $val ) ) {
1267 $val = $val->getData();
1268 }
1269
1270 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1271 $val = '31-12-2030 12:00:00.000000';
1272 }
1273
1274 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1275 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1276 $e = oci_error( $stmt );
1277 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1278 return false;
1279 }
1280 } else {
1281 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1282 $e = oci_error( $stmt );
1283 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1284 }
1285
1286 if ( $col_type == 'BLOB' ) {
1287 $lob[$col]->writeTemporary( $val );
1288 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1289 } else {
1290 $lob[$col]->writeTemporary( $val );
1291 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1292 }
1293 }
1294 }
1295
1296 wfSuppressWarnings();
1297
1298 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1299 $e = oci_error( $stmt );
1300 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1301 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1302 return false;
1303 } else {
1304 $this->mAffectedRows = oci_num_rows( $stmt );
1305 }
1306 } else {
1307 $this->mAffectedRows = oci_num_rows( $stmt );
1308 }
1309
1310 wfRestoreWarnings();
1311
1312 if ( isset( $lob ) ) {
1313 foreach ( $lob as $lob_v ) {
1314 $lob_v->free();
1315 }
1316 }
1317
1318 if ( !$this->mTrxLevel ) {
1319 oci_commit( $this->mConn );
1320 }
1321
1322 oci_free_statement( $stmt );
1323 }
1324
1325 function bitNot( $field ) {
1326 // expecting bit-fields smaller than 4bytes
1327 return 'BITNOT(' . $field . ')';
1328 }
1329
1330 function bitAnd( $fieldLeft, $fieldRight ) {
1331 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1332 }
1333
1334 function bitOr( $fieldLeft, $fieldRight ) {
1335 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1336 }
1337
1338 function setFakeMaster( $enabled = true ) {
1339 }
1340
1341 function getDBname() {
1342 return $this->mDBname;
1343 }
1344
1345 function getServer() {
1346 return $this->mServer;
1347 }
1348
1349 public function getSearchEngine() {
1350 return 'SearchOracle';
1351 }
1352
1353 public function getInfinity() {
1354 return '31-12-2030 12:00:00.000000';
1355 }
1356
1357 } // end DatabaseOracle class