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