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