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