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