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