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