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