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