Merge "Enable users to watch category membership changes #2"
[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 * @since 1.27 Added $join_conds parameter
1711 *
1712 * @param array|string $tables Table names
1713 * @param string $vars Unused
1714 * @param array|string $conds Filters on the table
1715 * @param string $fname Function name for profiling
1716 * @param array $options Options for select
1717 * @param array $join_conds Join conditions (since 1.27)
1718 * @return int Row count
1719 */
1720 public function selectRowCount(
1721 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = array(), $join_conds = array()
1722 ) {
1723 $rows = 0;
1724 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1725 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1726
1727 if ( $res ) {
1728 $row = $this->fetchRow( $res );
1729 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1730 }
1731
1732 return $rows;
1733 }
1734
1735 /**
1736 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1737 * It's only slightly flawed. Don't use for anything important.
1738 *
1739 * @param string $sql A SQL Query
1740 *
1741 * @return string
1742 */
1743 protected static function generalizeSQL( $sql ) {
1744 # This does the same as the regexp below would do, but in such a way
1745 # as to avoid crashing php on some large strings.
1746 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1747
1748 $sql = str_replace( "\\\\", '', $sql );
1749 $sql = str_replace( "\\'", '', $sql );
1750 $sql = str_replace( "\\\"", '', $sql );
1751 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1752 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1753
1754 # All newlines, tabs, etc replaced by single space
1755 $sql = preg_replace( '/\s+/', ' ', $sql );
1756
1757 # All numbers => N,
1758 # except the ones surrounded by characters, e.g. l10n
1759 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1760 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1761
1762 return $sql;
1763 }
1764
1765 /**
1766 * Determines whether a field exists in a table
1767 *
1768 * @param string $table Table name
1769 * @param string $field Filed to check on that table
1770 * @param string $fname Calling function name (optional)
1771 * @return bool Whether $table has filed $field
1772 */
1773 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1774 $info = $this->fieldInfo( $table, $field );
1775
1776 return (bool)$info;
1777 }
1778
1779 /**
1780 * Determines whether an index exists
1781 * Usually throws a DBQueryError on failure
1782 * If errors are explicitly ignored, returns NULL on failure
1783 *
1784 * @param string $table
1785 * @param string $index
1786 * @param string $fname
1787 * @return bool|null
1788 */
1789 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1790 if ( !$this->tableExists( $table ) ) {
1791 return null;
1792 }
1793
1794 $info = $this->indexInfo( $table, $index, $fname );
1795 if ( is_null( $info ) ) {
1796 return null;
1797 } else {
1798 return $info !== false;
1799 }
1800 }
1801
1802 /**
1803 * Query whether a given table exists
1804 *
1805 * @param string $table
1806 * @param string $fname
1807 * @return bool
1808 */
1809 public function tableExists( $table, $fname = __METHOD__ ) {
1810 $table = $this->tableName( $table );
1811 $old = $this->ignoreErrors( true );
1812 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1813 $this->ignoreErrors( $old );
1814
1815 return (bool)$res;
1816 }
1817
1818 /**
1819 * Determines if a given index is unique
1820 *
1821 * @param string $table
1822 * @param string $index
1823 *
1824 * @return bool
1825 */
1826 public function indexUnique( $table, $index ) {
1827 $indexInfo = $this->indexInfo( $table, $index );
1828
1829 if ( !$indexInfo ) {
1830 return null;
1831 }
1832
1833 return !$indexInfo[0]->Non_unique;
1834 }
1835
1836 /**
1837 * Helper for DatabaseBase::insert().
1838 *
1839 * @param array $options
1840 * @return string
1841 */
1842 protected function makeInsertOptions( $options ) {
1843 return implode( ' ', $options );
1844 }
1845
1846 /**
1847 * INSERT wrapper, inserts an array into a table.
1848 *
1849 * $a may be either:
1850 *
1851 * - A single associative array. The array keys are the field names, and
1852 * the values are the values to insert. The values are treated as data
1853 * and will be quoted appropriately. If NULL is inserted, this will be
1854 * converted to a database NULL.
1855 * - An array with numeric keys, holding a list of associative arrays.
1856 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1857 * each subarray must be identical to each other, and in the same order.
1858 *
1859 * $options is an array of options, with boolean options encoded as values
1860 * with numeric keys, in the same style as $options in
1861 * DatabaseBase::select(). Supported options are:
1862 *
1863 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1864 * any rows which cause duplicate key errors are not inserted. It's
1865 * possible to determine how many rows were successfully inserted using
1866 * DatabaseBase::affectedRows().
1867 *
1868 * @param string $table Table name. This will be passed through
1869 * DatabaseBase::tableName().
1870 * @param array $a Array of rows to insert
1871 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1872 * @param array $options Array of options
1873 *
1874 * @throws DBQueryError Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1875 * returns success.
1876 *
1877 * @return bool
1878 */
1879 public function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
1880 # No rows to insert, easy just return now
1881 if ( !count( $a ) ) {
1882 return true;
1883 }
1884
1885 $table = $this->tableName( $table );
1886
1887 if ( !is_array( $options ) ) {
1888 $options = array( $options );
1889 }
1890
1891 $fh = null;
1892 if ( isset( $options['fileHandle'] ) ) {
1893 $fh = $options['fileHandle'];
1894 }
1895 $options = $this->makeInsertOptions( $options );
1896
1897 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1898 $multi = true;
1899 $keys = array_keys( $a[0] );
1900 } else {
1901 $multi = false;
1902 $keys = array_keys( $a );
1903 }
1904
1905 $sql = 'INSERT ' . $options .
1906 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1907
1908 if ( $multi ) {
1909 $first = true;
1910 foreach ( $a as $row ) {
1911 if ( $first ) {
1912 $first = false;
1913 } else {
1914 $sql .= ',';
1915 }
1916 $sql .= '(' . $this->makeList( $row ) . ')';
1917 }
1918 } else {
1919 $sql .= '(' . $this->makeList( $a ) . ')';
1920 }
1921
1922 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1923 return false;
1924 } elseif ( $fh !== null ) {
1925 return true;
1926 }
1927
1928 return (bool)$this->query( $sql, $fname );
1929 }
1930
1931 /**
1932 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1933 *
1934 * @param array $options
1935 * @return array
1936 */
1937 protected function makeUpdateOptionsArray( $options ) {
1938 if ( !is_array( $options ) ) {
1939 $options = array( $options );
1940 }
1941
1942 $opts = array();
1943
1944 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1945 $opts[] = $this->lowPriorityOption();
1946 }
1947
1948 if ( in_array( 'IGNORE', $options ) ) {
1949 $opts[] = 'IGNORE';
1950 }
1951
1952 return $opts;
1953 }
1954
1955 /**
1956 * Make UPDATE options for the DatabaseBase::update function
1957 *
1958 * @param array $options The options passed to DatabaseBase::update
1959 * @return string
1960 */
1961 protected function makeUpdateOptions( $options ) {
1962 $opts = $this->makeUpdateOptionsArray( $options );
1963
1964 return implode( ' ', $opts );
1965 }
1966
1967 /**
1968 * UPDATE wrapper. Takes a condition array and a SET array.
1969 *
1970 * @param string $table Name of the table to UPDATE. This will be passed through
1971 * DatabaseBase::tableName().
1972 * @param array $values An array of values to SET. For each array element,
1973 * the key gives the field name, and the value gives the data to set
1974 * that field to. The data will be quoted by DatabaseBase::addQuotes().
1975 * @param array $conds An array of conditions (WHERE). See
1976 * DatabaseBase::select() for the details of the format of condition
1977 * arrays. Use '*' to update all rows.
1978 * @param string $fname The function name of the caller (from __METHOD__),
1979 * for logging and profiling.
1980 * @param array $options An array of UPDATE options, can be:
1981 * - IGNORE: Ignore unique key conflicts
1982 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1983 * @return bool
1984 */
1985 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
1986 $table = $this->tableName( $table );
1987 $opts = $this->makeUpdateOptions( $options );
1988 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1989
1990 if ( $conds !== array() && $conds !== '*' ) {
1991 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1992 }
1993
1994 return $this->query( $sql, $fname );
1995 }
1996
1997 /**
1998 * Makes an encoded list of strings from an array
1999 *
2000 * @param array $a Containing the data
2001 * @param int $mode Constant
2002 * - LIST_COMMA: Comma separated, no field names
2003 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2004 * documentation for $conds in DatabaseBase::select().
2005 * - LIST_OR: ORed WHERE clause (without the WHERE)
2006 * - LIST_SET: Comma separated with field names, like a SET clause
2007 * - LIST_NAMES: Comma separated field names
2008 * @throws MWException|DBUnexpectedError
2009 * @return string
2010 */
2011 public function makeList( $a, $mode = LIST_COMMA ) {
2012 if ( !is_array( $a ) ) {
2013 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2014 }
2015
2016 $first = true;
2017 $list = '';
2018
2019 foreach ( $a as $field => $value ) {
2020 if ( !$first ) {
2021 if ( $mode == LIST_AND ) {
2022 $list .= ' AND ';
2023 } elseif ( $mode == LIST_OR ) {
2024 $list .= ' OR ';
2025 } else {
2026 $list .= ',';
2027 }
2028 } else {
2029 $first = false;
2030 }
2031
2032 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
2033 $list .= "($value)";
2034 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
2035 $list .= "$value";
2036 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
2037 // Remove null from array to be handled separately if found
2038 $includeNull = false;
2039 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2040 $includeNull = true;
2041 unset( $value[$nullKey] );
2042 }
2043 if ( count( $value ) == 0 && !$includeNull ) {
2044 throw new MWException( __METHOD__ . ": empty input for field $field" );
2045 } elseif ( count( $value ) == 0 ) {
2046 // only check if $field is null
2047 $list .= "$field IS NULL";
2048 } else {
2049 // IN clause contains at least one valid element
2050 if ( $includeNull ) {
2051 // Group subconditions to ensure correct precedence
2052 $list .= '(';
2053 }
2054 if ( count( $value ) == 1 ) {
2055 // Special-case single values, as IN isn't terribly efficient
2056 // Don't necessarily assume the single key is 0; we don't
2057 // enforce linear numeric ordering on other arrays here.
2058 $value = array_values( $value );
2059 $list .= $field . " = " . $this->addQuotes( $value[0] );
2060 } else {
2061 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2062 }
2063 // if null present in array, append IS NULL
2064 if ( $includeNull ) {
2065 $list .= " OR $field IS NULL)";
2066 }
2067 }
2068 } elseif ( $value === null ) {
2069 if ( $mode == LIST_AND || $mode == LIST_OR ) {
2070 $list .= "$field IS ";
2071 } elseif ( $mode == LIST_SET ) {
2072 $list .= "$field = ";
2073 }
2074 $list .= 'NULL';
2075 } else {
2076 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
2077 $list .= "$field = ";
2078 }
2079 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
2080 }
2081 }
2082
2083 return $list;
2084 }
2085
2086 /**
2087 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2088 * The keys on each level may be either integers or strings.
2089 *
2090 * @param array $data Organized as 2-d
2091 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2092 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2093 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2094 * @return string|bool SQL fragment, or false if no items in array
2095 */
2096 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2097 $conds = array();
2098
2099 foreach ( $data as $base => $sub ) {
2100 if ( count( $sub ) ) {
2101 $conds[] = $this->makeList(
2102 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2103 LIST_AND );
2104 }
2105 }
2106
2107 if ( $conds ) {
2108 return $this->makeList( $conds, LIST_OR );
2109 } else {
2110 // Nothing to search for...
2111 return false;
2112 }
2113 }
2114
2115 /**
2116 * Return aggregated value alias
2117 *
2118 * @param array $valuedata
2119 * @param string $valuename
2120 *
2121 * @return string
2122 */
2123 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2124 return $valuename;
2125 }
2126
2127 /**
2128 * @param string $field
2129 * @return string
2130 */
2131 public function bitNot( $field ) {
2132 return "(~$field)";
2133 }
2134
2135 /**
2136 * @param string $fieldLeft
2137 * @param string $fieldRight
2138 * @return string
2139 */
2140 public function bitAnd( $fieldLeft, $fieldRight ) {
2141 return "($fieldLeft & $fieldRight)";
2142 }
2143
2144 /**
2145 * @param string $fieldLeft
2146 * @param string $fieldRight
2147 * @return string
2148 */
2149 public function bitOr( $fieldLeft, $fieldRight ) {
2150 return "($fieldLeft | $fieldRight)";
2151 }
2152
2153 /**
2154 * Build a concatenation list to feed into a SQL query
2155 * @param array $stringList List of raw SQL expressions; caller is
2156 * responsible for any quoting
2157 * @return string
2158 */
2159 public function buildConcat( $stringList ) {
2160 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2161 }
2162
2163 /**
2164 * Build a GROUP_CONCAT or equivalent statement for a query.
2165 *
2166 * This is useful for combining a field for several rows into a single string.
2167 * NULL values will not appear in the output, duplicated values will appear,
2168 * and the resulting delimiter-separated values have no defined sort order.
2169 * Code using the results may need to use the PHP unique() or sort() methods.
2170 *
2171 * @param string $delim Glue to bind the results together
2172 * @param string|array $table Table name
2173 * @param string $field Field name
2174 * @param string|array $conds Conditions
2175 * @param string|array $join_conds Join conditions
2176 * @return string SQL text
2177 * @since 1.23
2178 */
2179 public function buildGroupConcatField(
2180 $delim, $table, $field, $conds = '', $join_conds = array()
2181 ) {
2182 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2183
2184 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2185 }
2186
2187 /**
2188 * Change the current database
2189 *
2190 * @todo Explain what exactly will fail if this is not overridden.
2191 *
2192 * @param string $db
2193 *
2194 * @return bool Success or failure
2195 */
2196 public function selectDB( $db ) {
2197 # Stub. Shouldn't cause serious problems if it's not overridden, but
2198 # if your database engine supports a concept similar to MySQL's
2199 # databases you may as well.
2200 $this->mDBname = $db;
2201
2202 return true;
2203 }
2204
2205 /**
2206 * Get the current DB name
2207 * @return string
2208 */
2209 public function getDBname() {
2210 return $this->mDBname;
2211 }
2212
2213 /**
2214 * Get the server hostname or IP address
2215 * @return string
2216 */
2217 public function getServer() {
2218 return $this->mServer;
2219 }
2220
2221 /**
2222 * Format a table name ready for use in constructing an SQL query
2223 *
2224 * This does two important things: it quotes the table names to clean them up,
2225 * and it adds a table prefix if only given a table name with no quotes.
2226 *
2227 * All functions of this object which require a table name call this function
2228 * themselves. Pass the canonical name to such functions. This is only needed
2229 * when calling query() directly.
2230 *
2231 * @param string $name Database table name
2232 * @param string $format One of:
2233 * quoted - Automatically pass the table name through addIdentifierQuotes()
2234 * so that it can be used in a query.
2235 * raw - Do not add identifier quotes to the table name
2236 * @return string Full database name
2237 */
2238 public function tableName( $name, $format = 'quoted' ) {
2239 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2240 # Skip the entire process when we have a string quoted on both ends.
2241 # Note that we check the end so that we will still quote any use of
2242 # use of `database`.table. But won't break things if someone wants
2243 # to query a database table with a dot in the name.
2244 if ( $this->isQuotedIdentifier( $name ) ) {
2245 return $name;
2246 }
2247
2248 # Lets test for any bits of text that should never show up in a table
2249 # name. Basically anything like JOIN or ON which are actually part of
2250 # SQL queries, but may end up inside of the table value to combine
2251 # sql. Such as how the API is doing.
2252 # Note that we use a whitespace test rather than a \b test to avoid
2253 # any remote case where a word like on may be inside of a table name
2254 # surrounded by symbols which may be considered word breaks.
2255 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2256 return $name;
2257 }
2258
2259 # Split database and table into proper variables.
2260 # We reverse the explode so that database.table and table both output
2261 # the correct table.
2262 $dbDetails = explode( '.', $name, 3 );
2263 if ( count( $dbDetails ) == 3 ) {
2264 list( $database, $schema, $table ) = $dbDetails;
2265 # We don't want any prefix added in this case
2266 $prefix = '';
2267 } elseif ( count( $dbDetails ) == 2 ) {
2268 list( $database, $table ) = $dbDetails;
2269 # We don't want any prefix added in this case
2270 # In dbs that support it, $database may actually be the schema
2271 # but that doesn't affect any of the functionality here
2272 $prefix = '';
2273 $schema = null;
2274 } else {
2275 list( $table ) = $dbDetails;
2276 if ( $wgSharedDB !== null # We have a shared database
2277 && $this->mForeign == false # We're not working on a foreign database
2278 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2279 && in_array( $table, $wgSharedTables ) # A shared table is selected
2280 ) {
2281 $database = $wgSharedDB;
2282 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
2283 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
2284 } else {
2285 $database = null;
2286 $schema = $this->mSchema; # Default schema
2287 $prefix = $this->mTablePrefix; # Default prefix
2288 }
2289 }
2290
2291 # Quote $table and apply the prefix if not quoted.
2292 # $tableName might be empty if this is called from Database::replaceVars()
2293 $tableName = "{$prefix}{$table}";
2294 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2295 $tableName = $this->addIdentifierQuotes( $tableName );
2296 }
2297
2298 # Quote $schema and merge it with the table name if needed
2299 if ( strlen( $schema ) ) {
2300 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2301 $schema = $this->addIdentifierQuotes( $schema );
2302 }
2303 $tableName = $schema . '.' . $tableName;
2304 }
2305
2306 # Quote $database and merge it with the table name if needed
2307 if ( $database !== null ) {
2308 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2309 $database = $this->addIdentifierQuotes( $database );
2310 }
2311 $tableName = $database . '.' . $tableName;
2312 }
2313
2314 return $tableName;
2315 }
2316
2317 /**
2318 * Fetch a number of table names into an array
2319 * This is handy when you need to construct SQL for joins
2320 *
2321 * Example:
2322 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2323 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2324 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2325 *
2326 * @return array
2327 */
2328 public function tableNames() {
2329 $inArray = func_get_args();
2330 $retVal = array();
2331
2332 foreach ( $inArray as $name ) {
2333 $retVal[$name] = $this->tableName( $name );
2334 }
2335
2336 return $retVal;
2337 }
2338
2339 /**
2340 * Fetch a number of table names into an zero-indexed numerical array
2341 * This is handy when you need to construct SQL for joins
2342 *
2343 * Example:
2344 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2345 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2346 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2347 *
2348 * @return array
2349 */
2350 public function tableNamesN() {
2351 $inArray = func_get_args();
2352 $retVal = array();
2353
2354 foreach ( $inArray as $name ) {
2355 $retVal[] = $this->tableName( $name );
2356 }
2357
2358 return $retVal;
2359 }
2360
2361 /**
2362 * Get an aliased table name
2363 * e.g. tableName AS newTableName
2364 *
2365 * @param string $name Table name, see tableName()
2366 * @param string|bool $alias Alias (optional)
2367 * @return string SQL name for aliased table. Will not alias a table to its own name
2368 */
2369 public function tableNameWithAlias( $name, $alias = false ) {
2370 if ( !$alias || $alias == $name ) {
2371 return $this->tableName( $name );
2372 } else {
2373 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2374 }
2375 }
2376
2377 /**
2378 * Gets an array of aliased table names
2379 *
2380 * @param array $tables Array( [alias] => table )
2381 * @return string[] See tableNameWithAlias()
2382 */
2383 public function tableNamesWithAlias( $tables ) {
2384 $retval = array();
2385 foreach ( $tables as $alias => $table ) {
2386 if ( is_numeric( $alias ) ) {
2387 $alias = $table;
2388 }
2389 $retval[] = $this->tableNameWithAlias( $table, $alias );
2390 }
2391
2392 return $retval;
2393 }
2394
2395 /**
2396 * Get an aliased field name
2397 * e.g. fieldName AS newFieldName
2398 *
2399 * @param string $name Field name
2400 * @param string|bool $alias Alias (optional)
2401 * @return string SQL name for aliased field. Will not alias a field to its own name
2402 */
2403 public function fieldNameWithAlias( $name, $alias = false ) {
2404 if ( !$alias || (string)$alias === (string)$name ) {
2405 return $name;
2406 } else {
2407 return $name . ' AS ' . $alias; // PostgreSQL needs AS
2408 }
2409 }
2410
2411 /**
2412 * Gets an array of aliased field names
2413 *
2414 * @param array $fields Array( [alias] => field )
2415 * @return string[] See fieldNameWithAlias()
2416 */
2417 public function fieldNamesWithAlias( $fields ) {
2418 $retval = array();
2419 foreach ( $fields as $alias => $field ) {
2420 if ( is_numeric( $alias ) ) {
2421 $alias = $field;
2422 }
2423 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2424 }
2425
2426 return $retval;
2427 }
2428
2429 /**
2430 * Get the aliased table name clause for a FROM clause
2431 * which might have a JOIN and/or USE INDEX clause
2432 *
2433 * @param array $tables ( [alias] => table )
2434 * @param array $use_index Same as for select()
2435 * @param array $join_conds Same as for select()
2436 * @return string
2437 */
2438 protected function tableNamesWithUseIndexOrJOIN(
2439 $tables, $use_index = array(), $join_conds = array()
2440 ) {
2441 $ret = array();
2442 $retJOIN = array();
2443 $use_index = (array)$use_index;
2444 $join_conds = (array)$join_conds;
2445
2446 foreach ( $tables as $alias => $table ) {
2447 if ( !is_string( $alias ) ) {
2448 // No alias? Set it equal to the table name
2449 $alias = $table;
2450 }
2451 // Is there a JOIN clause for this table?
2452 if ( isset( $join_conds[$alias] ) ) {
2453 list( $joinType, $conds ) = $join_conds[$alias];
2454 $tableClause = $joinType;
2455 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2456 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2457 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2458 if ( $use != '' ) {
2459 $tableClause .= ' ' . $use;
2460 }
2461 }
2462 $on = $this->makeList( (array)$conds, LIST_AND );
2463 if ( $on != '' ) {
2464 $tableClause .= ' ON (' . $on . ')';
2465 }
2466
2467 $retJOIN[] = $tableClause;
2468 } elseif ( isset( $use_index[$alias] ) ) {
2469 // Is there an INDEX clause for this table?
2470 $tableClause = $this->tableNameWithAlias( $table, $alias );
2471 $tableClause .= ' ' . $this->useIndexClause(
2472 implode( ',', (array)$use_index[$alias] )
2473 );
2474
2475 $ret[] = $tableClause;
2476 } else {
2477 $tableClause = $this->tableNameWithAlias( $table, $alias );
2478
2479 $ret[] = $tableClause;
2480 }
2481 }
2482
2483 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2484 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2485 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2486
2487 // Compile our final table clause
2488 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2489 }
2490
2491 /**
2492 * Get the name of an index in a given table.
2493 *
2494 * @protected Don't use outside of DatabaseBase and childs
2495 * @param string $index
2496 * @return string
2497 */
2498 public function indexName( $index ) {
2499 // @FIXME: Make this protected once we move away from PHP 5.3
2500 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2501
2502 // Backwards-compatibility hack
2503 $renamed = array(
2504 'ar_usertext_timestamp' => 'usertext_timestamp',
2505 'un_user_id' => 'user_id',
2506 'un_user_ip' => 'user_ip',
2507 );
2508
2509 if ( isset( $renamed[$index] ) ) {
2510 return $renamed[$index];
2511 } else {
2512 return $index;
2513 }
2514 }
2515
2516 /**
2517 * Adds quotes and backslashes.
2518 *
2519 * @param string|Blob $s
2520 * @return string
2521 */
2522 public function addQuotes( $s ) {
2523 if ( $s instanceof Blob ) {
2524 $s = $s->fetch();
2525 }
2526 if ( $s === null ) {
2527 return 'NULL';
2528 } else {
2529 # This will also quote numeric values. This should be harmless,
2530 # and protects against weird problems that occur when they really
2531 # _are_ strings such as article titles and string->number->string
2532 # conversion is not 1:1.
2533 return "'" . $this->strencode( $s ) . "'";
2534 }
2535 }
2536
2537 /**
2538 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2539 * MySQL uses `backticks` while basically everything else uses double quotes.
2540 * Since MySQL is the odd one out here the double quotes are our generic
2541 * and we implement backticks in DatabaseMysql.
2542 *
2543 * @param string $s
2544 * @return string
2545 */
2546 public function addIdentifierQuotes( $s ) {
2547 return '"' . str_replace( '"', '""', $s ) . '"';
2548 }
2549
2550 /**
2551 * Returns if the given identifier looks quoted or not according to
2552 * the database convention for quoting identifiers .
2553 *
2554 * @param string $name
2555 * @return bool
2556 */
2557 public function isQuotedIdentifier( $name ) {
2558 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2559 }
2560
2561 /**
2562 * @param string $s
2563 * @return string
2564 */
2565 protected function escapeLikeInternal( $s ) {
2566 return addcslashes( $s, '\%_' );
2567 }
2568
2569 /**
2570 * LIKE statement wrapper, receives a variable-length argument list with
2571 * parts of pattern to match containing either string literals that will be
2572 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2573 * the function could be provided with an array of aforementioned
2574 * parameters.
2575 *
2576 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2577 * a LIKE clause that searches for subpages of 'My page title'.
2578 * Alternatively:
2579 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2580 * $query .= $dbr->buildLike( $pattern );
2581 *
2582 * @since 1.16
2583 * @return string Fully built LIKE statement
2584 */
2585 public function buildLike() {
2586 $params = func_get_args();
2587
2588 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2589 $params = $params[0];
2590 }
2591
2592 $s = '';
2593
2594 foreach ( $params as $value ) {
2595 if ( $value instanceof LikeMatch ) {
2596 $s .= $value->toString();
2597 } else {
2598 $s .= $this->escapeLikeInternal( $value );
2599 }
2600 }
2601
2602 return " LIKE {$this->addQuotes( $s )} ";
2603 }
2604
2605 /**
2606 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2607 *
2608 * @return LikeMatch
2609 */
2610 public function anyChar() {
2611 return new LikeMatch( '_' );
2612 }
2613
2614 /**
2615 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2616 *
2617 * @return LikeMatch
2618 */
2619 public function anyString() {
2620 return new LikeMatch( '%' );
2621 }
2622
2623 /**
2624 * Returns an appropriately quoted sequence value for inserting a new row.
2625 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2626 * subclass will return an integer, and save the value for insertId()
2627 *
2628 * Any implementation of this function should *not* involve reusing
2629 * sequence numbers created for rolled-back transactions.
2630 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2631 * @param string $seqName
2632 * @return null|int
2633 */
2634 public function nextSequenceValue( $seqName ) {
2635 return null;
2636 }
2637
2638 /**
2639 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2640 * is only needed because a) MySQL must be as efficient as possible due to
2641 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2642 * which index to pick. Anyway, other databases might have different
2643 * indexes on a given table. So don't bother overriding this unless you're
2644 * MySQL.
2645 * @param string $index
2646 * @return string
2647 */
2648 public function useIndexClause( $index ) {
2649 return '';
2650 }
2651
2652 /**
2653 * REPLACE query wrapper.
2654 *
2655 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2656 * except that when there is a duplicate key error, the old row is deleted
2657 * and the new row is inserted in its place.
2658 *
2659 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2660 * perform the delete, we need to know what the unique indexes are so that
2661 * we know how to find the conflicting rows.
2662 *
2663 * It may be more efficient to leave off unique indexes which are unlikely
2664 * to collide. However if you do this, you run the risk of encountering
2665 * errors which wouldn't have occurred in MySQL.
2666 *
2667 * @param string $table The table to replace the row(s) in.
2668 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2669 * a field name or an array of field names
2670 * @param array $rows Can be either a single row to insert, or multiple rows,
2671 * in the same format as for DatabaseBase::insert()
2672 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2673 */
2674 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2675 $quotedTable = $this->tableName( $table );
2676
2677 if ( count( $rows ) == 0 ) {
2678 return;
2679 }
2680
2681 # Single row case
2682 if ( !is_array( reset( $rows ) ) ) {
2683 $rows = array( $rows );
2684 }
2685
2686 // @FXIME: this is not atomic, but a trx would break affectedRows()
2687 foreach ( $rows as $row ) {
2688 # Delete rows which collide
2689 if ( $uniqueIndexes ) {
2690 $sql = "DELETE FROM $quotedTable WHERE ";
2691 $first = true;
2692 foreach ( $uniqueIndexes as $index ) {
2693 if ( $first ) {
2694 $first = false;
2695 $sql .= '( ';
2696 } else {
2697 $sql .= ' ) OR ( ';
2698 }
2699 if ( is_array( $index ) ) {
2700 $first2 = true;
2701 foreach ( $index as $col ) {
2702 if ( $first2 ) {
2703 $first2 = false;
2704 } else {
2705 $sql .= ' AND ';
2706 }
2707 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2708 }
2709 } else {
2710 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2711 }
2712 }
2713 $sql .= ' )';
2714 $this->query( $sql, $fname );
2715 }
2716
2717 # Now insert the row
2718 $this->insert( $table, $row, $fname );
2719 }
2720 }
2721
2722 /**
2723 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2724 * statement.
2725 *
2726 * @param string $table Table name
2727 * @param array|string $rows Row(s) to insert
2728 * @param string $fname Caller function name
2729 *
2730 * @return ResultWrapper
2731 */
2732 protected function nativeReplace( $table, $rows, $fname ) {
2733 $table = $this->tableName( $table );
2734
2735 # Single row case
2736 if ( !is_array( reset( $rows ) ) ) {
2737 $rows = array( $rows );
2738 }
2739
2740 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2741 $first = true;
2742
2743 foreach ( $rows as $row ) {
2744 if ( $first ) {
2745 $first = false;
2746 } else {
2747 $sql .= ',';
2748 }
2749
2750 $sql .= '(' . $this->makeList( $row ) . ')';
2751 }
2752
2753 return $this->query( $sql, $fname );
2754 }
2755
2756 /**
2757 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2758 *
2759 * This updates any conflicting rows (according to the unique indexes) using
2760 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2761 *
2762 * $rows may be either:
2763 * - A single associative array. The array keys are the field names, and
2764 * the values are the values to insert. The values are treated as data
2765 * and will be quoted appropriately. If NULL is inserted, this will be
2766 * converted to a database NULL.
2767 * - An array with numeric keys, holding a list of associative arrays.
2768 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2769 * each subarray must be identical to each other, and in the same order.
2770 *
2771 * It may be more efficient to leave off unique indexes which are unlikely
2772 * to collide. However if you do this, you run the risk of encountering
2773 * errors which wouldn't have occurred in MySQL.
2774 *
2775 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2776 * returns success.
2777 *
2778 * @since 1.22
2779 *
2780 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2781 * @param array $rows A single row or list of rows to insert
2782 * @param array $uniqueIndexes List of single field names or field name tuples
2783 * @param array $set An array of values to SET. For each array element, the
2784 * key gives the field name, and the value gives the data to set that
2785 * field to. The data will be quoted by DatabaseBase::addQuotes().
2786 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2787 * @throws Exception
2788 * @return bool
2789 */
2790 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2791 $fname = __METHOD__
2792 ) {
2793 if ( !count( $rows ) ) {
2794 return true; // nothing to do
2795 }
2796
2797 if ( !is_array( reset( $rows ) ) ) {
2798 $rows = array( $rows );
2799 }
2800
2801 if ( count( $uniqueIndexes ) ) {
2802 $clauses = array(); // list WHERE clauses that each identify a single row
2803 foreach ( $rows as $row ) {
2804 foreach ( $uniqueIndexes as $index ) {
2805 $index = is_array( $index ) ? $index : array( $index ); // columns
2806 $rowKey = array(); // unique key to this row
2807 foreach ( $index as $column ) {
2808 $rowKey[$column] = $row[$column];
2809 }
2810 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2811 }
2812 }
2813 $where = array( $this->makeList( $clauses, LIST_OR ) );
2814 } else {
2815 $where = false;
2816 }
2817
2818 $useTrx = !$this->mTrxLevel;
2819 if ( $useTrx ) {
2820 $this->begin( $fname );
2821 }
2822 try {
2823 # Update any existing conflicting row(s)
2824 if ( $where !== false ) {
2825 $ok = $this->update( $table, $set, $where, $fname );
2826 } else {
2827 $ok = true;
2828 }
2829 # Now insert any non-conflicting row(s)
2830 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2831 } catch ( Exception $e ) {
2832 if ( $useTrx ) {
2833 $this->rollback( $fname );
2834 }
2835 throw $e;
2836 }
2837 if ( $useTrx ) {
2838 $this->commit( $fname );
2839 }
2840
2841 return $ok;
2842 }
2843
2844 /**
2845 * DELETE where the condition is a join.
2846 *
2847 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2848 * we use sub-selects
2849 *
2850 * For safety, an empty $conds will not delete everything. If you want to
2851 * delete all rows where the join condition matches, set $conds='*'.
2852 *
2853 * DO NOT put the join condition in $conds.
2854 *
2855 * @param string $delTable The table to delete from.
2856 * @param string $joinTable The other table.
2857 * @param string $delVar The variable to join on, in the first table.
2858 * @param string $joinVar The variable to join on, in the second table.
2859 * @param array $conds Condition array of field names mapped to variables,
2860 * ANDed together in the WHERE clause
2861 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2862 * @throws DBUnexpectedError
2863 */
2864 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2865 $fname = __METHOD__
2866 ) {
2867 if ( !$conds ) {
2868 throw new DBUnexpectedError( $this,
2869 'DatabaseBase::deleteJoin() called with empty $conds' );
2870 }
2871
2872 $delTable = $this->tableName( $delTable );
2873 $joinTable = $this->tableName( $joinTable );
2874 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2875 if ( $conds != '*' ) {
2876 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2877 }
2878 $sql .= ')';
2879
2880 $this->query( $sql, $fname );
2881 }
2882
2883 /**
2884 * Returns the size of a text field, or -1 for "unlimited"
2885 *
2886 * @param string $table
2887 * @param string $field
2888 * @return int
2889 */
2890 public function textFieldSize( $table, $field ) {
2891 $table = $this->tableName( $table );
2892 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2893 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2894 $row = $this->fetchObject( $res );
2895
2896 $m = array();
2897
2898 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2899 $size = $m[1];
2900 } else {
2901 $size = -1;
2902 }
2903
2904 return $size;
2905 }
2906
2907 /**
2908 * A string to insert into queries to show that they're low-priority, like
2909 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2910 * string and nothing bad should happen.
2911 *
2912 * @return string Returns the text of the low priority option if it is
2913 * supported, or a blank string otherwise
2914 */
2915 public function lowPriorityOption() {
2916 return '';
2917 }
2918
2919 /**
2920 * DELETE query wrapper.
2921 *
2922 * @param array $table Table name
2923 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2924 * for the format. Use $conds == "*" to delete all rows
2925 * @param string $fname Name of the calling function
2926 * @throws DBUnexpectedError
2927 * @return bool|ResultWrapper
2928 */
2929 public function delete( $table, $conds, $fname = __METHOD__ ) {
2930 if ( !$conds ) {
2931 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2932 }
2933
2934 $table = $this->tableName( $table );
2935 $sql = "DELETE FROM $table";
2936
2937 if ( $conds != '*' ) {
2938 if ( is_array( $conds ) ) {
2939 $conds = $this->makeList( $conds, LIST_AND );
2940 }
2941 $sql .= ' WHERE ' . $conds;
2942 }
2943
2944 return $this->query( $sql, $fname );
2945 }
2946
2947 /**
2948 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2949 * into another table.
2950 *
2951 * @param string $destTable The table name to insert into
2952 * @param string|array $srcTable May be either a table name, or an array of table names
2953 * to include in a join.
2954 *
2955 * @param array $varMap Must be an associative array of the form
2956 * array( 'dest1' => 'source1', ...). Source items may be literals
2957 * rather than field names, but strings should be quoted with
2958 * DatabaseBase::addQuotes()
2959 *
2960 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2961 * the details of the format of condition arrays. May be "*" to copy the
2962 * whole table.
2963 *
2964 * @param string $fname The function name of the caller, from __METHOD__
2965 *
2966 * @param array $insertOptions Options for the INSERT part of the query, see
2967 * DatabaseBase::insert() for details.
2968 * @param array $selectOptions Options for the SELECT part of the query, see
2969 * DatabaseBase::select() for details.
2970 *
2971 * @return ResultWrapper
2972 */
2973 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2974 $fname = __METHOD__,
2975 $insertOptions = array(), $selectOptions = array()
2976 ) {
2977 $destTable = $this->tableName( $destTable );
2978
2979 if ( !is_array( $insertOptions ) ) {
2980 $insertOptions = array( $insertOptions );
2981 }
2982
2983 $insertOptions = $this->makeInsertOptions( $insertOptions );
2984
2985 if ( !is_array( $selectOptions ) ) {
2986 $selectOptions = array( $selectOptions );
2987 }
2988
2989 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2990
2991 if ( is_array( $srcTable ) ) {
2992 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2993 } else {
2994 $srcTable = $this->tableName( $srcTable );
2995 }
2996
2997 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2998 " SELECT $startOpts " . implode( ',', $varMap ) .
2999 " FROM $srcTable $useIndex ";
3000
3001 if ( $conds != '*' ) {
3002 if ( is_array( $conds ) ) {
3003 $conds = $this->makeList( $conds, LIST_AND );
3004 }
3005 $sql .= " WHERE $conds";
3006 }
3007
3008 $sql .= " $tailOpts";
3009
3010 return $this->query( $sql, $fname );
3011 }
3012
3013 /**
3014 * Construct a LIMIT query with optional offset. This is used for query
3015 * pages. The SQL should be adjusted so that only the first $limit rows
3016 * are returned. If $offset is provided as well, then the first $offset
3017 * rows should be discarded, and the next $limit rows should be returned.
3018 * If the result of the query is not ordered, then the rows to be returned
3019 * are theoretically arbitrary.
3020 *
3021 * $sql is expected to be a SELECT, if that makes a difference.
3022 *
3023 * The version provided by default works in MySQL and SQLite. It will very
3024 * likely need to be overridden for most other DBMSes.
3025 *
3026 * @param string $sql SQL query we will append the limit too
3027 * @param int $limit The SQL limit
3028 * @param int|bool $offset The SQL offset (default false)
3029 * @throws DBUnexpectedError
3030 * @return string
3031 */
3032 public function limitResult( $sql, $limit, $offset = false ) {
3033 if ( !is_numeric( $limit ) ) {
3034 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3035 }
3036
3037 return "$sql LIMIT "
3038 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3039 . "{$limit} ";
3040 }
3041
3042 /**
3043 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3044 * within the UNION construct.
3045 * @return bool
3046 */
3047 public function unionSupportsOrderAndLimit() {
3048 return true; // True for almost every DB supported
3049 }
3050
3051 /**
3052 * Construct a UNION query
3053 * This is used for providing overload point for other DB abstractions
3054 * not compatible with the MySQL syntax.
3055 * @param array $sqls SQL statements to combine
3056 * @param bool $all Use UNION ALL
3057 * @return string SQL fragment
3058 */
3059 public function unionQueries( $sqls, $all ) {
3060 $glue = $all ? ') UNION ALL (' : ') UNION (';
3061
3062 return '(' . implode( $glue, $sqls ) . ')';
3063 }
3064
3065 /**
3066 * Returns an SQL expression for a simple conditional. This doesn't need
3067 * to be overridden unless CASE isn't supported in your DBMS.
3068 *
3069 * @param string|array $cond SQL expression which will result in a boolean value
3070 * @param string $trueVal SQL expression to return if true
3071 * @param string $falseVal SQL expression to return if false
3072 * @return string SQL fragment
3073 */
3074 public function conditional( $cond, $trueVal, $falseVal ) {
3075 if ( is_array( $cond ) ) {
3076 $cond = $this->makeList( $cond, LIST_AND );
3077 }
3078
3079 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3080 }
3081
3082 /**
3083 * Returns a comand for str_replace function in SQL query.
3084 * Uses REPLACE() in MySQL
3085 *
3086 * @param string $orig Column to modify
3087 * @param string $old Column to seek
3088 * @param string $new Column to replace with
3089 *
3090 * @return string
3091 */
3092 public function strreplace( $orig, $old, $new ) {
3093 return "REPLACE({$orig}, {$old}, {$new})";
3094 }
3095
3096 /**
3097 * Determines how long the server has been up
3098 * STUB
3099 *
3100 * @return int
3101 */
3102 public function getServerUptime() {
3103 return 0;
3104 }
3105
3106 /**
3107 * Determines if the last failure was due to a deadlock
3108 * STUB
3109 *
3110 * @return bool
3111 */
3112 public function wasDeadlock() {
3113 return false;
3114 }
3115
3116 /**
3117 * Determines if the last failure was due to a lock timeout
3118 * STUB
3119 *
3120 * @return bool
3121 */
3122 public function wasLockTimeout() {
3123 return false;
3124 }
3125
3126 /**
3127 * Determines if the last query error was something that should be dealt
3128 * with by pinging the connection and reissuing the query.
3129 * STUB
3130 *
3131 * @return bool
3132 */
3133 public function wasErrorReissuable() {
3134 return false;
3135 }
3136
3137 /**
3138 * Determines if the last failure was due to the database being read-only.
3139 * STUB
3140 *
3141 * @return bool
3142 */
3143 public function wasReadOnlyError() {
3144 return false;
3145 }
3146
3147 /**
3148 * Determines if the given query error was a connection drop
3149 * STUB
3150 *
3151 * @param integer|string $errno
3152 * @return bool
3153 */
3154 public function wasConnectionError( $errno ) {
3155 return false;
3156 }
3157
3158 /**
3159 * Perform a deadlock-prone transaction.
3160 *
3161 * This function invokes a callback function to perform a set of write
3162 * queries. If a deadlock occurs during the processing, the transaction
3163 * will be rolled back and the callback function will be called again.
3164 *
3165 * Usage:
3166 * $dbw->deadlockLoop( callback, ... );
3167 *
3168 * Extra arguments are passed through to the specified callback function.
3169 *
3170 * Returns whatever the callback function returned on its successful,
3171 * iteration, or false on error, for example if the retry limit was
3172 * reached.
3173 *
3174 * @return mixed
3175 * @throws DBQueryError
3176 */
3177 public function deadlockLoop() {
3178 $args = func_get_args();
3179 $function = array_shift( $args );
3180 $tries = self::DEADLOCK_TRIES;
3181
3182 $this->begin( __METHOD__ );
3183
3184 $retVal = null;
3185 $e = null;
3186 do {
3187 try {
3188 $retVal = call_user_func_array( $function, $args );
3189 break;
3190 } catch ( DBQueryError $e ) {
3191 if ( $this->wasDeadlock() ) {
3192 // Retry after a randomized delay
3193 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3194 } else {
3195 // Throw the error back up
3196 throw $e;
3197 }
3198 }
3199 } while ( --$tries > 0 );
3200
3201 if ( $tries <= 0 ) {
3202 // Too many deadlocks; give up
3203 $this->rollback( __METHOD__ );
3204 throw $e;
3205 } else {
3206 $this->commit( __METHOD__ );
3207
3208 return $retVal;
3209 }
3210 }
3211
3212 /**
3213 * Wait for the slave to catch up to a given master position.
3214 *
3215 * @param DBMasterPos $pos
3216 * @param int $timeout The maximum number of seconds to wait for
3217 * synchronisation
3218 * @return int Zero if the slave was past that position already,
3219 * greater than zero if we waited for some period of time, less than
3220 * zero if we timed out.
3221 */
3222 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3223 # Real waits are implemented in the subclass.
3224 return 0;
3225 }
3226
3227 /**
3228 * Get the replication position of this slave
3229 *
3230 * @return DBMasterPos|bool False if this is not a slave.
3231 */
3232 public function getSlavePos() {
3233 # Stub
3234 return false;
3235 }
3236
3237 /**
3238 * Get the position of this master
3239 *
3240 * @return DBMasterPos|bool False if this is not a master
3241 */
3242 public function getMasterPos() {
3243 # Stub
3244 return false;
3245 }
3246
3247 /**
3248 * Run an anonymous function as soon as there is no transaction pending.
3249 * If there is a transaction and it is rolled back, then the callback is cancelled.
3250 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3251 * Callbacks must commit any transactions that they begin.
3252 *
3253 * This is useful for updates to different systems or when separate transactions are needed.
3254 * For example, one might want to enqueue jobs into a system outside the database, but only
3255 * after the database is updated so that the jobs will see the data when they actually run.
3256 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3257 *
3258 * @param callable $callback
3259 * @since 1.20
3260 */
3261 final public function onTransactionIdle( $callback ) {
3262 $this->mTrxIdleCallbacks[] = array( $callback, wfGetCaller() );
3263 if ( !$this->mTrxLevel ) {
3264 $this->runOnTransactionIdleCallbacks();
3265 }
3266 }
3267
3268 /**
3269 * Run an anonymous function before the current transaction commits or now if there is none.
3270 * If there is a transaction and it is rolled back, then the callback is cancelled.
3271 * Callbacks must not start nor commit any transactions.
3272 *
3273 * This is useful for updates that easily cause deadlocks if locks are held too long
3274 * but where atomicity is strongly desired for these updates and some related updates.
3275 *
3276 * @param callable $callback
3277 * @since 1.22
3278 */
3279 final public function onTransactionPreCommitOrIdle( $callback ) {
3280 if ( $this->mTrxLevel ) {
3281 $this->mTrxPreCommitCallbacks[] = array( $callback, wfGetCaller() );
3282 } else {
3283 $this->onTransactionIdle( $callback ); // this will trigger immediately
3284 }
3285 }
3286
3287 /**
3288 * Actually any "on transaction idle" callbacks.
3289 *
3290 * @since 1.20
3291 */
3292 protected function runOnTransactionIdleCallbacks() {
3293 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
3294
3295 $e = $ePrior = null; // last exception
3296 do { // callbacks may add callbacks :)
3297 $callbacks = $this->mTrxIdleCallbacks;
3298 $this->mTrxIdleCallbacks = array(); // recursion guard
3299 foreach ( $callbacks as $callback ) {
3300 try {
3301 list( $phpCallback ) = $callback;
3302 $this->clearFlag( DBO_TRX ); // make each query its own transaction
3303 call_user_func( $phpCallback );
3304 $this->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
3305 } catch ( Exception $e ) {
3306 if ( $ePrior ) {
3307 MWExceptionHandler::logException( $ePrior );
3308 }
3309 $ePrior = $e;
3310 }
3311 }
3312 } while ( count( $this->mTrxIdleCallbacks ) );
3313
3314 if ( $e instanceof Exception ) {
3315 throw $e; // re-throw any last exception
3316 }
3317 }
3318
3319 /**
3320 * Actually any "on transaction pre-commit" callbacks.
3321 *
3322 * @since 1.22
3323 */
3324 protected function runOnTransactionPreCommitCallbacks() {
3325 $e = $ePrior = null; // last exception
3326 do { // callbacks may add callbacks :)
3327 $callbacks = $this->mTrxPreCommitCallbacks;
3328 $this->mTrxPreCommitCallbacks = array(); // recursion guard
3329 foreach ( $callbacks as $callback ) {
3330 try {
3331 list( $phpCallback ) = $callback;
3332 call_user_func( $phpCallback );
3333 } catch ( Exception $e ) {
3334 if ( $ePrior ) {
3335 MWExceptionHandler::logException( $ePrior );
3336 }
3337 $ePrior = $e;
3338 }
3339 }
3340 } while ( count( $this->mTrxPreCommitCallbacks ) );
3341
3342 if ( $e instanceof Exception ) {
3343 throw $e; // re-throw any last exception
3344 }
3345 }
3346
3347 /**
3348 * Begin an atomic section of statements
3349 *
3350 * If a transaction has been started already, just keep track of the given
3351 * section name to make sure the transaction is not committed pre-maturely.
3352 * This function can be used in layers (with sub-sections), so use a stack
3353 * to keep track of the different atomic sections. If there is no transaction,
3354 * start one implicitly.
3355 *
3356 * The goal of this function is to create an atomic section of SQL queries
3357 * without having to start a new transaction if it already exists.
3358 *
3359 * Atomic sections are more strict than transactions. With transactions,
3360 * attempting to begin a new transaction when one is already running results
3361 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3362 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3363 * and any database transactions cannot be began or committed until all atomic
3364 * levels are closed. There is no such thing as implicitly opening or closing
3365 * an atomic section.
3366 *
3367 * @since 1.23
3368 * @param string $fname
3369 * @throws DBError
3370 */
3371 final public function startAtomic( $fname = __METHOD__ ) {
3372 if ( !$this->mTrxLevel ) {
3373 $this->begin( $fname );
3374 $this->mTrxAutomatic = true;
3375 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3376 // in all changes being in one transaction to keep requests transactional.
3377 if ( !$this->getFlag( DBO_TRX ) ) {
3378 $this->mTrxAutomaticAtomic = true;
3379 }
3380 }
3381
3382 $this->mTrxAtomicLevels[] = $fname;
3383 }
3384
3385 /**
3386 * Ends an atomic section of SQL statements
3387 *
3388 * Ends the next section of atomic SQL statements and commits the transaction
3389 * if necessary.
3390 *
3391 * @since 1.23
3392 * @see DatabaseBase::startAtomic
3393 * @param string $fname
3394 * @throws DBError
3395 */
3396 final public function endAtomic( $fname = __METHOD__ ) {
3397 if ( !$this->mTrxLevel ) {
3398 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3399 }
3400 if ( !$this->mTrxAtomicLevels ||
3401 array_pop( $this->mTrxAtomicLevels ) !== $fname
3402 ) {
3403 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3404 }
3405
3406 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
3407 $this->commit( $fname, 'flush' );
3408 }
3409 }
3410
3411 /**
3412 * Begin a transaction. If a transaction is already in progress,
3413 * that transaction will be committed before the new transaction is started.
3414 *
3415 * Note that when the DBO_TRX flag is set (which is usually the case for web
3416 * requests, but not for maintenance scripts), any previous database query
3417 * will have started a transaction automatically.
3418 *
3419 * Nesting of transactions is not supported. Attempts to nest transactions
3420 * will cause a warning, unless the current transaction was started
3421 * automatically because of the DBO_TRX flag.
3422 *
3423 * @param string $fname
3424 * @throws DBError
3425 */
3426 final public function begin( $fname = __METHOD__ ) {
3427 if ( $this->mTrxLevel ) { // implicit commit
3428 if ( $this->mTrxAtomicLevels ) {
3429 // If the current transaction was an automatic atomic one, then we definitely have
3430 // a problem. Same if there is any unclosed atomic level.
3431 $levels = implode( ', ', $this->mTrxAtomicLevels );
3432 throw new DBUnexpectedError(
3433 $this,
3434 "Got explicit BEGIN while atomic sections $levels are still open."
3435 );
3436 } elseif ( !$this->mTrxAutomatic ) {
3437 // We want to warn about inadvertently nested begin/commit pairs, but not about
3438 // auto-committing implicit transactions that were started by query() via DBO_TRX
3439 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3440 " performing implicit commit!";
3441 wfWarn( $msg );
3442 wfLogDBError( $msg,
3443 $this->getLogContext( array(
3444 'method' => __METHOD__,
3445 'fname' => $fname,
3446 ) )
3447 );
3448 } else {
3449 // if the transaction was automatic and has done write operations
3450 if ( $this->mTrxDoneWrites ) {
3451 wfDebug( "$fname: Automatic transaction with writes in progress" .
3452 " (from {$this->mTrxFname}), performing implicit commit!\n"
3453 );
3454 }
3455 }
3456
3457 $this->runOnTransactionPreCommitCallbacks();
3458 $writeTime = $this->pendingWriteQueryDuration();
3459 $this->doCommit( $fname );
3460 if ( $this->mTrxDoneWrites ) {
3461 $this->mDoneWrites = microtime( true );
3462 $this->getTransactionProfiler()->transactionWritingOut(
3463 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3464 }
3465 $this->runOnTransactionIdleCallbacks();
3466 }
3467
3468 # Avoid fatals if close() was called
3469 $this->assertOpen();
3470
3471 $this->doBegin( $fname );
3472 $this->mTrxTimestamp = microtime( true );
3473 $this->mTrxFname = $fname;
3474 $this->mTrxDoneWrites = false;
3475 $this->mTrxAutomatic = false;
3476 $this->mTrxAutomaticAtomic = false;
3477 $this->mTrxAtomicLevels = array();
3478 $this->mTrxIdleCallbacks = array();
3479 $this->mTrxPreCommitCallbacks = array();
3480 $this->mTrxShortId = wfRandomString( 12 );
3481 $this->mTrxWriteDuration = 0.0;
3482 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3483 // Get an estimate of the slave lag before then, treating estimate staleness
3484 // as lag itself just to be safe
3485 $status = $this->getApproximateLagStatus();
3486 $this->mTrxSlaveLag = $status['lag'] + ( microtime( true ) - $status['since'] );
3487 }
3488
3489 /**
3490 * Issues the BEGIN command to the database server.
3491 *
3492 * @see DatabaseBase::begin()
3493 * @param string $fname
3494 */
3495 protected function doBegin( $fname ) {
3496 $this->query( 'BEGIN', $fname );
3497 $this->mTrxLevel = 1;
3498 }
3499
3500 /**
3501 * Commits a transaction previously started using begin().
3502 * If no transaction is in progress, a warning is issued.
3503 *
3504 * Nesting of transactions is not supported.
3505 *
3506 * @param string $fname
3507 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3508 * explicitly committing implicit transactions, or calling commit when no
3509 * transaction is in progress. This will silently break any ongoing
3510 * explicit transaction. Only set the flush flag if you are sure that it
3511 * is safe to ignore these warnings in your context.
3512 * @throws DBUnexpectedError
3513 */
3514 final public function commit( $fname = __METHOD__, $flush = '' ) {
3515 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
3516 // There are still atomic sections open. This cannot be ignored
3517 $levels = implode( ', ', $this->mTrxAtomicLevels );
3518 throw new DBUnexpectedError(
3519 $this,
3520 "Got COMMIT while atomic sections $levels are still open"
3521 );
3522 }
3523
3524 if ( $flush === 'flush' ) {
3525 if ( !$this->mTrxLevel ) {
3526 return; // nothing to do
3527 } elseif ( !$this->mTrxAutomatic ) {
3528 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3529 }
3530 } else {
3531 if ( !$this->mTrxLevel ) {
3532 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3533 return; // nothing to do
3534 } elseif ( $this->mTrxAutomatic ) {
3535 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3536 }
3537 }
3538
3539 # Avoid fatals if close() was called
3540 $this->assertOpen();
3541
3542 $this->runOnTransactionPreCommitCallbacks();
3543 $writeTime = $this->pendingWriteQueryDuration();
3544 $this->doCommit( $fname );
3545 if ( $this->mTrxDoneWrites ) {
3546 $this->mDoneWrites = microtime( true );
3547 $this->getTransactionProfiler()->transactionWritingOut(
3548 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3549 }
3550 $this->runOnTransactionIdleCallbacks();
3551 }
3552
3553 /**
3554 * Issues the COMMIT command to the database server.
3555 *
3556 * @see DatabaseBase::commit()
3557 * @param string $fname
3558 */
3559 protected function doCommit( $fname ) {
3560 if ( $this->mTrxLevel ) {
3561 $this->query( 'COMMIT', $fname );
3562 $this->mTrxLevel = 0;
3563 }
3564 }
3565
3566 /**
3567 * Rollback a transaction previously started using begin().
3568 * If no transaction is in progress, a warning is issued.
3569 *
3570 * No-op on non-transactional databases.
3571 *
3572 * @param string $fname
3573 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3574 * calling rollback when no transaction is in progress. This will silently
3575 * break any ongoing explicit transaction. Only set the flush flag if you
3576 * are sure that it is safe to ignore these warnings in your context.
3577 * @throws DBUnexpectedError
3578 * @since 1.23 Added $flush parameter
3579 */
3580 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3581 if ( $flush !== 'flush' ) {
3582 if ( !$this->mTrxLevel ) {
3583 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3584 return; // nothing to do
3585 } elseif ( $this->mTrxAutomatic ) {
3586 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3587 }
3588 } else {
3589 if ( !$this->mTrxLevel ) {
3590 return; // nothing to do
3591 } elseif ( !$this->mTrxAutomatic ) {
3592 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3593 }
3594 }
3595
3596 # Avoid fatals if close() was called
3597 $this->assertOpen();
3598
3599 $this->doRollback( $fname );
3600 $this->mTrxIdleCallbacks = array(); // cancel
3601 $this->mTrxPreCommitCallbacks = array(); // cancel
3602 $this->mTrxAtomicLevels = array();
3603 if ( $this->mTrxDoneWrites ) {
3604 $this->getTransactionProfiler()->transactionWritingOut(
3605 $this->mServer, $this->mDBname, $this->mTrxShortId );
3606 }
3607 }
3608
3609 /**
3610 * Issues the ROLLBACK command to the database server.
3611 *
3612 * @see DatabaseBase::rollback()
3613 * @param string $fname
3614 */
3615 protected function doRollback( $fname ) {
3616 if ( $this->mTrxLevel ) {
3617 $this->query( 'ROLLBACK', $fname, true );
3618 $this->mTrxLevel = 0;
3619 }
3620 }
3621
3622 /**
3623 * Creates a new table with structure copied from existing table
3624 * Note that unlike most database abstraction functions, this function does not
3625 * automatically append database prefix, because it works at a lower
3626 * abstraction level.
3627 * The table names passed to this function shall not be quoted (this
3628 * function calls addIdentifierQuotes when needed).
3629 *
3630 * @param string $oldName Name of table whose structure should be copied
3631 * @param string $newName Name of table to be created
3632 * @param bool $temporary Whether the new table should be temporary
3633 * @param string $fname Calling function name
3634 * @throws MWException
3635 * @return bool True if operation was successful
3636 */
3637 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3638 $fname = __METHOD__
3639 ) {
3640 throw new MWException(
3641 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3642 }
3643
3644 /**
3645 * List all tables on the database
3646 *
3647 * @param string $prefix Only show tables with this prefix, e.g. mw_
3648 * @param string $fname Calling function name
3649 * @throws MWException
3650 * @return array
3651 */
3652 function listTables( $prefix = null, $fname = __METHOD__ ) {
3653 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3654 }
3655
3656 /**
3657 * Reset the views process cache set by listViews()
3658 * @since 1.22
3659 */
3660 final public function clearViewsCache() {
3661 $this->allViews = null;
3662 }
3663
3664 /**
3665 * Lists all the VIEWs in the database
3666 *
3667 * For caching purposes the list of all views should be stored in
3668 * $this->allViews. The process cache can be cleared with clearViewsCache()
3669 *
3670 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3671 * @param string $fname Name of calling function
3672 * @throws MWException
3673 * @return array
3674 * @since 1.22
3675 */
3676 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3677 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3678 }
3679
3680 /**
3681 * Differentiates between a TABLE and a VIEW
3682 *
3683 * @param string $name Name of the database-structure to test.
3684 * @throws MWException
3685 * @return bool
3686 * @since 1.22
3687 */
3688 public function isView( $name ) {
3689 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3690 }
3691
3692 /**
3693 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3694 * to the format used for inserting into timestamp fields in this DBMS.
3695 *
3696 * The result is unquoted, and needs to be passed through addQuotes()
3697 * before it can be included in raw SQL.
3698 *
3699 * @param string|int $ts
3700 *
3701 * @return string
3702 */
3703 public function timestamp( $ts = 0 ) {
3704 return wfTimestamp( TS_MW, $ts );
3705 }
3706
3707 /**
3708 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3709 * to the format used for inserting into timestamp fields in this DBMS. If
3710 * NULL is input, it is passed through, allowing NULL values to be inserted
3711 * into timestamp fields.
3712 *
3713 * The result is unquoted, and needs to be passed through addQuotes()
3714 * before it can be included in raw SQL.
3715 *
3716 * @param string|int $ts
3717 *
3718 * @return string
3719 */
3720 public function timestampOrNull( $ts = null ) {
3721 if ( is_null( $ts ) ) {
3722 return null;
3723 } else {
3724 return $this->timestamp( $ts );
3725 }
3726 }
3727
3728 /**
3729 * Take the result from a query, and wrap it in a ResultWrapper if
3730 * necessary. Boolean values are passed through as is, to indicate success
3731 * of write queries or failure.
3732 *
3733 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3734 * resource, and it was necessary to call this function to convert it to
3735 * a wrapper. Nowadays, raw database objects are never exposed to external
3736 * callers, so this is unnecessary in external code.
3737 *
3738 * @param bool|ResultWrapper|resource|object $result
3739 * @return bool|ResultWrapper
3740 */
3741 protected function resultObject( $result ) {
3742 if ( !$result ) {
3743 return false;
3744 } elseif ( $result instanceof ResultWrapper ) {
3745 return $result;
3746 } elseif ( $result === true ) {
3747 // Successful write query
3748 return $result;
3749 } else {
3750 return new ResultWrapper( $this, $result );
3751 }
3752 }
3753
3754 /**
3755 * Ping the server and try to reconnect if it there is no connection
3756 *
3757 * @return bool Success or failure
3758 */
3759 public function ping() {
3760 # Stub. Not essential to override.
3761 return true;
3762 }
3763
3764 /**
3765 * Get the slave lag when the current transaction started
3766 * or a general lag estimate if not transaction is active
3767 *
3768 * This is useful when transactions might use snapshot isolation
3769 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3770 * is this lag plus transaction duration. If they don't, it is still
3771 * safe to be pessimistic. In AUTO-COMMIT mode, this still gives an
3772 * indication of the staleness of subsequent reads.
3773 *
3774 * @return array ('lag': seconds, 'since': UNIX timestamp of BEGIN)
3775 * @since 1.27
3776 */
3777 public function getSessionLagStatus() {
3778 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
3779 }
3780
3781 /**
3782 * Get the slave lag when the current transaction started
3783 *
3784 * This is useful when transactions might use snapshot isolation
3785 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3786 * is this lag plus transaction duration. If they don't, it is still
3787 * safe to be pessimistic. This returns null if there is no transaction.
3788 *
3789 * @return array|null ('lag': seconds, 'since': UNIX timestamp of BEGIN)
3790 * @since 1.27
3791 */
3792 public function getTransactionLagStatus() {
3793 return $this->mTrxLevel
3794 ? array( 'lag' => $this->mTrxSlaveLag, 'since' => $this->trxTimestamp() )
3795 : null;
3796 }
3797
3798 /**
3799 * Get a slave lag estimate for this server
3800 *
3801 * @return array ('lag': seconds, 'since': UNIX timestamp of estimate)
3802 * @since 1.27
3803 */
3804 public function getApproximateLagStatus() {
3805 return array(
3806 'lag' => $this->getLBInfo( 'slave' ) ? $this->getLag() : 0,
3807 'since' => microtime( true )
3808 );
3809 }
3810
3811 /**
3812 * Merge the result of getSessionLagStatus() for several DBs
3813 * using the most pessimistic values to estimate the lag of
3814 * any data derived from them in combination
3815 *
3816 * This is information is useful for caching modules
3817 *
3818 * @see WANObjectCache::set()
3819 * @see WANObjectCache::getWithSetCallback()
3820 *
3821 * @param IDatabase $db1
3822 * @param IDatabase ...
3823 * @return array ('lag': highest lag, 'since': lowest estimate UNIX timestamp)
3824 * @since 1.27
3825 */
3826 public static function getCacheSetOptions( IDatabase $db1 ) {
3827 $res = array( 'lag' => 0, 'since' => INF );
3828 foreach ( func_get_args() as $db ) {
3829 /** @var IDatabase $db */
3830 $status = $db->getSessionLagStatus();
3831 $res['lag'] = max( $res['lag'], $status['lag'] );
3832 $res['since'] = min( $res['since'], $status['since'] );
3833 }
3834
3835 return $res;
3836 }
3837
3838 /**
3839 * Get slave lag. Currently supported only by MySQL.
3840 *
3841 * Note that this function will generate a fatal error on many
3842 * installations. Most callers should use LoadBalancer::safeGetLag()
3843 * instead.
3844 *
3845 * @return int Database replication lag in seconds
3846 */
3847 public function getLag() {
3848 return 0;
3849 }
3850
3851 /**
3852 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3853 *
3854 * @return int
3855 */
3856 function maxListLen() {
3857 return 0;
3858 }
3859
3860 /**
3861 * Some DBMSs have a special format for inserting into blob fields, they
3862 * don't allow simple quoted strings to be inserted. To insert into such
3863 * a field, pass the data through this function before passing it to
3864 * DatabaseBase::insert().
3865 *
3866 * @param string $b
3867 * @return string
3868 */
3869 public function encodeBlob( $b ) {
3870 return $b;
3871 }
3872
3873 /**
3874 * Some DBMSs return a special placeholder object representing blob fields
3875 * in result objects. Pass the object through this function to return the
3876 * original string.
3877 *
3878 * @param string|Blob $b
3879 * @return string
3880 */
3881 public function decodeBlob( $b ) {
3882 if ( $b instanceof Blob ) {
3883 $b = $b->fetch();
3884 }
3885 return $b;
3886 }
3887
3888 /**
3889 * Override database's default behavior. $options include:
3890 * 'connTimeout' : Set the connection timeout value in seconds.
3891 * May be useful for very long batch queries such as
3892 * full-wiki dumps, where a single query reads out over
3893 * hours or days.
3894 *
3895 * @param array $options
3896 * @return void
3897 */
3898 public function setSessionOptions( array $options ) {
3899 }
3900
3901 /**
3902 * Read and execute SQL commands from a file.
3903 *
3904 * Returns true on success, error string or exception on failure (depending
3905 * on object's error ignore settings).
3906 *
3907 * @param string $filename File name to open
3908 * @param bool|callable $lineCallback Optional function called before reading each line
3909 * @param bool|callable $resultCallback Optional function called for each MySQL result
3910 * @param bool|string $fname Calling function name or false if name should be
3911 * generated dynamically using $filename
3912 * @param bool|callable $inputCallback Optional function called for each
3913 * complete line sent
3914 * @throws Exception|MWException
3915 * @return bool|string
3916 */
3917 public function sourceFile(
3918 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3919 ) {
3920 MediaWiki\suppressWarnings();
3921 $fp = fopen( $filename, 'r' );
3922 MediaWiki\restoreWarnings();
3923
3924 if ( false === $fp ) {
3925 throw new MWException( "Could not open \"{$filename}\".\n" );
3926 }
3927
3928 if ( !$fname ) {
3929 $fname = __METHOD__ . "( $filename )";
3930 }
3931
3932 try {
3933 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3934 } catch ( Exception $e ) {
3935 fclose( $fp );
3936 throw $e;
3937 }
3938
3939 fclose( $fp );
3940
3941 return $error;
3942 }
3943
3944 /**
3945 * Get the full path of a patch file. Originally based on archive()
3946 * from updaters.inc. Keep in mind this always returns a patch, as
3947 * it fails back to MySQL if no DB-specific patch can be found
3948 *
3949 * @param string $patch The name of the patch, like patch-something.sql
3950 * @return string Full path to patch file
3951 */
3952 public function patchPath( $patch ) {
3953 global $IP;
3954
3955 $dbType = $this->getType();
3956 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3957 return "$IP/maintenance/$dbType/archives/$patch";
3958 } else {
3959 return "$IP/maintenance/archives/$patch";
3960 }
3961 }
3962
3963 /**
3964 * Set variables to be used in sourceFile/sourceStream, in preference to the
3965 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3966 * all. If it's set to false, $GLOBALS will be used.
3967 *
3968 * @param bool|array $vars Mapping variable name to value.
3969 */
3970 public function setSchemaVars( $vars ) {
3971 $this->mSchemaVars = $vars;
3972 }
3973
3974 /**
3975 * Read and execute commands from an open file handle.
3976 *
3977 * Returns true on success, error string or exception on failure (depending
3978 * on object's error ignore settings).
3979 *
3980 * @param resource $fp File handle
3981 * @param bool|callable $lineCallback Optional function called before reading each query
3982 * @param bool|callable $resultCallback Optional function called for each MySQL result
3983 * @param string $fname Calling function name
3984 * @param bool|callable $inputCallback Optional function called for each complete query sent
3985 * @return bool|string
3986 */
3987 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3988 $fname = __METHOD__, $inputCallback = false
3989 ) {
3990 $cmd = '';
3991
3992 while ( !feof( $fp ) ) {
3993 if ( $lineCallback ) {
3994 call_user_func( $lineCallback );
3995 }
3996
3997 $line = trim( fgets( $fp ) );
3998
3999 if ( $line == '' ) {
4000 continue;
4001 }
4002
4003 if ( '-' == $line[0] && '-' == $line[1] ) {
4004 continue;
4005 }
4006
4007 if ( $cmd != '' ) {
4008 $cmd .= ' ';
4009 }
4010
4011 $done = $this->streamStatementEnd( $cmd, $line );
4012
4013 $cmd .= "$line\n";
4014
4015 if ( $done || feof( $fp ) ) {
4016 $cmd = $this->replaceVars( $cmd );
4017
4018 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
4019 $res = $this->query( $cmd, $fname );
4020
4021 if ( $resultCallback ) {
4022 call_user_func( $resultCallback, $res, $this );
4023 }
4024
4025 if ( false === $res ) {
4026 $err = $this->lastError();
4027
4028 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4029 }
4030 }
4031 $cmd = '';
4032 }
4033 }
4034
4035 return true;
4036 }
4037
4038 /**
4039 * Called by sourceStream() to check if we've reached a statement end
4040 *
4041 * @param string $sql SQL assembled so far
4042 * @param string $newLine New line about to be added to $sql
4043 * @return bool Whether $newLine contains end of the statement
4044 */
4045 public function streamStatementEnd( &$sql, &$newLine ) {
4046 if ( $this->delimiter ) {
4047 $prev = $newLine;
4048 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
4049 if ( $newLine != $prev ) {
4050 return true;
4051 }
4052 }
4053
4054 return false;
4055 }
4056
4057 /**
4058 * Database independent variable replacement. Replaces a set of variables
4059 * in an SQL statement with their contents as given by $this->getSchemaVars().
4060 *
4061 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4062 *
4063 * - '{$var}' should be used for text and is passed through the database's
4064 * addQuotes method.
4065 * - `{$var}` should be used for identifiers (e.g. table and database names).
4066 * It is passed through the database's addIdentifierQuotes method which
4067 * can be overridden if the database uses something other than backticks.
4068 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4069 * database's tableName method.
4070 * - / *i* / passes the name that follows through the database's indexName method.
4071 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4072 * its use should be avoided. In 1.24 and older, string encoding was applied.
4073 *
4074 * @param string $ins SQL statement to replace variables in
4075 * @return string The new SQL statement with variables replaced
4076 */
4077 protected function replaceVars( $ins ) {
4078 $that = $this;
4079 $vars = $this->getSchemaVars();
4080 return preg_replace_callback(
4081 '!
4082 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4083 \'\{\$ (\w+) }\' | # 3. addQuotes
4084 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4085 /\*\$ (\w+) \*/ # 5. leave unencoded
4086 !x',
4087 function ( $m ) use ( $that, $vars ) {
4088 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4089 // check for both nonexistent keys *and* the empty string.
4090 if ( isset( $m[1] ) && $m[1] !== '' ) {
4091 if ( $m[1] === 'i' ) {
4092 return $that->indexName( $m[2] );
4093 } else {
4094 return $that->tableName( $m[2] );
4095 }
4096 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4097 return $that->addQuotes( $vars[$m[3]] );
4098 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4099 return $that->addIdentifierQuotes( $vars[$m[4]] );
4100 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4101 return $vars[$m[5]];
4102 } else {
4103 return $m[0];
4104 }
4105 },
4106 $ins
4107 );
4108 }
4109
4110 /**
4111 * Get schema variables. If none have been set via setSchemaVars(), then
4112 * use some defaults from the current object.
4113 *
4114 * @return array
4115 */
4116 protected function getSchemaVars() {
4117 if ( $this->mSchemaVars ) {
4118 return $this->mSchemaVars;
4119 } else {
4120 return $this->getDefaultSchemaVars();
4121 }
4122 }
4123
4124 /**
4125 * Get schema variables to use if none have been set via setSchemaVars().
4126 *
4127 * Override this in derived classes to provide variables for tables.sql
4128 * and SQL patch files.
4129 *
4130 * @return array
4131 */
4132 protected function getDefaultSchemaVars() {
4133 return array();
4134 }
4135
4136 /**
4137 * Check to see if a named lock is available (non-blocking)
4138 *
4139 * @param string $lockName Name of lock to poll
4140 * @param string $method Name of method calling us
4141 * @return bool
4142 * @since 1.20
4143 */
4144 public function lockIsFree( $lockName, $method ) {
4145 return true;
4146 }
4147
4148 /**
4149 * Acquire a named lock
4150 *
4151 * Named locks are not related to transactions
4152 *
4153 * @param string $lockName Name of lock to aquire
4154 * @param string $method Name of method calling us
4155 * @param int $timeout
4156 * @return bool
4157 */
4158 public function lock( $lockName, $method, $timeout = 5 ) {
4159 return true;
4160 }
4161
4162 /**
4163 * Release a lock
4164 *
4165 * Named locks are not related to transactions
4166 *
4167 * @param string $lockName Name of lock to release
4168 * @param string $method Name of method calling us
4169 *
4170 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4171 * by this thread (in which case the lock is not released), and NULL if the named
4172 * lock did not exist
4173 */
4174 public function unlock( $lockName, $method ) {
4175 return true;
4176 }
4177
4178 /**
4179 * Check to see if a named lock used by lock() use blocking queues
4180 *
4181 * @return bool
4182 * @since 1.26
4183 */
4184 public function namedLocksEnqueue() {
4185 return false;
4186 }
4187
4188 /**
4189 * Lock specific tables
4190 *
4191 * @param array $read Array of tables to lock for read access
4192 * @param array $write Array of tables to lock for write access
4193 * @param string $method Name of caller
4194 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4195 * @return bool
4196 */
4197 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4198 return true;
4199 }
4200
4201 /**
4202 * Unlock specific tables
4203 *
4204 * @param string $method The caller
4205 * @return bool
4206 */
4207 public function unlockTables( $method ) {
4208 return true;
4209 }
4210
4211 /**
4212 * Delete a table
4213 * @param string $tableName
4214 * @param string $fName
4215 * @return bool|ResultWrapper
4216 * @since 1.18
4217 */
4218 public function dropTable( $tableName, $fName = __METHOD__ ) {
4219 if ( !$this->tableExists( $tableName, $fName ) ) {
4220 return false;
4221 }
4222 $sql = "DROP TABLE " . $this->tableName( $tableName );
4223 if ( $this->cascadingDeletes() ) {
4224 $sql .= " CASCADE";
4225 }
4226
4227 return $this->query( $sql, $fName );
4228 }
4229
4230 /**
4231 * Get search engine class. All subclasses of this need to implement this
4232 * if they wish to use searching.
4233 *
4234 * @return string
4235 */
4236 public function getSearchEngine() {
4237 return 'SearchEngineDummy';
4238 }
4239
4240 /**
4241 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4242 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4243 * because "i" sorts after all numbers.
4244 *
4245 * @return string
4246 */
4247 public function getInfinity() {
4248 return 'infinity';
4249 }
4250
4251 /**
4252 * Encode an expiry time into the DBMS dependent format
4253 *
4254 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4255 * @return string
4256 */
4257 public function encodeExpiry( $expiry ) {
4258 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4259 ? $this->getInfinity()
4260 : $this->timestamp( $expiry );
4261 }
4262
4263 /**
4264 * Decode an expiry time into a DBMS independent format
4265 *
4266 * @param string $expiry DB timestamp field value for expiry
4267 * @param int $format TS_* constant, defaults to TS_MW
4268 * @return string
4269 */
4270 public function decodeExpiry( $expiry, $format = TS_MW ) {
4271 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4272 ? 'infinity'
4273 : wfTimestamp( $format, $expiry );
4274 }
4275
4276 /**
4277 * Allow or deny "big selects" for this session only. This is done by setting
4278 * the sql_big_selects session variable.
4279 *
4280 * This is a MySQL-specific feature.
4281 *
4282 * @param bool|string $value True for allow, false for deny, or "default" to
4283 * restore the initial value
4284 */
4285 public function setBigSelects( $value = true ) {
4286 // no-op
4287 }
4288
4289 /**
4290 * @since 1.19
4291 * @return string
4292 */
4293 public function __toString() {
4294 return (string)$this->mConn;
4295 }
4296
4297 /**
4298 * Run a few simple sanity checks
4299 */
4300 public function __destruct() {
4301 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
4302 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4303 }
4304 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
4305 $callers = array();
4306 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
4307 $callers[] = $callbackInfo[1];
4308 }
4309 $callers = implode( ', ', $callers );
4310 trigger_error( "DB transaction callbacks still pending (from $callers)." );
4311 }
4312 }
4313 }
4314
4315 /**
4316 * @since 1.27
4317 */
4318 abstract class Database extends DatabaseBase {
4319 // B/C until nothing type hints for DatabaseBase
4320 // @TODO: finish renaming DatabaseBase => Database
4321 }