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