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