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