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