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