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