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