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