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