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