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