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