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