Make SVGMetadataExtractor less noisy when it reads SVGs from Adobe Illustrator.
[lhc/web/wiklou.git] / includes / db / DatabaseOracle.php
1 <?php
2 /**
3 * This is the Oracle database abstraction layer.
4 *
5 * @file
6 * @ingroup Database
7 */
8
9 /**
10 * The oci8 extension is fairly weak and doesn't support oci_num_rows, among
11 * other things. We use a wrapper class to handle that and other
12 * Oracle-specific bits, like converting column names back to lowercase.
13 * @ingroup Database
14 */
15 class ORAResult {
16 private $rows;
17 private $cursor;
18 private $nrows;
19
20 private $columns = array();
21
22 private function array_unique_md( $array_in ) {
23 $array_out = array();
24 $array_hashes = array();
25
26 foreach ( $array_in as $item ) {
27 $hash = md5( serialize( $item ) );
28 if ( !isset( $array_hashes[$hash] ) ) {
29 $array_hashes[$hash] = $hash;
30 $array_out[] = $item;
31 }
32 }
33
34 return $array_out;
35 }
36
37 function __construct( &$db, $stmt, $unique = false ) {
38 $this->db =& $db;
39
40 if ( ( $this->nrows = oci_fetch_all( $stmt, $this->rows, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM ) ) === false ) {
41 $e = oci_error( $stmt );
42 $db->reportQueryError( $e['message'], $e['code'], '', __METHOD__ );
43 $this->free();
44 return;
45 }
46
47 if ( $unique ) {
48 $this->rows = $this->array_unique_md( $this->rows );
49 $this->nrows = count( $this->rows );
50 }
51
52 if ($this->nrows > 0) {
53 foreach ( $this->rows[0] as $k => $v ) {
54 $this->columns[$k] = strtolower( oci_field_name( $stmt, $k + 1 ) );
55 }
56 }
57
58 $this->cursor = 0;
59 oci_free_statement( $stmt );
60 }
61
62 public function free() {
63 unset($this->db);
64 }
65
66 public function seek( $row ) {
67 $this->cursor = min( $row, $this->nrows );
68 }
69
70 public function numRows() {
71 return $this->nrows;
72 }
73
74 public function numFields() {
75 return count($this->columns);
76 }
77
78 public function fetchObject() {
79 if ( $this->cursor >= $this->nrows ) {
80 return false;
81 }
82 $row = $this->rows[$this->cursor++];
83 $ret = new stdClass();
84 foreach ( $row as $k => $v ) {
85 $lc = $this->columns[$k];
86 $ret->$lc = $v;
87 }
88
89 return $ret;
90 }
91
92 public function fetchRow() {
93 if ( $this->cursor >= $this->nrows ) {
94 return false;
95 }
96
97 $row = $this->rows[$this->cursor++];
98 $ret = array();
99 foreach ( $row as $k => $v ) {
100 $lc = $this->columns[$k];
101 $ret[$lc] = $v;
102 $ret[$k] = $v;
103 }
104 return $ret;
105 }
106 }
107
108 /**
109 * Utility class.
110 * @ingroup Database
111 */
112 class ORAField implements Field {
113 private $name, $tablename, $default, $max_length, $nullable,
114 $is_pk, $is_unique, $is_multiple, $is_key, $type;
115
116 function __construct( $info ) {
117 $this->name = $info['column_name'];
118 $this->tablename = $info['table_name'];
119 $this->default = $info['data_default'];
120 $this->max_length = $info['data_length'];
121 $this->nullable = $info['not_null'];
122 $this->is_pk = isset( $info['prim'] ) && $info['prim'] == 1 ? 1 : 0;
123 $this->is_unique = isset( $info['uniq'] ) && $info['uniq'] == 1 ? 1 : 0;
124 $this->is_multiple = isset( $info['nonuniq'] ) && $info['nonuniq'] == 1 ? 1 : 0;
125 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
126 $this->type = $info['data_type'];
127 }
128
129 function name() {
130 return $this->name;
131 }
132
133 function tableName() {
134 return $this->tablename;
135 }
136
137 function defaultValue() {
138 return $this->default;
139 }
140
141 function maxLength() {
142 return $this->max_length;
143 }
144
145 function isNullable() {
146 return $this->nullable;
147 }
148
149 function isKey() {
150 return $this->is_key;
151 }
152
153 function isMultipleKey() {
154 return $this->is_multiple;
155 }
156
157 function type() {
158 return $this->type;
159 }
160 }
161
162 /**
163 * @ingroup Database
164 */
165 class DatabaseOracle extends DatabaseBase {
166 var $mInsertId = null;
167 var $mLastResult = null;
168 var $numeric_version = null;
169 var $lastResult = null;
170 var $cursor = 0;
171 var $mAffectedRows;
172
173 var $ignore_DUP_VAL_ON_INDEX = false;
174 var $sequenceData = null;
175
176 var $defaultCharset = 'AL32UTF8';
177
178 var $mFieldInfoCache = array();
179
180 function __construct( $server = false, $user = false, $password = false, $dbName = false,
181 $flags = 0, $tablePrefix = 'get from global' )
182 {
183 $tablePrefix = $tablePrefix == 'get from global' ? $tablePrefix : strtoupper( $tablePrefix );
184 parent::__construct( $server, $user, $password, $dbName, $flags, $tablePrefix );
185 wfRunHooks( 'DatabaseOraclePostInit', array( $this ) );
186 }
187
188 function getType() {
189 return 'oracle';
190 }
191
192 function cascadingDeletes() {
193 return true;
194 }
195 function cleanupTriggers() {
196 return true;
197 }
198 function strictIPs() {
199 return true;
200 }
201 function realTimestamps() {
202 return true;
203 }
204 function implicitGroupby() {
205 return false;
206 }
207 function implicitOrderby() {
208 return false;
209 }
210 function searchableIPs() {
211 return true;
212 }
213
214 /**
215 * Usually aborts on failure
216 */
217 function open( $server, $user, $password, $dbName ) {
218 if ( !function_exists( 'oci_connect' ) ) {
219 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" );
220 }
221
222 $this->close();
223 $this->mUser = $user;
224 $this->mPassword = $password;
225 // changed internal variables functions
226 // mServer now holds the TNS endpoint
227 // mDBname is schema name if different from username
228 if ( !$server ) {
229 // backward compatibillity (server used to be null and TNS was supplied in dbname)
230 $this->mServer = $dbName;
231 $this->mDBname = $user;
232 } else {
233 $this->mServer = $server;
234 if ( !$dbName ) {
235 $this->mDBname = $user;
236 } else {
237 $this->mDBname = $dbName;
238 }
239 }
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( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
248 } else {
249 $this->mConn = oci_connect( $this->mUser, $this->mPassword, $this->mServer, $this->defaultCharset, $session_mode );
250 }
251
252 if ( $this->mUser != $this->mDBname ) {
253 //change current schema in session
254 $this->selectDB( $this->mDBname );
255 }
256
257 if ( !$this->mConn ) {
258 throw new DBConnectionError( $this, $this->lastError() );
259 }
260
261 $this->mOpened = true;
262
263 # removed putenv calls because they interfere with the system globaly
264 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
265 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
266 return $this->mConn;
267 }
268
269 /**
270 * Closes a database connection, if it is open
271 * Returns success, true if already closed
272 */
273 function close() {
274 $this->mOpened = false;
275 if ( $this->mConn ) {
276 return oci_close( $this->mConn );
277 } else {
278 return true;
279 }
280 }
281
282 function execFlags() {
283 return $this->mTrxLevel ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
284 }
285
286 function doQuery( $sql ) {
287 wfDebug( "SQL: [$sql]\n" );
288 if ( !mb_check_encoding( $sql ) ) {
289 throw new MWException( "SQL encoding is invalid\n$sql" );
290 }
291
292 // handle some oracle specifics
293 // remove AS column/table/subquery namings
294 if( !$this->getFlag( DBO_DDLMODE ) ) {
295 $sql = preg_replace( '/ as /i', ' ', $sql );
296 }
297
298 // Oracle has issues with UNION clause if the statement includes LOB fields
299 // So we do a UNION ALL and then filter the results array with array_unique
300 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
301 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
302 // you have to select data from plan table after explain
303 $explain_id = date( 'dmYHis' );
304
305 $sql = preg_replace( '/^EXPLAIN /', 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR', $sql, 1, $explain_count );
306
307 wfSuppressWarnings();
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, __METHOD__ );
312 return false;
313 }
314
315 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
316 $e = oci_error( $stmt );
317 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
318 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
319 return false;
320 }
321 }
322
323 wfRestoreWarnings();
324
325 if ( $explain_count > 0 ) {
326 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table WHERE statement_id = \'' . $explain_id . '\'' );
327 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
328 return new ORAResult( $this, $stmt, $union_unique );
329 } else {
330 $this->mAffectedRows = oci_num_rows( $stmt );
331 return true;
332 }
333 }
334
335 function queryIgnore( $sql, $fname = '' ) {
336 return $this->query( $sql, $fname, true );
337 }
338
339 function freeResult( $res ) {
340 if ( $res instanceof ResultWrapper ) {
341 $res = $res->result;
342 }
343
344 $res->free();
345 }
346
347 function fetchObject( $res ) {
348 if ( $res instanceof ResultWrapper ) {
349 $res = $res->result;
350 }
351
352 return $res->fetchObject();
353 }
354
355 function fetchRow( $res ) {
356 if ( $res instanceof ResultWrapper ) {
357 $res = $res->result;
358 }
359
360 return $res->fetchRow();
361 }
362
363 function numRows( $res ) {
364 if ( $res instanceof ResultWrapper ) {
365 $res = $res->result;
366 }
367
368 return $res->numRows();
369 }
370
371 function numFields( $res ) {
372 if ( $res instanceof ResultWrapper ) {
373 $res = $res->result;
374 }
375
376 return $res->numFields();
377 }
378
379 function fieldName( $stmt, $n ) {
380 return oci_field_name( $stmt, $n );
381 }
382
383 /**
384 * This must be called after nextSequenceVal
385 */
386 function insertId() {
387 return $this->mInsertId;
388 }
389
390 function dataSeek( $res, $row ) {
391 if ( $res instanceof ORAResult ) {
392 $res->seek( $row );
393 } else {
394 $res->result->seek( $row );
395 }
396 }
397
398 function lastError() {
399 if ( $this->mConn === false ) {
400 $e = oci_error();
401 } else {
402 $e = oci_error( $this->mConn );
403 }
404 return $e['message'];
405 }
406
407 function lastErrno() {
408 if ( $this->mConn === false ) {
409 $e = oci_error();
410 } else {
411 $e = oci_error( $this->mConn );
412 }
413 return $e['code'];
414 }
415
416 function affectedRows() {
417 return $this->mAffectedRows;
418 }
419
420 /**
421 * Returns information about an index
422 * If errors are explicitly ignored, returns NULL on failure
423 */
424 function indexInfo( $table, $index, $fname = 'DatabaseOracle::indexExists' ) {
425 return false;
426 }
427
428 function indexUnique( $table, $index, $fname = 'DatabaseOracle::indexUnique' ) {
429 return false;
430 }
431
432 function insert( $table, $a, $fname = 'DatabaseOracle::insert', $options = array() ) {
433 if ( !count( $a ) ) {
434 return true;
435 }
436
437 if ( !is_array( $options ) ) {
438 $options = array( $options );
439 }
440
441 if ( in_array( 'IGNORE', $options ) ) {
442 $this->ignore_DUP_VAL_ON_INDEX = true;
443 }
444
445 if ( !is_array( reset( $a ) ) ) {
446 $a = array( $a );
447 }
448
449 foreach ( $a as &$row ) {
450 $this->insertOneRow( $table, $row, $fname );
451 }
452 $retVal = true;
453
454 if ( in_array( 'IGNORE', $options ) ) {
455 $this->ignore_DUP_VAL_ON_INDEX = false;
456 }
457
458 return $retVal;
459 }
460
461 private function fieldBindStatement ( $table, $col, &$val, $includeCol = false ) {
462 $col_info = $this->fieldInfoMulti( $table, $col );
463 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
464
465 $bind = '';
466 if ( is_numeric( $col ) ) {
467 $bind = $val;
468 $val = null;
469 return $bind;
470 } else if ( $includeCol ) {
471 $bind = "$col = ";
472 }
473
474 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
475 $val = null;
476 }
477
478 if ( $val === null ) {
479 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
480 $bind .= 'DEFAULT';
481 } else {
482 $bind .= 'NULL';
483 }
484 } else {
485 $bind .= ':' . $col;
486 }
487
488 return $bind;
489 }
490
491 private function insertOneRow( $table, $row, $fname ) {
492 global $wgContLang;
493
494 $table = $this->tableName( $table );
495 // "INSERT INTO tables (a, b, c)"
496 $sql = "INSERT INTO " . $table . " (" . join( ',', array_keys( $row ) ) . ')';
497 $sql .= " VALUES (";
498
499 // for each value, append ":key"
500 $first = true;
501 foreach ( $row as $col => &$val ) {
502 if ( !$first ) {
503 $sql .= ', ';
504 } else {
505 $first = false;
506 }
507
508 $sql .= $this->fieldBindStatement( $table, $col, $val );
509 }
510 $sql .= ')';
511
512 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
513 $e = oci_error( $this->mConn );
514 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
515 return false;
516 }
517 foreach ( $row as $col => &$val ) {
518 $col_info = $this->fieldInfoMulti( $table, $col );
519 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
520
521 if ( $val === null ) {
522 // do nothing ... null was inserted in statement creation
523 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
524 if ( is_object( $val ) ) {
525 $val = $val->fetch();
526 }
527
528 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
529 $val = '31-12-2030 12:00:00.000000';
530 }
531
532 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
533 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
534 $e = oci_error( $stmt );
535 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
536 return false;
537 }
538 } else {
539 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
540 $e = oci_error( $stmt );
541 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
542 }
543
544 if ( is_object( $val ) ) {
545 $val = $val->fetch();
546 }
547
548 if ( $col_type == 'BLOB' ) {
549 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
550 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB );
551 } else {
552 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
553 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
554 }
555 }
556 }
557
558 wfSuppressWarnings();
559
560 if ( oci_execute( $stmt, OCI_DEFAULT ) === false ) {
561 $e = oci_error( $stmt );
562 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
563 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
564 return false;
565 } else {
566 $this->mAffectedRows = oci_num_rows( $stmt );
567 }
568 } else {
569 $this->mAffectedRows = oci_num_rows( $stmt );
570 }
571
572 wfRestoreWarnings();
573
574 if ( isset( $lob ) ) {
575 foreach ( $lob as $lob_v ) {
576 $lob_v->free();
577 }
578 }
579
580 if ( !$this->mTrxLevel ) {
581 oci_commit( $this->mConn );
582 }
583
584 oci_free_statement( $stmt );
585 }
586
587 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseOracle::insertSelect',
588 $insertOptions = array(), $selectOptions = array() )
589 {
590 $destTable = $this->tableName( $destTable );
591 if ( !is_array( $selectOptions ) ) {
592 $selectOptions = array( $selectOptions );
593 }
594 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
595 if ( is_array( $srcTable ) ) {
596 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
597 } else {
598 $srcTable = $this->tableName( $srcTable );
599 }
600
601 if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
602 !isset( $varMap[$sequenceData['column']] ) )
603 {
604 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
605 }
606
607 // count-alias subselect fields to avoid abigious definition errors
608 $i = 0;
609 foreach ( $varMap as &$val ) {
610 $val = $val . ' field' . ( $i++ );
611 }
612
613 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
614 " SELECT $startOpts " . implode( ',', $varMap ) .
615 " FROM $srcTable $useIndex ";
616 if ( $conds != '*' ) {
617 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
618 }
619 $sql .= " $tailOpts";
620
621 if ( in_array( 'IGNORE', $insertOptions ) ) {
622 $this->ignore_DUP_VAL_ON_INDEX = true;
623 }
624
625 $retval = $this->query( $sql, $fname );
626
627 if ( in_array( 'IGNORE', $insertOptions ) ) {
628 $this->ignore_DUP_VAL_ON_INDEX = false;
629 }
630
631 return $retval;
632 }
633
634 function tableName( $name ) {
635 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
636 /*
637 Replace reserved words with better ones
638 Using uppercase because that's the only way Oracle can handle
639 quoted tablenames
640 */
641 switch( $name ) {
642 case 'user':
643 $name = 'MWUSER';
644 break;
645 case 'text':
646 $name = 'PAGECONTENT';
647 break;
648 }
649
650 /*
651 The rest of procedure is equal to generic Databse class
652 except for the quoting style
653 */
654 if ( $name[0] == '"' && substr( $name, - 1, 1 ) == '"' ) {
655 return $name;
656 }
657 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
658 return $name;
659 }
660 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
661 if ( isset( $dbDetails[1] ) ) {
662 @list( $table, $database ) = $dbDetails;
663 } else {
664 @list( $table ) = $dbDetails;
665 }
666
667 $prefix = $this->mTablePrefix;
668
669 if ( isset( $database ) ) {
670 $table = ( $table[0] == '`' ? $table : "`{$table}`" );
671 }
672
673 if ( !isset( $database ) && isset( $wgSharedDB ) && $table[0] != '"'
674 && isset( $wgSharedTables )
675 && is_array( $wgSharedTables )
676 && in_array( $table, $wgSharedTables )
677 ) {
678 $database = $wgSharedDB;
679 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
680 }
681
682 if ( isset( $database ) ) {
683 $database = ( $database[0] == '"' ? $database : "\"{$database}\"" );
684 }
685 $table = ( $table[0] == '"') ? $table : "\"{$prefix}{$table}\"" ;
686
687 $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
688
689 return strtoupper( $tableName );
690 }
691
692 /**
693 * Return the next in a sequence, save the value for retrieval via insertId()
694 */
695 function nextSequenceValue( $seqName ) {
696 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
697 $row = $this->fetchRow( $res );
698 $this->mInsertId = $row[0];
699 return $this->mInsertId;
700 }
701
702 /**
703 * Return sequence_name if table has a sequence
704 */
705 private function getSequenceData( $table ) {
706 if ( $this->sequenceData == null ) {
707 $result = $this->doQuery( '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\'' );
708
709 while ( ( $row = $result->fetchRow() ) !== false ) {
710 $this->sequenceData[$this->tableName( $row[1] )] = array(
711 'sequence' => $row[0],
712 'column' => $row[2]
713 );
714 }
715 }
716
717 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
718 }
719
720 /**
721 * REPLACE query wrapper
722 * Oracle simulates this with a DELETE followed by INSERT
723 * $row is the row to insert, an associative array
724 * $uniqueIndexes is an array of indexes. Each element may be either a
725 * field name or an array of field names
726 *
727 * It may be more efficient to leave off unique indexes which are unlikely to collide.
728 * However if you do this, you run the risk of encountering errors which wouldn't have
729 * occurred in MySQL.
730 *
731 * @param $table String: table name
732 * @param $uniqueIndexes Array: array of indexes. Each element may be
733 * either a field name or an array of field names
734 * @param $rows Array: rows to insert to $table
735 * @param $fname String: function name, you can use __METHOD__ here
736 */
737 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseOracle::replace' ) {
738 $table = $this->tableName( $table );
739
740 if ( count( $rows ) == 0 ) {
741 return;
742 }
743
744 # Single row case
745 if ( !is_array( reset( $rows ) ) ) {
746 $rows = array( $rows );
747 }
748
749 $sequenceData = $this->getSequenceData( $table );
750
751 foreach ( $rows as $row ) {
752 # Delete rows which collide
753 if ( $uniqueIndexes ) {
754 $condsDelete = array();
755 foreach ( $uniqueIndexes as $index ) {
756 $condsDelete[$index] = $row[$index];
757 }
758 if ( count( $condsDelete ) > 0 ) {
759 $this->delete( $table, $condsDelete, $fname );
760 }
761 }
762
763 if ( $sequenceData !== false && !isset( $row[$sequenceData['column']] ) ) {
764 $row[$sequenceData['column']] = $this->nextSequenceValue( $sequenceData['sequence'] );
765 }
766
767 # Now insert the row
768 $this->insert( $table, $row, $fname );
769 }
770 }
771
772 # DELETE where the condition is a join
773 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseOracle::deleteJoin' ) {
774 if ( !$conds ) {
775 throw new DBUnexpectedError( $this, 'DatabaseOracle::deleteJoin() called with empty $conds' );
776 }
777
778 $delTable = $this->tableName( $delTable );
779 $joinTable = $this->tableName( $joinTable );
780 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
781 if ( $conds != '*' ) {
782 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
783 }
784 $sql .= ')';
785
786 $this->query( $sql, $fname );
787 }
788
789 # Returns the size of a text field, or -1 for "unlimited"
790 function textFieldSize( $table, $field ) {
791 $fieldInfoData = $this->fieldInfo( $table, $field);
792 if ( $fieldInfoData->type() == 'varchar' ) {
793 $size = $row->size - 4;
794 } else {
795 $size = $row->size;
796 }
797 return $size;
798 }
799
800 function limitResult( $sql, $limit, $offset = false ) {
801 if ( $offset === false ) {
802 $offset = 0;
803 }
804 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
805 }
806
807 function encodeBlob( $b ) {
808 return new Blob( $b );
809 }
810
811 function decodeBlob( $b ) {
812 if ( $b instanceof Blob ) {
813 $b = $b->fetch();
814 }
815 return $b;
816 }
817
818 function unionQueries( $sqls, $all ) {
819 $glue = ' UNION ALL ';
820 return 'SELECT * ' . ( $all ? '':'/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')' ;
821 }
822
823 function wasDeadlock() {
824 return $this->lastErrno() == 'OCI-00060';
825 }
826
827 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseOracle::duplicateTableStructure' ) {
828 global $wgDBprefix;
829
830 $temporary = $temporary ? 'TRUE' : 'FALSE';
831
832 $newName = trim( strtoupper( $newName ), '"');
833 $oldName = trim( strtoupper( $oldName ), '"');
834
835 $tabName = substr( $newName, strlen( $wgDBprefix ) );
836 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
837
838 return $this->doQuery( 'BEGIN DUPLICATE_TABLE(\'' . $tabName . '\', \'' . $oldPrefix . '\', \'' . strtoupper( $wgDBprefix ) . '\', ' . $temporary . '); END;' );
839 }
840
841 function listTables( $prefix = null, $fname = 'DatabaseOracle::listTables' ) {
842 $listWhere = '';
843 if (!empty($prefix)) {
844 $listWhere = ' AND table_name LIKE \''.strtoupper($prefix).'%\'';
845 }
846
847 $result = $this->doQuery( "SELECT table_name FROM user_tables WHERE table_name NOT LIKE '%!_IDX$_' ESCAPE '!' $listWhere" );
848
849 // dirty code ... i know
850 $endArray = array();
851 $endArray[] = $prefix.'MWUSER';
852 $endArray[] = $prefix.'PAGE';
853 $endArray[] = $prefix.'IMAGE';
854 $fixedOrderTabs = $endArray;
855 while (($row = $result->fetchRow()) !== false) {
856 if (!in_array($row['table_name'], $fixedOrderTabs))
857 $endArray[] = $row['table_name'];
858 }
859
860 return $endArray;
861 }
862
863 public function dropTable( $tableName, $fName = 'DatabaseOracle::dropTable' ) {
864 $tableName = $this->tableName($tableName);
865 if( !$this->tableExists( $tableName ) ) {
866 return false;
867 }
868
869 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
870 }
871
872 function timestamp( $ts = 0 ) {
873 return wfTimestamp( TS_ORACLE, $ts );
874 }
875
876 /**
877 * Return aggregated value function call
878 */
879 function aggregateValue ( $valuedata, $valuename = 'value' ) {
880 return $valuedata;
881 }
882
883 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
884 # Ignore errors during error handling to avoid infinite
885 # recursion
886 $ignore = $this->ignoreErrors( true );
887 ++$this->mErrorCount;
888
889 if ( $ignore || $tempIgnore ) {
890 wfDebug( "SQL ERROR (ignored): $error\n" );
891 $this->ignoreErrors( $ignore );
892 } else {
893 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
894 }
895 }
896
897 /**
898 * @return string wikitext of a link to the server software's web site
899 */
900 public static function getSoftwareLink() {
901 return '[http://www.oracle.com/ Oracle]';
902 }
903
904 /**
905 * @return string Version information from the database
906 */
907 function getServerVersion() {
908 //better version number, fallback on driver
909 $rset = $this->doQuery( 'SELECT version FROM product_component_version WHERE UPPER(product) LIKE \'ORACLE DATABASE%\'' );
910 if ( !( $row = $rset->fetchRow() ) ) {
911 return oci_server_version( $this->mConn );
912 }
913 return $row['version'];
914 }
915
916 /**
917 * Query whether a given table exists (in the given schema, or the default mw one if not given)
918 */
919 function tableExists( $table ) {
920 $table = trim($this->tableName($table), '"');
921 $SQL = "SELECT 1 FROM user_tables WHERE table_name='$table'";
922 $res = $this->doQuery( $SQL );
923 if ( $res ) {
924 $count = $res->numRows();
925 $res->free();
926 } else {
927 $count = 0;
928 }
929 return $count;
930 }
931
932 /**
933 * Function translates mysql_fetch_field() functionality on ORACLE.
934 * Caching is present for reducing query time.
935 * For internal calls. Use fieldInfo for normal usage.
936 * Returns false if the field doesn't exist
937 *
938 * @param $table Array
939 * @param $field String
940 * @return ORAField
941 */
942 private function fieldInfoMulti( $table, $field ) {
943 $field = strtoupper( $field );
944 if ( is_array( $table ) ) {
945 $table = array_map( array( &$this, 'tableName' ), $table );
946 $tableWhere = 'IN (';
947 foreach( $table as &$singleTable ) {
948 $singleTable = strtoupper( trim( $singleTable, '"' ) );
949 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
950 return $this->mFieldInfoCache["$singleTable.$field"];
951 }
952 $tableWhere .= '\'' . $singleTable . '\',';
953 }
954 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
955 } else {
956 $table = strtoupper( trim( $this->tableName( $table ), '"' ) );
957 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
958 return $this->mFieldInfoCache["$table.$field"];
959 }
960 $tableWhere = '= \''.$table.'\'';
961 }
962
963 $fieldInfoStmt = oci_parse( $this->mConn, 'SELECT * FROM wiki_field_info_full WHERE table_name '.$tableWhere.' and column_name = \''.$field.'\'' );
964 if ( oci_execute( $fieldInfoStmt, OCI_DEFAULT ) === false ) {
965 $e = oci_error( $fieldInfoStmt );
966 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
967 return false;
968 }
969 $res = new ORAResult( $this, $fieldInfoStmt );
970 if ( $res->numRows() == 0 ) {
971 if ( is_array( $table ) ) {
972 foreach( $table as &$singleTable ) {
973 $this->mFieldInfoCache["$singleTable.$field"] = false;
974 }
975 } else {
976 $this->mFieldInfoCache["$table.$field"] = false;
977 }
978 $fieldInfoTemp = null;
979 } else {
980 $fieldInfoTemp = new ORAField( $res->fetchRow() );
981 $table = $fieldInfoTemp->tableName();
982 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
983 }
984 $res->free();
985 return $fieldInfoTemp;
986 }
987
988 /**
989 * @throws DBUnexpectedError
990 * @param $table
991 * @param $field
992 * @return ORAField
993 */
994 function fieldInfo( $table, $field ) {
995 if ( is_array( $table ) ) {
996 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
997 }
998 return $this->fieldInfoMulti ($table, $field);
999 }
1000
1001 function begin( $fname = '' ) {
1002 $this->mTrxLevel = 1;
1003 }
1004
1005 function commit( $fname = '' ) {
1006 oci_commit( $this->mConn );
1007 $this->mTrxLevel = 0;
1008 }
1009
1010 /* Not even sure why this is used in the main codebase... */
1011 function limitResultForUpdate( $sql, $num ) {
1012 return $sql;
1013 }
1014
1015 /* defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}'; */
1016 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseOracle::sourceStream' ) {
1017 $cmd = '';
1018 $done = false;
1019 $dollarquote = false;
1020
1021 $replacements = array();
1022
1023 while ( ! feof( $fp ) ) {
1024 if ( $lineCallback ) {
1025 call_user_func( $lineCallback );
1026 }
1027 $line = trim( fgets( $fp, 1024 ) );
1028 $sl = strlen( $line ) - 1;
1029
1030 if ( $sl < 0 ) {
1031 continue;
1032 }
1033 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
1034 continue;
1035 }
1036
1037 // Allow dollar quoting for function declarations
1038 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1039 if ( $dollarquote ) {
1040 $dollarquote = false;
1041 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1042 $done = true;
1043 } else {
1044 $dollarquote = true;
1045 }
1046 } elseif ( !$dollarquote ) {
1047 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
1048 $done = true;
1049 $line = substr( $line, 0, $sl );
1050 }
1051 }
1052
1053 if ( $cmd != '' ) {
1054 $cmd .= ' ';
1055 }
1056 $cmd .= "$line\n";
1057
1058 if ( $done ) {
1059 $cmd = str_replace( ';;', ";", $cmd );
1060 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1061 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1062 $replacements[$defines[2]] = $defines[1];
1063 }
1064 } else {
1065 foreach ( $replacements as $mwVar => $scVar ) {
1066 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1067 }
1068
1069 $cmd = $this->replaceVars( $cmd );
1070 $res = $this->doQuery( $cmd );
1071 if ( $resultCallback ) {
1072 call_user_func( $resultCallback, $res, $this );
1073 }
1074
1075 if ( false === $res ) {
1076 $err = $this->lastError();
1077 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1078 }
1079 }
1080
1081 $cmd = '';
1082 $done = false;
1083 }
1084 }
1085 return true;
1086 }
1087
1088 function selectDB( $db ) {
1089 $this->mDBname = $db;
1090 if ( $db == null || $db == $this->mUser ) {
1091 return true;
1092 }
1093 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper($db);
1094 $stmt = oci_parse( $this->mConn, $sql );
1095 wfSuppressWarnings();
1096 $success = oci_execute( $stmt );
1097 wfRestoreWarnings();
1098 if ( !$success ) {
1099 $e = oci_error( $stmt );
1100 if ( $e['code'] != '1435' ) {
1101 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1102 }
1103 return false;
1104 }
1105 return true;
1106 }
1107
1108 function strencode( $s ) {
1109 return str_replace( "'", "''", $s );
1110 }
1111
1112 function addQuotes( $s ) {
1113 global $wgContLang;
1114 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1115 $s = $wgContLang->checkTitleEncoding( $s );
1116 }
1117 return "'" . $this->strencode( $s ) . "'";
1118 }
1119
1120 public function addIdentifierQuotes( $s ) {
1121 if ( !$this->mFlags & DBO_DDLMODE ) {
1122 $s = '"' . str_replace( '"', '""', $s ) . '"';
1123 }
1124 return $s;
1125 }
1126
1127 function selectRow( $table, $vars, $conds, $fname = 'DatabaseOracle::selectRow', $options = array(), $join_conds = array() ) {
1128 global $wgContLang;
1129
1130 if ($conds != null) {
1131 $conds2 = array();
1132 $conds = ( !is_array( $conds ) ) ? array( $conds ) : $conds;
1133 foreach ( $conds as $col => $val ) {
1134 $col_info = $this->fieldInfoMulti( $table, $col );
1135 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1136 if ( $col_type == 'CLOB' ) {
1137 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1138 } elseif ( $col_type == 'VARCHAR2' && !mb_check_encoding( $val ) ) {
1139 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1140 } else {
1141 $conds2[$col] = $val;
1142 }
1143 }
1144
1145 return parent::selectRow( $table, $vars, $conds2, $fname, $options, $join_conds );
1146 } else {
1147 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1148 }
1149 }
1150
1151 /**
1152 * Returns an optional USE INDEX clause to go after the table, and a
1153 * string to go at the end of the query
1154 *
1155 * @private
1156 *
1157 * @param $options Array: an associative array of options to be turned into
1158 * an SQL query, valid keys are listed in the function.
1159 * @return array
1160 */
1161 function makeSelectOptions( $options ) {
1162 $preLimitTail = $postLimitTail = '';
1163 $startOpts = '';
1164
1165 $noKeyOptions = array();
1166 foreach ( $options as $key => $option ) {
1167 if ( is_numeric( $key ) ) {
1168 $noKeyOptions[$option] = true;
1169 }
1170 }
1171
1172 if ( isset( $options['GROUP BY'] ) ) {
1173 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1174 }
1175 if ( isset( $options['ORDER BY'] ) ) {
1176 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1177 }
1178
1179 # if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
1180 # if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
1181 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1182 $startOpts .= 'DISTINCT';
1183 }
1184
1185 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1186 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1187 } else {
1188 $useIndex = '';
1189 }
1190
1191 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1192 }
1193
1194 public function delete( $table, $conds, $fname = 'DatabaseOracle::delete' ) {
1195 global $wgContLang;
1196
1197 if ( $wgContLang != null && $conds != null && $conds != '*' ) {
1198 $conds2 = array();
1199 $conds = ( !is_array( $conds ) ) ? array( $conds ) : $conds;
1200 foreach ( $conds as $col => $val ) {
1201 $col_info = $this->fieldInfoMulti( $table, $col );
1202 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1203 if ( $col_type == 'CLOB' ) {
1204 $conds2['TO_CHAR(' . $col . ')'] = $wgContLang->checkTitleEncoding( $val );
1205 } else {
1206 if ( is_array( $val ) ) {
1207 $conds2[$col] = $val;
1208 foreach ( $conds2[$col] as &$val2 ) {
1209 $val2 = $wgContLang->checkTitleEncoding( $val2 );
1210 }
1211 } else {
1212 $conds2[$col] = $wgContLang->checkTitleEncoding( $val );
1213 }
1214 }
1215 }
1216
1217 return parent::delete( $table, $conds2, $fname );
1218 } else {
1219 return parent::delete( $table, $conds, $fname );
1220 }
1221 }
1222
1223 function update( $table, $values, $conds, $fname = 'DatabaseOracle::update', $options = array() ) {
1224 global $wgContLang;
1225
1226 $table = $this->tableName( $table );
1227 $opts = $this->makeUpdateOptions( $options );
1228 $sql = "UPDATE $opts $table SET ";
1229
1230 $first = true;
1231 foreach ( $values as $col => &$val ) {
1232 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1233
1234 if ( !$first ) {
1235 $sqlSet = ', ' . $sqlSet;
1236 } else {
1237 $first = false;
1238 }
1239 $sql .= $sqlSet;
1240 }
1241
1242 if ( $conds != '*' ) {
1243 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1244 }
1245
1246 if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
1247 $e = oci_error( $this->mConn );
1248 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1249 return false;
1250 }
1251 foreach ( $values as $col => &$val ) {
1252 $col_info = $this->fieldInfoMulti( $table, $col );
1253 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1254
1255 if ( $val === null ) {
1256 // do nothing ... null was inserted in statement creation
1257 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1258 if ( is_object( $val ) ) {
1259 $val = $val->getData();
1260 }
1261
1262 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1263 $val = '31-12-2030 12:00:00.000000';
1264 }
1265
1266 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1267 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1268 $e = oci_error( $stmt );
1269 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1270 return false;
1271 }
1272 } else {
1273 if ( ( $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB ) ) === false ) {
1274 $e = oci_error( $stmt );
1275 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1276 }
1277
1278 if ( $col_type == 'BLOB' ) {
1279 $lob[$col]->writeTemporary( $val );
1280 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
1281 } else {
1282 $lob[$col]->writeTemporary( $val );
1283 oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
1284 }
1285 }
1286 }
1287
1288 wfSuppressWarnings();
1289
1290 if ( oci_execute( $stmt, OCI_DEFAULT ) === false ) {
1291 $e = oci_error( $stmt );
1292 if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
1293 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1294 return false;
1295 } else {
1296 $this->mAffectedRows = oci_num_rows( $stmt );
1297 }
1298 } else {
1299 $this->mAffectedRows = oci_num_rows( $stmt );
1300 }
1301
1302 wfRestoreWarnings();
1303
1304 if ( isset( $lob ) ) {
1305 foreach ( $lob as $lob_v ) {
1306 $lob_v->free();
1307 }
1308 }
1309
1310 if ( !$this->mTrxLevel ) {
1311 oci_commit( $this->mConn );
1312 }
1313
1314 oci_free_statement( $stmt );
1315 }
1316
1317 function bitNot( $field ) {
1318 // expecting bit-fields smaller than 4bytes
1319 return 'BITNOT(' . $field . ')';
1320 }
1321
1322 function bitAnd( $fieldLeft, $fieldRight ) {
1323 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1324 }
1325
1326 function bitOr( $fieldLeft, $fieldRight ) {
1327 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1328 }
1329
1330 function setFakeMaster( $enabled = true ) { }
1331
1332 function getDBname() {
1333 return $this->mDBname;
1334 }
1335
1336 function getServer() {
1337 return $this->mServer;
1338 }
1339
1340 public function getSearchEngine() {
1341 return 'SearchOracle';
1342 }
1343 } // end DatabaseOracle class