7f79ca1c0bfe977f7f2c2c09ebc8c343889184b2
[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 Wikimedia\Timestamp\ConvertibleTimestamp;
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
59 // @TODO: dependency inject
60 Hooks::run( 'DatabaseOraclePostInit', [ $this ] );
61 }
62
63 function __destruct() {
64 if ( $this->opened ) {
65 Wikimedia\suppressWarnings();
66 $this->close();
67 Wikimedia\restoreWarnings();
68 }
69 }
70
71 function getType() {
72 return 'oracle';
73 }
74
75 function implicitGroupby() {
76 return false;
77 }
78
79 function implicitOrderby() {
80 return false;
81 }
82
83 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
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 $session_mode = ( $this->flags & DBO_SYSDBA ) ? OCI_SYSDBA : OCI_DEFAULT;
111
112 Wikimedia\suppressWarnings();
113 if ( $this->flags & DBO_PERSISTENT ) {
114 $this->conn = oci_pconnect(
115 $this->user,
116 $this->password,
117 $this->server,
118 $this->defaultCharset,
119 $session_mode
120 );
121 } elseif ( $this->flags & DBO_DEFAULT ) {
122 $this->conn = oci_new_connect(
123 $this->user,
124 $this->password,
125 $this->server,
126 $this->defaultCharset,
127 $session_mode
128 );
129 } else {
130 $this->conn = oci_connect(
131 $this->user,
132 $this->password,
133 $this->server,
134 $this->defaultCharset,
135 $session_mode
136 );
137 }
138 Wikimedia\restoreWarnings();
139
140 if ( $this->user != $realDatabase ) {
141 // change current schema in session
142 $this->selectDB( $realDatabase );
143 } else {
144 $this->currentDomain = new DatabaseDomain(
145 $realDatabase,
146 null,
147 $tablePrefix
148 );
149 }
150
151 if ( !$this->conn ) {
152 throw new DBConnectionError( $this, $this->lastError() );
153 }
154
155 $this->opened = true;
156
157 # removed putenv calls because they interfere with the system globaly
158 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
159 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
160 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
161
162 return (bool)$this->conn;
163 }
164
165 /**
166 * Closes a database connection, if it is open
167 * Returns success, true if already closed
168 * @return bool
169 */
170 protected function closeConnection() {
171 return oci_close( $this->conn );
172 }
173
174 function execFlags() {
175 return $this->trxLevel ? OCI_NO_AUTO_COMMIT : OCI_COMMIT_ON_SUCCESS;
176 }
177
178 /**
179 * @param string $sql
180 * @return bool|mixed|ORAResult
181 */
182 protected function doQuery( $sql ) {
183 wfDebug( "SQL: [$sql]\n" );
184 if ( !mb_check_encoding( (string)$sql, 'UTF-8' ) ) {
185 throw new DBUnexpectedError( $this, "SQL encoding is invalid\n$sql" );
186 }
187
188 // handle some oracle specifics
189 // remove AS column/table/subquery namings
190 if ( !$this->getFlag( DBO_DDLMODE ) ) {
191 $sql = preg_replace( '/ as /i', ' ', $sql );
192 }
193
194 // Oracle has issues with UNION clause if the statement includes LOB fields
195 // So we do a UNION ALL and then filter the results array with array_unique
196 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
197 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
198 // you have to select data from plan table after explain
199 $explain_id = MWTimestamp::getLocalInstance()->format( 'dmYHis' );
200
201 $sql = preg_replace(
202 '/^EXPLAIN /',
203 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
204 $sql,
205 1,
206 $explain_count
207 );
208
209 Wikimedia\suppressWarnings();
210
211 $this->mLastResult = $stmt = oci_parse( $this->conn, $sql );
212 if ( $stmt === false ) {
213 $e = oci_error( $this->conn );
214 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
215
216 return false;
217 }
218
219 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
220 $e = oci_error( $stmt );
221 if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
222 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
223
224 return false;
225 }
226 }
227
228 Wikimedia\restoreWarnings();
229
230 if ( $explain_count > 0 ) {
231 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
232 'WHERE statement_id = \'' . $explain_id . '\'' );
233 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
234 return new ORAResult( $this, $stmt, $union_unique );
235 } else {
236 $this->mAffectedRows = oci_num_rows( $stmt );
237
238 return true;
239 }
240 }
241
242 function queryIgnore( $sql, $fname = '' ) {
243 return $this->query( $sql, $fname, true );
244 }
245
246 /**
247 * Frees resources associated with the LOB descriptor
248 * @param ResultWrapper|ORAResult $res
249 */
250 function freeResult( $res ) {
251 if ( $res instanceof ResultWrapper ) {
252 $res = $res->result;
253 }
254
255 $res->free();
256 }
257
258 /**
259 * @param ResultWrapper|ORAResult $res
260 * @return mixed
261 */
262 function fetchObject( $res ) {
263 if ( $res instanceof ResultWrapper ) {
264 $res = $res->result;
265 }
266
267 return $res->fetchObject();
268 }
269
270 /**
271 * @param ResultWrapper|ORAResult $res
272 * @return mixed
273 */
274 function fetchRow( $res ) {
275 if ( $res instanceof ResultWrapper ) {
276 $res = $res->result;
277 }
278
279 return $res->fetchRow();
280 }
281
282 /**
283 * @param ResultWrapper|ORAResult $res
284 * @return int
285 */
286 function numRows( $res ) {
287 if ( $res instanceof ResultWrapper ) {
288 $res = $res->result;
289 }
290
291 return $res->numRows();
292 }
293
294 /**
295 * @param ResultWrapper|ORAResult $res
296 * @return int
297 */
298 function numFields( $res ) {
299 if ( $res instanceof ResultWrapper ) {
300 $res = $res->result;
301 }
302
303 return $res->numFields();
304 }
305
306 function fieldName( $stmt, $n ) {
307 return oci_field_name( $stmt, $n );
308 }
309
310 function insertId() {
311 $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
312 $row = $this->fetchRow( $res );
313 return is_null( $row[0] ) ? null : (int)$row[0];
314 }
315
316 /**
317 * @param mixed $res
318 * @param int $row
319 */
320 function dataSeek( $res, $row ) {
321 if ( $res instanceof ORAResult ) {
322 $res->seek( $row );
323 } else {
324 $res->result->seek( $row );
325 }
326 }
327
328 function lastError() {
329 if ( $this->conn === false ) {
330 $e = oci_error();
331 } else {
332 $e = oci_error( $this->conn );
333 }
334
335 return $e['message'];
336 }
337
338 function lastErrno() {
339 if ( $this->conn === false ) {
340 $e = oci_error();
341 } else {
342 $e = oci_error( $this->conn );
343 }
344
345 return $e['code'];
346 }
347
348 protected function fetchAffectedRowCount() {
349 return $this->mAffectedRows;
350 }
351
352 /**
353 * Returns information about an index
354 * If errors are explicitly ignored, returns NULL on failure
355 * @param string $table
356 * @param string $index
357 * @param string $fname
358 * @return bool
359 */
360 function indexInfo( $table, $index, $fname = __METHOD__ ) {
361 return false;
362 }
363
364 function indexUnique( $table, $index, $fname = __METHOD__ ) {
365 return false;
366 }
367
368 function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
369 if ( !count( $a ) ) {
370 return true;
371 }
372
373 if ( !is_array( $options ) ) {
374 $options = [ $options ];
375 }
376
377 if ( in_array( 'IGNORE', $options ) ) {
378 $this->ignoreDupValOnIndex = true;
379 }
380
381 if ( !is_array( reset( $a ) ) ) {
382 $a = [ $a ];
383 }
384
385 foreach ( $a as &$row ) {
386 $this->insertOneRow( $table, $row, $fname );
387 }
388
389 if ( in_array( 'IGNORE', $options ) ) {
390 $this->ignoreDupValOnIndex = false;
391 }
392
393 return true;
394 }
395
396 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
397 $col_info = $this->fieldInfoMulti( $table, $col );
398 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
399
400 $bind = '';
401 if ( is_numeric( $col ) ) {
402 $bind = $val;
403 $val = null;
404
405 return $bind;
406 } elseif ( $includeCol ) {
407 $bind = "$col = ";
408 }
409
410 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
411 $val = null;
412 }
413
414 if ( $val === 'NULL' ) {
415 $val = null;
416 }
417
418 if ( $val === null ) {
419 if (
420 $col_info != false &&
421 $col_info->isNullable() == 0 &&
422 $col_info->defaultValue() != null
423 ) {
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 (
485 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
486 strtolower( $val ) == 'infinity'
487 ) {
488 $val = $this->getInfinity();
489 }
490
491 $val = $this->getVerifiedUTF8( $val );
492 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR ) === false ) {
493 $e = oci_error( $stmt );
494 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
495
496 return false;
497 }
498 } else {
499 /** @var OCI_Lob[] $lob */
500 $lob[$col] = oci_new_descriptor( $this->conn, OCI_D_LOB );
501 if ( $lob[$col] === false ) {
502 $e = oci_error( $stmt );
503 throw new DBUnexpectedError(
504 $this,
505 "Cannot create LOB descriptor: " . $e['message']
506 );
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']] =
563 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
564 }
565
566 // count-alias subselect fields to avoid abigious definition errors
567 $i = 0;
568 foreach ( $varMap as &$val ) {
569 $val .= ' field' . $i;
570 $i++;
571 }
572
573 $selectSql = $this->selectSQLText(
574 $srcTable,
575 array_values( $varMap ),
576 $conds,
577 $fname,
578 $selectOptions,
579 $selectJoinConds
580 );
581
582 $sql = "INSERT INTO $destTable (" .
583 implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
584
585 if ( in_array( 'IGNORE', $insertOptions ) ) {
586 $this->ignoreDupValOnIndex = true;
587 }
588
589 $this->query( $sql, $fname );
590
591 if ( in_array( 'IGNORE', $insertOptions ) ) {
592 $this->ignoreDupValOnIndex = false;
593 }
594 }
595
596 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
597 $fname = __METHOD__
598 ) {
599 if ( $rows === [] ) {
600 return true; // nothing to do
601 }
602
603 if ( !is_array( reset( $rows ) ) ) {
604 $rows = [ $rows ];
605 }
606
607 $sequenceData = $this->getSequenceData( $table );
608 if ( $sequenceData !== false ) {
609 // add sequence column to each list of columns, when not set
610 foreach ( $rows as &$row ) {
611 if ( !isset( $row[$sequenceData['column']] ) ) {
612 $row[$sequenceData['column']] =
613 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
614 $sequenceData['sequence'] . '\')' );
615 }
616 }
617 }
618
619 return parent::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
620 }
621
622 function tableName( $name, $format = 'quoted' ) {
623 /*
624 Replace reserved words with better ones
625 Using uppercase because that's the only way Oracle can handle
626 quoted tablenames
627 */
628 switch ( $name ) {
629 case 'user':
630 $name = 'MWUSER';
631 break;
632 case 'text':
633 $name = 'PAGECONTENT';
634 break;
635 }
636
637 return strtoupper( parent::tableName( $name, $format ) );
638 }
639
640 function tableNameInternal( $name ) {
641 $name = $this->tableName( $name );
642
643 return preg_replace( '/.*\.(.*)/', '$1', $name );
644 }
645
646 /**
647 * Return sequence_name if table has a sequence
648 *
649 * @param string $table
650 * @return bool
651 */
652 private function getSequenceData( $table ) {
653 if ( $this->sequenceData == null ) {
654 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
655 lower(atc.table_name),
656 lower(atc.column_name)
657 FROM all_sequences asq, all_tab_columns atc
658 WHERE decode(
659 atc.table_name,
660 '{$this->tablePrefix}MWUSER',
661 '{$this->tablePrefix}USER',
662 atc.table_name
663 ) || '_' ||
664 atc.column_name || '_SEQ' = '{$this->tablePrefix}' || asq.sequence_name
665 AND asq.sequence_owner = upper('{$this->getDBname()}')
666 AND atc.owner = upper('{$this->getDBname()}')" );
667
668 while ( ( $row = $result->fetchRow() ) !== false ) {
669 $this->sequenceData[$row[1]] = [
670 'sequence' => $row[0],
671 'column' => $row[2]
672 ];
673 }
674 }
675 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
676
677 return $this->sequenceData[$table] ?? false;
678 }
679
680 /**
681 * Returns the size of a text field, or -1 for "unlimited"
682 *
683 * @param string $table
684 * @param string $field
685 * @return mixed
686 */
687 function textFieldSize( $table, $field ) {
688 $fieldInfoData = $this->fieldInfo( $table, $field );
689
690 return $fieldInfoData->maxLength();
691 }
692
693 function limitResult( $sql, $limit, $offset = false ) {
694 if ( $offset === false ) {
695 $offset = 0;
696 }
697
698 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
699 }
700
701 function encodeBlob( $b ) {
702 return new Blob( $b );
703 }
704
705 function unionQueries( $sqls, $all ) {
706 $glue = ' UNION ALL ';
707
708 return 'SELECT * ' . ( $all ? '' : '/* UNION_UNIQUE */ ' ) .
709 'FROM (' . implode( $glue, $sqls ) . ')';
710 }
711
712 function wasDeadlock() {
713 return $this->lastErrno() == 'OCI-00060';
714 }
715
716 function duplicateTableStructure( $oldName, $newName, $temporary = false,
717 $fname = __METHOD__
718 ) {
719 $temporary = $temporary ? 'TRUE' : 'FALSE';
720
721 $newName = strtoupper( $newName );
722 $oldName = strtoupper( $oldName );
723
724 $tabName = substr( $newName, strlen( $this->tablePrefix ) );
725 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
726 $newPrefix = strtoupper( $this->tablePrefix );
727
728 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
729 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
730 }
731
732 function listTables( $prefix = null, $fname = __METHOD__ ) {
733 $listWhere = '';
734 if ( !empty( $prefix ) ) {
735 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
736 }
737
738 $owner = strtoupper( $this->getDBname() );
739 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
740 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
741
742 // dirty code ... i know
743 $endArray = [];
744 $endArray[] = strtoupper( $prefix . 'MWUSER' );
745 $endArray[] = strtoupper( $prefix . 'PAGE' );
746 $endArray[] = strtoupper( $prefix . 'IMAGE' );
747 $fixedOrderTabs = $endArray;
748 while ( ( $row = $result->fetchRow() ) !== false ) {
749 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
750 $endArray[] = $row['table_name'];
751 }
752 }
753
754 return $endArray;
755 }
756
757 public function dropTable( $tableName, $fName = __METHOD__ ) {
758 $tableName = $this->tableName( $tableName );
759 if ( !$this->tableExists( $tableName ) ) {
760 return false;
761 }
762
763 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
764 }
765
766 public function timestamp( $ts = 0 ) {
767 $t = new ConvertibleTimestamp( $ts );
768 // Let errors bubble up to avoid putting garbage in the DB
769 return $t->getTimestamp( TS_ORACLE );
770 }
771
772 /**
773 * Return aggregated value function call
774 *
775 * @param array $valuedata
776 * @param string $valuename
777 * @return mixed
778 */
779 public function aggregateValue( $valuedata, $valuename = 'value' ) {
780 return $valuedata;
781 }
782
783 /**
784 * @return string Wikitext of a link to the server software's web site
785 */
786 public function getSoftwareLink() {
787 return '[{{int:version-db-oracle-url}} Oracle]';
788 }
789
790 /**
791 * @return string Version information from the database
792 */
793 function getServerVersion() {
794 // better version number, fallback on driver
795 $rset = $this->doQuery(
796 'SELECT version FROM product_component_version ' .
797 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
798 );
799 $row = $rset->fetchRow();
800 if ( !$row ) {
801 return oci_server_version( $this->conn );
802 }
803
804 return $row['version'];
805 }
806
807 /**
808 * Query whether a given index exists
809 * @param string $table
810 * @param string $index
811 * @param string $fname
812 * @return bool
813 */
814 function indexExists( $table, $index, $fname = __METHOD__ ) {
815 $table = $this->tableName( $table );
816 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
817 $index = strtoupper( $index );
818 $owner = strtoupper( $this->getDBname() );
819 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
820 $res = $this->doQuery( $sql );
821 if ( $res ) {
822 $count = $res->numRows();
823 $res->free();
824 } else {
825 $count = 0;
826 }
827
828 return $count != 0;
829 }
830
831 /**
832 * Query whether a given table exists (in the given schema, or the default mw one if not given)
833 * @param string $table
834 * @param string $fname
835 * @return bool
836 */
837 function tableExists( $table, $fname = __METHOD__ ) {
838 $table = $this->tableName( $table );
839 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
840 $owner = $this->addQuotes( strtoupper( $this->getDBname() ) );
841 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
842 $res = $this->doQuery( $sql );
843 if ( $res && $res->numRows() > 0 ) {
844 $exists = true;
845 } else {
846 $exists = false;
847 }
848
849 $res->free();
850
851 return $exists;
852 }
853
854 /**
855 * Function translates mysql_fetch_field() functionality on ORACLE.
856 * Caching is present for reducing query time.
857 * For internal calls. Use fieldInfo for normal usage.
858 * Returns false if the field doesn't exist
859 *
860 * @param array|string $table
861 * @param string $field
862 * @return ORAField|ORAResult|false
863 */
864 private function fieldInfoMulti( $table, $field ) {
865 $field = strtoupper( $field );
866 if ( is_array( $table ) ) {
867 $table = array_map( [ $this, 'tableNameInternal' ], $table );
868 $tableWhere = 'IN (';
869 foreach ( $table as &$singleTable ) {
870 $singleTable = $this->removeIdentifierQuotes( $singleTable );
871 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
872 return $this->mFieldInfoCache["$singleTable.$field"];
873 }
874 $tableWhere .= '\'' . $singleTable . '\',';
875 }
876 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
877 } else {
878 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
879 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
880 return $this->mFieldInfoCache["$table.$field"];
881 }
882 $tableWhere = '= \'' . $table . '\'';
883 }
884
885 $fieldInfoStmt = oci_parse(
886 $this->conn,
887 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
888 $tableWhere . ' and column_name = \'' . $field . '\''
889 );
890 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
891 $e = oci_error( $fieldInfoStmt );
892 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
893
894 return false;
895 }
896 $res = new ORAResult( $this, $fieldInfoStmt );
897 if ( $res->numRows() == 0 ) {
898 if ( is_array( $table ) ) {
899 foreach ( $table as &$singleTable ) {
900 $this->mFieldInfoCache["$singleTable.$field"] = false;
901 }
902 } else {
903 $this->mFieldInfoCache["$table.$field"] = false;
904 }
905 $fieldInfoTemp = null;
906 } else {
907 $fieldInfoTemp = new ORAField( $res->fetchRow() );
908 $table = $fieldInfoTemp->tableName();
909 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
910 }
911 $res->free();
912
913 return $fieldInfoTemp;
914 }
915
916 /**
917 * @throws DBUnexpectedError
918 * @param string $table
919 * @param string $field
920 * @return ORAField
921 */
922 function fieldInfo( $table, $field ) {
923 if ( is_array( $table ) ) {
924 throw new DBUnexpectedError(
925 $this,
926 'DatabaseOracle::fieldInfo called with table array!'
927 );
928 }
929
930 return $this->fieldInfoMulti( $table, $field );
931 }
932
933 protected function doBegin( $fname = __METHOD__ ) {
934 $this->trxLevel = 1;
935 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
936 }
937
938 protected function doCommit( $fname = __METHOD__ ) {
939 if ( $this->trxLevel ) {
940 $ret = oci_commit( $this->conn );
941 if ( !$ret ) {
942 throw new DBUnexpectedError( $this, $this->lastError() );
943 }
944 $this->trxLevel = 0;
945 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
946 }
947 }
948
949 protected function doRollback( $fname = __METHOD__ ) {
950 if ( $this->trxLevel ) {
951 oci_rollback( $this->conn );
952 $this->trxLevel = 0;
953 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
954 }
955 }
956
957 function sourceStream(
958 $fp,
959 callable $lineCallback = null,
960 callable $resultCallback = null,
961 $fname = __METHOD__, callable $inputCallback = null
962 ) {
963 $cmd = '';
964 $done = false;
965 $dollarquote = false;
966
967 $replacements = [];
968 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
969 while ( !feof( $fp ) ) {
970 if ( $lineCallback ) {
971 $lineCallback();
972 }
973 $line = trim( fgets( $fp, 1024 ) );
974 $sl = strlen( $line ) - 1;
975
976 if ( $sl < 0 ) {
977 continue;
978 }
979 if ( $line[0] == '-' && $line[1] == '-' ) {
980 continue;
981 }
982
983 // Allow dollar quoting for function declarations
984 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
985 if ( $dollarquote ) {
986 $dollarquote = false;
987 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
988 $done = true;
989 } else {
990 $dollarquote = true;
991 }
992 } elseif ( !$dollarquote ) {
993 if ( $line[$sl] == ';' && ( $sl < 2 || $line[$sl - 1] != ';' ) ) {
994 $done = true;
995 $line = substr( $line, 0, $sl );
996 }
997 }
998
999 if ( $cmd != '' ) {
1000 $cmd .= ' ';
1001 }
1002 $cmd .= "$line\n";
1003
1004 if ( $done ) {
1005 $cmd = str_replace( ';;', ";", $cmd );
1006 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1007 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1008 $replacements[$defines[2]] = $defines[1];
1009 }
1010 } else {
1011 foreach ( $replacements as $mwVar => $scVar ) {
1012 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1013 }
1014
1015 $cmd = $this->replaceVars( $cmd );
1016 if ( $inputCallback ) {
1017 $inputCallback( $cmd );
1018 }
1019 $res = $this->doQuery( $cmd );
1020 if ( $resultCallback ) {
1021 call_user_func( $resultCallback, $res, $this );
1022 }
1023
1024 if ( $res === false ) {
1025 $err = $this->lastError();
1026
1027 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1028 }
1029 }
1030
1031 $cmd = '';
1032 $done = false;
1033 }
1034 }
1035
1036 return true;
1037 }
1038
1039 protected function doSelectDomain( DatabaseDomain $domain ) {
1040 if ( $domain->getSchema() !== null ) {
1041 // We use the *database* aspect of $domain for schema, not the domain schema
1042 throw new DBExpectedError( $this, __CLASS__ . ": domain schemas are not supported." );
1043 }
1044
1045 $database = $domain->getDatabase();
1046 if ( $database === null || $database === $this->user ) {
1047 // Backward compatibility
1048 $this->currentDomain = $domain;
1049
1050 return true;
1051 }
1052
1053 // https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj32268.html
1054 $encDatabase = $this->addIdentifierQuotes( strtoupper( $database ) );
1055 $sql = "ALTER SESSION SET CURRENT_SCHEMA=$encDatabase";
1056 $stmt = oci_parse( $this->conn, $sql );
1057 Wikimedia\suppressWarnings();
1058 $success = oci_execute( $stmt );
1059 Wikimedia\restoreWarnings();
1060 if ( $success ) {
1061 // Update that domain fields on success (no exception thrown)
1062 $this->currentDomain = $domain;
1063 } else {
1064 $e = oci_error( $stmt );
1065 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1066 }
1067
1068 return true;
1069 }
1070
1071 function strencode( $s ) {
1072 return str_replace( "'", "''", $s );
1073 }
1074
1075 function addQuotes( $s ) {
1076 return "'" . $this->strencode( $this->getVerifiedUTF8( $s ) ) . "'";
1077 }
1078
1079 public function addIdentifierQuotes( $s ) {
1080 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1081 $s = '/*Q*/' . $s;
1082 }
1083
1084 return $s;
1085 }
1086
1087 public function removeIdentifierQuotes( $s ) {
1088 return strpos( $s, '/*Q*/' ) === false ? $s : substr( $s, 5 );
1089 }
1090
1091 public function isQuotedIdentifier( $s ) {
1092 return strpos( $s, '/*Q*/' ) !== false;
1093 }
1094
1095 private function wrapFieldForWhere( $table, &$col, &$val ) {
1096 $col_info = $this->fieldInfoMulti( $table, $col );
1097 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1098 if ( $col_type == 'CLOB' ) {
1099 $col = 'TO_CHAR(' . $col . ')';
1100 $val = $this->getVerifiedUTF8( $val );
1101 } elseif ( $col_type == 'VARCHAR2' ) {
1102 $val = $this->getVerifiedUTF8( $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 (
1269 preg_match( '/^timestamp.*/i', $col_type ) == 1 &&
1270 strtolower( $val ) == 'infinity'
1271 ) {
1272 $val = '31-12-2030 12:00:00.000000';
1273 }
1274
1275 $val = $this->getVerifiedUTF8( $val );
1276 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1277 $e = oci_error( $stmt );
1278 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1279
1280 return false;
1281 }
1282 } else {
1283 /** @var OCI_Lob[] $lob */
1284 $lob[$col] = oci_new_descriptor( $this->conn, OCI_D_LOB );
1285 if ( $lob[$col] === false ) {
1286 $e = oci_error( $stmt );
1287 throw new DBUnexpectedError(
1288 $this,
1289 "Cannot create LOB descriptor: " . $e['message']
1290 );
1291 }
1292
1293 if ( is_object( $val ) ) {
1294 $val = $val->getData();
1295 }
1296
1297 if ( $col_type == 'BLOB' ) {
1298 $lob[$col]->writeTemporary( $val );
1299 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB );
1300 } else {
1301 $lob[$col]->writeTemporary( $val );
1302 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB );
1303 }
1304 }
1305 }
1306
1307 Wikimedia\suppressWarnings();
1308
1309 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1310 $e = oci_error( $stmt );
1311 if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
1312 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1313
1314 return false;
1315 } else {
1316 $this->mAffectedRows = oci_num_rows( $stmt );
1317 }
1318 } else {
1319 $this->mAffectedRows = oci_num_rows( $stmt );
1320 }
1321
1322 Wikimedia\restoreWarnings();
1323
1324 if ( isset( $lob ) ) {
1325 foreach ( $lob as $lob_v ) {
1326 $lob_v->free();
1327 }
1328 }
1329
1330 if ( !$this->trxLevel ) {
1331 oci_commit( $this->conn );
1332 }
1333
1334 return oci_free_statement( $stmt );
1335 }
1336
1337 function bitNot( $field ) {
1338 // expecting bit-fields smaller than 4bytes
1339 return 'BITNOT(' . $field . ')';
1340 }
1341
1342 function bitAnd( $fieldLeft, $fieldRight ) {
1343 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1344 }
1345
1346 function bitOr( $fieldLeft, $fieldRight ) {
1347 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1348 }
1349
1350 public function buildGroupConcatField(
1351 $delim, $table, $field, $conds = '', $join_conds = []
1352 ) {
1353 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1354
1355 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1356 }
1357
1358 public function buildSubstring( $input, $startPosition, $length = null ) {
1359 $this->assertBuildSubstringParams( $startPosition, $length );
1360 $params = [ $input, $startPosition ];
1361 if ( $length !== null ) {
1362 $params[] = $length;
1363 }
1364 return 'SUBSTR(' . implode( ',', $params ) . ')';
1365 }
1366
1367 /**
1368 * @param string $field Field or column to cast
1369 * @return string
1370 * @since 1.28
1371 */
1372 public function buildStringCast( $field ) {
1373 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1374 }
1375
1376 public function getInfinity() {
1377 return '31-12-2030 12:00:00.000000';
1378 }
1379
1380 /**
1381 * @param string $s
1382 * @return string
1383 */
1384 private function getVerifiedUTF8( $s ) {
1385 if ( mb_check_encoding( (string)$s, 'UTF-8' ) ) {
1386 return $s; // valid
1387 }
1388
1389 throw new DBUnexpectedError( $this, "Non BLOB/CLOB field must be UTF-8." );
1390 }
1391 }