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