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