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