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