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