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