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