And while I'm at it: removed unused global declarations of $wgFeedClasses
[lhc/web/wiklou.git] / includes / db / DatabaseOracle.php
1 <?php
2 /**
3 * @ingroup Database
4 * @file
5 */
6
7 /**
8 * This is the Oracle database abstraction layer.
9 * @ingroup Database
10 */
11 class ORABlob {
12 var $mData;
13
14 function __construct( $data ) {
15 $this->mData = $data;
16 }
17
18 function getData() {
19 return $this->mData;
20 }
21 }
22
23 /**
24 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
25 * other things. We use a wrapper class to handle that and other
26 * Oracle-specific bits, like converting column names back to lowercase.
27 * @ingroup Database
28 */
29 class ORAResult {
30 private $rows;
31 private $cursor;
32 private $stmt;
33 private $nrows;
34
35 private $unique;
36 private function array_unique_md( $array_in ) {
37 $array_out = array();
38 $array_hashes = array();
39
40 foreach ( $array_in as $key => $item ) {
41 $hash = md5( serialize( $item ) );
42 if ( !isset( $array_hashes[$hash] ) ) {
43 $array_hashes[$hash] = $hash;
44 $array_out[] = $item;
45 }
46 }
47
48 return $array_out;
49 }
50
51 function __construct( &$db, $stmt, $unique = false ) {
52 $this->db =& $db;
53
54 if ( ( $this->nrows = oci_fetch_all( $stmt, $this->rows, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM ) ) === false ) {
55 $e = oci_error( $stmt );
56 $db->reportQueryError( $e['message'], $e['code'], '', __FUNCTION__ );
57 return;
58 }
59
60 if ( $unique ) {
61 $this->rows = $this->array_unique_md( $this->rows );
62 $this->nrows = count( $this->rows );
63 }
64
65 $this->cursor = 0;
66 $this->stmt = $stmt;
67 }
68
69 public function free() {
70 oci_free_statement( $this->stmt );
71 }
72
73 public function seek( $row ) {
74 $this->cursor = min( $row, $this->nrows );
75 }
76
77 public function numRows() {
78 return $this->nrows;
79 }
80
81 public function numFields() {
82 return oci_num_fields( $this->stmt );
83 }
84
85 public function fetchObject() {
86 if ( $this->cursor >= $this->nrows ) {
87 return false;
88 }
89 $row = $this->rows[$this->cursor++];
90 $ret = new stdClass();
91 foreach ( $row as $k => $v ) {
92 $lc = strtolower( oci_field_name( $this->stmt, $k + 1 ) );
93 $ret->$lc = $v;
94 }
95
96 return $ret;
97 }
98
99 public function fetchRow() {
100 if ( $this->cursor >= $this->nrows ) {
101 return false;
102 }
103
104 $row = $this->rows[$this->cursor++];
105 $ret = array();
106 foreach ( $row as $k => $v ) {
107 $lc = strtolower( oci_field_name( $this->stmt, $k + 1 ) );
108 $ret[$lc] = $v;
109 $ret[$k] = $v;
110 }
111 return $ret;
112 }
113 }
114
115 /**
116 * Utility class.
117 * @ingroup Database
118 */
119 class ORAField {
120 private $name, $tablename, $default, $max_length, $nullable,
121 $is_pk, $is_unique, $is_multiple, $is_key, $type;
122
123 function __construct( $info ) {
124 $this->name = $info['column_name'];
125 $this->tablename = $info['table_name'];
126 $this->default = $info['data_default'];
127 $this->max_length = $info['data_length'];
128 $this->nullable = $info['not_null'];
129 $this->is_pk = isset( $info['prim'] ) && $info['prim'] == 1 ? 1 : 0;
130 $this->is_unique = isset( $info['uniq'] ) && $info['uniq'] == 1 ? 1 : 0;
131 $this->is_multiple = isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ? 1 : 0;
132 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
133 $this->type = $info['data_type'];
134 }
135
136 function name() {
137 return $this->name;
138 }
139
140 function tableName() {
141 return $this->tablename;
142 }
143
144 function defaultValue() {
145 return $this->default;
146 }
147
148 function maxLength() {
149 return $this->max_length;
150 }
151
152 function nullable() {
153 return $this->nullable;
154 }
155
156 function isKey() {
157 return $this->is_key;
158 }
159
160 function isMultipleKey() {
161 return $this->is_multiple;
162 }
163
164 function type() {
165 return $this->type;
166 }
167 }
168
169 /**
170 * @ingroup Database
171 */
172 class DatabaseOracle extends DatabaseBase {
173 var $mInsertId = null;
174 var $mLastResult = null;
175 var $numeric_version = null;
176 var $lastResult = null;
177 var $cursor = 0;
178 var $mAffectedRows;
179
180 var $ignore_DUP_VAL_ON_INDEX = false;
181 var $sequenceData = null;
182
183 var $defaultCharset = 'AL32UTF8';
184
185 var $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 == false ) {
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
305 wfSuppressWarnings();
306
307 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
308 $e = oci_error( $this->mConn );
309 $this->reportQueryError( $e['message'], $e['code'], $sql, __FUNCTION__ );
310 }
311
312 if ( oci_execute( $stmt, $this->execFlags() ) == false ) {
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 }
317 }
318
319 wfRestoreWarnings();
320
321 if ( $explain_count > 0 ) {
322 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
323 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
324 return new ORAResult( $this, $stmt, $union_unique );
325 } else {
326 $this->mAffectedRows = oci_num_rows( $stmt );
327 return true;
328 }
329 }
330
331 function queryIgnore( $sql, $fname = '' ) {
332 return $this->query( $sql, $fname, true );
333 }
334
335 function freeResult( $res ) {
336 if ( $res instanceof ORAResult ) {
337 $res->free();
338 } else {
339 $res->result->free();
340 }
341 }
342
343 function fetchObject( $res ) {
344 if ( $res instanceof ORAResult ) {
345 return $res->numRows();
346 } else {
347 return $res->result->fetchObject();
348 }
349 }
350
351 function fetchRow( $res ) {
352 if ( $res instanceof ORAResult ) {
353 return $res->fetchRow();
354 } else {
355 return $res->result->fetchRow();
356 }
357 }
358
359 function numRows( $res ) {
360 if ( $res instanceof ORAResult ) {
361 return $res->numRows();
362 } else {
363 return $res->result->numRows();
364 }
365 }
366
367 function numFields( $res ) {
368 if ( $res instanceof ORAResult ) {
369 return $res->numFields();
370 } else {
371 return $res->result->numFields();
372 }
373 }
374
375 function fieldName( $stmt, $n ) {
376 return oci_field_name( $stmt, $n );
377 }
378
379 /**
380 * This must be called after nextSequenceVal
381 */
382 function insertId() {
383 return $this->mInsertId;
384 }
385
386 function dataSeek( $res, $row ) {
387 if ( $res instanceof ORAResult ) {
388 $res->seek( $row );
389 } else {
390 $res->result->seek( $row );
391 }
392 }
393
394 function lastError() {
395 if ( $this->mConn === false ) {
396 $e = oci_error();
397 } else {
398 $e = oci_error( $this->mConn );
399 }
400 return $e['message'];
401 }
402
403 function lastErrno() {
404 if ( $this->mConn === false ) {
405 $e = oci_error();
406 } else {
407 $e = oci_error( $this->mConn );
408 }
409 return $e['code'];
410 }
411
412 function affectedRows() {
413 return $this->mAffectedRows;
414 }
415
416 /**
417 * Returns information about an index
418 * If errors are explicitly ignored, returns NULL on failure
419 */
420 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
421 return false;
422 }
423
424 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
425 return false;
426 }
427
428 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
429 if ( !count( $a ) ) {
430 return true;
431 }
432
433 if ( !is_array( $options ) ) {
434 $options = array( $options );
435 }
436
437 if ( in_array( 'IGNORE', $options ) ) {
438 $this->ignore_DUP_VAL_ON_INDEX = true;
439 }
440
441 if ( !is_array( reset( $a ) ) ) {
442 $a = array( $a );
443 }
444
445 foreach ( $a as &$row ) {
446 $this->insertOneRow( $table, $row, $fname );
447 }
448 $retVal = true;
449
450 if ( in_array( 'IGNORE', $options ) ) {
451 $this->ignore_DUP_VAL_ON_INDEX = false;
452 }
453
454 return $retVal;
455 }
456
457 function insertOneRow( $table, $row, $fname ) {
458 global $wgLang;
459
460 // "INSERT INTO tables (a, b, c)"
461 $sql = "INSERT INTO " . $this->tableName( $table ) . " (" . join( ',', array_keys( $row ) ) . ')';
462 $sql .= " VALUES (";
463
464 // for each value, append ":key"
465 $first = true;
466 foreach ( $row as $col => $val ) {
467 if ( $first ) {
468 $sql .= $val !== null ? ':' . $col : 'NULL';
469 } else {
470 $sql .= $val !== null ? ', :' . $col : ', NULL';
471 }
472
473 $first = false;
474 }
475 $sql .= ')';
476
477 $stmt = oci_parse( $this->mConn, $sql );
478 foreach ( $row as $col => &$val ) {
479 $col_info = $this->fieldInfo( $this->tableName( $table ), $col );
480 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
481
482 if ( $val === null ) {
483 // do nothing ... null was inserted in statement creation
484 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
485 if ( is_object( $val ) ) {
486 $val = $val->getData();
487 }
488
489 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
490 $val = '31-12-2030 12:00:00.000000';
491 }
492
493 $val = ( $wgLang != null ) ? $wgLang->checkTitleEncoding( $val ) : $val;
494 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
495 $this->reportQueryError( $this->lastErrno(), $this->lastError(), $sql, __METHOD__ );
496 }
497 } else {
498 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
499 $e = oci_error( $stmt );
500 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
501 }
502
503 if ( $col_type == 'BLOB' ) { // is_object($val)) {
504 $lob[$col]->writeTemporary( $val ); // ->getData());
505 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
506 } else {
507 $lob[$col]->writeTemporary( $val );
508 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
509 }
510 }
511 }
512
513 wfSuppressWarnings();
514
515 if ( oci_execute( $stmt, OCI_DEFAULT ) === false ) {
516 $e = oci_error( $stmt );
517
518 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
519 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
520 } else {
521 $this->mAffectedRows = oci_num_rows( $stmt );
522 }
523 } else {
524 $this->mAffectedRows = oci_num_rows( $stmt );
525 }
526
527 wfRestoreWarnings();
528
529 if ( isset( $lob ) ) {
530 foreach ( $lob as $lob_i => $lob_v ) {
531 $lob_v->free();
532 }
533 }
534
535 if ( !$this->mTrxLevel ) {
536 oci_commit( $this->mConn );
537 }
538
539 oci_free_statement( $stmt );
540 }
541
542 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
543 $insertOptions = array(), $selectOptions = array() )
544 {
545 $destTable = $this->tableName( $destTable );
546 if ( !is_array( $selectOptions ) ) {
547 $selectOptions = array( $selectOptions );
548 }
549 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
550 if ( is_array( $srcTable ) ) {
551 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
552 } else {
553 $srcTable = $this->tableName( $srcTable );
554 }
555
556 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
557 !isset( $varMap[$sequenceData['column']] ) )
558 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
559
560 // count-alias subselect fields to avoid abigious definition errors
561 $i = 0;
562 foreach ( $varMap as $key => &$val ) {
563 $val = $val . ' field' . ( $i++ );
564 }
565
566 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
567 " SELECT $startOpts " . implode( ',', $varMap ) .
568 " FROM $srcTable $useIndex ";
569 if ( $conds != '*' ) {
570 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
571 }
572 $sql .= " $tailOpts";
573
574 if ( in_array( 'IGNORE', $insertOptions ) ) {
575 $this->ignore_DUP_VAL_ON_INDEX = true;
576 }
577
578 $retval = $this->query( $sql, $fname );
579
580 if ( in_array( 'IGNORE', $insertOptions ) ) {
581 $this->ignore_DUP_VAL_ON_INDEX = false;
582 }
583
584 return $retval;
585 }
586
587 function tableName( $name ) {
588 if (is_array($name)) {
589 foreach($name as &$single_name) {
590 $single_name = $this->tableName($single_name);
591 }
592 return $name;
593 }
594
595 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
596 /*
597 Replace reserved words with better ones
598 Using uppercase because that's the only way Oracle can handle
599 quoted tablenames
600 */
601 switch( $name ) {
602 case 'user':
603 $name = 'MWUSER';
604 break;
605 case 'text':
606 $name = 'PAGECONTENT';
607 break;
608 }
609
610 /*
611 The rest of procedure is equal to generic Databse class
612 except for the quoting style
613 */
614 if ( $name[0] == '"' && substr( $name, - 1, 1 ) == '"' ) {
615 return $name;
616 }
617 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
618 return $name;
619 }
620 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
621 if ( isset( $dbDetails[1] ) ) {
622 @list( $table, $database ) = $dbDetails;
623 } else {
624 @list( $table ) = $dbDetails;
625 }
626
627 $prefix = $this->mTablePrefix;
628
629 if ( isset( $database ) ) {
630 $table = ( $table[0] == '`' ? $table : "`{$table}`" );
631 }
632
633 if ( !isset( $database ) && isset( $wgSharedDB ) && $table[0] != '"'
634 && isset( $wgSharedTables )
635 && is_array( $wgSharedTables )
636 && in_array( $table, $wgSharedTables )
637 ) {
638 $database = $wgSharedDB;
639 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
640 }
641
642 if ( isset( $database ) ) {
643 $database = ( $database[0] == '"' ? $database : "\"{$database}\"" );
644 }
645 $table = ( $table[0] == '"' ? $table : "\"{$prefix}{$table}\"" );
646
647 $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
648
649 return strtoupper( $tableName );
650 }
651
652 /**
653 * Return the next in a sequence, save the value for retrieval via insertId()
654 */
655 function nextSequenceValue( $seqName ) {
656 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
657 $row = $this->fetchRow( $res );
658 $this->mInsertId = $row[0];
659 $this->freeResult( $res );
660 return $this->mInsertId;
661 }
662
663 /**
664 * Return sequence_name if table has a sequence
665 */
666 function getSequenceData( $table ) {
667 if ( $this->sequenceData == null ) {
668 $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'" );
669
670 while ( ( $row = $result->fetchRow() ) !== false ) {
671 $this->sequenceData[$this->tableName( $row[1] )] = array(
672 'sequence' => $row[0],
673 'column' => $row[2]
674 );
675 }
676 }
677
678 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
679 }
680
681 # REPLACE query wrapper
682 # Oracle simulates this with a DELETE followed by INSERT
683 # $row is the row to insert, an associative array
684 # $uniqueIndexes is an array of indexes. Each element may be either a
685 # field name or an array of field names
686 #
687 # It may be more efficient to leave off unique indexes which are unlikely to collide.
688 # However if you do this, you run the risk of encountering errors which wouldn't have
689 # occurred in MySQL
690 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
691 $table = $this->tableName( $table );
692
693 if ( count( $rows ) == 0 ) {
694 return;
695 }
696
697 # Single row case
698 if ( !is_array( reset( $rows ) ) ) {
699 $rows = array( $rows );
700 }
701
702 $sequenceData = $this->getSequenceData( $table );
703
704 foreach ( $rows as $row ) {
705 # Delete rows which collide
706 if ( $uniqueIndexes ) {
707 $condsDelete = array();
708 foreach ( $uniqueIndexes as $index )
709 $condsDelete[$index] = $row[$index];
710 if (count($condsDelete) > 0) {
711 $this->delete( $table, $condsDelete, $fname );
712 }
713 }
714
715 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
716 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
717 }
718
719 # Now insert the row
720 $this->insert( $table, $row, $fname );
721 }
722 }
723
724 # DELETE where the condition is a join
725 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "DatabaseOracle::deleteJoin" ) {
726 if ( !$conds ) {
727 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
728 }
729
730 $delTable = $this->tableName( $delTable );
731 $joinTable = $this->tableName( $joinTable );
732 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
733 if ( $conds != '*' ) {
734 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
735 }
736 $sql .= ')';
737
738 $this->query( $sql, $fname );
739 }
740
741 # Returns the size of a text field, or -1 for "unlimited"
742 function textFieldSize( $table, $field ) {
743 $table = $this->tableName( $table );
744 $sql = "SELECT t.typname as ftype,a.atttypmod as size
745 FROM pg_class c, pg_attribute a, pg_type t
746 WHERE relname='$table' AND a.attrelid=c.oid AND
747 a.atttypid=t.oid and a.attname='$field'";
748 $res = $this->query( $sql );
749 $row = $this->fetchObject( $res );
750 if ( $row->ftype == "varchar" ) {
751 $size = $row->size - 4;
752 } else {
753 $size = $row->size;
754 }
755 $this->freeResult( $res );
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
767 function unionQueries( $sqls, $all ) {
768 $glue = ' UNION ALL ';
769 return 'SELECT * ' . ( $all ? '':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
770 }
771
772 function wasDeadlock() {
773 return $this->lastErrno() == 'OCI-00060';
774 }
775
776
777 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
778 $temporary = $temporary ? 'TRUE' : 'FALSE';
779 return $this->query( 'BEGIN DUPLICATE_TABLE(\'' . $oldName . '\', \'' . $newName . '\', ' . $temporary . '); END;', $fname );
780 }
781
782 function timestamp( $ts = 0 ) {
783 return wfTimestamp( TS_ORACLE, $ts );
784 }
785
786 /**
787 * Return aggregated value function call
788 */
789 function aggregateValue ( $valuedata, $valuename = 'value' ) {
790 return $valuedata;
791 }
792
793 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
794 # Ignore errors during error handling to avoid infinite
795 # recursion
796 $ignore = $this->ignoreErrors( true );
797 ++$this->mErrorCount;
798
799 if ( $ignore || $tempIgnore ) {
800 wfDebug( "SQL ERROR (ignored): $error\n" );
801 $this->ignoreErrors( $ignore );
802 } else {
803 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
804 }
805 }
806
807 /**
808 * @return string wikitext of a link to the server software's web site
809 */
810 function getSoftwareLink() {
811 return '[http://www.oracle.com/ Oracle]';
812 }
813
814 /**
815 * @return string Version information from the database
816 */
817 function getServerVersion() {
818 return oci_server_version( $this->mConn );
819 }
820
821 /**
822 * Query whether a given table exists (in the given schema, or the default mw one if not given)
823 */
824 function tableExists( $table ) {
825 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
826 $res = $this->doQuery( $SQL );
827 if ( $res ) {
828 $count = $res->numRows();
829 $res->free();
830 } else {
831 $count = 0;
832 }
833 return $count;
834 }
835
836 /**
837 * Query whether a given column exists in the mediawiki schema
838 * based on prebuilt table to simulate MySQL field info and keep query speed minimal
839 */
840 function fieldExists( $table, $field, $fname = 'DatabaseOracle::fieldExists' ) {
841 return (bool)$this->fieldInfo( $table, $field, $fname );
842 }
843
844 function fieldInfo( $table, $field ) {
845 $tableWhere = '';
846 $field = strtoupper($field);
847 if (is_array($table)) {
848 $tableWhere = 'IN (';
849 foreach($table as &$singleTable) {
850 $singleTable = strtoupper(trim( $singleTable, '"' ));
851 if (isset($this->mFieldInfoCache["$singleTable.$field"])) {
852 return $this->mFieldInfoCache["$singleTable.$field"];
853 }
854 $tableWhere .= '\''.$singleTable.'\',';
855 }
856 $tableWhere = rtrim($tableWhere, ',').')';
857 } else {
858 $table = strtoupper(trim( $table, '"' ));
859 if (isset($this->mFieldInfoCache["$table.$field"])) {
860 return $this->mFieldInfoCache["$table.$field"];
861 }
862 $tableWhere = '= \''.$table.'\'';
863 }
864
865 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
866 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT ) === false ) {
867 $e = oci_error( $fieldInfoStmt );
868 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
869 return false;
870 }
871 $res = new ORAResult( $this, $fieldInfoStmt );
872 if ($res->numRows() == 0 ) {
873 if (is_array($table)) {
874 foreach($table as &$singleTable) {
875 $this->mFieldInfoCache["$singleTable.$field"] = false;
876 }
877 } else {
878 $this->mFieldInfoCache["$table.$field"] = false;
879 }
880 } else {
881 $fieldInfoTemp = new ORAField( $res->fetchRow() );
882 $table = $fieldInfoTemp->tableName();
883 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
884 return $fieldInfoTemp;
885 }
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 function addQuotes( $s ) {
1010 global $wgLang;
1011 if ( isset( $wgLang->mLoaded ) && $wgLang->mLoaded ) {
1012 $s = $wgLang->checkTitleEncoding( $s );
1013 }
1014 return "'" . $this->strencode( $s ) . "'";
1015 }
1016
1017 function quote_ident( $s ) {
1018 return $s;
1019 }
1020
1021 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1022 global $wgLang;
1023
1024 $conds2 = array();
1025 $conds = ($conds != null && !is_array($conds)) ? array($conds) : $conds;
1026 foreach ( $conds as $col => $val ) {
1027 $col_info = $this->fieldInfo( $this->tableName( $table ), $col );
1028 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1029 if ( $col_type == 'CLOB' ) {
1030 $conds2['TO_CHAR(' . $col . ')'] = $wgLang->checkTitleEncoding( $val );
1031 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1032 $conds2[$col] = $wgLang->checkTitleEncoding( $val );
1033 } else {
1034 $conds2[$col] = $val;
1035 }
1036 }
1037
1038 if ( is_array( $table ) ) {
1039 foreach ( $table as $tab ) {
1040 $tab = $this->tableName( $tab );
1041 }
1042 } else {
1043 $table = $this->tableName( $table );
1044 }
1045
1046 return parent::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1047 }
1048
1049 /**
1050 * Returns an optional USE INDEX clause to go after the table, and a
1051 * string to go at the end of the query
1052 *
1053 * @private
1054 *
1055 * @param $options Array: an associative array of options to be turned into
1056 * an SQL query, valid keys are listed in the function.
1057 * @return array
1058 */
1059 function makeSelectOptions( $options ) {
1060 $preLimitTail = $postLimitTail = '';
1061 $startOpts = '';
1062
1063 $noKeyOptions = array();
1064 foreach ( $options as $key => $option ) {
1065 if ( is_numeric( $key ) ) {
1066 $noKeyOptions[$option] = true;
1067 }
1068 }
1069
1070 if ( isset( $options['GROUP BY'] ) ) {
1071 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1072 }
1073 if ( isset( $options['ORDER BY'] ) ) {
1074 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1075 }
1076
1077 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1078 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1079 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1080 $startOpts .= 'DISTINCT';
1081 }
1082
1083 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1084 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1085 } else {
1086 $useIndex = '';
1087 }
1088
1089 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1090 }
1091
1092 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1093 global $wgLang;
1094
1095 if ( $wgLang != null ) {
1096 $conds2 = array();
1097 $conds = ($conds != null && !is_array($conds)) ? array($conds) : $conds;
1098 foreach ( $conds as $col => $val ) {
1099 $col_info = $this->fieldInfo( $this->tableName( $table ), $col );
1100 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1101 if ( $col_type == 'CLOB' ) {
1102 $conds2['TO_CHAR(' . $col . ')'] = $wgLang->checkTitleEncoding( $val );
1103 } else {
1104 if ( is_array( $val ) ) {
1105 $conds2[$col] = $val;
1106 foreach ( $conds2[$col] as &$val2 ) {
1107 $val2 = $wgLang->checkTitleEncoding( $val2 );
1108 }
1109 } else {
1110 $conds2[$col] = $wgLang->checkTitleEncoding( $val );
1111 }
1112 }
1113 }
1114
1115 return parent::delete( $table, $conds2, $fname );
1116 } else {
1117 return parent::delete( $table, $conds, $fname );
1118 }
1119 }
1120
1121 function bitNot( $field ) {
1122 // expecting bit-fields smaller than 4bytes
1123 return 'BITNOT(' . $bitField . ')';
1124 }
1125
1126 function bitAnd( $fieldLeft, $fieldRight ) {
1127 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1128 }
1129
1130 function bitOr( $fieldLeft, $fieldRight ) {
1131 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1132 }
1133
1134 /**
1135 * How lagged is this slave?
1136 *
1137 * @return int
1138 */
1139 public function getLag() {
1140 # Not implemented for Oracle
1141 return 0;
1142 }
1143
1144 function setFakeSlaveLag( $lag ) { }
1145 function setFakeMaster( $enabled = true ) { }
1146
1147 function getDBname() {
1148 return $this->mDBname;
1149 }
1150
1151 function getServer() {
1152 return $this->mServer;
1153 }
1154
1155 public function replaceVars( $ins ) {
1156 $varnames = array( 'wgDBprefix' );
1157 if ( $this->mFlags & DBO_SYSDBA ) {
1158 $varnames[] = 'wgDBOracleDefTS';
1159 $varnames[] = 'wgDBOracleTempTS';
1160 }
1161
1162 // Ordinary variables
1163 foreach ( $varnames as $var ) {
1164 if ( isset( $GLOBALS[$var] ) ) {
1165 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1166 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1167 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1168 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1169 }
1170 }
1171
1172 return parent::replaceVars( $ins );
1173 }
1174
1175 public function getSearchEngine() {
1176 return 'SearchOracle';
1177 }
1178 } // end DatabaseOracle class