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