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