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