Add forgotten RELEASE-NOTES line
[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 } elseif ( $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 strtoupper( parent::tableName( $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 bool
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 && $res->numRows() > 0 ) {
895 $exists = true;
896 } else {
897 $exists = false;
898 }
899
900 $res->free();
901 return $exists;
902 }
903
904 /**
905 * Function translates mysql_fetch_field() functionality on ORACLE.
906 * Caching is present for reducing query time.
907 * For internal calls. Use fieldInfo for normal usage.
908 * Returns false if the field doesn't exist
909 *
910 * @param $table Array
911 * @param $field String
912 * @return ORAField|ORAResult
913 */
914 private function fieldInfoMulti( $table, $field ) {
915 $field = strtoupper( $field );
916 if ( is_array( $table ) ) {
917 $table = array_map( array( &$this, 'tableNameInternal' ), $table );
918 $tableWhere = 'IN (';
919 foreach ( $table as &$singleTable ) {
920 $singleTable = $this->removeIdentifierQuotes( $singleTable );
921 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
922 return $this->mFieldInfoCache["$singleTable.$field"];
923 }
924 $tableWhere .= '\'' . $singleTable . '\',';
925 }
926 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
927 } else {
928 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
929 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
930 return $this->mFieldInfoCache["$table.$field"];
931 }
932 $tableWhere = '= \'' . $table . '\'';
933 }
934
935 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name ' . $tableWhere . ' and column_name = \'' . $field . '\'' );
936 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
937 $e = oci_error( $fieldInfoStmt );
938 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
939 return false;
940 }
941 $res = new ORAResult( $this, $fieldInfoStmt );
942 if ( $res->numRows() == 0 ) {
943 if ( is_array( $table ) ) {
944 foreach ( $table as &$singleTable ) {
945 $this->mFieldInfoCache["$singleTable.$field"] = false;
946 }
947 } else {
948 $this->mFieldInfoCache["$table.$field"] = false;
949 }
950 $fieldInfoTemp = null;
951 } else {
952 $fieldInfoTemp = new ORAField( $res->fetchRow() );
953 $table = $fieldInfoTemp->tableName();
954 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
955 }
956 $res->free();
957 return $fieldInfoTemp;
958 }
959
960 /**
961 * @throws DBUnexpectedError
962 * @param $table
963 * @param $field
964 * @return ORAField
965 */
966 function fieldInfo( $table, $field ) {
967 if ( is_array( $table ) ) {
968 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
969 }
970 return $this->fieldInfoMulti( $table, $field );
971 }
972
973 protected function doBegin( $fname = __METHOD__ ) {
974 $this->mTrxLevel = 1;
975 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
976 }
977
978 protected function doCommit( $fname = __METHOD__ ) {
979 if ( $this->mTrxLevel ) {
980 $ret = oci_commit( $this->mConn );
981 if ( !$ret ) {
982 throw new DBUnexpectedError( $this, $this->lastError() );
983 }
984 $this->mTrxLevel = 0;
985 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
986 }
987 }
988
989 protected function doRollback( $fname = __METHOD__ ) {
990 if ( $this->mTrxLevel ) {
991 oci_rollback( $this->mConn );
992 $this->mTrxLevel = 0;
993 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
994 }
995 }
996
997 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
998 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
999 $fname = __METHOD__, $inputCallback = false ) {
1000 $cmd = '';
1001 $done = false;
1002 $dollarquote = false;
1003
1004 $replacements = array();
1005
1006 while ( ! feof( $fp ) ) {
1007 if ( $lineCallback ) {
1008 call_user_func( $lineCallback );
1009 }
1010 $line = trim( fgets( $fp, 1024 ) );
1011 $sl = strlen( $line ) - 1;
1012
1013 if ( $sl < 0 ) {
1014 continue;
1015 }
1016 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1017 continue;
1018 }
1019
1020 // Allow dollar quoting for function declarations
1021 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1022 if ( $dollarquote ) {
1023 $dollarquote = false;
1024 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1025 $done = true;
1026 } else {
1027 $dollarquote = true;
1028 }
1029 } elseif ( !$dollarquote ) {
1030 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1031 $done = true;
1032 $line = substr( $line, 0, $sl );
1033 }
1034 }
1035
1036 if ( $cmd != '' ) {
1037 $cmd .= ' ';
1038 }
1039 $cmd .= "$line\n";
1040
1041 if ( $done ) {
1042 $cmd = str_replace( ';;', ";", $cmd );
1043 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1044 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1045 $replacements[$defines[2]] = $defines[1];
1046 }
1047 } else {
1048 foreach ( $replacements as $mwVar => $scVar ) {
1049 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1050 }
1051
1052 $cmd = $this->replaceVars( $cmd );
1053 if ( $inputCallback ) {
1054 call_user_func( $inputCallback, $cmd );
1055 }
1056 $res = $this->doQuery( $cmd );
1057 if ( $resultCallback ) {
1058 call_user_func( $resultCallback, $res, $this );
1059 }
1060
1061 if ( false === $res ) {
1062 $err = $this->lastError();
1063 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1064 }
1065 }
1066
1067 $cmd = '';
1068 $done = false;
1069 }
1070 }
1071 return true;
1072 }
1073
1074 function selectDB( $db ) {
1075 $this->mDBname = $db;
1076 if ( $db == null || $db == $this->mUser ) {
1077 return true;
1078 }
1079 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1080 $stmt = oci_parse( $this->mConn, $sql );
1081 wfSuppressWarnings();
1082 $success = oci_execute( $stmt );
1083 wfRestoreWarnings();
1084 if ( !$success ) {
1085 $e = oci_error( $stmt );
1086 if ( $e['code'] != '1435' ) {
1087 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1088 }
1089 return false;
1090 }
1091 return true;
1092 }
1093
1094 function strencode( $s ) {
1095 return str_replace( "'", "''", $s );
1096 }
1097
1098 function addQuotes( $s ) {
1099 global $wgContLang;
1100 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1101 $s = $wgContLang->checkTitleEncoding( $s );
1102 }
1103 return "'" . $this->strencode( $s ) . "'";
1104 }
1105
1106 public function addIdentifierQuotes( $s ) {
1107 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1108 $s = '/*Q*/' . $s;
1109 }
1110 return $s;
1111 }
1112
1113 public function removeIdentifierQuotes( $s ) {
1114 return strpos( $s, '/*Q*/' ) === false ? $s : substr( $s, 5 );
1115 }
1116
1117 public function isQuotedIdentifier( $s ) {
1118 return strpos( $s, '/*Q*/' ) !== false;
1119 }
1120
1121 private function wrapFieldForWhere( $table, &$col, &$val ) {
1122 global $wgContLang;
1123
1124 $col_info = $this->fieldInfoMulti( $table, $col );
1125 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1126 if ( $col_type == 'CLOB' ) {
1127 $col = 'TO_CHAR(' . $col . ')';
1128 $val = $wgContLang->checkTitleEncoding( $val );
1129 } elseif ( $col_type == 'VARCHAR2' ) {
1130 $val = $wgContLang->checkTitleEncoding( $val );
1131 }
1132 }
1133
1134 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1135 $conds2 = array();
1136 foreach ( $conds as $col => $val ) {
1137 if ( is_array( $val ) ) {
1138 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1139 } else {
1140 if ( is_numeric( $col ) && $parentCol != null ) {
1141 $this->wrapFieldForWhere( $table, $parentCol, $val );
1142 } else {
1143 $this->wrapFieldForWhere( $table, $col, $val );
1144 }
1145 $conds2[$col] = $val;
1146 }
1147 }
1148 return $conds2;
1149 }
1150
1151 function selectRow( $table, $vars, $conds, $fname = __METHOD__, $options = array(), $join_conds = array() ) {
1152 if ( is_array( $conds ) ) {
1153 $conds = $this->wrapConditionsForWhere( $table, $conds );
1154 }
1155 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1156 }
1157
1158 /**
1159 * Returns an optional USE INDEX clause to go after the table, and a
1160 * string to go at the end of the query
1161 *
1162 * @private
1163 *
1164 * @param array $options an associative array of options to be turned into
1165 * an SQL query, valid keys are listed in the function.
1166 * @return array
1167 */
1168 function makeSelectOptions( $options ) {
1169 $preLimitTail = $postLimitTail = '';
1170 $startOpts = '';
1171
1172 $noKeyOptions = array();
1173 foreach ( $options as $key => $option ) {
1174 if ( is_numeric( $key ) ) {
1175 $noKeyOptions[$option] = true;
1176 }
1177 }
1178
1179 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1180
1181 $preLimitTail .= $this->makeOrderBy( $options );
1182
1183 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1184 $postLimitTail .= ' FOR UPDATE';
1185 }
1186
1187 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1188 $startOpts .= 'DISTINCT';
1189 }
1190
1191 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1192 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1193 } else {
1194 $useIndex = '';
1195 }
1196
1197 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1198 }
1199
1200 public function delete( $table, $conds, $fname = __METHOD__ ) {
1201 if ( is_array( $conds ) ) {
1202 $conds = $this->wrapConditionsForWhere( $table, $conds );
1203 }
1204 // a hack for deleting pages, users and images (which have non-nullable FKs)
1205 // all deletions on these tables have transactions so final failure rollbacks these updates
1206 $table = $this->tableName( $table );
1207 if ( $table == $this->tableName( 'user' ) ) {
1208 $this->update( 'archive', array( 'ar_user' => 0 ), array( 'ar_user' => $conds['user_id'] ), $fname );
1209 $this->update( 'ipblocks', array( 'ipb_user' => 0 ), array( 'ipb_user' => $conds['user_id'] ), $fname );
1210 $this->update( 'image', array( 'img_user' => 0 ), array( 'img_user' => $conds['user_id'] ), $fname );
1211 $this->update( 'oldimage', array( 'oi_user' => 0 ), array( 'oi_user' => $conds['user_id'] ), $fname );
1212 $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ), array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
1213 $this->update( 'filearchive', array( 'fa_user' => 0 ), array( 'fa_user' => $conds['user_id'] ), $fname );
1214 $this->update( 'uploadstash', array( 'us_user' => 0 ), array( 'us_user' => $conds['user_id'] ), $fname );
1215 $this->update( 'recentchanges', array( 'rc_user' => 0 ), array( 'rc_user' => $conds['user_id'] ), $fname );
1216 $this->update( 'logging', array( 'log_user' => 0 ), array( 'log_user' => $conds['user_id'] ), $fname );
1217 } elseif ( $table == $this->tableName( 'image' ) ) {
1218 $this->update( 'oldimage', array( 'oi_name' => 0 ), array( 'oi_name' => $conds['img_name'] ), $fname );
1219 }
1220 return parent::delete( $table, $conds, $fname );
1221 }
1222
1223 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
1224 global $wgContLang;
1225
1226 $table = $this->tableName( $table );
1227 $opts = $this->makeUpdateOptions( $options );
1228 $sql = "UPDATE $opts $table SET ";
1229
1230 $first = true;
1231 foreach ( $values as $col => &$val ) {
1232 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1233
1234 if ( !$first ) {
1235 $sqlSet = ', ' . $sqlSet;
1236 } else {
1237 $first = false;
1238 }
1239 $sql .= $sqlSet;
1240 }
1241
1242 if ( $conds !== array() && $conds !== '*' ) {
1243 $conds = $this->wrapConditionsForWhere( $table, $conds );
1244 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1245 }
1246
1247 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1248 $e = oci_error( $this->mConn );
1249 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1250 return false;
1251 }
1252 foreach ( $values as $col => &$val ) {
1253 $col_info = $this->fieldInfoMulti( $table, $col );
1254 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1255
1256 if ( $val === null ) {
1257 // do nothing ... null was inserted in statement creation
1258 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1259 if ( is_object( $val ) ) {
1260 $val = $val->getData();
1261 }
1262
1263 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1264 $val = '31-12-2030 12:00:00.000000';
1265 }
1266
1267 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1268 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1269 $e = oci_error( $stmt );
1270 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1271 return false;
1272 }
1273 } else {
1274 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1275 $e = oci_error( $stmt );
1276 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1277 }
1278
1279 if ( $col_type == 'BLOB' ) {
1280 $lob[$col]->writeTemporary( $val );
1281 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1282 } else {
1283 $lob[$col]->writeTemporary( $val );
1284 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1285 }
1286 }
1287 }
1288
1289 wfSuppressWarnings();
1290
1291 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1292 $e = oci_error( $stmt );
1293 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1294 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1295 return false;
1296 } else {
1297 $this->mAffectedRows = oci_num_rows( $stmt );
1298 }
1299 } else {
1300 $this->mAffectedRows = oci_num_rows( $stmt );
1301 }
1302
1303 wfRestoreWarnings();
1304
1305 if ( isset( $lob ) ) {
1306 foreach ( $lob as $lob_v ) {
1307 $lob_v->free();
1308 }
1309 }
1310
1311 if ( !$this->mTrxLevel ) {
1312 oci_commit( $this->mConn );
1313 }
1314
1315 oci_free_statement( $stmt );
1316 }
1317
1318 function bitNot( $field ) {
1319 // expecting bit-fields smaller than 4bytes
1320 return 'BITNOT(' . $field . ')';
1321 }
1322
1323 function bitAnd( $fieldLeft, $fieldRight ) {
1324 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1325 }
1326
1327 function bitOr( $fieldLeft, $fieldRight ) {
1328 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1329 }
1330
1331 function setFakeMaster( $enabled = true ) {
1332 }
1333
1334 function getDBname() {
1335 return $this->mDBname;
1336 }
1337
1338 function getServer() {
1339 return $this->mServer;
1340 }
1341
1342 public function getSearchEngine() {
1343 return 'SearchOracle';
1344 }
1345
1346 public function getInfinity() {
1347 return '31-12-2030 12:00:00.000000';
1348 }
1349
1350 } // end DatabaseOracle class