More unused globals
[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 function array_unique_md( $array_in ) {
36 $array_out = array();
37 $array_hashes = array();
38
39 foreach ( $array_in as $key => $item ) {
40 $hash = md5( serialize( $item ) );
41 if ( !isset( $array_hashes[$hash] ) ) {
42 $array_hashes[$hash] = $hash;
43 $array_out[] = $item;
44 }
45 }
46
47 return $array_out;
48 }
49
50 function __construct( &$db, $stmt, $unique = false ) {
51 $this->db =& $db;
52
53 if ( ( $this->nrows = oci_fetch_all( $stmt, $this->rows, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM ) ) === false ) {
54 $e = oci_error( $stmt );
55 $db->reportQueryError( $e['message'], $e['code'], '', __FUNCTION__ );
56 return;
57 }
58
59 if ( $unique ) {
60 $this->rows = $this->array_unique_md( $this->rows );
61 $this->nrows = count( $this->rows );
62 }
63
64 $this->cursor = 0;
65 $this->stmt = $stmt;
66 }
67
68 public function free() {
69 oci_free_statement( $this->stmt );
70 }
71
72 public function seek( $row ) {
73 $this->cursor = min( $row, $this->nrows );
74 }
75
76 public function numRows() {
77 return $this->nrows;
78 }
79
80 public function numFields() {
81 return oci_num_fields( $this->stmt );
82 }
83
84 public function fetchObject() {
85 if ( $this->cursor >= $this->nrows ) {
86 return false;
87 }
88 $row = $this->rows[$this->cursor++];
89 $ret = new stdClass();
90 foreach ( $row as $k => $v ) {
91 $lc = strtolower( oci_field_name( $this->stmt, $k + 1 ) );
92 $ret->$lc = $v;
93 }
94
95 return $ret;
96 }
97
98 public function fetchRow() {
99 if ( $this->cursor >= $this->nrows ) {
100 return false;
101 }
102
103 $row = $this->rows[$this->cursor++];
104 $ret = array();
105 foreach ( $row as $k => $v ) {
106 $lc = strtolower( oci_field_name( $this->stmt, $k + 1 ) );
107 $ret[$lc] = $v;
108 $ret[$k] = $v;
109 }
110 return $ret;
111 }
112 }
113
114 /**
115 * Utility class.
116 * @ingroup Database
117 */
118 class ORAField {
119 private $name, $tablename, $default, $max_length, $nullable,
120 $is_pk, $is_unique, $is_multiple, $is_key, $type;
121
122 function __construct( $info ) {
123 $this->name = $info['column_name'];
124 $this->tablename = $info['table_name'];
125 $this->default = $info['data_default'];
126 $this->max_length = $info['data_length'];
127 $this->nullable = $info['not_null'];
128 $this->is_pk = isset( $info['prim'] ) && $info['prim'] == 1 ? 1 : 0;
129 $this->is_unique = isset( $info['uniq'] ) && $info['uniq'] == 1 ? 1 : 0;
130 $this->is_multiple = isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ? 1 : 0;
131 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
132 $this->type = $info['data_type'];
133 }
134
135 function name() {
136 return $this->name;
137 }
138
139 function tableName() {
140 return $this->tablename;
141 }
142
143 function defaultValue() {
144 return $this->default;
145 }
146
147 function maxLength() {
148 return $this->max_length;
149 }
150
151 function nullable() {
152 return $this->nullable;
153 }
154
155 function isKey() {
156 return $this->is_key;
157 }
158
159 function isMultipleKey() {
160 return $this->is_multiple;
161 }
162
163 function type() {
164 return $this->type;
165 }
166 }
167
168 /**
169 * @ingroup Database
170 */
171 class DatabaseOracle extends DatabaseBase {
172 var $mInsertId = null;
173 var $mLastResult = null;
174 var $numeric_version = null;
175 var $lastResult = null;
176 var $cursor = 0;
177 var $mAffectedRows;
178
179 var $ignore_DUP_VAL_ON_INDEX = false;
180 var $sequenceData = null;
181
182 var $defaultCharset = 'AL32UTF8';
183
184 var $mFieldInfoCache = array();
185
186 function __construct( $server = false, $user = false, $password = false, $dbName = false,
187 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' )
188 {
189 $tablePrefix = $tablePrefix == 'get from global' ? $tablePrefix : strtoupper( $tablePrefix );
190 parent::__construct( $server, $user, $password, $dbName, $failFunction, $flags, $tablePrefix );
191 wfRunHooks( 'DatabaseOraclePostInit', array( &$this ) );
192 }
193
194 function getType() {
195 return 'oracle';
196 }
197
198 function cascadingDeletes() {
199 return true;
200 }
201 function cleanupTriggers() {
202 return true;
203 }
204 function strictIPs() {
205 return true;
206 }
207 function realTimestamps() {
208 return true;
209 }
210 function implicitGroupby() {
211 return false;
212 }
213 function implicitOrderby() {
214 return false;
215 }
216 function searchableIPs() {
217 return true;
218 }
219
220 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
221 {
222 return new DatabaseOracle( $server, $user, $password, $dbName, $failFunction, $flags );
223 }
224
225 /**
226 * Usually aborts on failure
227 * If the failFunction is set to a non-zero integer, returns success
228 */
229 function open( $server, $user, $password, $dbName ) {
230 if ( !function_exists( 'oci_connect' ) ) {
231 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" );
232 }
233
234 $this->close();
235 $this->mServer = $server;
236 $this->mUser = $user;
237 $this->mPassword = $password;
238 $this->mDBname = $dbName;
239
240 if ( !strlen( $user ) ) { # e.g. the class is being loaded
241 return;
242 }
243
244 $session_mode = $this->mFlags & DBO_SYSDBA ? OCI_SYSDBA : OCI_DEFAULT;
245 if ( $this->mFlags & DBO_DEFAULT ) {
246 $this->mConn = oci_new_connect( $user, $password, $dbName, $this->defaultCharset, $session_mode );
247 } else {
248 $this->mConn = oci_connect( $user, $password, $dbName, $this->defaultCharset, $session_mode );
249 }
250
251 if ( !$this->mConn ) {
252 wfDebug( "DB connection error\n" );
253 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
254 wfDebug( $this->lastError() . "\n" );
255 return false;
256 }
257
258 $this->mOpened = true;
259
260 # removed putenv calls because they interfere with the system globaly
261 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
262 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
263 return $this->mConn;
264 }
265
266 /**
267 * Closes a database connection, if it is open
268 * Returns success, true if already closed
269 */
270 function close() {
271 $this->mOpened = false;
272 if ( $this->mConn ) {
273 return oci_close( $this->mConn );
274 } else {
275 return true;
276 }
277 }
278
279 function execFlags() {
280 return $this->mTrxLevel ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
281 }
282
283 function doQuery( $sql ) {
284 wfDebug( "SQL: [$sql]\n" );
285 if ( !mb_check_encoding( $sql ) ) {
286 throw new MWException( "SQL encoding is invalid\n$sql" );
287 }
288
289 // handle some oracle specifics
290 // remove AS column/table/subquery namings
291 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
292 $sql = preg_replace( '/ as /i', ' ', $sql );
293 }
294 // Oracle has issues with UNION clause if the statement includes LOB fields
295 // So we do a UNION ALL and then filter the results array with array_unique
296 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
297 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
298 // you have to select data from plan table after explain
299 $explain_id = date( 'dmYHis' );
300
301 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
302
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, __FUNCTION__ );
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, __FUNCTION__ );
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 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
563
564 // count-alias subselect fields to avoid abigious definition errors
565 $i = 0;
566 foreach ( $varMap as $key => &$val ) {
567 $val = $val . ' field' . ( $i++ );
568 }
569
570 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
571 " SELECT $startOpts " . implode( ',', $varMap ) .
572 " FROM $srcTable $useIndex ";
573 if ( $conds != '*' ) {
574 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
575 }
576 $sql .= " $tailOpts";
577
578 if ( in_array( 'IGNORE', $insertOptions ) ) {
579 $this->ignore_DUP_VAL_ON_INDEX = true;
580 }
581
582 $retval = $this->query( $sql, $fname );
583
584 if ( in_array( 'IGNORE', $insertOptions ) ) {
585 $this->ignore_DUP_VAL_ON_INDEX = false;
586 }
587
588 return $retval;
589 }
590
591 function tableName( $name ) {
592 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
593 /*
594 Replace reserved words with better ones
595 Using uppercase because that's the only way Oracle can handle
596 quoted tablenames
597 */
598 switch( $name ) {
599 case 'user':
600 $name = 'MWUSER';
601 break;
602 case 'text':
603 $name = 'PAGECONTENT';
604 break;
605 }
606
607 /*
608 The rest of procedure is equal to generic Databse class
609 except for the quoting style
610 */
611 if ( $name[0] == '"' && substr( $name, - 1, 1 ) == '"' ) {
612 return $name;
613 }
614 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
615 return $name;
616 }
617 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
618 if ( isset( $dbDetails[1] ) ) {
619 @list( $table, $database ) = $dbDetails;
620 } else {
621 @list( $table ) = $dbDetails;
622 }
623
624 $prefix = $this->mTablePrefix;
625
626 if ( isset( $database ) ) {
627 $table = ( $table[0] == '`' ? $table : "`{$table}`" );
628 }
629
630 if ( !isset( $database ) && isset( $wgSharedDB ) && $table[0] != '"'
631 && isset( $wgSharedTables )
632 && is_array( $wgSharedTables )
633 && in_array( $table, $wgSharedTables )
634 ) {
635 $database = $wgSharedDB;
636 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
637 }
638
639 if ( isset( $database ) ) {
640 $database = ( $database[0] == '"' ? $database : "\"{$database}\"" );
641 }
642 $table = ( $table[0] == '"' ? $table : "\"{$prefix}{$table}\"" );
643
644 $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
645
646 return strtoupper( $tableName );
647 }
648
649 /**
650 * Return the next in a sequence, save the value for retrieval via insertId()
651 */
652 function nextSequenceValue( $seqName ) {
653 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
654 $row = $this->fetchRow( $res );
655 $this->mInsertId = $row[0];
656 $this->freeResult( $res );
657 return $this->mInsertId;
658 }
659
660 /**
661 * Return sequence_name if table has a sequence
662 */
663 private function getSequenceData( $table ) {
664 if ( $this->sequenceData == null ) {
665 $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'" );
666
667 while ( ( $row = $result->fetchRow() ) !== false ) {
668 $this->sequenceData[$this->tableName( $row[1] )] = array(
669 'sequence' => $row[0],
670 'column' => $row[2]
671 );
672 }
673 }
674
675 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
676 }
677
678 # REPLACE query wrapper
679 # Oracle simulates this with a DELETE followed by INSERT
680 # $row is the row to insert, an associative array
681 # $uniqueIndexes is an array of indexes. Each element may be either a
682 # field name or an array of field names
683 #
684 # It may be more efficient to leave off unique indexes which are unlikely to collide.
685 # However if you do this, you run the risk of encountering errors which wouldn't have
686 # occurred in MySQL
687 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
688 $table = $this->tableName( $table );
689
690 if ( count( $rows ) == 0 ) {
691 return;
692 }
693
694 # Single row case
695 if ( !is_array( reset( $rows ) ) ) {
696 $rows = array( $rows );
697 }
698
699 $sequenceData = $this->getSequenceData( $table );
700
701 foreach ( $rows as $row ) {
702 # Delete rows which collide
703 if ( $uniqueIndexes ) {
704 $condsDelete = array();
705 foreach ( $uniqueIndexes as $index )
706 $condsDelete[$index] = $row[$index];
707 if (count($condsDelete) > 0) {
708 $this->delete( $table, $condsDelete, $fname );
709 }
710 }
711
712 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
713 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
714 }
715
716 # Now insert the row
717 $this->insert( $table, $row, $fname );
718 }
719 }
720
721 # DELETE where the condition is a join
722 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseOracle::deleteJoin" ) {
723 if ( !$conds ) {
724 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
725 }
726
727 $delTable = $this->tableName( $delTable );
728 $joinTable = $this->tableName( $joinTable );
729 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
730 if ( $conds != '*' ) {
731 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
732 }
733 $sql .= ')';
734
735 $this->query( $sql, $fname );
736 }
737
738 # Returns the size of a text field, or -1 for "unlimited"
739 function textFieldSize( $table, $field ) {
740 $fieldInfoData = $this->fieldInfo( $table, $field);
741 if ( $fieldInfoData->type == "varchar" ) {
742 $size = $row->size - 4;
743 } else {
744 $size = $row->size;
745 }
746 return $size;
747 }
748
749 function limitResult( $sql, $limit, $offset = false ) {
750 if ( $offset === false ) {
751 $offset = 0;
752 }
753 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
754 }
755
756
757 function unionQueries( $sqls, $all ) {
758 $glue = ' UNION ALL ';
759 return 'SELECT * ' . ( $all ? '':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
760 }
761
762 function wasDeadlock() {
763 return $this->lastErrno() == 'OCI-00060';
764 }
765
766
767 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
768 $temporary = $temporary ? 'TRUE' : 'FALSE';
769 $oldName = trim(strtoupper($oldName), '"');
770 $oldParts = explode('_', $oldName);
771
772 $newName = trim(strtoupper($newName), '"');
773 $newParts = explode('_', $newName);
774
775 $oldPrefix = '';
776 $newPrefix = '';
777 for ($i = count($oldParts)-1; $i >= 0; $i--) {
778 if ($oldParts[$i] != $newParts[$i]) {
779 $oldPrefix = implode('_', $oldParts).'_';
780 $newPrefix = implode('_', $newParts).'_';
781 break;
782 }
783 unset($oldParts[$i]);
784 unset($newParts[$i]);
785 }
786
787 $tabName = substr($oldName, strlen($oldPrefix));
788
789 return $this->query( 'BEGIN DUPLICATE_TABLE(\'' . $tabName . '\', \'' . $oldPrefix . '\', \''.$newPrefix.'\', ' . $temporary . '); END;', $fname );
790 }
791
792 function timestamp( $ts = 0 ) {
793 return wfTimestamp( TS_ORACLE, $ts );
794 }
795
796 /**
797 * Return aggregated value function call
798 */
799 function aggregateValue ( $valuedata, $valuename = 'value' ) {
800 return $valuedata;
801 }
802
803 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
804 # Ignore errors during error handling to avoid infinite
805 # recursion
806 $ignore = $this->ignoreErrors( true );
807 ++$this->mErrorCount;
808
809 if ( $ignore || $tempIgnore ) {
810 wfDebug( "SQL ERROR (ignored): $error\n" );
811 $this->ignoreErrors( $ignore );
812 } else {
813 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
814 }
815 }
816
817 /**
818 * @return string wikitext of a link to the server software's web site
819 */
820 function getSoftwareLink() {
821 return '[http://www.oracle.com/ Oracle]';
822 }
823
824 /**
825 * @return string Version information from the database
826 */
827 function getServerVersion() {
828 return oci_server_version( $this->mConn );
829 }
830
831 /**
832 * Query whether a given table exists (in the given schema, or the default mw one if not given)
833 */
834 function tableExists( $table ) {
835 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
836 $res = $this->doQuery( $SQL );
837 if ( $res ) {
838 $count = $res->numRows();
839 $res->free();
840 } else {
841 $count = 0;
842 }
843 return $count;
844 }
845
846 /**
847 * Function translates mysql_fetch_field() functionality on ORACLE.
848 * Caching is present for reducing query time.
849 * For internal calls. Use fieldInfo for normal usage.
850 * Returns false if the field doesn't exist
851 *
852 * @param $table Array
853 * @param $field String
854 */
855 private function fieldInfoMulti( $table, $field ) {
856 $tableWhere = '';
857 $field = strtoupper($field);
858 if (is_array($table)) {
859 $table = array_map( array( &$this, 'tableName' ), $table );
860 $tableWhere = 'IN (';
861 foreach($table as &$singleTable) {
862 $singleTable = strtoupper(trim( $singleTable, '"' ));
863 if (isset($this->mFieldInfoCache["$singleTable.$field"])) {
864 return $this->mFieldInfoCache["$singleTable.$field"];
865 }
866 $tableWhere .= '\''.$singleTable.'\',';
867 }
868 $tableWhere = rtrim($tableWhere, ',').')';
869 } else {
870 $table = strtoupper(trim( $this->tableName($table), '"' ));
871 if (isset($this->mFieldInfoCache["$table.$field"])) {
872 return $this->mFieldInfoCache["$table.$field"];
873 }
874 $tableWhere = '= \''.$table.'\'';
875 }
876
877 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
878 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT ) === false ) {
879 $e = oci_error( $fieldInfoStmt );
880 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
881 return false;
882 }
883 $res = new ORAResult( $this, $fieldInfoStmt );
884 if ($res->numRows() == 0 ) {
885 if (is_array($table)) {
886 foreach($table as &$singleTable) {
887 $this->mFieldInfoCache["$singleTable.$field"] = false;
888 }
889 } else {
890 $this->mFieldInfoCache["$table.$field"] = false;
891 }
892 } else {
893 $fieldInfoTemp = new ORAField( $res->fetchRow() );
894 $table = $fieldInfoTemp->tableName();
895 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
896 return $fieldInfoTemp;
897 }
898 }
899
900 function fieldInfo( $table, $field ) {
901 if ( is_array( $table ) ) {
902 throw new DBUnexpectedError( $this, 'Database::fieldInfo called with table array!' );
903 }
904 return $this->fieldInfoMulti ($table, $field);
905 }
906
907 function begin( $fname = '' ) {
908 $this->mTrxLevel = 1;
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 $res = $this->sourceFile( "../maintenance/ora/tables.sql" );
995 if ($res === true) {
996 print " done.</li>\n";
997 } else {
998 print " <b>FAILED</b></li>\n";
999 dieout( htmlspecialchars( $res ) );
1000 }
1001
1002 // Avoid the non-standard "REPLACE INTO" syntax
1003 echo "<li>Populating interwiki table</li>\n";
1004 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1005 if ( !$f ) {
1006 dieout( "Could not find the interwiki.sql file" );
1007 }
1008
1009 // do it like the postgres :D
1010 $SQL = "INSERT INTO ".$this->tableName('interwiki')." (iw_prefix,iw_url,iw_local) VALUES ";
1011 while ( !feof( $f ) ) {
1012 $line = fgets( $f, 1024 );
1013 $matches = array();
1014 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) {
1015 continue;
1016 }
1017 $this->query( "$SQL $matches[1],$matches[2])" );
1018 }
1019
1020 echo "<li>Table interwiki successfully populated</li>\n";
1021 }
1022
1023 function strencode( $s ) {
1024 return str_replace( "'", "''", $s );
1025 }
1026
1027 function addQuotes( $s ) {
1028 global $wgContLang;
1029 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1030 $s = $wgContLang->checkTitleEncoding( $s );
1031 }
1032 return "'" . $this->strencode( $s ) . "'";
1033 }
1034
1035 function quote_ident( $s ) {
1036 return $s;
1037 }
1038
1039 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1040 global $wgContLang;
1041
1042 $conds2 = array();
1043 $conds = ($conds != null && !is_array($conds)) ? array($conds) : $conds;
1044 foreach ( $conds as $col => $val ) {
1045 $col_info = $this->fieldInfoMulti( $table, $col );
1046 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1047 if ( $col_type == 'CLOB' ) {
1048 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1049 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1050 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1051 } else {
1052 $conds2[$col] = $val;
1053 }
1054 }
1055
1056 return parent::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1057 }
1058
1059 /**
1060 * Returns an optional USE INDEX clause to go after the table, and a
1061 * string to go at the end of the query
1062 *
1063 * @private
1064 *
1065 * @param $options Array: an associative array of options to be turned into
1066 * an SQL query, valid keys are listed in the function.
1067 * @return array
1068 */
1069 function makeSelectOptions( $options ) {
1070 $preLimitTail = $postLimitTail = '';
1071 $startOpts = '';
1072
1073 $noKeyOptions = array();
1074 foreach ( $options as $key => $option ) {
1075 if ( is_numeric( $key ) ) {
1076 $noKeyOptions[$option] = true;
1077 }
1078 }
1079
1080 if ( isset( $options['GROUP BY'] ) ) {
1081 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1082 }
1083 if ( isset( $options['ORDER BY'] ) ) {
1084 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1085 }
1086
1087 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1088 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1089 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1090 $startOpts .= 'DISTINCT';
1091 }
1092
1093 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1094 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1095 } else {
1096 $useIndex = '';
1097 }
1098
1099 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1100 }
1101
1102 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1103 global $wgContLang;
1104
1105 if ( $wgContLang != null ) {
1106 $conds2 = array();
1107 $conds = ($conds != null && !is_array($conds)) ? array($conds) : $conds;
1108 foreach ( $conds as $col => $val ) {
1109 $col_info = $this->fieldInfoMulti( $table, $col );
1110 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1111 if ( $col_type == 'CLOB' ) {
1112 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1113 } else {
1114 if ( is_array( $val ) ) {
1115 $conds2[$col] = $val;
1116 foreach ( $conds2[$col] as &$val2 ) {
1117 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1118 }
1119 } else {
1120 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1121 }
1122 }
1123 }
1124
1125 return parent::delete( $table, $conds2, $fname );
1126 } else {
1127 return parent::delete( $table, $conds, $fname );
1128 }
1129 }
1130
1131 function bitNot( $field ) {
1132 // expecting bit-fields smaller than 4bytes
1133 return 'BITNOT(' . $bitField . ')';
1134 }
1135
1136 function bitAnd( $fieldLeft, $fieldRight ) {
1137 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1138 }
1139
1140 function bitOr( $fieldLeft, $fieldRight ) {
1141 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1142 }
1143
1144 function setFakeMaster( $enabled = true ) { }
1145
1146 function getDBname() {
1147 return $this->mDBname;
1148 }
1149
1150 function getServer() {
1151 return $this->mServer;
1152 }
1153
1154 public function replaceVars( $ins ) {
1155 $varnames = array( 'wgDBprefix' );
1156 if ( $this->mFlags & DBO_SYSDBA ) {
1157 $varnames[] = 'wgDBOracleDefTS';
1158 $varnames[] = 'wgDBOracleTempTS';
1159 }
1160
1161 // Ordinary variables
1162 foreach ( $varnames as $var ) {
1163 if ( isset( $GLOBALS[$var] ) ) {
1164 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1165 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1166 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1167 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1168 }
1169 }
1170
1171 return parent::replaceVars( $ins );
1172 }
1173
1174 public function getSearchEngine() {
1175 return 'SearchOracle';
1176 }
1177 } // end DatabaseOracle class