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