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