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