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