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