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