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