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