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