Re add wpScrolltop id in EditPage
[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 = [], $selectJoinConds = []
562 ) {
563 $destTable = $this->tableName( $destTable );
564
565 $sequenceData = $this->getSequenceData( $destTable );
566 if ( $sequenceData !== false &&
567 !isset( $varMap[$sequenceData['column']] )
568 ) {
569 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
570 }
571
572 // count-alias subselect fields to avoid abigious definition errors
573 $i = 0;
574 foreach ( $varMap as &$val ) {
575 $val = $val . ' field' . ( $i++ );
576 }
577
578 $selectSql = $this->selectSQLText(
579 $srcTable,
580 array_values( $varMap ),
581 $conds,
582 $fname,
583 $selectOptions,
584 $selectJoinConds
585 );
586
587 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
588
589 if ( in_array( 'IGNORE', $insertOptions ) ) {
590 $this->ignoreDupValOnIndex = true;
591 }
592
593 $retval = $this->query( $sql, $fname );
594
595 if ( in_array( 'IGNORE', $insertOptions ) ) {
596 $this->ignoreDupValOnIndex = false;
597 }
598
599 return $retval;
600 }
601
602 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
603 $fname = __METHOD__
604 ) {
605 if ( !count( $rows ) ) {
606 return true; // nothing to do
607 }
608
609 if ( !is_array( reset( $rows ) ) ) {
610 $rows = [ $rows ];
611 }
612
613 $sequenceData = $this->getSequenceData( $table );
614 if ( $sequenceData !== false ) {
615 // add sequence column to each list of columns, when not set
616 foreach ( $rows as &$row ) {
617 if ( !isset( $row[$sequenceData['column']] ) ) {
618 $row[$sequenceData['column']] =
619 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
620 $sequenceData['sequence'] . '\')' );
621 }
622 }
623 }
624
625 return parent::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
626 }
627
628 function tableName( $name, $format = 'quoted' ) {
629 /*
630 Replace reserved words with better ones
631 Using uppercase because that's the only way Oracle can handle
632 quoted tablenames
633 */
634 switch ( $name ) {
635 case 'user':
636 $name = 'MWUSER';
637 break;
638 case 'text':
639 $name = 'PAGECONTENT';
640 break;
641 }
642
643 return strtoupper( parent::tableName( $name, $format ) );
644 }
645
646 function tableNameInternal( $name ) {
647 $name = $this->tableName( $name );
648
649 return preg_replace( '/.*\.(.*)/', '$1', $name );
650 }
651
652 /**
653 * Return the next in a sequence, save the value for retrieval via insertId()
654 *
655 * @param string $seqName
656 * @return null|int
657 */
658 function nextSequenceValue( $seqName ) {
659 $res = $this->query( "SELECT $seqName.nextval FROM dual" );
660 $row = $this->fetchRow( $res );
661 $this->mInsertId = $row[0];
662
663 return $this->mInsertId;
664 }
665
666 /**
667 * Return sequence_name if table has a sequence
668 *
669 * @param string $table
670 * @return bool
671 */
672 private function getSequenceData( $table ) {
673 if ( $this->sequenceData == null ) {
674 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
675 lower(atc.table_name),
676 lower(atc.column_name)
677 FROM all_sequences asq, all_tab_columns atc
678 WHERE decode(
679 atc.table_name,
680 '{$this->mTablePrefix}MWUSER',
681 '{$this->mTablePrefix}USER',
682 atc.table_name
683 ) || '_' ||
684 atc.column_name || '_SEQ' = '{$this->mTablePrefix}' || asq.sequence_name
685 AND asq.sequence_owner = upper('{$this->mDBname}')
686 AND atc.owner = upper('{$this->mDBname}')" );
687
688 while ( ( $row = $result->fetchRow() ) !== false ) {
689 $this->sequenceData[$row[1]] = [
690 'sequence' => $row[0],
691 'column' => $row[2]
692 ];
693 }
694 }
695 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
696
697 return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
698 }
699
700 /**
701 * Returns the size of a text field, or -1 for "unlimited"
702 *
703 * @param string $table
704 * @param string $field
705 * @return mixed
706 */
707 function textFieldSize( $table, $field ) {
708 $fieldInfoData = $this->fieldInfo( $table, $field );
709
710 return $fieldInfoData->maxLength();
711 }
712
713 function limitResult( $sql, $limit, $offset = false ) {
714 if ( $offset === false ) {
715 $offset = 0;
716 }
717
718 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
719 }
720
721 function encodeBlob( $b ) {
722 return new Blob( $b );
723 }
724
725 function decodeBlob( $b ) {
726 if ( $b instanceof Blob ) {
727 $b = $b->fetch();
728 }
729
730 return $b;
731 }
732
733 function unionQueries( $sqls, $all ) {
734 $glue = ' UNION ALL ';
735
736 return 'SELECT * ' . ( $all ? '' : '/* UNION_UNIQUE */ ' ) .
737 'FROM (' . implode( $glue, $sqls ) . ')';
738 }
739
740 function wasDeadlock() {
741 return $this->lastErrno() == 'OCI-00060';
742 }
743
744 function duplicateTableStructure( $oldName, $newName, $temporary = false,
745 $fname = __METHOD__
746 ) {
747 $temporary = $temporary ? 'TRUE' : 'FALSE';
748
749 $newName = strtoupper( $newName );
750 $oldName = strtoupper( $oldName );
751
752 $tabName = substr( $newName, strlen( $this->mTablePrefix ) );
753 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
754 $newPrefix = strtoupper( $this->mTablePrefix );
755
756 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
757 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
758 }
759
760 function listTables( $prefix = null, $fname = __METHOD__ ) {
761 $listWhere = '';
762 if ( !empty( $prefix ) ) {
763 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
764 }
765
766 $owner = strtoupper( $this->mDBname );
767 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
768 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
769
770 // dirty code ... i know
771 $endArray = [];
772 $endArray[] = strtoupper( $prefix . 'MWUSER' );
773 $endArray[] = strtoupper( $prefix . 'PAGE' );
774 $endArray[] = strtoupper( $prefix . 'IMAGE' );
775 $fixedOrderTabs = $endArray;
776 while ( ( $row = $result->fetchRow() ) !== false ) {
777 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
778 $endArray[] = $row['table_name'];
779 }
780 }
781
782 return $endArray;
783 }
784
785 public function dropTable( $tableName, $fName = __METHOD__ ) {
786 $tableName = $this->tableName( $tableName );
787 if ( !$this->tableExists( $tableName ) ) {
788 return false;
789 }
790
791 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
792 }
793
794 function timestamp( $ts = 0 ) {
795 return wfTimestamp( TS_ORACLE, $ts );
796 }
797
798 /**
799 * Return aggregated value function call
800 *
801 * @param array $valuedata
802 * @param string $valuename
803 * @return mixed
804 */
805 public function aggregateValue( $valuedata, $valuename = 'value' ) {
806 return $valuedata;
807 }
808
809 /**
810 * @return string Wikitext of a link to the server software's web site
811 */
812 public function getSoftwareLink() {
813 return '[{{int:version-db-oracle-url}} Oracle]';
814 }
815
816 /**
817 * @return string Version information from the database
818 */
819 function getServerVersion() {
820 // better version number, fallback on driver
821 $rset = $this->doQuery(
822 'SELECT version FROM product_component_version ' .
823 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
824 );
825 $row = $rset->fetchRow();
826 if ( !$row ) {
827 return oci_server_version( $this->mConn );
828 }
829
830 return $row['version'];
831 }
832
833 /**
834 * Query whether a given index exists
835 * @param string $table
836 * @param string $index
837 * @param string $fname
838 * @return bool
839 */
840 function indexExists( $table, $index, $fname = __METHOD__ ) {
841 $table = $this->tableName( $table );
842 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
843 $index = strtoupper( $index );
844 $owner = strtoupper( $this->mDBname );
845 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
846 $res = $this->doQuery( $sql );
847 if ( $res ) {
848 $count = $res->numRows();
849 $res->free();
850 } else {
851 $count = 0;
852 }
853
854 return $count != 0;
855 }
856
857 /**
858 * Query whether a given table exists (in the given schema, or the default mw one if not given)
859 * @param string $table
860 * @param string $fname
861 * @return bool
862 */
863 function tableExists( $table, $fname = __METHOD__ ) {
864 $table = $this->tableName( $table );
865 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
866 $owner = $this->addQuotes( strtoupper( $this->mDBname ) );
867 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
868 $res = $this->doQuery( $sql );
869 if ( $res && $res->numRows() > 0 ) {
870 $exists = true;
871 } else {
872 $exists = false;
873 }
874
875 $res->free();
876
877 return $exists;
878 }
879
880 /**
881 * Function translates mysql_fetch_field() functionality on ORACLE.
882 * Caching is present for reducing query time.
883 * For internal calls. Use fieldInfo for normal usage.
884 * Returns false if the field doesn't exist
885 *
886 * @param array|string $table
887 * @param string $field
888 * @return ORAField|ORAResult|false
889 */
890 private function fieldInfoMulti( $table, $field ) {
891 $field = strtoupper( $field );
892 if ( is_array( $table ) ) {
893 $table = array_map( [ $this, 'tableNameInternal' ], $table );
894 $tableWhere = 'IN (';
895 foreach ( $table as &$singleTable ) {
896 $singleTable = $this->removeIdentifierQuotes( $singleTable );
897 if ( isset( $this->mFieldInfoCache["$singleTable.$field"] ) ) {
898 return $this->mFieldInfoCache["$singleTable.$field"];
899 }
900 $tableWhere .= '\'' . $singleTable . '\',';
901 }
902 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
903 } else {
904 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
905 if ( isset( $this->mFieldInfoCache["$table.$field"] ) ) {
906 return $this->mFieldInfoCache["$table.$field"];
907 }
908 $tableWhere = '= \'' . $table . '\'';
909 }
910
911 $fieldInfoStmt = oci_parse(
912 $this->mConn,
913 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
914 $tableWhere . ' and column_name = \'' . $field . '\''
915 );
916 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
917 $e = oci_error( $fieldInfoStmt );
918 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
919
920 return false;
921 }
922 $res = new ORAResult( $this, $fieldInfoStmt );
923 if ( $res->numRows() == 0 ) {
924 if ( is_array( $table ) ) {
925 foreach ( $table as &$singleTable ) {
926 $this->mFieldInfoCache["$singleTable.$field"] = false;
927 }
928 } else {
929 $this->mFieldInfoCache["$table.$field"] = false;
930 }
931 $fieldInfoTemp = null;
932 } else {
933 $fieldInfoTemp = new ORAField( $res->fetchRow() );
934 $table = $fieldInfoTemp->tableName();
935 $this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
936 }
937 $res->free();
938
939 return $fieldInfoTemp;
940 }
941
942 /**
943 * @throws DBUnexpectedError
944 * @param string $table
945 * @param string $field
946 * @return ORAField
947 */
948 function fieldInfo( $table, $field ) {
949 if ( is_array( $table ) ) {
950 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
951 }
952
953 return $this->fieldInfoMulti( $table, $field );
954 }
955
956 protected function doBegin( $fname = __METHOD__ ) {
957 $this->mTrxLevel = 1;
958 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
959 }
960
961 protected function doCommit( $fname = __METHOD__ ) {
962 if ( $this->mTrxLevel ) {
963 $ret = oci_commit( $this->mConn );
964 if ( !$ret ) {
965 throw new DBUnexpectedError( $this, $this->lastError() );
966 }
967 $this->mTrxLevel = 0;
968 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
969 }
970 }
971
972 protected function doRollback( $fname = __METHOD__ ) {
973 if ( $this->mTrxLevel ) {
974 oci_rollback( $this->mConn );
975 $this->mTrxLevel = 0;
976 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
977 }
978 }
979
980 function sourceStream(
981 $fp,
982 callable $lineCallback = null,
983 callable $resultCallback = null,
984 $fname = __METHOD__, callable $inputCallback = null
985 ) {
986 $cmd = '';
987 $done = false;
988 $dollarquote = false;
989
990 $replacements = [];
991 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
992 while ( !feof( $fp ) ) {
993 if ( $lineCallback ) {
994 call_user_func( $lineCallback );
995 }
996 $line = trim( fgets( $fp, 1024 ) );
997 $sl = strlen( $line ) - 1;
998
999 if ( $sl < 0 ) {
1000 continue;
1001 }
1002 if ( '-' == $line[0] && '-' == $line[1] ) {
1003 continue;
1004 }
1005
1006 // Allow dollar quoting for function declarations
1007 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
1008 if ( $dollarquote ) {
1009 $dollarquote = false;
1010 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
1011 $done = true;
1012 } else {
1013 $dollarquote = true;
1014 }
1015 } elseif ( !$dollarquote ) {
1016 if ( ';' == $line[$sl] && ( $sl < 2 || ';' != $line[$sl - 1] ) ) {
1017 $done = true;
1018 $line = substr( $line, 0, $sl );
1019 }
1020 }
1021
1022 if ( $cmd != '' ) {
1023 $cmd .= ' ';
1024 }
1025 $cmd .= "$line\n";
1026
1027 if ( $done ) {
1028 $cmd = str_replace( ';;', ";", $cmd );
1029 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1030 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1031 $replacements[$defines[2]] = $defines[1];
1032 }
1033 } else {
1034 foreach ( $replacements as $mwVar => $scVar ) {
1035 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1036 }
1037
1038 $cmd = $this->replaceVars( $cmd );
1039 if ( $inputCallback ) {
1040 call_user_func( $inputCallback, $cmd );
1041 }
1042 $res = $this->doQuery( $cmd );
1043 if ( $resultCallback ) {
1044 call_user_func( $resultCallback, $res, $this );
1045 }
1046
1047 if ( false === $res ) {
1048 $err = $this->lastError();
1049
1050 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1051 }
1052 }
1053
1054 $cmd = '';
1055 $done = false;
1056 }
1057 }
1058
1059 return true;
1060 }
1061
1062 function selectDB( $db ) {
1063 $this->mDBname = $db;
1064 if ( $db == null || $db == $this->mUser ) {
1065 return true;
1066 }
1067 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1068 $stmt = oci_parse( $this->mConn, $sql );
1069 MediaWiki\suppressWarnings();
1070 $success = oci_execute( $stmt );
1071 MediaWiki\restoreWarnings();
1072 if ( !$success ) {
1073 $e = oci_error( $stmt );
1074 if ( $e['code'] != '1435' ) {
1075 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1076 }
1077
1078 return false;
1079 }
1080
1081 return true;
1082 }
1083
1084 function strencode( $s ) {
1085 return str_replace( "'", "''", $s );
1086 }
1087
1088 function addQuotes( $s ) {
1089 global $wgContLang;
1090 if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
1091 $s = $wgContLang->checkTitleEncoding( $s );
1092 }
1093
1094 return "'" . $this->strencode( $s ) . "'";
1095 }
1096
1097 public function addIdentifierQuotes( $s ) {
1098 if ( !$this->getFlag( DBO_DDLMODE ) ) {
1099 $s = '/*Q*/' . $s;
1100 }
1101
1102 return $s;
1103 }
1104
1105 public function removeIdentifierQuotes( $s ) {
1106 return strpos( $s, '/*Q*/' ) === false ? $s : substr( $s, 5 );
1107 }
1108
1109 public function isQuotedIdentifier( $s ) {
1110 return strpos( $s, '/*Q*/' ) !== false;
1111 }
1112
1113 private function wrapFieldForWhere( $table, &$col, &$val ) {
1114 global $wgContLang;
1115
1116 $col_info = $this->fieldInfoMulti( $table, $col );
1117 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1118 if ( $col_type == 'CLOB' ) {
1119 $col = 'TO_CHAR(' . $col . ')';
1120 $val = $wgContLang->checkTitleEncoding( $val );
1121 } elseif ( $col_type == 'VARCHAR2' ) {
1122 $val = $wgContLang->checkTitleEncoding( $val );
1123 }
1124 }
1125
1126 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1127 $conds2 = [];
1128 foreach ( $conds as $col => $val ) {
1129 if ( is_array( $val ) ) {
1130 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1131 } else {
1132 if ( is_numeric( $col ) && $parentCol != null ) {
1133 $this->wrapFieldForWhere( $table, $parentCol, $val );
1134 } else {
1135 $this->wrapFieldForWhere( $table, $col, $val );
1136 }
1137 $conds2[$col] = $val;
1138 }
1139 }
1140
1141 return $conds2;
1142 }
1143
1144 function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1145 $options = [], $join_conds = []
1146 ) {
1147 if ( is_array( $conds ) ) {
1148 $conds = $this->wrapConditionsForWhere( $table, $conds );
1149 }
1150
1151 return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1152 }
1153
1154 /**
1155 * Returns an optional USE INDEX clause to go after the table, and a
1156 * string to go at the end of the query
1157 *
1158 * @param array $options An associative array of options to be turned into
1159 * an SQL query, valid keys are listed in the function.
1160 * @return array
1161 */
1162 function makeSelectOptions( $options ) {
1163 $preLimitTail = $postLimitTail = '';
1164 $startOpts = '';
1165
1166 $noKeyOptions = [];
1167 foreach ( $options as $key => $option ) {
1168 if ( is_numeric( $key ) ) {
1169 $noKeyOptions[$option] = true;
1170 }
1171 }
1172
1173 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1174
1175 $preLimitTail .= $this->makeOrderBy( $options );
1176
1177 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1178 $postLimitTail .= ' FOR UPDATE';
1179 }
1180
1181 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1182 $startOpts .= 'DISTINCT';
1183 }
1184
1185 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1186 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1187 } else {
1188 $useIndex = '';
1189 }
1190
1191 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1192 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1193 } else {
1194 $ignoreIndex = '';
1195 }
1196
1197 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1198 }
1199
1200 public function delete( $table, $conds, $fname = __METHOD__ ) {
1201 if ( is_array( $conds ) ) {
1202 $conds = $this->wrapConditionsForWhere( $table, $conds );
1203 }
1204 // a hack for deleting pages, users and images (which have non-nullable FKs)
1205 // all deletions on these tables have transactions so final failure rollbacks these updates
1206 $table = $this->tableName( $table );
1207 if ( $table == $this->tableName( 'user' ) ) {
1208 $this->update( 'archive', [ 'ar_user' => 0 ],
1209 [ 'ar_user' => $conds['user_id'] ], $fname );
1210 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1211 [ 'ipb_user' => $conds['user_id'] ], $fname );
1212 $this->update( 'image', [ 'img_user' => 0 ],
1213 [ 'img_user' => $conds['user_id'] ], $fname );
1214 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1215 [ 'oi_user' => $conds['user_id'] ], $fname );
1216 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1217 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1218 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1219 [ 'fa_user' => $conds['user_id'] ], $fname );
1220 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1221 [ 'us_user' => $conds['user_id'] ], $fname );
1222 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1223 [ 'rc_user' => $conds['user_id'] ], $fname );
1224 $this->update( 'logging', [ 'log_user' => 0 ],
1225 [ 'log_user' => $conds['user_id'] ], $fname );
1226 } elseif ( $table == $this->tableName( 'image' ) ) {
1227 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1228 [ 'oi_name' => $conds['img_name'] ], $fname );
1229 }
1230
1231 return parent::delete( $table, $conds, $fname );
1232 }
1233
1234 /**
1235 * @param string $table
1236 * @param array $values
1237 * @param array $conds
1238 * @param string $fname
1239 * @param array $options
1240 * @return bool
1241 * @throws DBUnexpectedError
1242 */
1243 function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1244 global $wgContLang;
1245
1246 $table = $this->tableName( $table );
1247 $opts = $this->makeUpdateOptions( $options );
1248 $sql = "UPDATE $opts $table SET ";
1249
1250 $first = true;
1251 foreach ( $values as $col => &$val ) {
1252 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1253
1254 if ( !$first ) {
1255 $sqlSet = ', ' . $sqlSet;
1256 } else {
1257 $first = false;
1258 }
1259 $sql .= $sqlSet;
1260 }
1261
1262 if ( $conds !== [] && $conds !== '*' ) {
1263 $conds = $this->wrapConditionsForWhere( $table, $conds );
1264 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1265 }
1266
1267 $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql );
1268 if ( $stmt === false ) {
1269 $e = oci_error( $this->mConn );
1270 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1271
1272 return false;
1273 }
1274 foreach ( $values as $col => &$val ) {
1275 $col_info = $this->fieldInfoMulti( $table, $col );
1276 $col_type = $col_info != false ? $col_info->type() : 'CONSTANT';
1277
1278 if ( $val === null ) {
1279 // do nothing ... null was inserted in statement creation
1280 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1281 if ( is_object( $val ) ) {
1282 $val = $val->getData();
1283 }
1284
1285 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1286 $val = '31-12-2030 12:00:00.000000';
1287 }
1288
1289 $val = ( $wgContLang != null ) ? $wgContLang->checkTitleEncoding( $val ) : $val;
1290 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1291 $e = oci_error( $stmt );
1292 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1293
1294 return false;
1295 }
1296 } else {
1297 /** @var OCI_Lob[] $lob */
1298 $lob[$col] = oci_new_descriptor( $this->mConn, OCI_D_LOB );
1299 if ( $lob[$col] === false ) {
1300 $e = oci_error( $stmt );
1301 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1302 }
1303
1304 if ( is_object( $val ) ) {
1305 $val = $val->getData();
1306 }
1307
1308 if ( $col_type == 'BLOB' ) {
1309 $lob[$col]->writeTemporary( $val );
1310 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB );
1311 } else {
1312 $lob[$col]->writeTemporary( $val );
1313 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB );
1314 }
1315 }
1316 }
1317
1318 MediaWiki\suppressWarnings();
1319
1320 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1321 $e = oci_error( $stmt );
1322 if ( !$this->ignoreDupValOnIndex || $e['code'] != '1' ) {
1323 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
1324
1325 return false;
1326 } else {
1327 $this->mAffectedRows = oci_num_rows( $stmt );
1328 }
1329 } else {
1330 $this->mAffectedRows = oci_num_rows( $stmt );
1331 }
1332
1333 MediaWiki\restoreWarnings();
1334
1335 if ( isset( $lob ) ) {
1336 foreach ( $lob as $lob_v ) {
1337 $lob_v->free();
1338 }
1339 }
1340
1341 if ( !$this->mTrxLevel ) {
1342 oci_commit( $this->mConn );
1343 }
1344
1345 return oci_free_statement( $stmt );
1346 }
1347
1348 function bitNot( $field ) {
1349 // expecting bit-fields smaller than 4bytes
1350 return 'BITNOT(' . $field . ')';
1351 }
1352
1353 function bitAnd( $fieldLeft, $fieldRight ) {
1354 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1355 }
1356
1357 function bitOr( $fieldLeft, $fieldRight ) {
1358 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1359 }
1360
1361 function getDBname() {
1362 return $this->mDBname;
1363 }
1364
1365 function getServer() {
1366 return $this->mServer;
1367 }
1368
1369 public function buildGroupConcatField(
1370 $delim, $table, $field, $conds = '', $join_conds = []
1371 ) {
1372 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1373
1374 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1375 }
1376
1377 /**
1378 * @param string $field Field or column to cast
1379 * @return string
1380 * @since 1.28
1381 */
1382 public function buildStringCast( $field ) {
1383 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1384 }
1385
1386 public function getInfinity() {
1387 return '31-12-2030 12:00:00.000000';
1388 }
1389 }