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