Merge "Block: Explicit convert Message to string"
[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 }
570
571 $selectSql = $this->selectSQLText(
572 $srcTable,
573 array_values( $varMap ),
574 $conds,
575 $fname,
576 $selectOptions,
577 $selectJoinConds
578 );
579
580 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
581
582 if ( in_array( 'IGNORE', $insertOptions ) ) {
583 $this->ignoreDupValOnIndex = true;
584 }
585
586 $this->query( $sql, $fname );
587
588 if ( in_array( 'IGNORE', $insertOptions ) ) {
589 $this->ignoreDupValOnIndex = false;
590 }
591 }
592
593 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
594 $fname = __METHOD__
595 ) {
596 if ( $rows === [] ) {
597 return true; // nothing to do
598 }
599
600 if ( !is_array( reset( $rows ) ) ) {
601 $rows = [ $rows ];
602 }
603
604 $sequenceData = $this->getSequenceData( $table );
605 if ( $sequenceData !== false ) {
606 // add sequence column to each list of columns, when not set
607 foreach ( $rows as &$row ) {
608 if ( !isset( $row[$sequenceData['column']] ) ) {
609 $row[$sequenceData['column']] =
610 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
611 $sequenceData['sequence'] . '\')' );
612 }
613 }
614 }
615
616 return parent::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
617 }
618
619 function tableName( $name, $format = 'quoted' ) {
620 /*
621 Replace reserved words with better ones
622 Using uppercase because that's the only way Oracle can handle
623 quoted tablenames
624 */
625 switch ( $name ) {
626 case 'user':
627 $name = 'MWUSER';
628 break;
629 case 'text':
630 $name = 'PAGECONTENT';
631 break;
632 }
633
634 return strtoupper( parent::tableName( $name, $format ) );
635 }
636
637 function tableNameInternal( $name ) {
638 $name = $this->tableName( $name );
639
640 return preg_replace( '/.*\.(.*)/', '$1', $name );
641 }
642
643 /**
644 * Return sequence_name if table has a sequence
645 *
646 * @param string $table
647 * @return bool
648 */
649 private function getSequenceData( $table ) {
650 if ( $this->sequenceData == null ) {
651 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
652 lower(atc.table_name),
653 lower(atc.column_name)
654 FROM all_sequences asq, all_tab_columns atc
655 WHERE decode(
656 atc.table_name,
657 '{$this->tablePrefix}MWUSER',
658 '{$this->tablePrefix}USER',
659 atc.table_name
660 ) || '_' ||
661 atc.column_name || '_SEQ' = '{$this->tablePrefix}' || asq.sequence_name
662 AND asq.sequence_owner = upper('{$this->getDBname()}')
663 AND atc.owner = upper('{$this->getDBname()}')" );
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 decodeBlob( $b ) {
703 if ( $b instanceof Blob ) {
704 $b = $b->fetch();
705 }
706
707 return $b;
708 }
709
710 function unionQueries( $sqls, $all ) {
711 $glue = ' UNION ALL ';
712
713 return 'SELECT * ' . ( $all ? '' : '/* UNION_UNIQUE */ ' ) .
714 'FROM (' . implode( $glue, $sqls ) . ')';
715 }
716
717 function wasDeadlock() {
718 return $this->lastErrno() == 'OCI-00060';
719 }
720
721 function duplicateTableStructure( $oldName, $newName, $temporary = false,
722 $fname = __METHOD__
723 ) {
724 $temporary = $temporary ? 'TRUE' : 'FALSE';
725
726 $newName = strtoupper( $newName );
727 $oldName = strtoupper( $oldName );
728
729 $tabName = substr( $newName, strlen( $this->tablePrefix ) );
730 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
731 $newPrefix = strtoupper( $this->tablePrefix );
732
733 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
734 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
735 }
736
737 function listTables( $prefix = null, $fname = __METHOD__ ) {
738 $listWhere = '';
739 if ( !empty( $prefix ) ) {
740 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
741 }
742
743 $owner = strtoupper( $this->getDBname() );
744 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
745 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
746
747 // dirty code ... i know
748 $endArray = [];
749 $endArray[] = strtoupper( $prefix . 'MWUSER' );
750 $endArray[] = strtoupper( $prefix . 'PAGE' );
751 $endArray[] = strtoupper( $prefix . 'IMAGE' );
752 $fixedOrderTabs = $endArray;
753 while ( ( $row = $result->fetchRow() ) !== false ) {
754 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
755 $endArray[] = $row['table_name'];
756 }
757 }
758
759 return $endArray;
760 }
761
762 public function dropTable( $tableName, $fName = __METHOD__ ) {
763 $tableName = $this->tableName( $tableName );
764 if ( !$this->tableExists( $tableName ) ) {
765 return false;
766 }
767
768 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
769 }
770
771 function timestamp( $ts = 0 ) {
772 return wfTimestamp( TS_ORACLE, $ts );
773 }
774
775 /**
776 * Return aggregated value function call
777 *
778 * @param array $valuedata
779 * @param string $valuename
780 * @return mixed
781 */
782 public function aggregateValue( $valuedata, $valuename = 'value' ) {
783 return $valuedata;
784 }
785
786 /**
787 * @return string Wikitext of a link to the server software's web site
788 */
789 public function getSoftwareLink() {
790 return '[{{int:version-db-oracle-url}} Oracle]';
791 }
792
793 /**
794 * @return string Version information from the database
795 */
796 function getServerVersion() {
797 // better version number, fallback on driver
798 $rset = $this->doQuery(
799 'SELECT version FROM product_component_version ' .
800 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
801 );
802 $row = $rset->fetchRow();
803 if ( !$row ) {
804 return oci_server_version( $this->conn );
805 }
806
807 return $row['version'];
808 }
809
810 /**
811 * Query whether a given index exists
812 * @param string $table
813 * @param string $index
814 * @param string $fname
815 * @return bool
816 */
817 function indexExists( $table, $index, $fname = __METHOD__ ) {
818 $table = $this->tableName( $table );
819 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
820 $index = strtoupper( $index );
821 $owner = strtoupper( $this->getDBname() );
822 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
823 $res = $this->doQuery( $sql );
824 if ( $res ) {
825 $count = $res->numRows();
826 $res->free();
827 } else {
828 $count = 0;
829 }
830
831 return $count != 0;
832 }
833
834 /**
835 * Query whether a given table exists (in the given schema, or the default mw one if not given)
836 * @param string $table
837 * @param string $fname
838 * @return bool
839 */
840 function tableExists( $table, $fname = __METHOD__ ) {
841 $table = $this->tableName( $table );
842 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
843 $owner = $this->addQuotes( strtoupper( $this->getDBname() ) );
844 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
845 $res = $this->doQuery( $sql );
846 if ( $res && $res->numRows() > 0 ) {
847 $exists = true;
848 } else {
849 $exists = false;
850 }
851
852 $res->free();
853
854 return $exists;
855 }
856
857 /**
858 * Function translates mysql_fetch_field() functionality on ORACLE.
859 * Caching is present for reducing query time.
860 * For internal calls. Use fieldInfo for normal usage.
861 * Returns false if the field doesn't exist
862 *
863 * @param array|string $table
864 * @param string $field
865 * @return ORAField|ORAResult|false
866 */
867 private function fieldInfoMulti( $table, $field ) {
868 $field = strtoupper( $field );
869 if ( is_array( $table ) ) {
870 $table = array_map( [ $this, 'tableNameInternal' ], $table );
871 $tableWhere = 'IN (';
872 foreach ( $table as &$singleTable ) {
873 $singleTable = $this->removeIdentifierQuotes( $singleTable );
874 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
875 return $this->mFieldInfoCache["$singleTable.$field"];
876 }
877 $tableWhere .= '\'' . $singleTable . '\',';
878 }
879 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
880 } else {
881 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
882 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
883 return $this->mFieldInfoCache["$table.$field"];
884 }
885 $tableWhere = '= \'' . $table . '\'';
886 }
887
888 $fieldInfoStmt = oci_parse(
889 $this->conn,
890 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
891 $tableWhere . ' and column_name = \'' . $field . '\''
892 );
893 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
894 $e = oci_error( $fieldInfoStmt );
895 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
896
897 return false;
898 }
899 $res = new ORAResult( $this, $fieldInfoStmt );
900 if ( $res->numRows() == 0 ) {
901 if ( is_array( $table ) ) {
902 foreach ( $table as &$singleTable ) {
903 $this->mFieldInfoCache["$singleTable.$field"] = false;
904 }
905 } else {
906 $this->mFieldInfoCache["$table.$field"] = false;
907 }
908 $fieldInfoTemp = null;
909 } else {
910 $fieldInfoTemp = new ORAField( $res->fetchRow() );
911 $table = $fieldInfoTemp->tableName();
912 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
913 }
914 $res->free();
915
916 return $fieldInfoTemp;
917 }
918
919 /**
920 * @throws DBUnexpectedError
921 * @param string $table
922 * @param string $field
923 * @return ORAField
924 */
925 function fieldInfo( $table, $field ) {
926 if ( is_array( $table ) ) {
927 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
928 }
929
930 return $this->fieldInfoMulti( $table, $field );
931 }
932
933 protected function doBegin( $fname = __METHOD__ ) {
934 $this->trxLevel = 1;
935 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
936 }
937
938 protected function doCommit( $fname = __METHOD__ ) {
939 if ( $this->trxLevel ) {
940 $ret = oci_commit( $this->conn );
941 if ( !$ret ) {
942 throw new DBUnexpectedError( $this, $this->lastError() );
943 }
944 $this->trxLevel = 0;
945 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
946 }
947 }
948
949 protected function doRollback( $fname = __METHOD__ ) {
950 if ( $this->trxLevel ) {
951 oci_rollback( $this->conn );
952 $this->trxLevel = 0;
953 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
954 }
955 }
956
957 function sourceStream(
958 $fp,
959 callable $lineCallback = null,
960 callable $resultCallback = null,
961 $fname = __METHOD__, callable $inputCallback = null
962 ) {
963 $cmd = '';
964 $done = false;
965 $dollarquote = false;
966
967 $replacements = [];
968 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
969 while ( !feof( $fp ) ) {
970 if ( $lineCallback ) {
971 call_user_func( $lineCallback );
972 }
973 $line = trim( fgets( $fp, 1024 ) );
974 $sl = strlen( $line ) - 1;
975
976 if ( $sl < 0 ) {
977 continue;
978 }
979 if ( $line[0] == '-' && $line[1] == '-' ) {
980 continue;
981 }
982
983 // Allow dollar quoting for function declarations
984 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
985 if ( $dollarquote ) {
986 $dollarquote = false;
987 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
988 $done = true;
989 } else {
990 $dollarquote = true;
991 }
992 } elseif ( !$dollarquote ) {
993 if ( $line[$sl] == ';' && ( $sl < 2 || $line[$sl - 1] != ';' ) ) {
994 $done = true;
995 $line = substr( $line, 0, $sl );
996 }
997 }
998
999 if ( $cmd != '' ) {
1000 $cmd .= ' ';
1001 }
1002 $cmd .= "$line\n";
1003
1004 if ( $done ) {
1005 $cmd = str_replace( ';;', ";", $cmd );
1006 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1007 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1008 $replacements[$defines[2]] = $defines[1];
1009 }
1010 } else {
1011 foreach ( $replacements as $mwVar => $scVar ) {
1012 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1013 }
1014
1015 $cmd = $this->replaceVars( $cmd );
1016 if ( $inputCallback ) {
1017 call_user_func( $inputCallback, $cmd );
1018 }
1019 $res = $this->doQuery( $cmd );
1020 if ( $resultCallback ) {
1021 call_user_func( $resultCallback, $res, $this );
1022 }
1023
1024 if ( $res === false ) {
1025 $err = $this->lastError();
1026
1027 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1028 }
1029 }
1030
1031 $cmd = '';
1032 $done = false;
1033 }
1034 }
1035
1036 return true;
1037 }
1038
1039 protected function doSelectDomain( DatabaseDomain $domain ) {
1040 if ( $domain->getSchema() !== null ) {
1041 // We use the *database* aspect of $domain for schema, not the domain schema
1042 throw new DBExpectedError( $this, __CLASS__ . ": domain schemas are not supported." );
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 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
1077 if ( isset( $contLang->mLoaded ) && $contLang->mLoaded ) {
1078 $s = $contLang->checkTitleEncoding( $s );
1079 }
1080
1081 return "'" . $this->strencode( $s ) . "'";
1082 }
1083
1084 public function addIdentifierQuotes( $s ) {
1085 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1086 $s = '/*Q*/' . $s;
1087 }
1088
1089 return $s;
1090 }
1091
1092 public function removeIdentifierQuotes( $s ) {
1093 return strpos( $s, '/*Q*/' ) === false ? $s : substr( $s, 5 );
1094 }
1095
1096 public function isQuotedIdentifier( $s ) {
1097 return strpos( $s, '/*Q*/' ) !== false;
1098 }
1099
1100 private function wrapFieldForWhere( $table, &$col, &$val ) {
1101 $col_info = $this->fieldInfoMulti( $table, $col );
1102 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1103 if ( $col_type == 'CLOB' ) {
1104 $col = 'TO_CHAR(' . $col . ')';
1105 $val =
1106 MediaWikiServices::getInstance()->getContentLanguage()->checkTitleEncoding( $val );
1107 } elseif ( $col_type == 'VARCHAR2' ) {
1108 $val =
1109 MediaWikiServices::getInstance()->getContentLanguage()->checkTitleEncoding( $val );
1110 }
1111 }
1112
1113 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1114 $conds2 = [];
1115 foreach ( $conds as $col => $val ) {
1116 if ( is_array( $val ) ) {
1117 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1118 } else {
1119 if ( is_numeric( $col ) && $parentCol != null ) {
1120 $this->wrapFieldForWhere( $table, $parentCol, $val );
1121 } else {
1122 $this->wrapFieldForWhere( $table, $col, $val );
1123 }
1124 $conds2[$col] = $val;
1125 }
1126 }
1127
1128 return $conds2;
1129 }
1130
1131 function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1132 $options = [], $join_conds = []
1133 ) {
1134 if ( is_array( $conds ) ) {
1135 $conds = $this->wrapConditionsForWhere( $table, $conds );
1136 }
1137
1138 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1139 }
1140
1141 /**
1142 * Returns an optional USE INDEX clause to go after the table, and a
1143 * string to go at the end of the query
1144 *
1145 * @param array $options An associative array of options to be turned into
1146 * an SQL query, valid keys are listed in the function.
1147 * @return array
1148 */
1149 function makeSelectOptions( $options ) {
1150 $preLimitTail = $postLimitTail = '';
1151 $startOpts = '';
1152
1153 $noKeyOptions = [];
1154 foreach ( $options as $key => $option ) {
1155 if ( is_numeric( $key ) ) {
1156 $noKeyOptions[$option] = true;
1157 }
1158 }
1159
1160 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1161
1162 $preLimitTail .= $this->makeOrderBy( $options );
1163
1164 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1165 $postLimitTail .= ' FOR UPDATE';
1166 }
1167
1168 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1169 $startOpts .= 'DISTINCT';
1170 }
1171
1172 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1173 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1174 } else {
1175 $useIndex = '';
1176 }
1177
1178 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1179 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1180 } else {
1181 $ignoreIndex = '';
1182 }
1183
1184 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1185 }
1186
1187 public function delete( $table, $conds, $fname = __METHOD__ ) {
1188 global $wgActorTableSchemaMigrationStage;
1189
1190 if ( is_array( $conds ) ) {
1191 $conds = $this->wrapConditionsForWhere( $table, $conds );
1192 }
1193 // a hack for deleting pages, users and images (which have non-nullable FKs)
1194 // all deletions on these tables have transactions so final failure rollbacks these updates
1195 // @todo: Normalize the schema to match MySQL, no special FKs and such
1196 $table = $this->tableName( $table );
1197 if ( $table == $this->tableName( 'user' ) &&
1198 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD )
1199 ) {
1200 $this->update( 'archive', [ 'ar_user' => 0 ],
1201 [ 'ar_user' => $conds['user_id'] ], $fname );
1202 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1203 [ 'ipb_user' => $conds['user_id'] ], $fname );
1204 $this->update( 'image', [ 'img_user' => 0 ],
1205 [ 'img_user' => $conds['user_id'] ], $fname );
1206 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1207 [ 'oi_user' => $conds['user_id'] ], $fname );
1208 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1209 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1210 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1211 [ 'fa_user' => $conds['user_id'] ], $fname );
1212 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1213 [ 'us_user' => $conds['user_id'] ], $fname );
1214 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1215 [ 'rc_user' => $conds['user_id'] ], $fname );
1216 $this->update( 'logging', [ 'log_user' => 0 ],
1217 [ 'log_user' => $conds['user_id'] ], $fname );
1218 } elseif ( $table == $this->tableName( 'image' ) ) {
1219 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1220 [ 'oi_name' => $conds['img_name'] ], $fname );
1221 }
1222
1223 return parent::delete( $table, $conds, $fname );
1224 }
1225
1226 /**
1227 * @param string $table
1228 * @param array $values
1229 * @param array $conds
1230 * @param string $fname
1231 * @param array $options
1232 * @return bool
1233 * @throws DBUnexpectedError
1234 */
1235 function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1236 $table = $this->tableName( $table );
1237 $opts = $this->makeUpdateOptions( $options );
1238 $sql = "UPDATE $opts $table SET ";
1239
1240 $first = true;
1241 foreach ( $values as $col => &$val ) {
1242 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1243
1244 if ( !$first ) {
1245 $sqlSet = ', ' . $sqlSet;
1246 } else {
1247 $first = false;
1248 }
1249 $sql .= $sqlSet;
1250 }
1251
1252 if ( $conds !== [] && $conds !== '*' ) {
1253 $conds = $this->wrapConditionsForWhere( $table, $conds );
1254 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1255 }
1256
1257 $this->mLastResult = $stmt = oci_parse( $this->conn, $sql );
1258 if ( $stmt === false ) {
1259 $e = oci_error( $this->conn );
1260 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1261
1262 return false;
1263 }
1264 foreach ( $values as $col => &$val ) {
1265 $col_info = $this->fieldInfoMulti( $table, $col );
1266 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1267
1268 if ( $val === null ) {
1269 // do nothing ... null was inserted in statement creation
1270 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1271 if ( is_object( $val ) ) {
1272 $val = $val->getData();
1273 }
1274
1275 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1276 $val = '31-12-2030 12:00:00.000000';
1277 }
1278
1279 $val = MediaWikiServices::getInstance()->getContentLanguage()->
1280 checkTitleEncoding( $val );
1281 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1282 $e = oci_error( $stmt );
1283 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1284
1285 return false;
1286 }
1287 } else {
1288 /** @var OCI_Lob[] $lob */
1289 $lob[$col] = oci_new_descriptor( $this->conn, OCI_D_LOB );
1290 if ( $lob[$col] === false ) {
1291 $e = oci_error( $stmt );
1292 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1293 }
1294
1295 if ( is_object( $val ) ) {
1296 $val = $val->getData();
1297 }
1298
1299 if ( $col_type == 'BLOB' ) {
1300 $lob[$col]->writeTemporary( $val );
1301 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB );
1302 } else {
1303 $lob[$col]->writeTemporary( $val );
1304 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB );
1305 }
1306 }
1307 }
1308
1309 Wikimedia\suppressWarnings();
1310
1311 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1312 $e = oci_error( $stmt );
1313 if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
1314 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1315
1316 return false;
1317 } else {
1318 $this->mAffectedRows = oci_num_rows( $stmt );
1319 }
1320 } else {
1321 $this->mAffectedRows = oci_num_rows( $stmt );
1322 }
1323
1324 Wikimedia\restoreWarnings();
1325
1326 if ( isset( $lob ) ) {
1327 foreach ( $lob as $lob_v ) {
1328 $lob_v->free();
1329 }
1330 }
1331
1332 if ( !$this->trxLevel ) {
1333 oci_commit( $this->conn );
1334 }
1335
1336 return oci_free_statement( $stmt );
1337 }
1338
1339 function bitNot( $field ) {
1340 // expecting bit-fields smaller than 4bytes
1341 return 'BITNOT(' . $field . ')';
1342 }
1343
1344 function bitAnd( $fieldLeft, $fieldRight ) {
1345 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1346 }
1347
1348 function bitOr( $fieldLeft, $fieldRight ) {
1349 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1350 }
1351
1352 function getServer() {
1353 return $this->server;
1354 }
1355
1356 public function buildGroupConcatField(
1357 $delim, $table, $field, $conds = '', $join_conds = []
1358 ) {
1359 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1360
1361 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1362 }
1363
1364 public function buildSubstring( $input, $startPosition, $length = null ) {
1365 $this->assertBuildSubstringParams( $startPosition, $length );
1366 $params = [ $input, $startPosition ];
1367 if ( $length !== null ) {
1368 $params[] = $length;
1369 }
1370 return 'SUBSTR(' . implode( ',', $params ) . ')';
1371 }
1372
1373 /**
1374 * @param string $field Field or column to cast
1375 * @return string
1376 * @since 1.28
1377 */
1378 public function buildStringCast( $field ) {
1379 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1380 }
1381
1382 public function getInfinity() {
1383 return '31-12-2030 12:00:00.000000';
1384 }
1385 }