Merge "Made recent changes purge jobs bail more aggressively"
[lhc/web/wiklou.git] / includes / db / Database.php
1 <?php
2
3 /**
4 * @defgroup Database Database
5 *
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 * @ingroup Database
26 */
27
28 /**
29 * Database abstraction object
30 * @ingroup Database
31 */
32 abstract class DatabaseBase implements IDatabase {
33 /** Number of times to re-try an operation in case of deadlock */
34 const DEADLOCK_TRIES = 4;
35
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN = 500000;
38
39 /** Maximum time to wait before retry */
40 const DEADLOCK_DELAY_MAX = 1500000;
41
42 protected $mLastQuery = '';
43 protected $mDoneWrites = false;
44 protected $mPHPError = false;
45
46 protected $mServer, $mUser, $mPassword, $mDBname;
47
48 /** @var resource Database connection */
49 protected $mConn = null;
50 protected $mOpened = false;
51
52 /** @var callable[] */
53 protected $mTrxIdleCallbacks = array();
54 /** @var callable[] */
55 protected $mTrxPreCommitCallbacks = array();
56
57 protected $mTablePrefix;
58 protected $mSchema;
59 protected $mFlags;
60 protected $mForeign;
61 protected $mErrorCount = 0;
62 protected $mLBInfo = array();
63 protected $mDefaultBigSelects = null;
64 protected $mSchemaVars = false;
65 /** @var array */
66 protected $mSessionVars = array();
67
68 protected $preparedArgs;
69
70 protected $htmlErrors;
71
72 protected $delimiter = ';';
73
74 /**
75 * Either 1 if a transaction is active or 0 otherwise.
76 * The other Trx fields may not be meaningfull if this is 0.
77 *
78 * @var int
79 */
80 protected $mTrxLevel = 0;
81
82 /**
83 * Either a short hexidecimal string if a transaction is active or ""
84 *
85 * @var string
86 * @see DatabaseBase::mTrxLevel
87 */
88 protected $mTrxShortId = '';
89
90 /**
91 * The UNIX time that the transaction started. Callers can assume that if
92 * snapshot isolation is used, then the data is *at least* up to date to that
93 * point (possibly more up-to-date since the first SELECT defines the snapshot).
94 *
95 * @var float|null
96 * @see DatabaseBase::mTrxLevel
97 */
98 private $mTrxTimestamp = null;
99
100 /**
101 * Remembers the function name given for starting the most recent transaction via begin().
102 * Used to provide additional context for error reporting.
103 *
104 * @var string
105 * @see DatabaseBase::mTrxLevel
106 */
107 private $mTrxFname = null;
108
109 /**
110 * Record if possible write queries were done in the last transaction started
111 *
112 * @var bool
113 * @see DatabaseBase::mTrxLevel
114 */
115 private $mTrxDoneWrites = false;
116
117 /**
118 * Record if the current transaction was started implicitly due to DBO_TRX being set.
119 *
120 * @var bool
121 * @see DatabaseBase::mTrxLevel
122 */
123 private $mTrxAutomatic = false;
124
125 /**
126 * Array of levels of atomicity within transactions
127 *
128 * @var SplStack
129 */
130 private $mTrxAtomicLevels;
131
132 /**
133 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
134 *
135 * @var bool
136 */
137 private $mTrxAutomaticAtomic = false;
138
139 /**
140 * Track the seconds spent in write queries for the current transaction
141 *
142 * @var float
143 */
144 private $mTrxWriteDuration = 0.0;
145
146 /**
147 * @since 1.21
148 * @var resource File handle for upgrade
149 */
150 protected $fileHandle = null;
151
152 /**
153 * @since 1.22
154 * @var string[] Process cache of VIEWs names in the database
155 */
156 protected $allViews = null;
157
158 /** @var TransactionProfiler */
159 protected $trxProfiler;
160
161 /**
162 * A string describing the current software version, and possibly
163 * other details in a user-friendly way. Will be listed on Special:Version, etc.
164 * Use getServerVersion() to get machine-friendly information.
165 *
166 * @return string Version information from the database server
167 */
168 public function getServerInfo() {
169 return $this->getServerVersion();
170 }
171
172 /**
173 * @return string Command delimiter used by this database engine
174 */
175 public function getDelimiter() {
176 return $this->delimiter;
177 }
178
179 /**
180 * Boolean, controls output of large amounts of debug information.
181 * @param bool|null $debug
182 * - true to enable debugging
183 * - false to disable debugging
184 * - omitted or null to do nothing
185 *
186 * @return bool|null Previous value of the flag
187 */
188 public function debug( $debug = null ) {
189 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
190 }
191
192 /**
193 * Turns buffering of SQL result sets on (true) or off (false). Default is
194 * "on".
195 *
196 * Unbuffered queries are very troublesome in MySQL:
197 *
198 * - If another query is executed while the first query is being read
199 * out, the first query is killed. This means you can't call normal
200 * MediaWiki functions while you are reading an unbuffered query result
201 * from a normal wfGetDB() connection.
202 *
203 * - Unbuffered queries cause the MySQL server to use large amounts of
204 * memory and to hold broad locks which block other queries.
205 *
206 * If you want to limit client-side memory, it's almost always better to
207 * split up queries into batches using a LIMIT clause than to switch off
208 * buffering.
209 *
210 * @param null|bool $buffer
211 * @return null|bool The previous value of the flag
212 */
213 public function bufferResults( $buffer = null ) {
214 if ( is_null( $buffer ) ) {
215 return !(bool)( $this->mFlags & DBO_NOBUFFER );
216 } else {
217 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
218 }
219 }
220
221 /**
222 * Turns on (false) or off (true) the automatic generation and sending
223 * of a "we're sorry, but there has been a database error" page on
224 * database errors. Default is on (false). When turned off, the
225 * code should use lastErrno() and lastError() to handle the
226 * situation as appropriate.
227 *
228 * Do not use this function outside of the Database classes.
229 *
230 * @param null|bool $ignoreErrors
231 * @return bool The previous value of the flag.
232 */
233 public function ignoreErrors( $ignoreErrors = null ) {
234 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
235 }
236
237 /**
238 * Gets the current transaction level.
239 *
240 * Historically, transactions were allowed to be "nested". This is no
241 * longer supported, so this function really only returns a boolean.
242 *
243 * @return int The previous value
244 */
245 public function trxLevel() {
246 return $this->mTrxLevel;
247 }
248
249 /**
250 * Get the UNIX timestamp of the time that the transaction was established
251 *
252 * This can be used to reason about the staleness of SELECT data
253 * in REPEATABLE-READ transaction isolation level.
254 *
255 * @return float|null Returns null if there is not active transaction
256 * @since 1.25
257 */
258 public function trxTimestamp() {
259 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
260 }
261
262 /**
263 * Get/set the number of errors logged. Only useful when errors are ignored
264 * @param int $count The count to set, or omitted to leave it unchanged.
265 * @return int The error count
266 */
267 public function errorCount( $count = null ) {
268 return wfSetVar( $this->mErrorCount, $count );
269 }
270
271 /**
272 * Get/set the table prefix.
273 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
274 * @return string The previous table prefix.
275 */
276 public function tablePrefix( $prefix = null ) {
277 return wfSetVar( $this->mTablePrefix, $prefix );
278 }
279
280 /**
281 * Get/set the db schema.
282 * @param string $schema The database schema to set, or omitted to leave it unchanged.
283 * @return string The previous db schema.
284 */
285 public function dbSchema( $schema = null ) {
286 return wfSetVar( $this->mSchema, $schema );
287 }
288
289 /**
290 * Set the filehandle to copy write statements to.
291 *
292 * @param resource $fh File handle
293 */
294 public function setFileHandle( $fh ) {
295 $this->fileHandle = $fh;
296 }
297
298 /**
299 * Get properties passed down from the server info array of the load
300 * balancer.
301 *
302 * @param string $name The entry of the info array to get, or null to get the
303 * whole array
304 *
305 * @return array|mixed|null
306 */
307 public function getLBInfo( $name = null ) {
308 if ( is_null( $name ) ) {
309 return $this->mLBInfo;
310 } else {
311 if ( array_key_exists( $name, $this->mLBInfo ) ) {
312 return $this->mLBInfo[$name];
313 } else {
314 return null;
315 }
316 }
317 }
318
319 /**
320 * Set the LB info array, or a member of it. If called with one parameter,
321 * the LB info array is set to that parameter. If it is called with two
322 * parameters, the member with the given name is set to the given value.
323 *
324 * @param string $name
325 * @param array $value
326 */
327 public function setLBInfo( $name, $value = null ) {
328 if ( is_null( $value ) ) {
329 $this->mLBInfo = $name;
330 } else {
331 $this->mLBInfo[$name] = $value;
332 }
333 }
334
335 /**
336 * Set lag time in seconds for a fake slave
337 *
338 * @param mixed $lag Valid values for this parameter are determined by the
339 * subclass, but should be a PHP scalar or array that would be sensible
340 * as part of $wgLBFactoryConf.
341 */
342 public function setFakeSlaveLag( $lag ) {
343 }
344
345 /**
346 * Make this connection a fake master
347 *
348 * @param bool $enabled
349 */
350 public function setFakeMaster( $enabled = true ) {
351 }
352
353 /**
354 * @return TransactionProfiler
355 */
356 protected function getTransactionProfiler() {
357 return $this->trxProfiler
358 ? $this->trxProfiler
359 : Profiler::instance()->getTransactionProfiler();
360 }
361
362 /**
363 * Returns true if this database supports (and uses) cascading deletes
364 *
365 * @return bool
366 */
367 public function cascadingDeletes() {
368 return false;
369 }
370
371 /**
372 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
373 *
374 * @return bool
375 */
376 public function cleanupTriggers() {
377 return false;
378 }
379
380 /**
381 * Returns true if this database is strict about what can be put into an IP field.
382 * Specifically, it uses a NULL value instead of an empty string.
383 *
384 * @return bool
385 */
386 public function strictIPs() {
387 return false;
388 }
389
390 /**
391 * Returns true if this database uses timestamps rather than integers
392 *
393 * @return bool
394 */
395 public function realTimestamps() {
396 return false;
397 }
398
399 /**
400 * Returns true if this database does an implicit sort when doing GROUP BY
401 *
402 * @return bool
403 */
404 public function implicitGroupby() {
405 return true;
406 }
407
408 /**
409 * Returns true if this database does an implicit order by when the column has an index
410 * For example: SELECT page_title FROM page LIMIT 1
411 *
412 * @return bool
413 */
414 public function implicitOrderby() {
415 return true;
416 }
417
418 /**
419 * Returns true if this database can do a native search on IP columns
420 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
421 *
422 * @return bool
423 */
424 public function searchableIPs() {
425 return false;
426 }
427
428 /**
429 * Returns true if this database can use functional indexes
430 *
431 * @return bool
432 */
433 public function functionalIndexes() {
434 return false;
435 }
436
437 /**
438 * Return the last query that went through DatabaseBase::query()
439 * @return string
440 */
441 public function lastQuery() {
442 return $this->mLastQuery;
443 }
444
445 /**
446 * Returns true if the connection may have been used for write queries.
447 * Should return true if unsure.
448 *
449 * @return bool
450 */
451 public function doneWrites() {
452 return (bool)$this->mDoneWrites;
453 }
454
455 /**
456 * Returns the last time the connection may have been used for write queries.
457 * Should return a timestamp if unsure.
458 *
459 * @return int|float UNIX timestamp or false
460 * @since 1.24
461 */
462 public function lastDoneWrites() {
463 return $this->mDoneWrites ?: false;
464 }
465
466 /**
467 * Returns true if there is a transaction open with possible write
468 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
469 *
470 * @return bool
471 */
472 public function writesOrCallbacksPending() {
473 return $this->mTrxLevel && (
474 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
475 );
476 }
477
478 /**
479 * Get the time spend running write queries for this
480 *
481 * High times could be due to scanning, updates, locking, and such
482 *
483 * @return float|bool Returns false if not transaction is active
484 * @since 1.26
485 */
486 public function pendingWriteQueryDuration() {
487 return $this->mTrxLevel ? $this->mTrxWriteDuration : false;
488 }
489
490 /**
491 * Is a connection to the database open?
492 * @return bool
493 */
494 public function isOpen() {
495 return $this->mOpened;
496 }
497
498 /**
499 * Set a flag for this connection
500 *
501 * @param int $flag DBO_* constants from Defines.php:
502 * - DBO_DEBUG: output some debug info (same as debug())
503 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
504 * - DBO_TRX: automatically start transactions
505 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
506 * and removes it in command line mode
507 * - DBO_PERSISTENT: use persistant database connection
508 */
509 public function setFlag( $flag ) {
510 global $wgDebugDBTransactions;
511 $this->mFlags |= $flag;
512 if ( ( $flag & DBO_TRX ) && $wgDebugDBTransactions ) {
513 wfDebug( "Implicit transactions are now enabled.\n" );
514 }
515 }
516
517 /**
518 * Clear a flag for this connection
519 *
520 * @param int $flag DBO_* constants from Defines.php:
521 * - DBO_DEBUG: output some debug info (same as debug())
522 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
523 * - DBO_TRX: automatically start transactions
524 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
525 * and removes it in command line mode
526 * - DBO_PERSISTENT: use persistant database connection
527 */
528 public function clearFlag( $flag ) {
529 global $wgDebugDBTransactions;
530 $this->mFlags &= ~$flag;
531 if ( ( $flag & DBO_TRX ) && $wgDebugDBTransactions ) {
532 wfDebug( "Implicit transactions are now disabled.\n" );
533 }
534 }
535
536 /**
537 * Returns a boolean whether the flag $flag is set for this connection
538 *
539 * @param int $flag DBO_* constants from Defines.php:
540 * - DBO_DEBUG: output some debug info (same as debug())
541 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
542 * - DBO_TRX: automatically start transactions
543 * - DBO_PERSISTENT: use persistant database connection
544 * @return bool
545 */
546 public function getFlag( $flag ) {
547 return !!( $this->mFlags & $flag );
548 }
549
550 /**
551 * General read-only accessor
552 *
553 * @param string $name
554 * @return string
555 */
556 public function getProperty( $name ) {
557 return $this->$name;
558 }
559
560 /**
561 * @return string
562 */
563 public function getWikiID() {
564 if ( $this->mTablePrefix ) {
565 return "{$this->mDBname}-{$this->mTablePrefix}";
566 } else {
567 return $this->mDBname;
568 }
569 }
570
571 /**
572 * Return a path to the DBMS-specific SQL file if it exists,
573 * otherwise default SQL file
574 *
575 * @param string $filename
576 * @return string
577 */
578 private function getSqlFilePath( $filename ) {
579 global $IP;
580 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
581 if ( file_exists( $dbmsSpecificFilePath ) ) {
582 return $dbmsSpecificFilePath;
583 } else {
584 return "$IP/maintenance/$filename";
585 }
586 }
587
588 /**
589 * Return a path to the DBMS-specific schema file,
590 * otherwise default to tables.sql
591 *
592 * @return string
593 */
594 public function getSchemaPath() {
595 return $this->getSqlFilePath( 'tables.sql' );
596 }
597
598 /**
599 * Return a path to the DBMS-specific update key file,
600 * otherwise default to update-keys.sql
601 *
602 * @return string
603 */
604 public function getUpdateKeysPath() {
605 return $this->getSqlFilePath( 'update-keys.sql' );
606 }
607
608 /**
609 * Get the type of the DBMS, as it appears in $wgDBtype.
610 *
611 * @return string
612 */
613 abstract function getType();
614
615 /**
616 * Open a connection to the database. Usually aborts on failure
617 *
618 * @param string $server Database server host
619 * @param string $user Database user name
620 * @param string $password Database user password
621 * @param string $dbName Database name
622 * @return bool
623 * @throws DBConnectionError
624 */
625 abstract function open( $server, $user, $password, $dbName );
626
627 /**
628 * Fetch the next row from the given result object, in object form.
629 * Fields can be retrieved with $row->fieldname, with fields acting like
630 * member variables.
631 * If no more rows are available, false is returned.
632 *
633 * @param ResultWrapper|stdClass $res Object as returned from DatabaseBase::query(), etc.
634 * @return stdClass|bool
635 * @throws DBUnexpectedError Thrown if the database returns an error
636 */
637 abstract function fetchObject( $res );
638
639 /**
640 * Fetch the next row from the given result object, in associative array
641 * form. Fields are retrieved with $row['fieldname'].
642 * If no more rows are available, false is returned.
643 *
644 * @param ResultWrapper $res Result object as returned from DatabaseBase::query(), etc.
645 * @return array|bool
646 * @throws DBUnexpectedError Thrown if the database returns an error
647 */
648 abstract function fetchRow( $res );
649
650 /**
651 * Get the number of rows in a result object
652 *
653 * @param mixed $res A SQL result
654 * @return int
655 */
656 abstract function numRows( $res );
657
658 /**
659 * Get the number of fields in a result object
660 * @see http://www.php.net/mysql_num_fields
661 *
662 * @param mixed $res A SQL result
663 * @return int
664 */
665 abstract function numFields( $res );
666
667 /**
668 * Get a field name in a result object
669 * @see http://www.php.net/mysql_field_name
670 *
671 * @param mixed $res A SQL result
672 * @param int $n
673 * @return string
674 */
675 abstract function fieldName( $res, $n );
676
677 /**
678 * Get the inserted value of an auto-increment row
679 *
680 * The value inserted should be fetched from nextSequenceValue()
681 *
682 * Example:
683 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
684 * $dbw->insert( 'page', array( 'page_id' => $id ) );
685 * $id = $dbw->insertId();
686 *
687 * @return int
688 */
689 abstract function insertId();
690
691 /**
692 * Change the position of the cursor in a result object
693 * @see http://www.php.net/mysql_data_seek
694 *
695 * @param mixed $res A SQL result
696 * @param int $row
697 */
698 abstract function dataSeek( $res, $row );
699
700 /**
701 * Get the last error number
702 * @see http://www.php.net/mysql_errno
703 *
704 * @return int
705 */
706 abstract function lastErrno();
707
708 /**
709 * Get a description of the last error
710 * @see http://www.php.net/mysql_error
711 *
712 * @return string
713 */
714 abstract function lastError();
715
716 /**
717 * mysql_fetch_field() wrapper
718 * Returns false if the field doesn't exist
719 *
720 * @param string $table Table name
721 * @param string $field Field name
722 *
723 * @return Field
724 */
725 abstract function fieldInfo( $table, $field );
726
727 /**
728 * Get information about an index into an object
729 * @param string $table Table name
730 * @param string $index Index name
731 * @param string $fname Calling function name
732 * @return mixed Database-specific index description class or false if the index does not exist
733 */
734 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
735
736 /**
737 * Get the number of rows affected by the last write query
738 * @see http://www.php.net/mysql_affected_rows
739 *
740 * @return int
741 */
742 abstract function affectedRows();
743
744 /**
745 * Wrapper for addslashes()
746 *
747 * @param string $s String to be slashed.
748 * @return string Slashed string.
749 */
750 abstract function strencode( $s );
751
752 /**
753 * Returns a wikitext link to the DB's website, e.g.,
754 * return "[http://www.mysql.com/ MySQL]";
755 * Should at least contain plain text, if for some reason
756 * your database has no website.
757 *
758 * @return string Wikitext of a link to the server software's web site
759 */
760 abstract function getSoftwareLink();
761
762 /**
763 * A string describing the current software version, like from
764 * mysql_get_server_info().
765 *
766 * @return string Version information from the database server.
767 */
768 abstract function getServerVersion();
769
770 /**
771 * Constructor.
772 *
773 * FIXME: It is possible to construct a Database object with no associated
774 * connection object, by specifying no parameters to __construct(). This
775 * feature is deprecated and should be removed.
776 *
777 * DatabaseBase subclasses should not be constructed directly in external
778 * code. DatabaseBase::factory() should be used instead.
779 *
780 * @param array $params Parameters passed from DatabaseBase::factory()
781 */
782 function __construct( array $params ) {
783 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
784
785 $this->mTrxAtomicLevels = new SplStack;
786
787 $server = $params['host'];
788 $user = $params['user'];
789 $password = $params['password'];
790 $dbName = $params['dbname'];
791 $flags = $params['flags'];
792 $tablePrefix = $params['tablePrefix'];
793 $schema = $params['schema'];
794 $foreign = $params['foreign'];
795
796 $this->mFlags = $flags;
797 if ( $this->mFlags & DBO_DEFAULT ) {
798 if ( $wgCommandLineMode ) {
799 $this->mFlags &= ~DBO_TRX;
800 if ( $wgDebugDBTransactions ) {
801 wfDebug( "Implicit transaction open disabled.\n" );
802 }
803 } else {
804 $this->mFlags |= DBO_TRX;
805 if ( $wgDebugDBTransactions ) {
806 wfDebug( "Implicit transaction open enabled.\n" );
807 }
808 }
809 }
810
811 $this->mSessionVars = $params['variables'];
812
813 /** Get the default table prefix*/
814 if ( $tablePrefix === 'get from global' ) {
815 $this->mTablePrefix = $wgDBprefix;
816 } else {
817 $this->mTablePrefix = $tablePrefix;
818 }
819
820 /** Get the database schema*/
821 if ( $schema === 'get from global' ) {
822 $this->mSchema = $wgDBmwschema;
823 } else {
824 $this->mSchema = $schema;
825 }
826
827 $this->mForeign = $foreign;
828
829 if ( isset( $params['trxProfiler'] ) ) {
830 $this->trxProfiler = $params['trxProfiler']; // override
831 }
832
833 if ( $user ) {
834 $this->open( $server, $user, $password, $dbName );
835 }
836 }
837
838 /**
839 * Called by serialize. Throw an exception when DB connection is serialized.
840 * This causes problems on some database engines because the connection is
841 * not restored on unserialize.
842 */
843 public function __sleep() {
844 throw new MWException( 'Database serialization may cause problems, since ' .
845 'the connection is not restored on wakeup.' );
846 }
847
848 /**
849 * Given a DB type, construct the name of the appropriate child class of
850 * DatabaseBase. This is designed to replace all of the manual stuff like:
851 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
852 * as well as validate against the canonical list of DB types we have
853 *
854 * This factory function is mostly useful for when you need to connect to a
855 * database other than the MediaWiki default (such as for external auth,
856 * an extension, et cetera). Do not use this to connect to the MediaWiki
857 * database. Example uses in core:
858 * @see LoadBalancer::reallyOpenConnection()
859 * @see ForeignDBRepo::getMasterDB()
860 * @see WebInstallerDBConnect::execute()
861 *
862 * @since 1.18
863 *
864 * @param string $dbType A possible DB type
865 * @param array $p An array of options to pass to the constructor.
866 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
867 * @throws MWException If the database driver or extension cannot be found
868 * @return DatabaseBase|null DatabaseBase subclass or null
869 */
870 final public static function factory( $dbType, $p = array() ) {
871 $canonicalDBTypes = array(
872 'mysql' => array( 'mysqli', 'mysql' ),
873 'postgres' => array(),
874 'sqlite' => array(),
875 'oracle' => array(),
876 'mssql' => array(),
877 );
878
879 $driver = false;
880 $dbType = strtolower( $dbType );
881 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
882 $possibleDrivers = $canonicalDBTypes[$dbType];
883 if ( !empty( $p['driver'] ) ) {
884 if ( in_array( $p['driver'], $possibleDrivers ) ) {
885 $driver = $p['driver'];
886 } else {
887 throw new MWException( __METHOD__ .
888 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
889 }
890 } else {
891 foreach ( $possibleDrivers as $posDriver ) {
892 if ( extension_loaded( $posDriver ) ) {
893 $driver = $posDriver;
894 break;
895 }
896 }
897 }
898 } else {
899 $driver = $dbType;
900 }
901 if ( $driver === false ) {
902 throw new MWException( __METHOD__ .
903 " no viable database extension found for type '$dbType'" );
904 }
905
906 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
907 // and everything else doesn't use a schema (e.g. null)
908 // Although postgres and oracle support schemas, we don't use them (yet)
909 // to maintain backwards compatibility
910 $defaultSchemas = array(
911 'mssql' => 'get from global',
912 );
913
914 $class = 'Database' . ucfirst( $driver );
915 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
916 // Resolve some defaults for b/c
917 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
918 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
919 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
920 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
921 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
922 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : array();
923 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global';
924 if ( !isset( $p['schema'] ) ) {
925 $p['schema'] = isset( $defaultSchemas[$dbType] ) ? $defaultSchemas[$dbType] : null;
926 }
927 $p['foreign'] = isset( $p['foreign'] ) ? $p['foreign'] : false;
928
929 return new $class( $p );
930 } else {
931 return null;
932 }
933 }
934
935 protected function installErrorHandler() {
936 $this->mPHPError = false;
937 $this->htmlErrors = ini_set( 'html_errors', '0' );
938 set_error_handler( array( $this, 'connectionErrorHandler' ) );
939 }
940
941 /**
942 * @return bool|string
943 */
944 protected function restoreErrorHandler() {
945 restore_error_handler();
946 if ( $this->htmlErrors !== false ) {
947 ini_set( 'html_errors', $this->htmlErrors );
948 }
949 if ( $this->mPHPError ) {
950 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
951 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
952
953 return $error;
954 } else {
955 return false;
956 }
957 }
958
959 /**
960 * @param int $errno
961 * @param string $errstr
962 */
963 public function connectionErrorHandler( $errno, $errstr ) {
964 $this->mPHPError = $errstr;
965 }
966
967 /**
968 * Create a log context to pass to wfLogDBError or other logging functions.
969 *
970 * @param array $extras Additional data to add to context
971 * @return array
972 */
973 protected function getLogContext( array $extras = array() ) {
974 return array_merge(
975 array(
976 'db_server' => $this->mServer,
977 'db_name' => $this->mDBname,
978 'db_user' => $this->mUser,
979 ),
980 $extras
981 );
982 }
983
984 /**
985 * Closes a database connection.
986 * if it is open : commits any open transactions
987 *
988 * @throws MWException
989 * @return bool Operation success. true if already closed.
990 */
991 public function close() {
992 if ( count( $this->mTrxIdleCallbacks ) ) { // sanity
993 throw new MWException( "Transaction idle callbacks still pending." );
994 }
995 if ( $this->mConn ) {
996 if ( $this->trxLevel() ) {
997 if ( !$this->mTrxAutomatic ) {
998 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
999 " performing implicit commit before closing connection!" );
1000 }
1001
1002 $this->commit( __METHOD__, 'flush' );
1003 }
1004
1005 $closed = $this->closeConnection();
1006 $this->mConn = false;
1007 } else {
1008 $closed = true;
1009 }
1010 $this->mOpened = false;
1011
1012 return $closed;
1013 }
1014
1015 /**
1016 * Make sure isOpen() returns true as a sanity check
1017 *
1018 * @throws DBUnexpectedError
1019 */
1020 protected function assertOpen() {
1021 if ( !$this->isOpen() ) {
1022 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1023 }
1024 }
1025
1026 /**
1027 * Closes underlying database connection
1028 * @since 1.20
1029 * @return bool Whether connection was closed successfully
1030 */
1031 abstract protected function closeConnection();
1032
1033 /**
1034 * @param string $error Fallback error message, used if none is given by DB
1035 * @throws DBConnectionError
1036 */
1037 function reportConnectionError( $error = 'Unknown error' ) {
1038 $myError = $this->lastError();
1039 if ( $myError ) {
1040 $error = $myError;
1041 }
1042
1043 # New method
1044 throw new DBConnectionError( $this, $error );
1045 }
1046
1047 /**
1048 * The DBMS-dependent part of query()
1049 *
1050 * @param string $sql SQL query.
1051 * @return ResultWrapper|bool Result object to feed to fetchObject,
1052 * fetchRow, ...; or false on failure
1053 */
1054 abstract protected function doQuery( $sql );
1055
1056 /**
1057 * Determine whether a query writes to the DB.
1058 * Should return true if unsure.
1059 *
1060 * @param string $sql
1061 * @return bool
1062 */
1063 protected function isWriteQuery( $sql ) {
1064 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1065 }
1066
1067 /**
1068 * Determine whether a SQL statement is sensitive to isolation level.
1069 * A SQL statement is considered transactable if its result could vary
1070 * depending on the transaction isolation level. Operational commands
1071 * such as 'SET' and 'SHOW' are not considered to be transactable.
1072 *
1073 * @param string $sql
1074 * @return bool
1075 */
1076 protected function isTransactableQuery( $sql ) {
1077 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
1078 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
1079 }
1080
1081 /**
1082 * Run an SQL query and return the result. Normally throws a DBQueryError
1083 * on failure. If errors are ignored, returns false instead.
1084 *
1085 * In new code, the query wrappers select(), insert(), update(), delete(),
1086 * etc. should be used where possible, since they give much better DBMS
1087 * independence and automatically quote or validate user input in a variety
1088 * of contexts. This function is generally only useful for queries which are
1089 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
1090 * as CREATE TABLE.
1091 *
1092 * However, the query wrappers themselves should call this function.
1093 *
1094 * @param string $sql SQL query
1095 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
1096 * comment (you can use __METHOD__ or add some extra info)
1097 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
1098 * maybe best to catch the exception instead?
1099 * @throws MWException
1100 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
1101 * for a successful read query, or false on failure if $tempIgnore set
1102 */
1103 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
1104 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
1105
1106 $this->mLastQuery = $sql;
1107
1108 $isWriteQuery = $this->isWriteQuery( $sql );
1109 if ( $isWriteQuery ) {
1110 if ( !$this->mDoneWrites ) {
1111 wfDebug( __METHOD__ . ': Writes done: ' .
1112 DatabaseBase::generalizeSQL( $sql ) . "\n" );
1113 }
1114 # Set a flag indicating that writes have been done
1115 $this->mDoneWrites = microtime( true );
1116 }
1117
1118 # Add a comment for easy SHOW PROCESSLIST interpretation
1119 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
1120 $userName = $wgUser->getName();
1121 if ( mb_strlen( $userName ) > 15 ) {
1122 $userName = mb_substr( $userName, 0, 15 ) . '...';
1123 }
1124 $userName = str_replace( '/', '', $userName );
1125 } else {
1126 $userName = '';
1127 }
1128
1129 // Add trace comment to the begin of the sql string, right after the operator.
1130 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
1131 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
1132
1133 if ( !$this->mTrxLevel && $this->getFlag( DBO_TRX ) && $this->isTransactableQuery( $sql ) ) {
1134 if ( $wgDebugDBTransactions ) {
1135 wfDebug( "Implicit transaction start.\n" );
1136 }
1137 $this->begin( __METHOD__ . " ($fname)" );
1138 $this->mTrxAutomatic = true;
1139 }
1140
1141 # Keep track of whether the transaction has write queries pending
1142 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWriteQuery ) {
1143 $this->mTrxDoneWrites = true;
1144 $this->getTransactionProfiler()->transactionWritingIn(
1145 $this->mServer, $this->mDBname, $this->mTrxShortId );
1146 }
1147
1148 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1149 # generalizeSQL will probably cut down the query to reasonable
1150 # logging size most of the time. The substr is really just a sanity check.
1151 if ( $isMaster ) {
1152 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
1153 $totalProf = 'DatabaseBase::query-master';
1154 } else {
1155 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
1156 $totalProf = 'DatabaseBase::query';
1157 }
1158 # Include query transaction state
1159 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
1160
1161 $profiler = Profiler::instance();
1162 if ( !$profiler instanceof ProfilerStub ) {
1163 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
1164 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
1165 }
1166
1167 if ( $this->debug() ) {
1168 static $cnt = 0;
1169
1170 $cnt++;
1171 $sqlx = $wgDebugDumpSqlLength ? substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1172 : $commentedSql;
1173 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1174
1175 $master = $isMaster ? 'master' : 'slave';
1176 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1177 }
1178
1179 $queryId = MWDebug::query( $sql, $fname, $isMaster );
1180
1181 # Avoid fatals if close() was called
1182 $this->assertOpen();
1183
1184 # Do the query and handle errors
1185 $startTime = microtime( true );
1186 $ret = $this->doQuery( $commentedSql );
1187 $queryRuntime = microtime( true ) - $startTime;
1188 # Log the query time and feed it into the DB trx profiler
1189 $this->getTransactionProfiler()->recordQueryCompletion(
1190 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1191
1192 MWDebug::queryTime( $queryId );
1193
1194 # Try reconnecting if the connection was lost
1195 if ( false === $ret && $this->wasErrorReissuable() ) {
1196 # Transaction is gone, like it or not
1197 $hadTrx = $this->mTrxLevel; // possible lost transaction
1198 $this->mTrxLevel = 0;
1199 $this->mTrxIdleCallbacks = array(); // bug 65263
1200 $this->mTrxPreCommitCallbacks = array(); // bug 65263
1201 wfDebug( "Connection lost, reconnecting...\n" );
1202 # Stash the last error values since ping() might clear them
1203 $lastError = $this->lastError();
1204 $lastErrno = $this->lastErrno();
1205 if ( $this->ping() ) {
1206 wfDebug( "Reconnected\n" );
1207 $server = $this->getServer();
1208 $msg = __METHOD__ . ": lost connection to $server; reconnected";
1209 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1210
1211 if ( $hadTrx ) {
1212 # Leave $ret as false and let an error be reported.
1213 # Callers may catch the exception and continue to use the DB.
1214 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1215 } else {
1216 # Should be safe to silently retry (no trx and thus no callbacks)
1217 $startTime = microtime( true );
1218 $ret = $this->doQuery( $commentedSql );
1219 $queryRuntime = microtime( true ) - $startTime;
1220 # Log the query time and feed it into the DB trx profiler
1221 $this->getTransactionProfiler()->recordQueryCompletion(
1222 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1223 }
1224 } else {
1225 wfDebug( "Failed\n" );
1226 }
1227 }
1228
1229 if ( false === $ret ) {
1230 $this->reportQueryError(
1231 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1232 }
1233
1234 $res = $this->resultObject( $ret );
1235
1236 // Destroy profile sections in the opposite order to their creation
1237 $queryProfSection = false;
1238 $totalProfSection = false;
1239
1240 if ( $isWriteQuery && $this->mTrxLevel ) {
1241 $this->mTrxWriteDuration += $queryRuntime;
1242 }
1243
1244 return $res;
1245 }
1246
1247 /**
1248 * Report a query error. Log the error, and if neither the object ignore
1249 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1250 *
1251 * @param string $error
1252 * @param int $errno
1253 * @param string $sql
1254 * @param string $fname
1255 * @param bool $tempIgnore
1256 * @throws DBQueryError
1257 */
1258 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1259 ++$this->mErrorCount;
1260
1261 if ( $this->ignoreErrors() || $tempIgnore ) {
1262 wfDebug( "SQL ERROR (ignored): $error\n" );
1263 } else {
1264 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1265 wfLogDBError(
1266 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1267 $this->getLogContext( array(
1268 'method' => __METHOD__,
1269 'errno' => $errno,
1270 'error' => $error,
1271 'sql1line' => $sql1line,
1272 'fname' => $fname,
1273 ) )
1274 );
1275 wfDebug( "SQL ERROR: " . $error . "\n" );
1276 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1277 }
1278 }
1279
1280 /**
1281 * Intended to be compatible with the PEAR::DB wrapper functions.
1282 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1283 *
1284 * ? = scalar value, quoted as necessary
1285 * ! = raw SQL bit (a function for instance)
1286 * & = filename; reads the file and inserts as a blob
1287 * (we don't use this though...)
1288 *
1289 * @param string $sql
1290 * @param string $func
1291 *
1292 * @return array
1293 */
1294 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1295 /* MySQL doesn't support prepared statements (yet), so just
1296 * pack up the query for reference. We'll manually replace
1297 * the bits later.
1298 */
1299 return array( 'query' => $sql, 'func' => $func );
1300 }
1301
1302 /**
1303 * Free a prepared query, generated by prepare().
1304 * @param string $prepared
1305 */
1306 protected function freePrepared( $prepared ) {
1307 /* No-op by default */
1308 }
1309
1310 /**
1311 * Execute a prepared query with the various arguments
1312 * @param string $prepared The prepared sql
1313 * @param mixed $args Either an array here, or put scalars as varargs
1314 *
1315 * @return ResultWrapper
1316 */
1317 public function execute( $prepared, $args = null ) {
1318 if ( !is_array( $args ) ) {
1319 # Pull the var args
1320 $args = func_get_args();
1321 array_shift( $args );
1322 }
1323
1324 $sql = $this->fillPrepared( $prepared['query'], $args );
1325
1326 return $this->query( $sql, $prepared['func'] );
1327 }
1328
1329 /**
1330 * For faking prepared SQL statements on DBs that don't support it directly.
1331 *
1332 * @param string $preparedQuery A 'preparable' SQL statement
1333 * @param array $args Array of Arguments to fill it with
1334 * @return string Executable SQL
1335 */
1336 public function fillPrepared( $preparedQuery, $args ) {
1337 reset( $args );
1338 $this->preparedArgs =& $args;
1339
1340 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1341 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1342 }
1343
1344 /**
1345 * preg_callback func for fillPrepared()
1346 * The arguments should be in $this->preparedArgs and must not be touched
1347 * while we're doing this.
1348 *
1349 * @param array $matches
1350 * @throws DBUnexpectedError
1351 * @return string
1352 */
1353 protected function fillPreparedArg( $matches ) {
1354 switch ( $matches[1] ) {
1355 case '\\?':
1356 return '?';
1357 case '\\!':
1358 return '!';
1359 case '\\&':
1360 return '&';
1361 }
1362
1363 list( /* $n */, $arg ) = each( $this->preparedArgs );
1364
1365 switch ( $matches[1] ) {
1366 case '?':
1367 return $this->addQuotes( $arg );
1368 case '!':
1369 return $arg;
1370 case '&':
1371 # return $this->addQuotes( file_get_contents( $arg ) );
1372 throw new DBUnexpectedError(
1373 $this,
1374 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1375 );
1376 default:
1377 throw new DBUnexpectedError(
1378 $this,
1379 'Received invalid match. This should never happen!'
1380 );
1381 }
1382 }
1383
1384 /**
1385 * Free a result object returned by query() or select(). It's usually not
1386 * necessary to call this, just use unset() or let the variable holding
1387 * the result object go out of scope.
1388 *
1389 * @param mixed $res A SQL result
1390 */
1391 public function freeResult( $res ) {
1392 }
1393
1394 /**
1395 * A SELECT wrapper which returns a single field from a single result row.
1396 *
1397 * Usually throws a DBQueryError on failure. If errors are explicitly
1398 * ignored, returns false on failure.
1399 *
1400 * If no result rows are returned from the query, false is returned.
1401 *
1402 * @param string|array $table Table name. See DatabaseBase::select() for details.
1403 * @param string $var The field name to select. This must be a valid SQL
1404 * fragment: do not use unvalidated user input.
1405 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1406 * @param string $fname The function name of the caller.
1407 * @param string|array $options The query options. See DatabaseBase::select() for details.
1408 *
1409 * @return bool|mixed The value from the field, or false on failure.
1410 */
1411 public function selectField(
1412 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1413 ) {
1414 if ( $var === '*' ) { // sanity
1415 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1416 }
1417
1418 if ( !is_array( $options ) ) {
1419 $options = array( $options );
1420 }
1421
1422 $options['LIMIT'] = 1;
1423
1424 $res = $this->select( $table, $var, $cond, $fname, $options );
1425 if ( $res === false || !$this->numRows( $res ) ) {
1426 return false;
1427 }
1428
1429 $row = $this->fetchRow( $res );
1430
1431 if ( $row !== false ) {
1432 return reset( $row );
1433 } else {
1434 return false;
1435 }
1436 }
1437
1438 /**
1439 * A SELECT wrapper which returns a list of single field values from result rows.
1440 *
1441 * Usually throws a DBQueryError on failure. If errors are explicitly
1442 * ignored, returns false on failure.
1443 *
1444 * If no result rows are returned from the query, false is returned.
1445 *
1446 * @param string|array $table Table name. See DatabaseBase::select() for details.
1447 * @param string $var The field name to select. This must be a valid SQL
1448 * fragment: do not use unvalidated user input.
1449 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1450 * @param string $fname The function name of the caller.
1451 * @param string|array $options The query options. See DatabaseBase::select() for details.
1452 *
1453 * @return bool|array The values from the field, or false on failure
1454 * @throws DBUnexpectedError
1455 * @since 1.25
1456 */
1457 public function selectFieldValues(
1458 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1459 ) {
1460 if ( $var === '*' ) { // sanity
1461 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1462 }
1463
1464 if ( !is_array( $options ) ) {
1465 $options = array( $options );
1466 }
1467
1468 $res = $this->select( $table, $var, $cond, $fname, $options );
1469 if ( $res === false ) {
1470 return false;
1471 }
1472
1473 $values = array();
1474 foreach ( $res as $row ) {
1475 $values[] = $row->$var;
1476 }
1477
1478 return $values;
1479 }
1480
1481 /**
1482 * Returns an optional USE INDEX clause to go after the table, and a
1483 * string to go at the end of the query.
1484 *
1485 * @param array $options Associative array of options to be turned into
1486 * an SQL query, valid keys are listed in the function.
1487 * @return array
1488 * @see DatabaseBase::select()
1489 */
1490 public function makeSelectOptions( $options ) {
1491 $preLimitTail = $postLimitTail = '';
1492 $startOpts = '';
1493
1494 $noKeyOptions = array();
1495
1496 foreach ( $options as $key => $option ) {
1497 if ( is_numeric( $key ) ) {
1498 $noKeyOptions[$option] = true;
1499 }
1500 }
1501
1502 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1503
1504 $preLimitTail .= $this->makeOrderBy( $options );
1505
1506 // if (isset($options['LIMIT'])) {
1507 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1508 // isset($options['OFFSET']) ? $options['OFFSET']
1509 // : false);
1510 // }
1511
1512 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1513 $postLimitTail .= ' FOR UPDATE';
1514 }
1515
1516 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1517 $postLimitTail .= ' LOCK IN SHARE MODE';
1518 }
1519
1520 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1521 $startOpts .= 'DISTINCT';
1522 }
1523
1524 # Various MySQL extensions
1525 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1526 $startOpts .= ' /*! STRAIGHT_JOIN */';
1527 }
1528
1529 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1530 $startOpts .= ' HIGH_PRIORITY';
1531 }
1532
1533 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1534 $startOpts .= ' SQL_BIG_RESULT';
1535 }
1536
1537 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1538 $startOpts .= ' SQL_BUFFER_RESULT';
1539 }
1540
1541 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1542 $startOpts .= ' SQL_SMALL_RESULT';
1543 }
1544
1545 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1546 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1547 }
1548
1549 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1550 $startOpts .= ' SQL_CACHE';
1551 }
1552
1553 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1554 $startOpts .= ' SQL_NO_CACHE';
1555 }
1556
1557 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1558 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1559 } else {
1560 $useIndex = '';
1561 }
1562
1563 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1564 }
1565
1566 /**
1567 * Returns an optional GROUP BY with an optional HAVING
1568 *
1569 * @param array $options Associative array of options
1570 * @return string
1571 * @see DatabaseBase::select()
1572 * @since 1.21
1573 */
1574 public function makeGroupByWithHaving( $options ) {
1575 $sql = '';
1576 if ( isset( $options['GROUP BY'] ) ) {
1577 $gb = is_array( $options['GROUP BY'] )
1578 ? implode( ',', $options['GROUP BY'] )
1579 : $options['GROUP BY'];
1580 $sql .= ' GROUP BY ' . $gb;
1581 }
1582 if ( isset( $options['HAVING'] ) ) {
1583 $having = is_array( $options['HAVING'] )
1584 ? $this->makeList( $options['HAVING'], LIST_AND )
1585 : $options['HAVING'];
1586 $sql .= ' HAVING ' . $having;
1587 }
1588
1589 return $sql;
1590 }
1591
1592 /**
1593 * Returns an optional ORDER BY
1594 *
1595 * @param array $options Associative array of options
1596 * @return string
1597 * @see DatabaseBase::select()
1598 * @since 1.21
1599 */
1600 public function makeOrderBy( $options ) {
1601 if ( isset( $options['ORDER BY'] ) ) {
1602 $ob = is_array( $options['ORDER BY'] )
1603 ? implode( ',', $options['ORDER BY'] )
1604 : $options['ORDER BY'];
1605
1606 return ' ORDER BY ' . $ob;
1607 }
1608
1609 return '';
1610 }
1611
1612 /**
1613 * Execute a SELECT query constructed using the various parameters provided.
1614 * See below for full details of the parameters.
1615 *
1616 * @param string|array $table Table name
1617 * @param string|array $vars Field names
1618 * @param string|array $conds Conditions
1619 * @param string $fname Caller function name
1620 * @param array $options Query options
1621 * @param array $join_conds Join conditions
1622 *
1623 *
1624 * @param string|array $table
1625 *
1626 * May be either an array of table names, or a single string holding a table
1627 * name. If an array is given, table aliases can be specified, for example:
1628 *
1629 * array( 'a' => 'user' )
1630 *
1631 * This includes the user table in the query, with the alias "a" available
1632 * for use in field names (e.g. a.user_name).
1633 *
1634 * All of the table names given here are automatically run through
1635 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1636 * added, and various other table name mappings to be performed.
1637 *
1638 *
1639 * @param string|array $vars
1640 *
1641 * May be either a field name or an array of field names. The field names
1642 * can be complete fragments of SQL, for direct inclusion into the SELECT
1643 * query. If an array is given, field aliases can be specified, for example:
1644 *
1645 * array( 'maxrev' => 'MAX(rev_id)' )
1646 *
1647 * This includes an expression with the alias "maxrev" in the query.
1648 *
1649 * If an expression is given, care must be taken to ensure that it is
1650 * DBMS-independent.
1651 *
1652 *
1653 * @param string|array $conds
1654 *
1655 * May be either a string containing a single condition, or an array of
1656 * conditions. If an array is given, the conditions constructed from each
1657 * element are combined with AND.
1658 *
1659 * Array elements may take one of two forms:
1660 *
1661 * - Elements with a numeric key are interpreted as raw SQL fragments.
1662 * - Elements with a string key are interpreted as equality conditions,
1663 * where the key is the field name.
1664 * - If the value of such an array element is a scalar (such as a
1665 * string), it will be treated as data and thus quoted appropriately.
1666 * If it is null, an IS NULL clause will be added.
1667 * - If the value is an array, an IN (...) clause will be constructed
1668 * from its non-null elements, and an IS NULL clause will be added
1669 * if null is present, such that the field may match any of the
1670 * elements in the array. The non-null elements will be quoted.
1671 *
1672 * Note that expressions are often DBMS-dependent in their syntax.
1673 * DBMS-independent wrappers are provided for constructing several types of
1674 * expression commonly used in condition queries. See:
1675 * - DatabaseBase::buildLike()
1676 * - DatabaseBase::conditional()
1677 *
1678 *
1679 * @param string|array $options
1680 *
1681 * Optional: Array of query options. Boolean options are specified by
1682 * including them in the array as a string value with a numeric key, for
1683 * example:
1684 *
1685 * array( 'FOR UPDATE' )
1686 *
1687 * The supported options are:
1688 *
1689 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1690 * with LIMIT can theoretically be used for paging through a result set,
1691 * but this is discouraged in MediaWiki for performance reasons.
1692 *
1693 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1694 * and then the first rows are taken until the limit is reached. LIMIT
1695 * is applied to a result set after OFFSET.
1696 *
1697 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1698 * changed until the next COMMIT.
1699 *
1700 * - DISTINCT: Boolean: return only unique result rows.
1701 *
1702 * - GROUP BY: May be either an SQL fragment string naming a field or
1703 * expression to group by, or an array of such SQL fragments.
1704 *
1705 * - HAVING: May be either an string containing a HAVING clause or an array of
1706 * conditions building the HAVING clause. If an array is given, the conditions
1707 * constructed from each element are combined with AND.
1708 *
1709 * - ORDER BY: May be either an SQL fragment giving a field name or
1710 * expression to order by, or an array of such SQL fragments.
1711 *
1712 * - USE INDEX: This may be either a string giving the index name to use
1713 * for the query, or an array. If it is an associative array, each key
1714 * gives the table name (or alias), each value gives the index name to
1715 * use for that table. All strings are SQL fragments and so should be
1716 * validated by the caller.
1717 *
1718 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1719 * instead of SELECT.
1720 *
1721 * And also the following boolean MySQL extensions, see the MySQL manual
1722 * for documentation:
1723 *
1724 * - LOCK IN SHARE MODE
1725 * - STRAIGHT_JOIN
1726 * - HIGH_PRIORITY
1727 * - SQL_BIG_RESULT
1728 * - SQL_BUFFER_RESULT
1729 * - SQL_SMALL_RESULT
1730 * - SQL_CALC_FOUND_ROWS
1731 * - SQL_CACHE
1732 * - SQL_NO_CACHE
1733 *
1734 *
1735 * @param string|array $join_conds
1736 *
1737 * Optional associative array of table-specific join conditions. In the
1738 * most common case, this is unnecessary, since the join condition can be
1739 * in $conds. However, it is useful for doing a LEFT JOIN.
1740 *
1741 * The key of the array contains the table name or alias. The value is an
1742 * array with two elements, numbered 0 and 1. The first gives the type of
1743 * join, the second is an SQL fragment giving the join condition for that
1744 * table. For example:
1745 *
1746 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1747 *
1748 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1749 * with no rows in it will be returned. If there was a query error, a
1750 * DBQueryError exception will be thrown, except if the "ignore errors"
1751 * option was set, in which case false will be returned.
1752 */
1753 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1754 $options = array(), $join_conds = array() ) {
1755 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1756
1757 return $this->query( $sql, $fname );
1758 }
1759
1760 /**
1761 * The equivalent of DatabaseBase::select() except that the constructed SQL
1762 * is returned, instead of being immediately executed. This can be useful for
1763 * doing UNION queries, where the SQL text of each query is needed. In general,
1764 * however, callers outside of Database classes should just use select().
1765 *
1766 * @param string|array $table Table name
1767 * @param string|array $vars Field names
1768 * @param string|array $conds Conditions
1769 * @param string $fname Caller function name
1770 * @param string|array $options Query options
1771 * @param string|array $join_conds Join conditions
1772 *
1773 * @return string SQL query string.
1774 * @see DatabaseBase::select()
1775 */
1776 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1777 $options = array(), $join_conds = array()
1778 ) {
1779 if ( is_array( $vars ) ) {
1780 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1781 }
1782
1783 $options = (array)$options;
1784 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1785 ? $options['USE INDEX']
1786 : array();
1787
1788 if ( is_array( $table ) ) {
1789 $from = ' FROM ' .
1790 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1791 } elseif ( $table != '' ) {
1792 if ( $table[0] == ' ' ) {
1793 $from = ' FROM ' . $table;
1794 } else {
1795 $from = ' FROM ' .
1796 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1797 }
1798 } else {
1799 $from = '';
1800 }
1801
1802 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1803 $this->makeSelectOptions( $options );
1804
1805 if ( !empty( $conds ) ) {
1806 if ( is_array( $conds ) ) {
1807 $conds = $this->makeList( $conds, LIST_AND );
1808 }
1809 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1810 } else {
1811 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1812 }
1813
1814 if ( isset( $options['LIMIT'] ) ) {
1815 $sql = $this->limitResult( $sql, $options['LIMIT'],
1816 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1817 }
1818 $sql = "$sql $postLimitTail";
1819
1820 if ( isset( $options['EXPLAIN'] ) ) {
1821 $sql = 'EXPLAIN ' . $sql;
1822 }
1823
1824 return $sql;
1825 }
1826
1827 /**
1828 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1829 * that a single row object is returned. If the query returns no rows,
1830 * false is returned.
1831 *
1832 * @param string|array $table Table name
1833 * @param string|array $vars Field names
1834 * @param array $conds Conditions
1835 * @param string $fname Caller function name
1836 * @param string|array $options Query options
1837 * @param array|string $join_conds Join conditions
1838 *
1839 * @return stdClass|bool
1840 */
1841 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1842 $options = array(), $join_conds = array()
1843 ) {
1844 $options = (array)$options;
1845 $options['LIMIT'] = 1;
1846 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1847
1848 if ( $res === false ) {
1849 return false;
1850 }
1851
1852 if ( !$this->numRows( $res ) ) {
1853 return false;
1854 }
1855
1856 $obj = $this->fetchObject( $res );
1857
1858 return $obj;
1859 }
1860
1861 /**
1862 * Estimate the number of rows in dataset
1863 *
1864 * MySQL allows you to estimate the number of rows that would be returned
1865 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1866 * index cardinality statistics, and is notoriously inaccurate, especially
1867 * when large numbers of rows have recently been added or deleted.
1868 *
1869 * For DBMSs that don't support fast result size estimation, this function
1870 * will actually perform the SELECT COUNT(*).
1871 *
1872 * Takes the same arguments as DatabaseBase::select().
1873 *
1874 * @param string $table Table name
1875 * @param string $vars Unused
1876 * @param array|string $conds Filters on the table
1877 * @param string $fname Function name for profiling
1878 * @param array $options Options for select
1879 * @return int Row count
1880 */
1881 public function estimateRowCount(
1882 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1883 ) {
1884 $rows = 0;
1885 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1886
1887 if ( $res ) {
1888 $row = $this->fetchRow( $res );
1889 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1890 }
1891
1892 return $rows;
1893 }
1894
1895 /**
1896 * Get the number of rows in dataset
1897 *
1898 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1899 *
1900 * Takes the same arguments as DatabaseBase::select().
1901 *
1902 * @param string $table Table name
1903 * @param string $vars Unused
1904 * @param array|string $conds Filters on the table
1905 * @param string $fname Function name for profiling
1906 * @param array $options Options for select
1907 * @return int Row count
1908 * @since 1.24
1909 */
1910 public function selectRowCount(
1911 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1912 ) {
1913 $rows = 0;
1914 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1915 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1916
1917 if ( $res ) {
1918 $row = $this->fetchRow( $res );
1919 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1920 }
1921
1922 return $rows;
1923 }
1924
1925 /**
1926 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1927 * It's only slightly flawed. Don't use for anything important.
1928 *
1929 * @param string $sql A SQL Query
1930 *
1931 * @return string
1932 */
1933 static function generalizeSQL( $sql ) {
1934 # This does the same as the regexp below would do, but in such a way
1935 # as to avoid crashing php on some large strings.
1936 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1937
1938 $sql = str_replace( "\\\\", '', $sql );
1939 $sql = str_replace( "\\'", '', $sql );
1940 $sql = str_replace( "\\\"", '', $sql );
1941 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1942 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1943
1944 # All newlines, tabs, etc replaced by single space
1945 $sql = preg_replace( '/\s+/', ' ', $sql );
1946
1947 # All numbers => N,
1948 # except the ones surrounded by characters, e.g. l10n
1949 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1950 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1951
1952 return $sql;
1953 }
1954
1955 /**
1956 * Determines whether a field exists in a table
1957 *
1958 * @param string $table Table name
1959 * @param string $field Filed to check on that table
1960 * @param string $fname Calling function name (optional)
1961 * @return bool Whether $table has filed $field
1962 */
1963 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1964 $info = $this->fieldInfo( $table, $field );
1965
1966 return (bool)$info;
1967 }
1968
1969 /**
1970 * Determines whether an index exists
1971 * Usually throws a DBQueryError on failure
1972 * If errors are explicitly ignored, returns NULL on failure
1973 *
1974 * @param string $table
1975 * @param string $index
1976 * @param string $fname
1977 * @return bool|null
1978 */
1979 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1980 if ( !$this->tableExists( $table ) ) {
1981 return null;
1982 }
1983
1984 $info = $this->indexInfo( $table, $index, $fname );
1985 if ( is_null( $info ) ) {
1986 return null;
1987 } else {
1988 return $info !== false;
1989 }
1990 }
1991
1992 /**
1993 * Query whether a given table exists
1994 *
1995 * @param string $table
1996 * @param string $fname
1997 * @return bool
1998 */
1999 public function tableExists( $table, $fname = __METHOD__ ) {
2000 $table = $this->tableName( $table );
2001 $old = $this->ignoreErrors( true );
2002 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
2003 $this->ignoreErrors( $old );
2004
2005 return (bool)$res;
2006 }
2007
2008 /**
2009 * Determines if a given index is unique
2010 *
2011 * @param string $table
2012 * @param string $index
2013 *
2014 * @return bool
2015 */
2016 public function indexUnique( $table, $index ) {
2017 $indexInfo = $this->indexInfo( $table, $index );
2018
2019 if ( !$indexInfo ) {
2020 return null;
2021 }
2022
2023 return !$indexInfo[0]->Non_unique;
2024 }
2025
2026 /**
2027 * Helper for DatabaseBase::insert().
2028 *
2029 * @param array $options
2030 * @return string
2031 */
2032 protected function makeInsertOptions( $options ) {
2033 return implode( ' ', $options );
2034 }
2035
2036 /**
2037 * INSERT wrapper, inserts an array into a table.
2038 *
2039 * $a may be either:
2040 *
2041 * - A single associative array. The array keys are the field names, and
2042 * the values are the values to insert. The values are treated as data
2043 * and will be quoted appropriately. If NULL is inserted, this will be
2044 * converted to a database NULL.
2045 * - An array with numeric keys, holding a list of associative arrays.
2046 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2047 * each subarray must be identical to each other, and in the same order.
2048 *
2049 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2050 * returns success.
2051 *
2052 * $options is an array of options, with boolean options encoded as values
2053 * with numeric keys, in the same style as $options in
2054 * DatabaseBase::select(). Supported options are:
2055 *
2056 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
2057 * any rows which cause duplicate key errors are not inserted. It's
2058 * possible to determine how many rows were successfully inserted using
2059 * DatabaseBase::affectedRows().
2060 *
2061 * @param string $table Table name. This will be passed through
2062 * DatabaseBase::tableName().
2063 * @param array $a Array of rows to insert
2064 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2065 * @param array $options Array of options
2066 *
2067 * @return bool
2068 */
2069 public function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
2070 # No rows to insert, easy just return now
2071 if ( !count( $a ) ) {
2072 return true;
2073 }
2074
2075 $table = $this->tableName( $table );
2076
2077 if ( !is_array( $options ) ) {
2078 $options = array( $options );
2079 }
2080
2081 $fh = null;
2082 if ( isset( $options['fileHandle'] ) ) {
2083 $fh = $options['fileHandle'];
2084 }
2085 $options = $this->makeInsertOptions( $options );
2086
2087 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2088 $multi = true;
2089 $keys = array_keys( $a[0] );
2090 } else {
2091 $multi = false;
2092 $keys = array_keys( $a );
2093 }
2094
2095 $sql = 'INSERT ' . $options .
2096 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2097
2098 if ( $multi ) {
2099 $first = true;
2100 foreach ( $a as $row ) {
2101 if ( $first ) {
2102 $first = false;
2103 } else {
2104 $sql .= ',';
2105 }
2106 $sql .= '(' . $this->makeList( $row ) . ')';
2107 }
2108 } else {
2109 $sql .= '(' . $this->makeList( $a ) . ')';
2110 }
2111
2112 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
2113 return false;
2114 } elseif ( $fh !== null ) {
2115 return true;
2116 }
2117
2118 return (bool)$this->query( $sql, $fname );
2119 }
2120
2121 /**
2122 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
2123 *
2124 * @param array $options
2125 * @return array
2126 */
2127 protected function makeUpdateOptionsArray( $options ) {
2128 if ( !is_array( $options ) ) {
2129 $options = array( $options );
2130 }
2131
2132 $opts = array();
2133
2134 if ( in_array( 'LOW_PRIORITY', $options ) ) {
2135 $opts[] = $this->lowPriorityOption();
2136 }
2137
2138 if ( in_array( 'IGNORE', $options ) ) {
2139 $opts[] = 'IGNORE';
2140 }
2141
2142 return $opts;
2143 }
2144
2145 /**
2146 * Make UPDATE options for the DatabaseBase::update function
2147 *
2148 * @param array $options The options passed to DatabaseBase::update
2149 * @return string
2150 */
2151 protected function makeUpdateOptions( $options ) {
2152 $opts = $this->makeUpdateOptionsArray( $options );
2153
2154 return implode( ' ', $opts );
2155 }
2156
2157 /**
2158 * UPDATE wrapper. Takes a condition array and a SET array.
2159 *
2160 * @param string $table Name of the table to UPDATE. This will be passed through
2161 * DatabaseBase::tableName().
2162 * @param array $values An array of values to SET. For each array element,
2163 * the key gives the field name, and the value gives the data to set
2164 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2165 * @param array $conds An array of conditions (WHERE). See
2166 * DatabaseBase::select() for the details of the format of condition
2167 * arrays. Use '*' to update all rows.
2168 * @param string $fname The function name of the caller (from __METHOD__),
2169 * for logging and profiling.
2170 * @param array $options An array of UPDATE options, can be:
2171 * - IGNORE: Ignore unique key conflicts
2172 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2173 * @return bool
2174 */
2175 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
2176 $table = $this->tableName( $table );
2177 $opts = $this->makeUpdateOptions( $options );
2178 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
2179
2180 if ( $conds !== array() && $conds !== '*' ) {
2181 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
2182 }
2183
2184 return $this->query( $sql, $fname );
2185 }
2186
2187 /**
2188 * Makes an encoded list of strings from an array
2189 *
2190 * @param array $a Containing the data
2191 * @param int $mode Constant
2192 * - LIST_COMMA: Comma separated, no field names
2193 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2194 * documentation for $conds in DatabaseBase::select().
2195 * - LIST_OR: ORed WHERE clause (without the WHERE)
2196 * - LIST_SET: Comma separated with field names, like a SET clause
2197 * - LIST_NAMES: Comma separated field names
2198 * @throws MWException|DBUnexpectedError
2199 * @return string
2200 */
2201 public function makeList( $a, $mode = LIST_COMMA ) {
2202 if ( !is_array( $a ) ) {
2203 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2204 }
2205
2206 $first = true;
2207 $list = '';
2208
2209 foreach ( $a as $field => $value ) {
2210 if ( !$first ) {
2211 if ( $mode == LIST_AND ) {
2212 $list .= ' AND ';
2213 } elseif ( $mode == LIST_OR ) {
2214 $list .= ' OR ';
2215 } else {
2216 $list .= ',';
2217 }
2218 } else {
2219 $first = false;
2220 }
2221
2222 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
2223 $list .= "($value)";
2224 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
2225 $list .= "$value";
2226 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
2227 // Remove null from array to be handled separately if found
2228 $includeNull = false;
2229 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2230 $includeNull = true;
2231 unset( $value[$nullKey] );
2232 }
2233 if ( count( $value ) == 0 && !$includeNull ) {
2234 throw new MWException( __METHOD__ . ": empty input for field $field" );
2235 } elseif ( count( $value ) == 0 ) {
2236 // only check if $field is null
2237 $list .= "$field IS NULL";
2238 } else {
2239 // IN clause contains at least one valid element
2240 if ( $includeNull ) {
2241 // Group subconditions to ensure correct precedence
2242 $list .= '(';
2243 }
2244 if ( count( $value ) == 1 ) {
2245 // Special-case single values, as IN isn't terribly efficient
2246 // Don't necessarily assume the single key is 0; we don't
2247 // enforce linear numeric ordering on other arrays here.
2248 $value = array_values( $value );
2249 $list .= $field . " = " . $this->addQuotes( $value[0] );
2250 } else {
2251 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2252 }
2253 // if null present in array, append IS NULL
2254 if ( $includeNull ) {
2255 $list .= " OR $field IS NULL)";
2256 }
2257 }
2258 } elseif ( $value === null ) {
2259 if ( $mode == LIST_AND || $mode == LIST_OR ) {
2260 $list .= "$field IS ";
2261 } elseif ( $mode == LIST_SET ) {
2262 $list .= "$field = ";
2263 }
2264 $list .= 'NULL';
2265 } else {
2266 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
2267 $list .= "$field = ";
2268 }
2269 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
2270 }
2271 }
2272
2273 return $list;
2274 }
2275
2276 /**
2277 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2278 * The keys on each level may be either integers or strings.
2279 *
2280 * @param array $data Organized as 2-d
2281 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2282 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2283 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2284 * @return string|bool SQL fragment, or false if no items in array
2285 */
2286 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2287 $conds = array();
2288
2289 foreach ( $data as $base => $sub ) {
2290 if ( count( $sub ) ) {
2291 $conds[] = $this->makeList(
2292 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2293 LIST_AND );
2294 }
2295 }
2296
2297 if ( $conds ) {
2298 return $this->makeList( $conds, LIST_OR );
2299 } else {
2300 // Nothing to search for...
2301 return false;
2302 }
2303 }
2304
2305 /**
2306 * Return aggregated value alias
2307 *
2308 * @param array $valuedata
2309 * @param string $valuename
2310 *
2311 * @return string
2312 */
2313 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2314 return $valuename;
2315 }
2316
2317 /**
2318 * @param string $field
2319 * @return string
2320 */
2321 public function bitNot( $field ) {
2322 return "(~$field)";
2323 }
2324
2325 /**
2326 * @param string $fieldLeft
2327 * @param string $fieldRight
2328 * @return string
2329 */
2330 public function bitAnd( $fieldLeft, $fieldRight ) {
2331 return "($fieldLeft & $fieldRight)";
2332 }
2333
2334 /**
2335 * @param string $fieldLeft
2336 * @param string $fieldRight
2337 * @return string
2338 */
2339 public function bitOr( $fieldLeft, $fieldRight ) {
2340 return "($fieldLeft | $fieldRight)";
2341 }
2342
2343 /**
2344 * Build a concatenation list to feed into a SQL query
2345 * @param array $stringList List of raw SQL expressions; caller is
2346 * responsible for any quoting
2347 * @return string
2348 */
2349 public function buildConcat( $stringList ) {
2350 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2351 }
2352
2353 /**
2354 * Build a GROUP_CONCAT or equivalent statement for a query.
2355 *
2356 * This is useful for combining a field for several rows into a single string.
2357 * NULL values will not appear in the output, duplicated values will appear,
2358 * and the resulting delimiter-separated values have no defined sort order.
2359 * Code using the results may need to use the PHP unique() or sort() methods.
2360 *
2361 * @param string $delim Glue to bind the results together
2362 * @param string|array $table Table name
2363 * @param string $field Field name
2364 * @param string|array $conds Conditions
2365 * @param string|array $join_conds Join conditions
2366 * @return string SQL text
2367 * @since 1.23
2368 */
2369 public function buildGroupConcatField(
2370 $delim, $table, $field, $conds = '', $join_conds = array()
2371 ) {
2372 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2373
2374 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2375 }
2376
2377 /**
2378 * Change the current database
2379 *
2380 * @todo Explain what exactly will fail if this is not overridden.
2381 *
2382 * @param string $db
2383 *
2384 * @return bool Success or failure
2385 */
2386 public function selectDB( $db ) {
2387 # Stub. Shouldn't cause serious problems if it's not overridden, but
2388 # if your database engine supports a concept similar to MySQL's
2389 # databases you may as well.
2390 $this->mDBname = $db;
2391
2392 return true;
2393 }
2394
2395 /**
2396 * Get the current DB name
2397 * @return string
2398 */
2399 public function getDBname() {
2400 return $this->mDBname;
2401 }
2402
2403 /**
2404 * Get the server hostname or IP address
2405 * @return string
2406 */
2407 public function getServer() {
2408 return $this->mServer;
2409 }
2410
2411 /**
2412 * Format a table name ready for use in constructing an SQL query
2413 *
2414 * This does two important things: it quotes the table names to clean them up,
2415 * and it adds a table prefix if only given a table name with no quotes.
2416 *
2417 * All functions of this object which require a table name call this function
2418 * themselves. Pass the canonical name to such functions. This is only needed
2419 * when calling query() directly.
2420 *
2421 * @param string $name Database table name
2422 * @param string $format One of:
2423 * quoted - Automatically pass the table name through addIdentifierQuotes()
2424 * so that it can be used in a query.
2425 * raw - Do not add identifier quotes to the table name
2426 * @return string Full database name
2427 */
2428 public function tableName( $name, $format = 'quoted' ) {
2429 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2430 # Skip the entire process when we have a string quoted on both ends.
2431 # Note that we check the end so that we will still quote any use of
2432 # use of `database`.table. But won't break things if someone wants
2433 # to query a database table with a dot in the name.
2434 if ( $this->isQuotedIdentifier( $name ) ) {
2435 return $name;
2436 }
2437
2438 # Lets test for any bits of text that should never show up in a table
2439 # name. Basically anything like JOIN or ON which are actually part of
2440 # SQL queries, but may end up inside of the table value to combine
2441 # sql. Such as how the API is doing.
2442 # Note that we use a whitespace test rather than a \b test to avoid
2443 # any remote case where a word like on may be inside of a table name
2444 # surrounded by symbols which may be considered word breaks.
2445 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2446 return $name;
2447 }
2448
2449 # Split database and table into proper variables.
2450 # We reverse the explode so that database.table and table both output
2451 # the correct table.
2452 $dbDetails = explode( '.', $name, 3 );
2453 if ( count( $dbDetails ) == 3 ) {
2454 list( $database, $schema, $table ) = $dbDetails;
2455 # We don't want any prefix added in this case
2456 $prefix = '';
2457 } elseif ( count( $dbDetails ) == 2 ) {
2458 list( $database, $table ) = $dbDetails;
2459 # We don't want any prefix added in this case
2460 # In dbs that support it, $database may actually be the schema
2461 # but that doesn't affect any of the functionality here
2462 $prefix = '';
2463 $schema = null;
2464 } else {
2465 list( $table ) = $dbDetails;
2466 if ( $wgSharedDB !== null # We have a shared database
2467 && $this->mForeign == false # We're not working on a foreign database
2468 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2469 && in_array( $table, $wgSharedTables ) # A shared table is selected
2470 ) {
2471 $database = $wgSharedDB;
2472 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
2473 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
2474 } else {
2475 $database = null;
2476 $schema = $this->mSchema; # Default schema
2477 $prefix = $this->mTablePrefix; # Default prefix
2478 }
2479 }
2480
2481 # Quote $table and apply the prefix if not quoted.
2482 # $tableName might be empty if this is called from Database::replaceVars()
2483 $tableName = "{$prefix}{$table}";
2484 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2485 $tableName = $this->addIdentifierQuotes( $tableName );
2486 }
2487
2488 # Quote $schema and merge it with the table name if needed
2489 if ( strlen( $schema ) ) {
2490 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2491 $schema = $this->addIdentifierQuotes( $schema );
2492 }
2493 $tableName = $schema . '.' . $tableName;
2494 }
2495
2496 # Quote $database and merge it with the table name if needed
2497 if ( $database !== null ) {
2498 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2499 $database = $this->addIdentifierQuotes( $database );
2500 }
2501 $tableName = $database . '.' . $tableName;
2502 }
2503
2504 return $tableName;
2505 }
2506
2507 /**
2508 * Fetch a number of table names into an array
2509 * This is handy when you need to construct SQL for joins
2510 *
2511 * Example:
2512 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2513 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2514 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2515 *
2516 * @return array
2517 */
2518 public function tableNames() {
2519 $inArray = func_get_args();
2520 $retVal = array();
2521
2522 foreach ( $inArray as $name ) {
2523 $retVal[$name] = $this->tableName( $name );
2524 }
2525
2526 return $retVal;
2527 }
2528
2529 /**
2530 * Fetch a number of table names into an zero-indexed numerical array
2531 * This is handy when you need to construct SQL for joins
2532 *
2533 * Example:
2534 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2535 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2536 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2537 *
2538 * @return array
2539 */
2540 public function tableNamesN() {
2541 $inArray = func_get_args();
2542 $retVal = array();
2543
2544 foreach ( $inArray as $name ) {
2545 $retVal[] = $this->tableName( $name );
2546 }
2547
2548 return $retVal;
2549 }
2550
2551 /**
2552 * Get an aliased table name
2553 * e.g. tableName AS newTableName
2554 *
2555 * @param string $name Table name, see tableName()
2556 * @param string|bool $alias Alias (optional)
2557 * @return string SQL name for aliased table. Will not alias a table to its own name
2558 */
2559 public function tableNameWithAlias( $name, $alias = false ) {
2560 if ( !$alias || $alias == $name ) {
2561 return $this->tableName( $name );
2562 } else {
2563 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2564 }
2565 }
2566
2567 /**
2568 * Gets an array of aliased table names
2569 *
2570 * @param array $tables Array( [alias] => table )
2571 * @return string[] See tableNameWithAlias()
2572 */
2573 public function tableNamesWithAlias( $tables ) {
2574 $retval = array();
2575 foreach ( $tables as $alias => $table ) {
2576 if ( is_numeric( $alias ) ) {
2577 $alias = $table;
2578 }
2579 $retval[] = $this->tableNameWithAlias( $table, $alias );
2580 }
2581
2582 return $retval;
2583 }
2584
2585 /**
2586 * Get an aliased field name
2587 * e.g. fieldName AS newFieldName
2588 *
2589 * @param string $name Field name
2590 * @param string|bool $alias Alias (optional)
2591 * @return string SQL name for aliased field. Will not alias a field to its own name
2592 */
2593 public function fieldNameWithAlias( $name, $alias = false ) {
2594 if ( !$alias || (string)$alias === (string)$name ) {
2595 return $name;
2596 } else {
2597 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2598 }
2599 }
2600
2601 /**
2602 * Gets an array of aliased field names
2603 *
2604 * @param array $fields Array( [alias] => field )
2605 * @return string[] See fieldNameWithAlias()
2606 */
2607 public function fieldNamesWithAlias( $fields ) {
2608 $retval = array();
2609 foreach ( $fields as $alias => $field ) {
2610 if ( is_numeric( $alias ) ) {
2611 $alias = $field;
2612 }
2613 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2614 }
2615
2616 return $retval;
2617 }
2618
2619 /**
2620 * Get the aliased table name clause for a FROM clause
2621 * which might have a JOIN and/or USE INDEX clause
2622 *
2623 * @param array $tables ( [alias] => table )
2624 * @param array $use_index Same as for select()
2625 * @param array $join_conds Same as for select()
2626 * @return string
2627 */
2628 protected function tableNamesWithUseIndexOrJOIN(
2629 $tables, $use_index = array(), $join_conds = array()
2630 ) {
2631 $ret = array();
2632 $retJOIN = array();
2633 $use_index = (array)$use_index;
2634 $join_conds = (array)$join_conds;
2635
2636 foreach ( $tables as $alias => $table ) {
2637 if ( !is_string( $alias ) ) {
2638 // No alias? Set it equal to the table name
2639 $alias = $table;
2640 }
2641 // Is there a JOIN clause for this table?
2642 if ( isset( $join_conds[$alias] ) ) {
2643 list( $joinType, $conds ) = $join_conds[$alias];
2644 $tableClause = $joinType;
2645 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2646 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2647 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2648 if ( $use != '' ) {
2649 $tableClause .= ' ' . $use;
2650 }
2651 }
2652 $on = $this->makeList( (array)$conds, LIST_AND );
2653 if ( $on != '' ) {
2654 $tableClause .= ' ON (' . $on . ')';
2655 }
2656
2657 $retJOIN[] = $tableClause;
2658 } elseif ( isset( $use_index[$alias] ) ) {
2659 // Is there an INDEX clause for this table?
2660 $tableClause = $this->tableNameWithAlias( $table, $alias );
2661 $tableClause .= ' ' . $this->useIndexClause(
2662 implode( ',', (array)$use_index[$alias] )
2663 );
2664
2665 $ret[] = $tableClause;
2666 } else {
2667 $tableClause = $this->tableNameWithAlias( $table, $alias );
2668
2669 $ret[] = $tableClause;
2670 }
2671 }
2672
2673 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2674 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2675 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2676
2677 // Compile our final table clause
2678 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2679 }
2680
2681 /**
2682 * Get the name of an index in a given table.
2683 *
2684 * @protected Don't use outside of DatabaseBase and childs
2685 * @param string $index
2686 * @return string
2687 */
2688 public function indexName( $index ) {
2689 // @FIXME: Make this protected once we move away from PHP 5.3
2690 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2691
2692 // Backwards-compatibility hack
2693 $renamed = array(
2694 'ar_usertext_timestamp' => 'usertext_timestamp',
2695 'un_user_id' => 'user_id',
2696 'un_user_ip' => 'user_ip',
2697 );
2698
2699 if ( isset( $renamed[$index] ) ) {
2700 return $renamed[$index];
2701 } else {
2702 return $index;
2703 }
2704 }
2705
2706 /**
2707 * Adds quotes and backslashes.
2708 *
2709 * @param string|Blob $s
2710 * @return string
2711 */
2712 public function addQuotes( $s ) {
2713 if ( $s instanceof Blob ) {
2714 $s = $s->fetch();
2715 }
2716 if ( $s === null ) {
2717 return 'NULL';
2718 } else {
2719 # This will also quote numeric values. This should be harmless,
2720 # and protects against weird problems that occur when they really
2721 # _are_ strings such as article titles and string->number->string
2722 # conversion is not 1:1.
2723 return "'" . $this->strencode( $s ) . "'";
2724 }
2725 }
2726
2727 /**
2728 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2729 * MySQL uses `backticks` while basically everything else uses double quotes.
2730 * Since MySQL is the odd one out here the double quotes are our generic
2731 * and we implement backticks in DatabaseMysql.
2732 *
2733 * @param string $s
2734 * @return string
2735 */
2736 public function addIdentifierQuotes( $s ) {
2737 return '"' . str_replace( '"', '""', $s ) . '"';
2738 }
2739
2740 /**
2741 * Returns if the given identifier looks quoted or not according to
2742 * the database convention for quoting identifiers .
2743 *
2744 * @param string $name
2745 * @return bool
2746 */
2747 public function isQuotedIdentifier( $name ) {
2748 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2749 }
2750
2751 /**
2752 * @param string $s
2753 * @return string
2754 */
2755 protected function escapeLikeInternal( $s ) {
2756 return addcslashes( $s, '\%_' );
2757 }
2758
2759 /**
2760 * LIKE statement wrapper, receives a variable-length argument list with
2761 * parts of pattern to match containing either string literals that will be
2762 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2763 * the function could be provided with an array of aforementioned
2764 * parameters.
2765 *
2766 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2767 * a LIKE clause that searches for subpages of 'My page title'.
2768 * Alternatively:
2769 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2770 * $query .= $dbr->buildLike( $pattern );
2771 *
2772 * @since 1.16
2773 * @return string Fully built LIKE statement
2774 */
2775 public function buildLike() {
2776 $params = func_get_args();
2777
2778 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2779 $params = $params[0];
2780 }
2781
2782 $s = '';
2783
2784 foreach ( $params as $value ) {
2785 if ( $value instanceof LikeMatch ) {
2786 $s .= $value->toString();
2787 } else {
2788 $s .= $this->escapeLikeInternal( $value );
2789 }
2790 }
2791
2792 return " LIKE {$this->addQuotes( $s )} ";
2793 }
2794
2795 /**
2796 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2797 *
2798 * @return LikeMatch
2799 */
2800 public function anyChar() {
2801 return new LikeMatch( '_' );
2802 }
2803
2804 /**
2805 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2806 *
2807 * @return LikeMatch
2808 */
2809 public function anyString() {
2810 return new LikeMatch( '%' );
2811 }
2812
2813 /**
2814 * Returns an appropriately quoted sequence value for inserting a new row.
2815 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2816 * subclass will return an integer, and save the value for insertId()
2817 *
2818 * Any implementation of this function should *not* involve reusing
2819 * sequence numbers created for rolled-back transactions.
2820 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2821 * @param string $seqName
2822 * @return null|int
2823 */
2824 public function nextSequenceValue( $seqName ) {
2825 return null;
2826 }
2827
2828 /**
2829 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2830 * is only needed because a) MySQL must be as efficient as possible due to
2831 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2832 * which index to pick. Anyway, other databases might have different
2833 * indexes on a given table. So don't bother overriding this unless you're
2834 * MySQL.
2835 * @param string $index
2836 * @return string
2837 */
2838 public function useIndexClause( $index ) {
2839 return '';
2840 }
2841
2842 /**
2843 * REPLACE query wrapper.
2844 *
2845 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2846 * except that when there is a duplicate key error, the old row is deleted
2847 * and the new row is inserted in its place.
2848 *
2849 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2850 * perform the delete, we need to know what the unique indexes are so that
2851 * we know how to find the conflicting rows.
2852 *
2853 * It may be more efficient to leave off unique indexes which are unlikely
2854 * to collide. However if you do this, you run the risk of encountering
2855 * errors which wouldn't have occurred in MySQL.
2856 *
2857 * @param string $table The table to replace the row(s) in.
2858 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2859 * a field name or an array of field names
2860 * @param array $rows Can be either a single row to insert, or multiple rows,
2861 * in the same format as for DatabaseBase::insert()
2862 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2863 */
2864 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2865 $quotedTable = $this->tableName( $table );
2866
2867 if ( count( $rows ) == 0 ) {
2868 return;
2869 }
2870
2871 # Single row case
2872 if ( !is_array( reset( $rows ) ) ) {
2873 $rows = array( $rows );
2874 }
2875
2876 foreach ( $rows as $row ) {
2877 # Delete rows which collide
2878 if ( $uniqueIndexes ) {
2879 $sql = "DELETE FROM $quotedTable WHERE ";
2880 $first = true;
2881 foreach ( $uniqueIndexes as $index ) {
2882 if ( $first ) {
2883 $first = false;
2884 $sql .= '( ';
2885 } else {
2886 $sql .= ' ) OR ( ';
2887 }
2888 if ( is_array( $index ) ) {
2889 $first2 = true;
2890 foreach ( $index as $col ) {
2891 if ( $first2 ) {
2892 $first2 = false;
2893 } else {
2894 $sql .= ' AND ';
2895 }
2896 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2897 }
2898 } else {
2899 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2900 }
2901 }
2902 $sql .= ' )';
2903 $this->query( $sql, $fname );
2904 }
2905
2906 # Now insert the row
2907 $this->insert( $table, $row, $fname );
2908 }
2909 }
2910
2911 /**
2912 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2913 * statement.
2914 *
2915 * @param string $table Table name
2916 * @param array|string $rows Row(s) to insert
2917 * @param string $fname Caller function name
2918 *
2919 * @return ResultWrapper
2920 */
2921 protected function nativeReplace( $table, $rows, $fname ) {
2922 $table = $this->tableName( $table );
2923
2924 # Single row case
2925 if ( !is_array( reset( $rows ) ) ) {
2926 $rows = array( $rows );
2927 }
2928
2929 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2930 $first = true;
2931
2932 foreach ( $rows as $row ) {
2933 if ( $first ) {
2934 $first = false;
2935 } else {
2936 $sql .= ',';
2937 }
2938
2939 $sql .= '(' . $this->makeList( $row ) . ')';
2940 }
2941
2942 return $this->query( $sql, $fname );
2943 }
2944
2945 /**
2946 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2947 *
2948 * This updates any conflicting rows (according to the unique indexes) using
2949 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2950 *
2951 * $rows may be either:
2952 * - A single associative array. The array keys are the field names, and
2953 * the values are the values to insert. The values are treated as data
2954 * and will be quoted appropriately. If NULL is inserted, this will be
2955 * converted to a database NULL.
2956 * - An array with numeric keys, holding a list of associative arrays.
2957 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2958 * each subarray must be identical to each other, and in the same order.
2959 *
2960 * It may be more efficient to leave off unique indexes which are unlikely
2961 * to collide. However if you do this, you run the risk of encountering
2962 * errors which wouldn't have occurred in MySQL.
2963 *
2964 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2965 * returns success.
2966 *
2967 * @since 1.22
2968 *
2969 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2970 * @param array $rows A single row or list of rows to insert
2971 * @param array $uniqueIndexes List of single field names or field name tuples
2972 * @param array $set An array of values to SET. For each array element, the
2973 * key gives the field name, and the value gives the data to set that
2974 * field to. The data will be quoted by DatabaseBase::addQuotes().
2975 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2976 * @throws Exception
2977 * @return bool
2978 */
2979 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2980 $fname = __METHOD__
2981 ) {
2982 if ( !count( $rows ) ) {
2983 return true; // nothing to do
2984 }
2985
2986 if ( !is_array( reset( $rows ) ) ) {
2987 $rows = array( $rows );
2988 }
2989
2990 if ( count( $uniqueIndexes ) ) {
2991 $clauses = array(); // list WHERE clauses that each identify a single row
2992 foreach ( $rows as $row ) {
2993 foreach ( $uniqueIndexes as $index ) {
2994 $index = is_array( $index ) ? $index : array( $index ); // columns
2995 $rowKey = array(); // unique key to this row
2996 foreach ( $index as $column ) {
2997 $rowKey[$column] = $row[$column];
2998 }
2999 $clauses[] = $this->makeList( $rowKey, LIST_AND );
3000 }
3001 }
3002 $where = array( $this->makeList( $clauses, LIST_OR ) );
3003 } else {
3004 $where = false;
3005 }
3006
3007 $useTrx = !$this->mTrxLevel;
3008 if ( $useTrx ) {
3009 $this->begin( $fname );
3010 }
3011 try {
3012 # Update any existing conflicting row(s)
3013 if ( $where !== false ) {
3014 $ok = $this->update( $table, $set, $where, $fname );
3015 } else {
3016 $ok = true;
3017 }
3018 # Now insert any non-conflicting row(s)
3019 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
3020 } catch ( Exception $e ) {
3021 if ( $useTrx ) {
3022 $this->rollback( $fname );
3023 }
3024 throw $e;
3025 }
3026 if ( $useTrx ) {
3027 $this->commit( $fname );
3028 }
3029
3030 return $ok;
3031 }
3032
3033 /**
3034 * DELETE where the condition is a join.
3035 *
3036 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
3037 * we use sub-selects
3038 *
3039 * For safety, an empty $conds will not delete everything. If you want to
3040 * delete all rows where the join condition matches, set $conds='*'.
3041 *
3042 * DO NOT put the join condition in $conds.
3043 *
3044 * @param string $delTable The table to delete from.
3045 * @param string $joinTable The other table.
3046 * @param string $delVar The variable to join on, in the first table.
3047 * @param string $joinVar The variable to join on, in the second table.
3048 * @param array $conds Condition array of field names mapped to variables,
3049 * ANDed together in the WHERE clause
3050 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
3051 * @throws DBUnexpectedError
3052 */
3053 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
3054 $fname = __METHOD__
3055 ) {
3056 if ( !$conds ) {
3057 throw new DBUnexpectedError( $this,
3058 'DatabaseBase::deleteJoin() called with empty $conds' );
3059 }
3060
3061 $delTable = $this->tableName( $delTable );
3062 $joinTable = $this->tableName( $joinTable );
3063 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
3064 if ( $conds != '*' ) {
3065 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
3066 }
3067 $sql .= ')';
3068
3069 $this->query( $sql, $fname );
3070 }
3071
3072 /**
3073 * Returns the size of a text field, or -1 for "unlimited"
3074 *
3075 * @param string $table
3076 * @param string $field
3077 * @return int
3078 */
3079 public function textFieldSize( $table, $field ) {
3080 $table = $this->tableName( $table );
3081 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
3082 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
3083 $row = $this->fetchObject( $res );
3084
3085 $m = array();
3086
3087 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
3088 $size = $m[1];
3089 } else {
3090 $size = -1;
3091 }
3092
3093 return $size;
3094 }
3095
3096 /**
3097 * A string to insert into queries to show that they're low-priority, like
3098 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
3099 * string and nothing bad should happen.
3100 *
3101 * @return string Returns the text of the low priority option if it is
3102 * supported, or a blank string otherwise
3103 */
3104 public function lowPriorityOption() {
3105 return '';
3106 }
3107
3108 /**
3109 * DELETE query wrapper.
3110 *
3111 * @param array $table Table name
3112 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
3113 * for the format. Use $conds == "*" to delete all rows
3114 * @param string $fname Name of the calling function
3115 * @throws DBUnexpectedError
3116 * @return bool|ResultWrapper
3117 */
3118 public function delete( $table, $conds, $fname = __METHOD__ ) {
3119 if ( !$conds ) {
3120 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
3121 }
3122
3123 $table = $this->tableName( $table );
3124 $sql = "DELETE FROM $table";
3125
3126 if ( $conds != '*' ) {
3127 if ( is_array( $conds ) ) {
3128 $conds = $this->makeList( $conds, LIST_AND );
3129 }
3130 $sql .= ' WHERE ' . $conds;
3131 }
3132
3133 return $this->query( $sql, $fname );
3134 }
3135
3136 /**
3137 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
3138 * into another table.
3139 *
3140 * @param string $destTable The table name to insert into
3141 * @param string|array $srcTable May be either a table name, or an array of table names
3142 * to include in a join.
3143 *
3144 * @param array $varMap Must be an associative array of the form
3145 * array( 'dest1' => 'source1', ...). Source items may be literals
3146 * rather than field names, but strings should be quoted with
3147 * DatabaseBase::addQuotes()
3148 *
3149 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
3150 * the details of the format of condition arrays. May be "*" to copy the
3151 * whole table.
3152 *
3153 * @param string $fname The function name of the caller, from __METHOD__
3154 *
3155 * @param array $insertOptions Options for the INSERT part of the query, see
3156 * DatabaseBase::insert() for details.
3157 * @param array $selectOptions Options for the SELECT part of the query, see
3158 * DatabaseBase::select() for details.
3159 *
3160 * @return ResultWrapper
3161 */
3162 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3163 $fname = __METHOD__,
3164 $insertOptions = array(), $selectOptions = array()
3165 ) {
3166 $destTable = $this->tableName( $destTable );
3167
3168 if ( !is_array( $insertOptions ) ) {
3169 $insertOptions = array( $insertOptions );
3170 }
3171
3172 $insertOptions = $this->makeInsertOptions( $insertOptions );
3173
3174 if ( !is_array( $selectOptions ) ) {
3175 $selectOptions = array( $selectOptions );
3176 }
3177
3178 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3179
3180 if ( is_array( $srcTable ) ) {
3181 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3182 } else {
3183 $srcTable = $this->tableName( $srcTable );
3184 }
3185
3186 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3187 " SELECT $startOpts " . implode( ',', $varMap ) .
3188 " FROM $srcTable $useIndex ";
3189
3190 if ( $conds != '*' ) {
3191 if ( is_array( $conds ) ) {
3192 $conds = $this->makeList( $conds, LIST_AND );
3193 }
3194 $sql .= " WHERE $conds";
3195 }
3196
3197 $sql .= " $tailOpts";
3198
3199 return $this->query( $sql, $fname );
3200 }
3201
3202 /**
3203 * Construct a LIMIT query with optional offset. This is used for query
3204 * pages. The SQL should be adjusted so that only the first $limit rows
3205 * are returned. If $offset is provided as well, then the first $offset
3206 * rows should be discarded, and the next $limit rows should be returned.
3207 * If the result of the query is not ordered, then the rows to be returned
3208 * are theoretically arbitrary.
3209 *
3210 * $sql is expected to be a SELECT, if that makes a difference.
3211 *
3212 * The version provided by default works in MySQL and SQLite. It will very
3213 * likely need to be overridden for most other DBMSes.
3214 *
3215 * @param string $sql SQL query we will append the limit too
3216 * @param int $limit The SQL limit
3217 * @param int|bool $offset The SQL offset (default false)
3218 * @throws DBUnexpectedError
3219 * @return string
3220 */
3221 public function limitResult( $sql, $limit, $offset = false ) {
3222 if ( !is_numeric( $limit ) ) {
3223 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3224 }
3225
3226 return "$sql LIMIT "
3227 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3228 . "{$limit} ";
3229 }
3230
3231 /**
3232 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3233 * within the UNION construct.
3234 * @return bool
3235 */
3236 public function unionSupportsOrderAndLimit() {
3237 return true; // True for almost every DB supported
3238 }
3239
3240 /**
3241 * Construct a UNION query
3242 * This is used for providing overload point for other DB abstractions
3243 * not compatible with the MySQL syntax.
3244 * @param array $sqls SQL statements to combine
3245 * @param bool $all Use UNION ALL
3246 * @return string SQL fragment
3247 */
3248 public function unionQueries( $sqls, $all ) {
3249 $glue = $all ? ') UNION ALL (' : ') UNION (';
3250
3251 return '(' . implode( $glue, $sqls ) . ')';
3252 }
3253
3254 /**
3255 * Returns an SQL expression for a simple conditional. This doesn't need
3256 * to be overridden unless CASE isn't supported in your DBMS.
3257 *
3258 * @param string|array $cond SQL expression which will result in a boolean value
3259 * @param string $trueVal SQL expression to return if true
3260 * @param string $falseVal SQL expression to return if false
3261 * @return string SQL fragment
3262 */
3263 public function conditional( $cond, $trueVal, $falseVal ) {
3264 if ( is_array( $cond ) ) {
3265 $cond = $this->makeList( $cond, LIST_AND );
3266 }
3267
3268 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3269 }
3270
3271 /**
3272 * Returns a comand for str_replace function in SQL query.
3273 * Uses REPLACE() in MySQL
3274 *
3275 * @param string $orig Column to modify
3276 * @param string $old Column to seek
3277 * @param string $new Column to replace with
3278 *
3279 * @return string
3280 */
3281 public function strreplace( $orig, $old, $new ) {
3282 return "REPLACE({$orig}, {$old}, {$new})";
3283 }
3284
3285 /**
3286 * Determines how long the server has been up
3287 * STUB
3288 *
3289 * @return int
3290 */
3291 public function getServerUptime() {
3292 return 0;
3293 }
3294
3295 /**
3296 * Determines if the last failure was due to a deadlock
3297 * STUB
3298 *
3299 * @return bool
3300 */
3301 public function wasDeadlock() {
3302 return false;
3303 }
3304
3305 /**
3306 * Determines if the last failure was due to a lock timeout
3307 * STUB
3308 *
3309 * @return bool
3310 */
3311 public function wasLockTimeout() {
3312 return false;
3313 }
3314
3315 /**
3316 * Determines if the last query error was something that should be dealt
3317 * with by pinging the connection and reissuing the query.
3318 * STUB
3319 *
3320 * @return bool
3321 */
3322 public function wasErrorReissuable() {
3323 return false;
3324 }
3325
3326 /**
3327 * Determines if the last failure was due to the database being read-only.
3328 * STUB
3329 *
3330 * @return bool
3331 */
3332 public function wasReadOnlyError() {
3333 return false;
3334 }
3335
3336 /**
3337 * Perform a deadlock-prone transaction.
3338 *
3339 * This function invokes a callback function to perform a set of write
3340 * queries. If a deadlock occurs during the processing, the transaction
3341 * will be rolled back and the callback function will be called again.
3342 *
3343 * Usage:
3344 * $dbw->deadlockLoop( callback, ... );
3345 *
3346 * Extra arguments are passed through to the specified callback function.
3347 *
3348 * Returns whatever the callback function returned on its successful,
3349 * iteration, or false on error, for example if the retry limit was
3350 * reached.
3351 *
3352 * @return bool
3353 */
3354 public function deadlockLoop() {
3355 $args = func_get_args();
3356 $function = array_shift( $args );
3357 $tries = self::DEADLOCK_TRIES;
3358 if ( is_array( $function ) ) {
3359 $fname = $function[0];
3360 } else {
3361 $fname = $function;
3362 }
3363
3364 $this->begin( __METHOD__ );
3365
3366 $e = null;
3367 do {
3368 try {
3369 $retVal = call_user_func_array( $function, $args );
3370 break;
3371 } catch ( DBQueryError $e ) {
3372 $error = $this->lastError();
3373 $errno = $this->lastErrno();
3374 $sql = $this->lastQuery();
3375 if ( $this->wasDeadlock() ) {
3376 // Retry after a randomized delay
3377 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3378 } else {
3379 // Throw the error back up
3380 throw $e;
3381 }
3382 }
3383 } while ( --$tries > 0 );
3384
3385 if ( $tries <= 0 ) {
3386 // Too many deadlocks; give up
3387 $this->rollback( __METHOD__ );
3388 throw $e;
3389 } else {
3390 $this->commit( __METHOD__ );
3391
3392 return $retVal;
3393 }
3394 }
3395
3396 /**
3397 * Wait for the slave to catch up to a given master position.
3398 *
3399 * @param DBMasterPos $pos
3400 * @param int $timeout The maximum number of seconds to wait for
3401 * synchronisation
3402 * @return int Zero if the slave was past that position already,
3403 * greater than zero if we waited for some period of time, less than
3404 * zero if we timed out.
3405 */
3406 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3407 # Real waits are implemented in the subclass.
3408 return 0;
3409 }
3410
3411 /**
3412 * Get the replication position of this slave
3413 *
3414 * @return DBMasterPos|bool False if this is not a slave.
3415 */
3416 public function getSlavePos() {
3417 # Stub
3418 return false;
3419 }
3420
3421 /**
3422 * Get the position of this master
3423 *
3424 * @return DBMasterPos|bool False if this is not a master
3425 */
3426 public function getMasterPos() {
3427 # Stub
3428 return false;
3429 }
3430
3431 /**
3432 * Run an anonymous function as soon as there is no transaction pending.
3433 * If there is a transaction and it is rolled back, then the callback is cancelled.
3434 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3435 * Callbacks must commit any transactions that they begin.
3436 *
3437 * This is useful for updates to different systems or when separate transactions are needed.
3438 * For example, one might want to enqueue jobs into a system outside the database, but only
3439 * after the database is updated so that the jobs will see the data when they actually run.
3440 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3441 *
3442 * @param callable $callback
3443 * @since 1.20
3444 */
3445 final public function onTransactionIdle( $callback ) {
3446 $this->mTrxIdleCallbacks[] = array( $callback, wfGetCaller() );
3447 if ( !$this->mTrxLevel ) {
3448 $this->runOnTransactionIdleCallbacks();
3449 }
3450 }
3451
3452 /**
3453 * Run an anonymous function before the current transaction commits or now if there is none.
3454 * If there is a transaction and it is rolled back, then the callback is cancelled.
3455 * Callbacks must not start nor commit any transactions.
3456 *
3457 * This is useful for updates that easily cause deadlocks if locks are held too long
3458 * but where atomicity is strongly desired for these updates and some related updates.
3459 *
3460 * @param callable $callback
3461 * @since 1.22
3462 */
3463 final public function onTransactionPreCommitOrIdle( $callback ) {
3464 if ( $this->mTrxLevel ) {
3465 $this->mTrxPreCommitCallbacks[] = array( $callback, wfGetCaller() );
3466 } else {
3467 $this->onTransactionIdle( $callback ); // this will trigger immediately
3468 }
3469 }
3470
3471 /**
3472 * Actually any "on transaction idle" callbacks.
3473 *
3474 * @since 1.20
3475 */
3476 protected function runOnTransactionIdleCallbacks() {
3477 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
3478
3479 $e = $ePrior = null; // last exception
3480 do { // callbacks may add callbacks :)
3481 $callbacks = $this->mTrxIdleCallbacks;
3482 $this->mTrxIdleCallbacks = array(); // recursion guard
3483 foreach ( $callbacks as $callback ) {
3484 try {
3485 list( $phpCallback ) = $callback;
3486 $this->clearFlag( DBO_TRX ); // make each query its own transaction
3487 call_user_func( $phpCallback );
3488 $this->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
3489 } catch ( Exception $e ) {
3490 if ( $ePrior ) {
3491 MWExceptionHandler::logException( $ePrior );
3492 }
3493 $ePrior = $e;
3494 }
3495 }
3496 } while ( count( $this->mTrxIdleCallbacks ) );
3497
3498 if ( $e instanceof Exception ) {
3499 throw $e; // re-throw any last exception
3500 }
3501 }
3502
3503 /**
3504 * Actually any "on transaction pre-commit" callbacks.
3505 *
3506 * @since 1.22
3507 */
3508 protected function runOnTransactionPreCommitCallbacks() {
3509 $e = $ePrior = null; // last exception
3510 do { // callbacks may add callbacks :)
3511 $callbacks = $this->mTrxPreCommitCallbacks;
3512 $this->mTrxPreCommitCallbacks = array(); // recursion guard
3513 foreach ( $callbacks as $callback ) {
3514 try {
3515 list( $phpCallback ) = $callback;
3516 call_user_func( $phpCallback );
3517 } catch ( Exception $e ) {
3518 if ( $ePrior ) {
3519 MWExceptionHandler::logException( $ePrior );
3520 }
3521 $ePrior = $e;
3522 }
3523 }
3524 } while ( count( $this->mTrxPreCommitCallbacks ) );
3525
3526 if ( $e instanceof Exception ) {
3527 throw $e; // re-throw any last exception
3528 }
3529 }
3530
3531 /**
3532 * Begin an atomic section of statements
3533 *
3534 * If a transaction has been started already, just keep track of the given
3535 * section name to make sure the transaction is not committed pre-maturely.
3536 * This function can be used in layers (with sub-sections), so use a stack
3537 * to keep track of the different atomic sections. If there is no transaction,
3538 * start one implicitly.
3539 *
3540 * The goal of this function is to create an atomic section of SQL queries
3541 * without having to start a new transaction if it already exists.
3542 *
3543 * Atomic sections are more strict than transactions. With transactions,
3544 * attempting to begin a new transaction when one is already running results
3545 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3546 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3547 * and any database transactions cannot be began or committed until all atomic
3548 * levels are closed. There is no such thing as implicitly opening or closing
3549 * an atomic section.
3550 *
3551 * @since 1.23
3552 * @param string $fname
3553 * @throws DBError
3554 */
3555 final public function startAtomic( $fname = __METHOD__ ) {
3556 if ( !$this->mTrxLevel ) {
3557 $this->begin( $fname );
3558 $this->mTrxAutomatic = true;
3559 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3560 // in all changes being in one transaction to keep requests transactional.
3561 if ( !$this->getFlag( DBO_TRX ) ) {
3562 $this->mTrxAutomaticAtomic = true;
3563 }
3564 }
3565
3566 $this->mTrxAtomicLevels->push( $fname );
3567 }
3568
3569 /**
3570 * Ends an atomic section of SQL statements
3571 *
3572 * Ends the next section of atomic SQL statements and commits the transaction
3573 * if necessary.
3574 *
3575 * @since 1.23
3576 * @see DatabaseBase::startAtomic
3577 * @param string $fname
3578 * @throws DBError
3579 */
3580 final public function endAtomic( $fname = __METHOD__ ) {
3581 if ( !$this->mTrxLevel ) {
3582 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3583 }
3584 if ( $this->mTrxAtomicLevels->isEmpty() ||
3585 $this->mTrxAtomicLevels->pop() !== $fname
3586 ) {
3587 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3588 }
3589
3590 if ( $this->mTrxAtomicLevels->isEmpty() && $this->mTrxAutomaticAtomic ) {
3591 $this->commit( $fname, 'flush' );
3592 }
3593 }
3594
3595 /**
3596 * Begin a transaction. If a transaction is already in progress,
3597 * that transaction will be committed before the new transaction is started.
3598 *
3599 * Note that when the DBO_TRX flag is set (which is usually the case for web
3600 * requests, but not for maintenance scripts), any previous database query
3601 * will have started a transaction automatically.
3602 *
3603 * Nesting of transactions is not supported. Attempts to nest transactions
3604 * will cause a warning, unless the current transaction was started
3605 * automatically because of the DBO_TRX flag.
3606 *
3607 * @param string $fname
3608 * @throws DBError
3609 */
3610 final public function begin( $fname = __METHOD__ ) {
3611 global $wgDebugDBTransactions;
3612
3613 if ( $this->mTrxLevel ) { // implicit commit
3614 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3615 // If the current transaction was an automatic atomic one, then we definitely have
3616 // a problem. Same if there is any unclosed atomic level.
3617 throw new DBUnexpectedError( $this,
3618 "Attempted to start explicit transaction when atomic levels are still open."
3619 );
3620 } elseif ( !$this->mTrxAutomatic ) {
3621 // We want to warn about inadvertently nested begin/commit pairs, but not about
3622 // auto-committing implicit transactions that were started by query() via DBO_TRX
3623 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3624 " performing implicit commit!";
3625 wfWarn( $msg );
3626 wfLogDBError( $msg,
3627 $this->getLogContext( array(
3628 'method' => __METHOD__,
3629 'fname' => $fname,
3630 ) )
3631 );
3632 } else {
3633 // if the transaction was automatic and has done write operations,
3634 // log it if $wgDebugDBTransactions is enabled.
3635 if ( $this->mTrxDoneWrites && $wgDebugDBTransactions ) {
3636 wfDebug( "$fname: Automatic transaction with writes in progress" .
3637 " (from {$this->mTrxFname}), performing implicit commit!\n"
3638 );
3639 }
3640 }
3641
3642 $this->runOnTransactionPreCommitCallbacks();
3643 $writeTime = $this->pendingWriteQueryDuration();
3644 $this->doCommit( $fname );
3645 if ( $this->mTrxDoneWrites ) {
3646 $this->mDoneWrites = microtime( true );
3647 $this->getTransactionProfiler()->transactionWritingOut(
3648 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3649 }
3650 $this->runOnTransactionIdleCallbacks();
3651 }
3652
3653 # Avoid fatals if close() was called
3654 $this->assertOpen();
3655
3656 $this->doBegin( $fname );
3657 $this->mTrxTimestamp = microtime( true );
3658 $this->mTrxFname = $fname;
3659 $this->mTrxDoneWrites = false;
3660 $this->mTrxAutomatic = false;
3661 $this->mTrxAutomaticAtomic = false;
3662 $this->mTrxAtomicLevels = new SplStack;
3663 $this->mTrxIdleCallbacks = array();
3664 $this->mTrxPreCommitCallbacks = array();
3665 $this->mTrxShortId = wfRandomString( 12 );
3666 $this->mTrxWriteDuration = 0.0;
3667 }
3668
3669 /**
3670 * Issues the BEGIN command to the database server.
3671 *
3672 * @see DatabaseBase::begin()
3673 * @param string $fname
3674 */
3675 protected function doBegin( $fname ) {
3676 $this->query( 'BEGIN', $fname );
3677 $this->mTrxLevel = 1;
3678 }
3679
3680 /**
3681 * Commits a transaction previously started using begin().
3682 * If no transaction is in progress, a warning is issued.
3683 *
3684 * Nesting of transactions is not supported.
3685 *
3686 * @param string $fname
3687 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3688 * explicitly committing implicit transactions, or calling commit when no
3689 * transaction is in progress. This will silently break any ongoing
3690 * explicit transaction. Only set the flush flag if you are sure that it
3691 * is safe to ignore these warnings in your context.
3692 * @throws DBUnexpectedError
3693 */
3694 final public function commit( $fname = __METHOD__, $flush = '' ) {
3695 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3696 // There are still atomic sections open. This cannot be ignored
3697 throw new DBUnexpectedError(
3698 $this,
3699 "Attempted to commit transaction while atomic sections are still open"
3700 );
3701 }
3702
3703 if ( $flush === 'flush' ) {
3704 if ( !$this->mTrxLevel ) {
3705 return; // nothing to do
3706 } elseif ( !$this->mTrxAutomatic ) {
3707 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3708 }
3709 } else {
3710 if ( !$this->mTrxLevel ) {
3711 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3712 return; // nothing to do
3713 } elseif ( $this->mTrxAutomatic ) {
3714 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3715 }
3716 }
3717
3718 # Avoid fatals if close() was called
3719 $this->assertOpen();
3720
3721 $this->runOnTransactionPreCommitCallbacks();
3722 $writeTime = $this->pendingWriteQueryDuration();
3723 $this->doCommit( $fname );
3724 if ( $this->mTrxDoneWrites ) {
3725 $this->mDoneWrites = microtime( true );
3726 $this->getTransactionProfiler()->transactionWritingOut(
3727 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3728 }
3729 $this->runOnTransactionIdleCallbacks();
3730 }
3731
3732 /**
3733 * Issues the COMMIT command to the database server.
3734 *
3735 * @see DatabaseBase::commit()
3736 * @param string $fname
3737 */
3738 protected function doCommit( $fname ) {
3739 if ( $this->mTrxLevel ) {
3740 $this->query( 'COMMIT', $fname );
3741 $this->mTrxLevel = 0;
3742 }
3743 }
3744
3745 /**
3746 * Rollback a transaction previously started using begin().
3747 * If no transaction is in progress, a warning is issued.
3748 *
3749 * No-op on non-transactional databases.
3750 *
3751 * @param string $fname
3752 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3753 * calling rollback when no transaction is in progress. This will silently
3754 * break any ongoing explicit transaction. Only set the flush flag if you
3755 * are sure that it is safe to ignore these warnings in your context.
3756 * @throws DBUnexpectedError
3757 * @since 1.23 Added $flush parameter
3758 */
3759 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3760 if ( $flush !== 'flush' ) {
3761 if ( !$this->mTrxLevel ) {
3762 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3763 return; // nothing to do
3764 } elseif ( $this->mTrxAutomatic ) {
3765 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3766 }
3767 } else {
3768 if ( !$this->mTrxLevel ) {
3769 return; // nothing to do
3770 } elseif ( !$this->mTrxAutomatic ) {
3771 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3772 }
3773 }
3774
3775 # Avoid fatals if close() was called
3776 $this->assertOpen();
3777
3778 $this->doRollback( $fname );
3779 $this->mTrxIdleCallbacks = array(); // cancel
3780 $this->mTrxPreCommitCallbacks = array(); // cancel
3781 $this->mTrxAtomicLevels = new SplStack;
3782 if ( $this->mTrxDoneWrites ) {
3783 $this->getTransactionProfiler()->transactionWritingOut(
3784 $this->mServer, $this->mDBname, $this->mTrxShortId );
3785 }
3786 }
3787
3788 /**
3789 * Issues the ROLLBACK command to the database server.
3790 *
3791 * @see DatabaseBase::rollback()
3792 * @param string $fname
3793 */
3794 protected function doRollback( $fname ) {
3795 if ( $this->mTrxLevel ) {
3796 $this->query( 'ROLLBACK', $fname, true );
3797 $this->mTrxLevel = 0;
3798 }
3799 }
3800
3801 /**
3802 * Creates a new table with structure copied from existing table
3803 * Note that unlike most database abstraction functions, this function does not
3804 * automatically append database prefix, because it works at a lower
3805 * abstraction level.
3806 * The table names passed to this function shall not be quoted (this
3807 * function calls addIdentifierQuotes when needed).
3808 *
3809 * @param string $oldName Name of table whose structure should be copied
3810 * @param string $newName Name of table to be created
3811 * @param bool $temporary Whether the new table should be temporary
3812 * @param string $fname Calling function name
3813 * @throws MWException
3814 * @return bool True if operation was successful
3815 */
3816 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3817 $fname = __METHOD__
3818 ) {
3819 throw new MWException(
3820 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3821 }
3822
3823 /**
3824 * List all tables on the database
3825 *
3826 * @param string $prefix Only show tables with this prefix, e.g. mw_
3827 * @param string $fname Calling function name
3828 * @throws MWException
3829 * @return array
3830 */
3831 function listTables( $prefix = null, $fname = __METHOD__ ) {
3832 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3833 }
3834
3835 /**
3836 * Reset the views process cache set by listViews()
3837 * @since 1.22
3838 */
3839 final public function clearViewsCache() {
3840 $this->allViews = null;
3841 }
3842
3843 /**
3844 * Lists all the VIEWs in the database
3845 *
3846 * For caching purposes the list of all views should be stored in
3847 * $this->allViews. The process cache can be cleared with clearViewsCache()
3848 *
3849 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3850 * @param string $fname Name of calling function
3851 * @throws MWException
3852 * @return array
3853 * @since 1.22
3854 */
3855 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3856 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3857 }
3858
3859 /**
3860 * Differentiates between a TABLE and a VIEW
3861 *
3862 * @param string $name Name of the database-structure to test.
3863 * @throws MWException
3864 * @return bool
3865 * @since 1.22
3866 */
3867 public function isView( $name ) {
3868 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3869 }
3870
3871 /**
3872 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3873 * to the format used for inserting into timestamp fields in this DBMS.
3874 *
3875 * The result is unquoted, and needs to be passed through addQuotes()
3876 * before it can be included in raw SQL.
3877 *
3878 * @param string|int $ts
3879 *
3880 * @return string
3881 */
3882 public function timestamp( $ts = 0 ) {
3883 return wfTimestamp( TS_MW, $ts );
3884 }
3885
3886 /**
3887 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3888 * to the format used for inserting into timestamp fields in this DBMS. If
3889 * NULL is input, it is passed through, allowing NULL values to be inserted
3890 * into timestamp fields.
3891 *
3892 * The result is unquoted, and needs to be passed through addQuotes()
3893 * before it can be included in raw SQL.
3894 *
3895 * @param string|int $ts
3896 *
3897 * @return string
3898 */
3899 public function timestampOrNull( $ts = null ) {
3900 if ( is_null( $ts ) ) {
3901 return null;
3902 } else {
3903 return $this->timestamp( $ts );
3904 }
3905 }
3906
3907 /**
3908 * Take the result from a query, and wrap it in a ResultWrapper if
3909 * necessary. Boolean values are passed through as is, to indicate success
3910 * of write queries or failure.
3911 *
3912 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3913 * resource, and it was necessary to call this function to convert it to
3914 * a wrapper. Nowadays, raw database objects are never exposed to external
3915 * callers, so this is unnecessary in external code. For compatibility with
3916 * old code, ResultWrapper objects are passed through unaltered.
3917 *
3918 * @param bool|ResultWrapper|resource $result
3919 * @return bool|ResultWrapper
3920 */
3921 public function resultObject( $result ) {
3922 if ( empty( $result ) ) {
3923 return false;
3924 } elseif ( $result instanceof ResultWrapper ) {
3925 return $result;
3926 } elseif ( $result === true ) {
3927 // Successful write query
3928 return $result;
3929 } else {
3930 return new ResultWrapper( $this, $result );
3931 }
3932 }
3933
3934 /**
3935 * Ping the server and try to reconnect if it there is no connection
3936 *
3937 * @return bool Success or failure
3938 */
3939 public function ping() {
3940 # Stub. Not essential to override.
3941 return true;
3942 }
3943
3944 /**
3945 * Get slave lag. Currently supported only by MySQL.
3946 *
3947 * Note that this function will generate a fatal error on many
3948 * installations. Most callers should use LoadBalancer::safeGetLag()
3949 * instead.
3950 *
3951 * @return int Database replication lag in seconds
3952 */
3953 public function getLag() {
3954 return 0;
3955 }
3956
3957 /**
3958 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3959 *
3960 * @return int
3961 */
3962 function maxListLen() {
3963 return 0;
3964 }
3965
3966 /**
3967 * Some DBMSs have a special format for inserting into blob fields, they
3968 * don't allow simple quoted strings to be inserted. To insert into such
3969 * a field, pass the data through this function before passing it to
3970 * DatabaseBase::insert().
3971 *
3972 * @param string $b
3973 * @return string
3974 */
3975 public function encodeBlob( $b ) {
3976 return $b;
3977 }
3978
3979 /**
3980 * Some DBMSs return a special placeholder object representing blob fields
3981 * in result objects. Pass the object through this function to return the
3982 * original string.
3983 *
3984 * @param string|Blob $b
3985 * @return string
3986 */
3987 public function decodeBlob( $b ) {
3988 if ( $b instanceof Blob ) {
3989 $b = $b->fetch();
3990 }
3991 return $b;
3992 }
3993
3994 /**
3995 * Override database's default behavior. $options include:
3996 * 'connTimeout' : Set the connection timeout value in seconds.
3997 * May be useful for very long batch queries such as
3998 * full-wiki dumps, where a single query reads out over
3999 * hours or days.
4000 *
4001 * @param array $options
4002 * @return void
4003 */
4004 public function setSessionOptions( array $options ) {
4005 }
4006
4007 /**
4008 * Read and execute SQL commands from a file.
4009 *
4010 * Returns true on success, error string or exception on failure (depending
4011 * on object's error ignore settings).
4012 *
4013 * @param string $filename File name to open
4014 * @param bool|callable $lineCallback Optional function called before reading each line
4015 * @param bool|callable $resultCallback Optional function called for each MySQL result
4016 * @param bool|string $fname Calling function name or false if name should be
4017 * generated dynamically using $filename
4018 * @param bool|callable $inputCallback Optional function called for each
4019 * complete line sent
4020 * @throws Exception|MWException
4021 * @return bool|string
4022 */
4023 public function sourceFile(
4024 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
4025 ) {
4026 MediaWiki\suppressWarnings();
4027 $fp = fopen( $filename, 'r' );
4028 MediaWiki\restoreWarnings();
4029
4030 if ( false === $fp ) {
4031 throw new MWException( "Could not open \"{$filename}\".\n" );
4032 }
4033
4034 if ( !$fname ) {
4035 $fname = __METHOD__ . "( $filename )";
4036 }
4037
4038 try {
4039 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4040 } catch ( Exception $e ) {
4041 fclose( $fp );
4042 throw $e;
4043 }
4044
4045 fclose( $fp );
4046
4047 return $error;
4048 }
4049
4050 /**
4051 * Get the full path of a patch file. Originally based on archive()
4052 * from updaters.inc. Keep in mind this always returns a patch, as
4053 * it fails back to MySQL if no DB-specific patch can be found
4054 *
4055 * @param string $patch The name of the patch, like patch-something.sql
4056 * @return string Full path to patch file
4057 */
4058 public function patchPath( $patch ) {
4059 global $IP;
4060
4061 $dbType = $this->getType();
4062 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
4063 return "$IP/maintenance/$dbType/archives/$patch";
4064 } else {
4065 return "$IP/maintenance/archives/$patch";
4066 }
4067 }
4068
4069 /**
4070 * Set variables to be used in sourceFile/sourceStream, in preference to the
4071 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
4072 * all. If it's set to false, $GLOBALS will be used.
4073 *
4074 * @param bool|array $vars Mapping variable name to value.
4075 */
4076 public function setSchemaVars( $vars ) {
4077 $this->mSchemaVars = $vars;
4078 }
4079
4080 /**
4081 * Read and execute commands from an open file handle.
4082 *
4083 * Returns true on success, error string or exception on failure (depending
4084 * on object's error ignore settings).
4085 *
4086 * @param resource $fp File handle
4087 * @param bool|callable $lineCallback Optional function called before reading each query
4088 * @param bool|callable $resultCallback Optional function called for each MySQL result
4089 * @param string $fname Calling function name
4090 * @param bool|callable $inputCallback Optional function called for each complete query sent
4091 * @return bool|string
4092 */
4093 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
4094 $fname = __METHOD__, $inputCallback = false
4095 ) {
4096 $cmd = '';
4097
4098 while ( !feof( $fp ) ) {
4099 if ( $lineCallback ) {
4100 call_user_func( $lineCallback );
4101 }
4102
4103 $line = trim( fgets( $fp ) );
4104
4105 if ( $line == '' ) {
4106 continue;
4107 }
4108
4109 if ( '-' == $line[0] && '-' == $line[1] ) {
4110 continue;
4111 }
4112
4113 if ( $cmd != '' ) {
4114 $cmd .= ' ';
4115 }
4116
4117 $done = $this->streamStatementEnd( $cmd, $line );
4118
4119 $cmd .= "$line\n";
4120
4121 if ( $done || feof( $fp ) ) {
4122 $cmd = $this->replaceVars( $cmd );
4123
4124 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
4125 $res = $this->query( $cmd, $fname );
4126
4127 if ( $resultCallback ) {
4128 call_user_func( $resultCallback, $res, $this );
4129 }
4130
4131 if ( false === $res ) {
4132 $err = $this->lastError();
4133
4134 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4135 }
4136 }
4137 $cmd = '';
4138 }
4139 }
4140
4141 return true;
4142 }
4143
4144 /**
4145 * Called by sourceStream() to check if we've reached a statement end
4146 *
4147 * @param string $sql SQL assembled so far
4148 * @param string $newLine New line about to be added to $sql
4149 * @return bool Whether $newLine contains end of the statement
4150 */
4151 public function streamStatementEnd( &$sql, &$newLine ) {
4152 if ( $this->delimiter ) {
4153 $prev = $newLine;
4154 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
4155 if ( $newLine != $prev ) {
4156 return true;
4157 }
4158 }
4159
4160 return false;
4161 }
4162
4163 /**
4164 * Database independent variable replacement. Replaces a set of variables
4165 * in an SQL statement with their contents as given by $this->getSchemaVars().
4166 *
4167 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4168 *
4169 * - '{$var}' should be used for text and is passed through the database's
4170 * addQuotes method.
4171 * - `{$var}` should be used for identifiers (e.g. table and database names).
4172 * It is passed through the database's addIdentifierQuotes method which
4173 * can be overridden if the database uses something other than backticks.
4174 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4175 * database's tableName method.
4176 * - / *i* / passes the name that follows through the database's indexName method.
4177 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4178 * its use should be avoided. In 1.24 and older, string encoding was applied.
4179 *
4180 * @param string $ins SQL statement to replace variables in
4181 * @return string The new SQL statement with variables replaced
4182 */
4183 protected function replaceVars( $ins ) {
4184 $that = $this;
4185 $vars = $this->getSchemaVars();
4186 return preg_replace_callback(
4187 '!
4188 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4189 \'\{\$ (\w+) }\' | # 3. addQuotes
4190 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4191 /\*\$ (\w+) \*/ # 5. leave unencoded
4192 !x',
4193 function ( $m ) use ( $that, $vars ) {
4194 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4195 // check for both nonexistent keys *and* the empty string.
4196 if ( isset( $m[1] ) && $m[1] !== '' ) {
4197 if ( $m[1] === 'i' ) {
4198 return $that->indexName( $m[2] );
4199 } else {
4200 return $that->tableName( $m[2] );
4201 }
4202 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4203 return $that->addQuotes( $vars[$m[3]] );
4204 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4205 return $that->addIdentifierQuotes( $vars[$m[4]] );
4206 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4207 return $vars[$m[5]];
4208 } else {
4209 return $m[0];
4210 }
4211 },
4212 $ins
4213 );
4214 }
4215
4216 /**
4217 * Get schema variables. If none have been set via setSchemaVars(), then
4218 * use some defaults from the current object.
4219 *
4220 * @return array
4221 */
4222 protected function getSchemaVars() {
4223 if ( $this->mSchemaVars ) {
4224 return $this->mSchemaVars;
4225 } else {
4226 return $this->getDefaultSchemaVars();
4227 }
4228 }
4229
4230 /**
4231 * Get schema variables to use if none have been set via setSchemaVars().
4232 *
4233 * Override this in derived classes to provide variables for tables.sql
4234 * and SQL patch files.
4235 *
4236 * @return array
4237 */
4238 protected function getDefaultSchemaVars() {
4239 return array();
4240 }
4241
4242 /**
4243 * Check to see if a named lock is available (non-blocking)
4244 *
4245 * @param string $lockName Name of lock to poll
4246 * @param string $method Name of method calling us
4247 * @return bool
4248 * @since 1.20
4249 */
4250 public function lockIsFree( $lockName, $method ) {
4251 return true;
4252 }
4253
4254 /**
4255 * Acquire a named lock
4256 *
4257 * Named locks are not related to transactions
4258 *
4259 * @param string $lockName Name of lock to aquire
4260 * @param string $method Name of method calling us
4261 * @param int $timeout
4262 * @return bool
4263 */
4264 public function lock( $lockName, $method, $timeout = 5 ) {
4265 return true;
4266 }
4267
4268 /**
4269 * Release a lock
4270 *
4271 * Named locks are not related to transactions
4272 *
4273 * @param string $lockName Name of lock to release
4274 * @param string $method Name of method calling us
4275 *
4276 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4277 * by this thread (in which case the lock is not released), and NULL if the named
4278 * lock did not exist
4279 */
4280 public function unlock( $lockName, $method ) {
4281 return true;
4282 }
4283
4284 /**
4285 * Check to see if a named lock used by lock() use blocking queues
4286 *
4287 * @return bool
4288 * @since 1.26
4289 */
4290 public function namedLocksEnqueue() {
4291 return false;
4292 }
4293
4294 /**
4295 * Lock specific tables
4296 *
4297 * @param array $read Array of tables to lock for read access
4298 * @param array $write Array of tables to lock for write access
4299 * @param string $method Name of caller
4300 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4301 * @return bool
4302 */
4303 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4304 return true;
4305 }
4306
4307 /**
4308 * Unlock specific tables
4309 *
4310 * @param string $method The caller
4311 * @return bool
4312 */
4313 public function unlockTables( $method ) {
4314 return true;
4315 }
4316
4317 /**
4318 * Delete a table
4319 * @param string $tableName
4320 * @param string $fName
4321 * @return bool|ResultWrapper
4322 * @since 1.18
4323 */
4324 public function dropTable( $tableName, $fName = __METHOD__ ) {
4325 if ( !$this->tableExists( $tableName, $fName ) ) {
4326 return false;
4327 }
4328 $sql = "DROP TABLE " . $this->tableName( $tableName );
4329 if ( $this->cascadingDeletes() ) {
4330 $sql .= " CASCADE";
4331 }
4332
4333 return $this->query( $sql, $fName );
4334 }
4335
4336 /**
4337 * Get search engine class. All subclasses of this need to implement this
4338 * if they wish to use searching.
4339 *
4340 * @return string
4341 */
4342 public function getSearchEngine() {
4343 return 'SearchEngineDummy';
4344 }
4345
4346 /**
4347 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4348 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4349 * because "i" sorts after all numbers.
4350 *
4351 * @return string
4352 */
4353 public function getInfinity() {
4354 return 'infinity';
4355 }
4356
4357 /**
4358 * Encode an expiry time into the DBMS dependent format
4359 *
4360 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4361 * @return string
4362 */
4363 public function encodeExpiry( $expiry ) {
4364 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4365 ? $this->getInfinity()
4366 : $this->timestamp( $expiry );
4367 }
4368
4369 /**
4370 * Decode an expiry time into a DBMS independent format
4371 *
4372 * @param string $expiry DB timestamp field value for expiry
4373 * @param int $format TS_* constant, defaults to TS_MW
4374 * @return string
4375 */
4376 public function decodeExpiry( $expiry, $format = TS_MW ) {
4377 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4378 ? 'infinity'
4379 : wfTimestamp( $format, $expiry );
4380 }
4381
4382 /**
4383 * Allow or deny "big selects" for this session only. This is done by setting
4384 * the sql_big_selects session variable.
4385 *
4386 * This is a MySQL-specific feature.
4387 *
4388 * @param bool|string $value True for allow, false for deny, or "default" to
4389 * restore the initial value
4390 */
4391 public function setBigSelects( $value = true ) {
4392 // no-op
4393 }
4394
4395 /**
4396 * @since 1.19
4397 * @return string
4398 */
4399 public function __toString() {
4400 return (string)$this->mConn;
4401 }
4402
4403 /**
4404 * Run a few simple sanity checks
4405 */
4406 public function __destruct() {
4407 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
4408 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4409 }
4410 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
4411 $callers = array();
4412 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
4413 $callers[] = $callbackInfo[1];
4414 }
4415 $callers = implode( ', ', $callers );
4416 trigger_error( "DB transaction callbacks still pending (from $callers)." );
4417 }
4418 }
4419 }