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