36ffdfb32a57cadda0b956e6220d51e0d52f8cf3
[lhc/web/wiklou.git] / includes / db / DatabaseOracle.php
1 <?php
2 /**
3 * This is the Oracle database abstraction layer.
4 *
5 * @file
6 * @ingroup Database
7 */
8
9 /**
10 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
11 * other things. We use a wrapper class to handle that and other
12 * Oracle-specific bits, like converting column names back to lowercase.
13 * @ingroup Database
14 */
15 class ORAResult {
16 private $rows;
17 private $cursor;
18 private $nrows;
19
20 private $columns = array();
21
22 private function array_unique_md( $array_in ) {
23 $array_out = array();
24 $array_hashes = array();
25
26 foreach ( $array_in as $item ) {
27 $hash = md5( serialize( $item ) );
28 if ( !isset( $array_hashes[$hash] ) ) {
29 $array_hashes[$hash] = $hash;
30 $array_out[] = $item;
31 }
32 }
33
34 return $array_out;
35 }
36
37 function __construct( &$db, $stmt, $unique = false ) {
38 $this->db =& $db;
39
40 if ( ( $this->nrows = oci_fetch_all( $stmt, $this->rows, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM ) ) === false ) {
41 $e = oci_error( $stmt );
42 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__ );
43 $this->free();
44 return;
45 }
46
47 if ( $unique ) {
48 $this->rows = $this->array_unique_md( $this->rows );
49 $this->nrows = count( $this->rows );
50 }
51
52 if ($this->nrows > 0) {
53 foreach ( $this->rows[0] as $k => $v ) {
54 $this->columns[$k] = strtolower( oci_field_name( $stmt, $k + 1 ) );
55 }
56 }
57
58 $this->cursor = 0;
59 oci_free_statement( $stmt );
60 }
61
62 public function free() {
63 unset($this->db);
64 }
65
66 public function seek( $row ) {
67 $this->cursor = min( $row, $this->nrows );
68 }
69
70 public function numRows() {
71 return $this->nrows;
72 }
73
74 public function numFields() {
75 return count($this->columns);
76 }
77
78 public function fetchObject() {
79 if ( $this->cursor >= $this->nrows ) {
80 return false;
81 }
82 $row = $this->rows[$this->cursor++];
83 $ret = new stdClass();
84 foreach ( $row as $k => $v ) {
85 $lc = $this->columns[$k];
86 $ret->$lc = $v;
87 }
88
89 return $ret;
90 }
91
92 public function fetchRow() {
93 if ( $this->cursor >= $this->nrows ) {
94 return false;
95 }
96
97 $row = $this->rows[$this->cursor++];
98 $ret = array();
99 foreach ( $row as $k => $v ) {
100 $lc = $this->columns[$k];
101 $ret[$lc] = $v;
102 $ret[$k] = $v;
103 }
104 return $ret;
105 }
106 }
107
108 /**
109 * Utility class.
110 * @ingroup Database
111 */
112 class ORAField implements Field {
113 private $name, $tablename, $default, $max_length, $nullable,
114 $is_pk, $is_unique, $is_multiple, $is_key, $type;
115
116 function __construct( $info ) {
117 $this->name = $info['column_name'];
118 $this->tablename = $info['table_name'];
119 $this->default = $info['data_default'];
120 $this->max_length = $info['data_length'];
121 $this->nullable = $info['not_null'];
122 $this->is_pk = isset( $info['prim'] ) && $info['prim'] == 1 ? 1 : 0;
123 $this->is_unique = isset( $info['uniq'] ) && $info['uniq'] == 1 ? 1 : 0;
124 $this->is_multiple = isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ? 1 : 0;
125 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
126 $this->type = $info['data_type'];
127 }
128
129 function name() {
130 return $this->name;
131 }
132
133 function tableName() {
134 return $this->tablename;
135 }
136
137 function defaultValue() {
138 return $this->default;
139 }
140
141 function maxLength() {
142 return $this->max_length;
143 }
144
145 function isNullable() {
146 return $this->nullable;
147 }
148
149 function isKey() {
150 return $this->is_key;
151 }
152
153 function isMultipleKey() {
154 return $this->is_multiple;
155 }
156
157 function type() {
158 return $this->type;
159 }
160 }
161
162 /**
163 * @ingroup Database
164 */
165 class DatabaseOracle extends DatabaseBase {
166 var $mInsertId = null;
167 var $mLastResult = null;
168 var $lastResult = null;
169 var $cursor = 0;
170 var $mAffectedRows;
171
172 var $ignore_DUP_VAL_ON_INDEX = false;
173 var $sequenceData = null;
174
175 var $defaultCharset = 'AL32UTF8';
176
177 var $mFieldInfoCache = array();
178
179 function __construct( $server = false, $user = false, $password = false, $dbName = false,
180 $flags = 0, $tablePrefix = 'get from global' )
181 {
182 $tablePrefix = $tablePrefix == 'get from global' ? $tablePrefix : strtoupper( $tablePrefix );
183 parent::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
184 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
185 }
186
187 function getType() {
188 return 'oracle';
189 }
190
191 function cascadingDeletes() {
192 return true;
193 }
194 function cleanupTriggers() {
195 return true;
196 }
197 function strictIPs() {
198 return true;
199 }
200 function realTimestamps() {
201 return true;
202 }
203 function implicitGroupby() {
204 return false;
205 }
206 function implicitOrderby() {
207 return false;
208 }
209 function searchableIPs() {
210 return true;
211 }
212
213 /**
214 * Usually aborts on failure
215 */
216 function open( $server, $user, $password, $dbName ) {
217 if ( !function_exists( 'oci_connect' ) ) {
218 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" );
219 }
220
221 $this->close();
222 $this->mUser = $user;
223 $this->mPassword = $password;
224 // changed internal variables functions
225 // mServer now holds the TNS endpoint
226 // mDBname is schema name if different from username
227 if ( !$server ) {
228 // backward compatibillity (server used to be null and TNS was supplied in dbname)
229 $this->mServer = $dbName;
230 $this->mDBname = $user;
231 } else {
232 $this->mServer = $server;
233 if ( !$dbName ) {
234 $this->mDBname = $user;
235 } else {
236 $this->mDBname = $dbName;
237 }
238 }
239
240 if ( !strlen( $user ) ) { # e.g. the class is being loaded
241 return;
242 }
243
244 $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
245 wfSuppressWarnings();
246 if ( $this->mFlags & DBO_DEFAULT ) {
247 $this->mConn = oci_new_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
248 } else {
249 $this->mConn = oci_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
250 }
251 wfRestoreWarnings();
252
253 if ( $this->mUser != $this->mDBname ) {
254 //change current schema in session
255 $this->selectDB( $this->mDBname );
256 }
257
258 if ( !$this->mConn ) {
259 throw new DBConnectionError( $this, $this->lastError() );
260 }
261
262 $this->mOpened = true;
263
264 # removed putenv calls because they interfere with the system globaly
265 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
266 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
267 return $this->mConn;
268 }
269
270 /**
271 * Closes a database connection, if it is open
272 * Returns success, true if already closed
273 */
274 function close() {
275 $this->mOpened = false;
276 if ( $this->mConn ) {
277 return oci_close( $this->mConn );
278 } else {
279 return true;
280 }
281 }
282
283 function execFlags() {
284 return $this->mTrxLevel ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
285 }
286
287 function doQuery( $sql ) {
288 wfDebug( "SQL: [$sql]\n" );
289 if ( !mb_check_encoding( $sql ) ) {
290 throw new MWException( "SQL encoding is invalid\n$sql" );
291 }
292
293 // handle some oracle specifics
294 // remove AS column/table/subquery namings
295 if( !$this->getFlag( DBO_DDLMODE ) ) {
296 $sql = preg_replace( '/ as /i', ' ', $sql );
297 }
298
299 // Oracle has issues with UNION clause if the statement includes LOB fields
300 // So we do a UNION ALL and then filter the results array with array_unique
301 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
302 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
303 // you have to select data from plan table after explain
304 $explain_id = date( 'dmYHis' );
305
306 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
307
308 wfSuppressWarnings();
309
310 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
311 $e = oci_error( $this->mConn );
312 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
313 return false;
314 }
315
316 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
317 $e = oci_error( $stmt );
318 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
319 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
320 return false;
321 }
322 }
323
324 wfRestoreWarnings();
325
326 if ( $explain_count > 0 ) {
327 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
328 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
329 return new ORAResult( $this, $stmt, $union_unique );
330 } else {
331 $this->mAffectedRows = oci_num_rows( $stmt );
332 return true;
333 }
334 }
335
336 function queryIgnore( $sql, $fname = '' ) {
337 return $this->query( $sql, $fname, true );
338 }
339
340 function freeResult( $res ) {
341 if ( $res instanceof ResultWrapper ) {
342 $res = $res->result;
343 }
344
345 $res->free();
346 }
347
348 function fetchObject( $res ) {
349 if ( $res instanceof ResultWrapper ) {
350 $res = $res->result;
351 }
352
353 return $res->fetchObject();
354 }
355
356 function fetchRow( $res ) {
357 if ( $res instanceof ResultWrapper ) {
358 $res = $res->result;
359 }
360
361 return $res->fetchRow();
362 }
363
364 function numRows( $res ) {
365 if ( $res instanceof ResultWrapper ) {
366 $res = $res->result;
367 }
368
369 return $res->numRows();
370 }
371
372 function numFields( $res ) {
373 if ( $res instanceof ResultWrapper ) {
374 $res = $res->result;
375 }
376
377 return $res->numFields();
378 }
379
380 function fieldName( $stmt, $n ) {
381 return oci_field_name( $stmt, $n );
382 }
383
384 /**
385 * This must be called after nextSequenceVal
386 */
387 function insertId() {
388 return $this->mInsertId;
389 }
390
391 function dataSeek( $res, $row ) {
392 if ( $res instanceof ORAResult ) {
393 $res->seek( $row );
394 } else {
395 $res->result->seek( $row );
396 }
397 }
398
399 function lastError() {
400 if ( $this->mConn === false ) {
401 $e = oci_error();
402 } else {
403 $e = oci_error( $this->mConn );
404 }
405 return $e['message'];
406 }
407
408 function lastErrno() {
409 if ( $this->mConn === false ) {
410 $e = oci_error();
411 } else {
412 $e = oci_error( $this->mConn );
413 }
414 return $e['code'];
415 }
416
417 function affectedRows() {
418 return $this->mAffectedRows;
419 }
420
421 /**
422 * Returns information about an index
423 * If errors are explicitly ignored, returns NULL on failure
424 */
425 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
426 return false;
427 }
428
429 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
430 return false;
431 }
432
433 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
434 if ( !count( $a ) ) {
435 return true;
436 }
437
438 if ( !is_array( $options ) ) {
439 $options = array( $options );
440 }
441
442 if ( in_array( 'IGNORE', $options ) ) {
443 $this->ignore_DUP_VAL_ON_INDEX = true;
444 }
445
446 if ( !is_array( reset( $a ) ) ) {
447 $a = array( $a );
448 }
449
450 foreach ( $a as &$row ) {
451 $this->insertOneRow( $table, $row, $fname );
452 }
453 $retVal = true;
454
455 if ( in_array( 'IGNORE', $options ) ) {
456 $this->ignore_DUP_VAL_ON_INDEX = false;
457 }
458
459 return $retVal;
460 }
461
462 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
463 $col_info = $this->fieldInfoMulti( $table, $col );
464 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
465
466 $bind = '';
467 if ( is_numeric( $col ) ) {
468 $bind = $val;
469 $val = null;
470 return $bind;
471 } else if ( $includeCol ) {
472 $bind = "$col = ";
473 }
474
475 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
476 $val = null;
477 }
478
479 if ( $val === null ) {
480 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
481 $bind .= 'DEFAULT';
482 } else {
483 $bind .= 'NULL';
484 }
485 } else {
486 $bind .= ':' . $col;
487 }
488
489 return $bind;
490 }
491
492 private function insertOneRow( $table, $row, $fname ) {
493 global $wgContLang;
494
495 $table = $this->tableName( $table );
496 // "INSERT INTO tables (a, b, c)"
497 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
498 $sql .= " VALUES (";
499
500 // for each value, append ":key"
501 $first = true;
502 foreach ( $row as $col => &$val ) {
503 if ( !$first ) {
504 $sql .= ', ';
505 } else {
506 $first = false;
507 }
508
509 $sql .= $this->fieldBindStatement( $table, $col, $val );
510 }
511 $sql .= ')';
512
513 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
514 $e = oci_error( $this->mConn );
515 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
516 return false;
517 }
518 foreach ( $row as $col => &$val ) {
519 $col_info = $this->fieldInfoMulti( $table, $col );
520 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
521
522 if ( $val === null ) {
523 // do nothing ... null was inserted in statement creation
524 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
525 if ( is_object( $val ) ) {
526 $val = $val->fetch();
527 }
528
529 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
530 $val = '31-12-2030 12:00:00.000000';
531 }
532
533 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
534 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
535 $e = oci_error( $stmt );
536 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
537 return false;
538 }
539 } else {
540 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
541 $e = oci_error( $stmt );
542 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
543 }
544
545 if ( is_object( $val ) ) {
546 $val = $val->fetch();
547 }
548
549 if ( $col_type == 'BLOB' ) {
550 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
551 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB );
552 } else {
553 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
554 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
555 }
556 }
557 }
558
559 wfSuppressWarnings();
560
561 if ( oci_execute( $stmt, OCI_DEFAULT ) === false ) {
562 $e = oci_error( $stmt );
563 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
564 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
565 return false;
566 } else {
567 $this->mAffectedRows = oci_num_rows( $stmt );
568 }
569 } else {
570 $this->mAffectedRows = oci_num_rows( $stmt );
571 }
572
573 wfRestoreWarnings();
574
575 if ( isset( $lob ) ) {
576 foreach ( $lob as $lob_v ) {
577 $lob_v->free();
578 }
579 }
580
581 if ( !$this->mTrxLevel ) {
582 oci_commit( $this->mConn );
583 }
584
585 oci_free_statement( $stmt );
586 }
587
588 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
589 $insertOptions = array(), $selectOptions = array() )
590 {
591 $destTable = $this->tableName( $destTable );
592 if ( !is_array( $selectOptions ) ) {
593 $selectOptions = array( $selectOptions );
594 }
595 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
596 if ( is_array( $srcTable ) ) {
597 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
598 } else {
599 $srcTable = $this->tableName( $srcTable );
600 }
601
602 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
603 !isset( $varMap[$sequenceData['column']] ) )
604 {
605 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
606 }
607
608 // count-alias subselect fields to avoid abigious definition errors
609 $i = 0;
610 foreach ( $varMap as &$val ) {
611 $val = $val . ' field' . ( $i++ );
612 }
613
614 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
615 " SELECT $startOpts " . implode( ',', $varMap ) .
616 " FROM $srcTable $useIndex ";
617 if ( $conds != '*' ) {
618 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
619 }
620 $sql .= " $tailOpts";
621
622 if ( in_array( 'IGNORE', $insertOptions ) ) {
623 $this->ignore_DUP_VAL_ON_INDEX = true;
624 }
625
626 $retval = $this->query( $sql, $fname );
627
628 if ( in_array( 'IGNORE', $insertOptions ) ) {
629 $this->ignore_DUP_VAL_ON_INDEX = false;
630 }
631
632 return $retval;
633 }
634
635 function tableName( $name, $quoted ) {
636 /*
637 Replace reserved words with better ones
638 Using uppercase because that's the only way Oracle can handle
639 quoted tablenames
640 */
641 switch( $name ) {
642 case 'user':
643 $name = 'MWUSER';
644 break;
645 case 'text':
646 $name = 'PAGECONTENT';
647 break;
648 }
649
650 return parent::tableName( strtoupper( $name ), $quoted );
651 }
652
653 /**
654 * Return the next in a sequence, save the value for retrieval via insertId()
655 */
656 function nextSequenceValue( $seqName ) {
657 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
658 $row = $this->fetchRow( $res );
659 $this->mInsertId = $row[0];
660 return $this->mInsertId;
661 }
662
663 /**
664 * Return sequence_name if table has a sequence
665 */
666 private function getSequenceData( $table ) {
667 if ( $this->sequenceData == null ) {
668 $result = $this->doQuery( 'SELECT lower(us.sequence_name), lower(utc.table_name), lower(utc.column_name) from user_sequences us, user_tab_columns utc where us.sequence_name = utc.table_name||\'_\'||utc.column_name||\'_SEQ\'' );
669
670 while ( ( $row = $result->fetchRow() ) !== false ) {
671 $this->sequenceData[$this->tableName( $row[1] )] = array(
672 'sequence' => $row[0],
673 'column' => $row[2]
674 );
675 }
676 }
677
678 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
679 }
680
681 /**
682 * REPLACE query wrapper
683 * Oracle simulates this with a DELETE followed by INSERT
684 * $row is the row to insert, an associative array
685 * $uniqueIndexes is an array of indexes. Each element may be either a
686 * field name or an array of field names
687 *
688 * It may be more efficient to leave off unique indexes which are unlikely to collide.
689 * However if you do this, you run the risk of encountering errors which wouldn't have
690 * occurred in MySQL.
691 *
692 * @param $table String: table name
693 * @param $uniqueIndexes Array: array of indexes. Each element may be
694 * either a field name or an array of field names
695 * @param $rows Array: rows to insert to $table
696 * @param $fname String: function name, you can use __METHOD__ here
697 */
698 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
699 $table = $this->tableName( $table );
700
701 if ( count( $rows ) == 0 ) {
702 return;
703 }
704
705 # Single row case
706 if ( !is_array( reset( $rows ) ) ) {
707 $rows = array( $rows );
708 }
709
710 $sequenceData = $this->getSequenceData( $table );
711
712 foreach ( $rows as $row ) {
713 # Delete rows which collide
714 if ( $uniqueIndexes ) {
715 $condsDelete = array();
716 foreach ( $uniqueIndexes as $index ) {
717 $condsDelete[$index] = $row[$index];
718 }
719 if ( count( $condsDelete ) > 0 ) {
720 $this->delete( $table, $condsDelete, $fname );
721 }
722 }
723
724 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
725 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
726 }
727
728 # Now insert the row
729 $this->insert( $table, $row, $fname );
730 }
731 }
732
733 # DELETE where the condition is a join
734 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
735 if ( !$conds ) {
736 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
737 }
738
739 $delTable = $this->tableName( $delTable );
740 $joinTable = $this->tableName( $joinTable );
741 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
742 if ( $conds != '*' ) {
743 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
744 }
745 $sql .= ')';
746
747 $this->query( $sql, $fname );
748 }
749
750 # Returns the size of a text field, or -1 for "unlimited"
751 function textFieldSize( $table, $field ) {
752 $fieldInfoData = $this->fieldInfo( $table, $field );
753 return $fieldInfoData->maxLength();
754 }
755
756 function limitResult( $sql, $limit, $offset = false ) {
757 if ( $offset === false ) {
758 $offset = 0;
759 }
760 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
761 }
762
763 function encodeBlob( $b ) {
764 return new Blob( $b );
765 }
766
767 function decodeBlob( $b ) {
768 if ( $b instanceof Blob ) {
769 $b = $b->fetch();
770 }
771 return $b;
772 }
773
774 function unionQueries( $sqls, $all ) {
775 $glue = ' UNION ALL ';
776 return 'SELECT * ' . ( $all ? '':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
777 }
778
779 function wasDeadlock() {
780 return $this->lastErrno() == 'OCI-00060';
781 }
782
783 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
784 global $wgDBprefix;
785 $this->setFlag( DBO_DDLMODE );
786
787 $temporary = $temporary ? 'TRUE' : 'FALSE';
788
789 $newName = strtoupper( $newName );
790 $oldName = strtoupper( $oldName );
791
792 $tabName = $this->addIdentifierQuotes( substr( $newName, strlen( $wgDBprefix ) ) );
793 $oldPrefix = $this->addIdentifierQuotes( substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) ) );
794 $newPrefix = $this->addIdentifierQuotes( $wgDBprefix );
795
796 $this->clearFlag( DBO_DDLMODE );
797 return $this->doQuery( "BEGIN DUPLICATE_TABLE( $tabName, $oldPrefix, $newPrefix, $temporary ); END;" );
798 }
799
800 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
801 $listWhere = '';
802 if (!empty($prefix)) {
803 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
804 }
805
806 $result = $this->doQuery( "SELECT table_name FROM user_tables WHERE table_name NOT LIKE '%!_IDX$_' ESCAPE '!' $listWhere" );
807
808 // dirty code ... i know
809 $endArray = array();
810 $endArray[] = $prefix.'MWUSER';
811 $endArray[] = $prefix.'PAGE';
812 $endArray[] = $prefix.'IMAGE';
813 $fixedOrderTabs = $endArray;
814 while (($row = $result->fetchRow()) !== false) {
815 if (!in_array($row['table_name'], $fixedOrderTabs))
816 $endArray[] = $row['table_name'];
817 }
818
819 return $endArray;
820 }
821
822 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
823 $tableName = $this->tableName($tableName);
824 if( !$this->tableExists( $tableName ) ) {
825 return false;
826 }
827
828 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
829 }
830
831 function timestamp( $ts = 0 ) {
832 return wfTimestamp( TS_ORACLE, $ts );
833 }
834
835 /**
836 * Return aggregated value function call
837 */
838 function aggregateValue ( $valuedata, $valuename = 'value' ) {
839 return $valuedata;
840 }
841
842 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
843 # Ignore errors during error handling to avoid infinite
844 # recursion
845 $ignore = $this->ignoreErrors( true );
846 ++$this->mErrorCount;
847
848 if ( $ignore || $tempIgnore ) {
849 wfDebug( "SQL ERROR (ignored): $error\n" );
850 $this->ignoreErrors( $ignore );
851 } else {
852 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
853 }
854 }
855
856 /**
857 * @return string wikitext of a link to the server software's web site
858 */
859 public static function getSoftwareLink() {
860 return '[http://www.oracle.com/ Oracle]';
861 }
862
863 /**
864 * @return string Version information from the database
865 */
866 function getServerVersion() {
867 //better version number, fallback on driver
868 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
869 if ( !( $row = $rset->fetchRow() ) ) {
870 return oci_server_version( $this->mConn );
871 }
872 return $row['version'];
873 }
874
875 /**
876 * Query whether a given table exists (in the given schema, or the default mw one if not given)
877 */
878 function tableExists( $table ) {
879 $table = trim($this->tableName($table), '"');
880 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
881 $res = $this->doQuery( $SQL );
882 if ( $res ) {
883 $count = $res->numRows();
884 $res->free();
885 } else {
886 $count = 0;
887 }
888 return $count;
889 }
890
891 /**
892 * Function translates mysql_fetch_field() functionality on ORACLE.
893 * Caching is present for reducing query time.
894 * For internal calls. Use fieldInfo for normal usage.
895 * Returns false if the field doesn't exist
896 *
897 * @param $table Array
898 * @param $field String
899 * @return ORAField
900 */
901 private function fieldInfoMulti( $table, $field ) {
902 $field = strtoupper( $field );
903 if ( is_array( $table ) ) {
904 $table = array_map( array( &$this, 'tableName' ), $table );
905 $tableWhere = 'IN (';
906 foreach( $table as &$singleTable ) {
907 $singleTable = strtoupper( trim( $singleTable, '"' ) );
908 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
909 return $this->mFieldInfoCache["$singleTable.$field"];
910 }
911 $tableWhere .= '\'' . $singleTable . '\',';
912 }
913 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
914 } else {
915 $table = strtoupper( trim( $this->tableName( $table ), '"' ) );
916 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
917 return $this->mFieldInfoCache["$table.$field"];
918 }
919 $tableWhere = '= \''.$table.'\'';
920 }
921
922 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
923 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT ) === false ) {
924 $e = oci_error( $fieldInfoStmt );
925 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
926 return false;
927 }
928 $res = new ORAResult( $this, $fieldInfoStmt );
929 if ( $res->numRows() == 0 ) {
930 if ( is_array( $table ) ) {
931 foreach( $table as &$singleTable ) {
932 $this->mFieldInfoCache["$singleTable.$field"] = false;
933 }
934 } else {
935 $this->mFieldInfoCache["$table.$field"] = false;
936 }
937 $fieldInfoTemp = null;
938 } else {
939 $fieldInfoTemp = new ORAField( $res->fetchRow() );
940 $table = $fieldInfoTemp->tableName();
941 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
942 }
943 $res->free();
944 return $fieldInfoTemp;
945 }
946
947 /**
948 * @throws DBUnexpectedError
949 * @param $table
950 * @param $field
951 * @return ORAField
952 */
953 function fieldInfo( $table, $field ) {
954 if ( is_array( $table ) ) {
955 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
956 }
957 return $this->fieldInfoMulti ($table, $field);
958 }
959
960 function begin( $fname = '' ) {
961 $this->mTrxLevel = 1;
962 }
963
964 function commit( $fname = '' ) {
965 oci_commit( $this->mConn );
966 $this->mTrxLevel = 0;
967 }
968
969 /* Not even sure why this is used in the main codebase... */
970 function limitResultForUpdate( $sql, $num ) {
971 return $sql;
972 }
973
974 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
975 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
976 $cmd = '';
977 $done = false;
978 $dollarquote = false;
979
980 $replacements = array();
981
982 while ( ! feof( $fp ) ) {
983 if ( $lineCallback ) {
984 call_user_func( $lineCallback );
985 }
986 $line = trim( fgets( $fp, 1024 ) );
987 $sl = strlen( $line ) - 1;
988
989 if ( $sl < 0 ) {
990 continue;
991 }
992 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
993 continue;
994 }
995
996 // Allow dollar quoting for function declarations
997 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
998 if ( $dollarquote ) {
999 $dollarquote = false;
1000 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1001 $done = true;
1002 } else {
1003 $dollarquote = true;
1004 }
1005 } elseif ( !$dollarquote ) {
1006 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1007 $done = true;
1008 $line = substr( $line, 0, $sl );
1009 }
1010 }
1011
1012 if ( $cmd != '' ) {
1013 $cmd .= ' ';
1014 }
1015 $cmd .= "$line\n";
1016
1017 if ( $done ) {
1018 $cmd = str_replace( ';;', ";", $cmd );
1019 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1020 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1021 $replacements[$defines[2]] = $defines[1];
1022 }
1023 } else {
1024 foreach ( $replacements as $mwVar => $scVar ) {
1025 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1026 }
1027
1028 $cmd = $this->replaceVars( $cmd );
1029 $res = $this->doQuery( $cmd );
1030 if ( $resultCallback ) {
1031 call_user_func( $resultCallback, $res, $this );
1032 }
1033
1034 if ( false === $res ) {
1035 $err = $this->lastError();
1036 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1037 }
1038 }
1039
1040 $cmd = '';
1041 $done = false;
1042 }
1043 }
1044 return true;
1045 }
1046
1047 function selectDB( $db ) {
1048 $this->mDBname = $db;
1049 if ( $db == null || $db == $this->mUser ) {
1050 return true;
1051 }
1052 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1053 $stmt = oci_parse( $this->mConn, $sql );
1054 wfSuppressWarnings();
1055 $success = oci_execute( $stmt );
1056 wfRestoreWarnings();
1057 if ( !$success ) {
1058 $e = oci_error( $stmt );
1059 if ( $e['code'] != '1435' ) {
1060 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1061 }
1062 return false;
1063 }
1064 return true;
1065 }
1066
1067 function strencode( $s ) {
1068 return str_replace( "'", "''", $s );
1069 }
1070
1071 function addQuotes( $s ) {
1072 global $wgContLang;
1073 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1074 $s = $wgContLang->checkTitleEncoding( $s );
1075 }
1076 return "'" . $this->strencode( $s ) . "'";
1077 }
1078
1079 public function addIdentifierQuotes( $s ) {
1080 return parent::addIdentifierQuotes( $s );
1081
1082 /* Does this old code make any sense?
1083 * We could always use quoted identifier.
1084 * See http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/sql_elements008.htm
1085 */
1086 if ( !$this->mFlags & DBO_DDLMODE ) {
1087 $s = '"' . str_replace( '"', '""', $s ) . '"';
1088 }
1089 return $s;
1090 }
1091
1092 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1093 global $wgContLang;
1094
1095 if ($conds != null) {
1096 $conds2 = array();
1097 $conds = ( !is_array( $conds ) ) ? array( $conds ) : $conds;
1098 foreach ( $conds as $col => $val ) {
1099 $col_info = $this->fieldInfoMulti( $table, $col );
1100 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1101 if ( $col_type == 'CLOB' ) {
1102 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1103 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1104 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1105 } else {
1106 $conds2[$col] = $val;
1107 }
1108 }
1109
1110 return parent::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1111 } else {
1112 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1113 }
1114 }
1115
1116 /**
1117 * Returns an optional USE INDEX clause to go after the table, and a
1118 * string to go at the end of the query
1119 *
1120 * @private
1121 *
1122 * @param $options Array: an associative array of options to be turned into
1123 * an SQL query, valid keys are listed in the function.
1124 * @return array
1125 */
1126 function makeSelectOptions( $options ) {
1127 $preLimitTail = $postLimitTail = '';
1128 $startOpts = '';
1129
1130 $noKeyOptions = array();
1131 foreach ( $options as $key => $option ) {
1132 if ( is_numeric( $key ) ) {
1133 $noKeyOptions[$option] = true;
1134 }
1135 }
1136
1137 if ( isset( $options['GROUP BY'] ) ) {
1138 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1139 }
1140 if ( isset( $options['ORDER BY'] ) ) {
1141 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1142 }
1143
1144 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1145 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1146 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1147 $startOpts .= 'DISTINCT';
1148 }
1149
1150 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1151 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1152 } else {
1153 $useIndex = '';
1154 }
1155
1156 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1157 }
1158
1159 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1160 global $wgContLang;
1161
1162 if ( $wgContLang != null && $conds != null && $conds != '*' ) {
1163 $conds2 = array();
1164 $conds = ( !is_array( $conds ) ) ? array( $conds ) : $conds;
1165 foreach ( $conds as $col => $val ) {
1166 $col_info = $this->fieldInfoMulti( $table, $col );
1167 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1168 if ( $col_type == 'CLOB' ) {
1169 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1170 } else {
1171 if ( is_array( $val ) ) {
1172 $conds2[$col] = $val;
1173 foreach ( $conds2[$col] as &$val2 ) {
1174 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1175 }
1176 } else {
1177 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1178 }
1179 }
1180 }
1181
1182 return parent::delete( $table, $conds2, $fname );
1183 } else {
1184 return parent::delete( $table, $conds, $fname );
1185 }
1186 }
1187
1188 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1189 global $wgContLang;
1190
1191 $table = $this->tableName( $table );
1192 $opts = $this->makeUpdateOptions( $options );
1193 $sql = "UPDATE $opts $table SET ";
1194
1195 $first = true;
1196 foreach ( $values as $col => &$val ) {
1197 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1198
1199 if ( !$first ) {
1200 $sqlSet = ', ' . $sqlSet;
1201 } else {
1202 $first = false;
1203 }
1204 $sql .= $sqlSet;
1205 }
1206
1207 if ( $conds != '*' ) {
1208 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1209 }
1210
1211 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1212 $e = oci_error( $this->mConn );
1213 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1214 return false;
1215 }
1216 foreach ( $values as $col => &$val ) {
1217 $col_info = $this->fieldInfoMulti( $table, $col );
1218 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1219
1220 if ( $val === null ) {
1221 // do nothing ... null was inserted in statement creation
1222 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1223 if ( is_object( $val ) ) {
1224 $val = $val->getData();
1225 }
1226
1227 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1228 $val = '31-12-2030 12:00:00.000000';
1229 }
1230
1231 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1232 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1233 $e = oci_error( $stmt );
1234 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1235 return false;
1236 }
1237 } else {
1238 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1239 $e = oci_error( $stmt );
1240 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1241 }
1242
1243 if ( $col_type == 'BLOB' ) {
1244 $lob[$col]->writeTemporary( $val );
1245 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1246 } else {
1247 $lob[$col]->writeTemporary( $val );
1248 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1249 }
1250 }
1251 }
1252
1253 wfSuppressWarnings();
1254
1255 if ( oci_execute( $stmt, OCI_DEFAULT ) === false ) {
1256 $e = oci_error( $stmt );
1257 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1258 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1259 return false;
1260 } else {
1261 $this->mAffectedRows = oci_num_rows( $stmt );
1262 }
1263 } else {
1264 $this->mAffectedRows = oci_num_rows( $stmt );
1265 }
1266
1267 wfRestoreWarnings();
1268
1269 if ( isset( $lob ) ) {
1270 foreach ( $lob as $lob_v ) {
1271 $lob_v->free();
1272 }
1273 }
1274
1275 if ( !$this->mTrxLevel ) {
1276 oci_commit( $this->mConn );
1277 }
1278
1279 oci_free_statement( $stmt );
1280 }
1281
1282 function bitNot( $field ) {
1283 // expecting bit-fields smaller than 4bytes
1284 return 'BITNOT(' . $field . ')';
1285 }
1286
1287 function bitAnd( $fieldLeft, $fieldRight ) {
1288 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1289 }
1290
1291 function bitOr( $fieldLeft, $fieldRight ) {
1292 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1293 }
1294
1295 function setFakeMaster( $enabled = true ) { }
1296
1297 function getDBname() {
1298 return $this->mDBname;
1299 }
1300
1301 function getServer() {
1302 return $this->mServer;
1303 }
1304
1305 public function getSearchEngine() {
1306 return 'SearchOracle';
1307 }
1308 } // end DatabaseOracle class