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