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