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