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