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