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