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