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