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