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