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