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