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