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