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