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