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