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