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