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