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