Changed use of tag_summary to use change_tag with GROUP_CONCAT()
[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 * Build a GROUP_CONCAT or equivalent statement for a query.
2084 *
2085 * This is useful for combining a field for several rows into a single string.
2086 * NULL values will not appear in the output, duplicated values will appear,
2087 * and the resulting delimiter-separated values have no defined sort order.
2088 * Code using the results may need to use the PHP unique() or sort() methods.
2089 *
2090 * @param string $delim Glue to bind the results together
2091 * @param string|array $table Table name
2092 * @param string $field Field name
2093 * @param string|array $conds Conditions
2094 * @param string|array $join_conds Join conditions
2095 * @return String SQL text
2096 * @since 1.23
2097 */
2098 public function buildGroupConcatField(
2099 $delim, $table, $field, $conds = '', $join_conds = array()
2100 ) {
2101 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2102 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2103 }
2104
2105 /**
2106 * Change the current database
2107 *
2108 * @todo Explain what exactly will fail if this is not overridden.
2109 *
2110 * @param $db
2111 *
2112 * @return bool Success or failure
2113 */
2114 public function selectDB( $db ) {
2115 # Stub. Shouldn't cause serious problems if it's not overridden, but
2116 # if your database engine supports a concept similar to MySQL's
2117 # databases you may as well.
2118 $this->mDBname = $db;
2119 return true;
2120 }
2121
2122 /**
2123 * Get the current DB name
2124 */
2125 public function getDBname() {
2126 return $this->mDBname;
2127 }
2128
2129 /**
2130 * Get the server hostname or IP address
2131 */
2132 public function getServer() {
2133 return $this->mServer;
2134 }
2135
2136 /**
2137 * Format a table name ready for use in constructing an SQL query
2138 *
2139 * This does two important things: it quotes the table names to clean them up,
2140 * and it adds a table prefix if only given a table name with no quotes.
2141 *
2142 * All functions of this object which require a table name call this function
2143 * themselves. Pass the canonical name to such functions. This is only needed
2144 * when calling query() directly.
2145 *
2146 * @param string $name database table name
2147 * @param string $format One of:
2148 * quoted - Automatically pass the table name through addIdentifierQuotes()
2149 * so that it can be used in a query.
2150 * raw - Do not add identifier quotes to the table name
2151 * @return String: full database name
2152 */
2153 public function tableName( $name, $format = 'quoted' ) {
2154 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
2155 # Skip the entire process when we have a string quoted on both ends.
2156 # Note that we check the end so that we will still quote any use of
2157 # use of `database`.table. But won't break things if someone wants
2158 # to query a database table with a dot in the name.
2159 if ( $this->isQuotedIdentifier( $name ) ) {
2160 return $name;
2161 }
2162
2163 # Lets test for any bits of text that should never show up in a table
2164 # name. Basically anything like JOIN or ON which are actually part of
2165 # SQL queries, but may end up inside of the table value to combine
2166 # sql. Such as how the API is doing.
2167 # Note that we use a whitespace test rather than a \b test to avoid
2168 # any remote case where a word like on may be inside of a table name
2169 # surrounded by symbols which may be considered word breaks.
2170 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2171 return $name;
2172 }
2173
2174 # Split database and table into proper variables.
2175 # We reverse the explode so that database.table and table both output
2176 # the correct table.
2177 $dbDetails = explode( '.', $name, 2 );
2178 if ( count( $dbDetails ) == 2 ) {
2179 list( $database, $table ) = $dbDetails;
2180 # We don't want any prefix added in this case
2181 $prefix = '';
2182 } else {
2183 list( $table ) = $dbDetails;
2184 if ( $wgSharedDB !== null # We have a shared database
2185 && $this->mForeign == false # We're not working on a foreign database
2186 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
2187 && in_array( $table, $wgSharedTables ) # A shared table is selected
2188 ) {
2189 $database = $wgSharedDB;
2190 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
2191 } else {
2192 $database = null;
2193 $prefix = $this->mTablePrefix; # Default prefix
2194 }
2195 }
2196
2197 # Quote $table and apply the prefix if not quoted.
2198 $tableName = "{$prefix}{$table}";
2199 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) ) {
2200 $tableName = $this->addIdentifierQuotes( $tableName );
2201 }
2202
2203 # Quote $database and merge it with the table name if needed
2204 if ( $database !== null ) {
2205 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2206 $database = $this->addIdentifierQuotes( $database );
2207 }
2208 $tableName = $database . '.' . $tableName;
2209 }
2210
2211 return $tableName;
2212 }
2213
2214 /**
2215 * Fetch a number of table names into an array
2216 * This is handy when you need to construct SQL for joins
2217 *
2218 * Example:
2219 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2220 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2221 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2222 *
2223 * @return array
2224 */
2225 public function tableNames() {
2226 $inArray = func_get_args();
2227 $retVal = array();
2228
2229 foreach ( $inArray as $name ) {
2230 $retVal[$name] = $this->tableName( $name );
2231 }
2232
2233 return $retVal;
2234 }
2235
2236 /**
2237 * Fetch a number of table names into an zero-indexed numerical array
2238 * This is handy when you need to construct SQL for joins
2239 *
2240 * Example:
2241 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2242 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2243 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2244 *
2245 * @return array
2246 */
2247 public function tableNamesN() {
2248 $inArray = func_get_args();
2249 $retVal = array();
2250
2251 foreach ( $inArray as $name ) {
2252 $retVal[] = $this->tableName( $name );
2253 }
2254
2255 return $retVal;
2256 }
2257
2258 /**
2259 * Get an aliased table name
2260 * e.g. tableName AS newTableName
2261 *
2262 * @param string $name Table name, see tableName()
2263 * @param string|bool $alias Alias (optional)
2264 * @return string SQL name for aliased table. Will not alias a table to its own name
2265 */
2266 public function tableNameWithAlias( $name, $alias = false ) {
2267 if ( !$alias || $alias == $name ) {
2268 return $this->tableName( $name );
2269 } else {
2270 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2271 }
2272 }
2273
2274 /**
2275 * Gets an array of aliased table names
2276 *
2277 * @param $tables array( [alias] => table )
2278 * @return array of strings, see tableNameWithAlias()
2279 */
2280 public function tableNamesWithAlias( $tables ) {
2281 $retval = array();
2282 foreach ( $tables as $alias => $table ) {
2283 if ( is_numeric( $alias ) ) {
2284 $alias = $table;
2285 }
2286 $retval[] = $this->tableNameWithAlias( $table, $alias );
2287 }
2288 return $retval;
2289 }
2290
2291 /**
2292 * Get an aliased field name
2293 * e.g. fieldName AS newFieldName
2294 *
2295 * @param string $name Field name
2296 * @param string|bool $alias Alias (optional)
2297 * @return string SQL name for aliased field. Will not alias a field to its own name
2298 */
2299 public function fieldNameWithAlias( $name, $alias = false ) {
2300 if ( !$alias || (string)$alias === (string)$name ) {
2301 return $name;
2302 } else {
2303 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2304 }
2305 }
2306
2307 /**
2308 * Gets an array of aliased field names
2309 *
2310 * @param $fields array( [alias] => field )
2311 * @return array of strings, see fieldNameWithAlias()
2312 */
2313 public function fieldNamesWithAlias( $fields ) {
2314 $retval = array();
2315 foreach ( $fields as $alias => $field ) {
2316 if ( is_numeric( $alias ) ) {
2317 $alias = $field;
2318 }
2319 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2320 }
2321 return $retval;
2322 }
2323
2324 /**
2325 * Get the aliased table name clause for a FROM clause
2326 * which might have a JOIN and/or USE INDEX clause
2327 *
2328 * @param array $tables ( [alias] => table )
2329 * @param $use_index array Same as for select()
2330 * @param $join_conds array Same as for select()
2331 * @return string
2332 */
2333 protected function tableNamesWithUseIndexOrJOIN(
2334 $tables, $use_index = array(), $join_conds = array()
2335 ) {
2336 $ret = array();
2337 $retJOIN = array();
2338 $use_index = (array)$use_index;
2339 $join_conds = (array)$join_conds;
2340
2341 foreach ( $tables as $alias => $table ) {
2342 if ( !is_string( $alias ) ) {
2343 // No alias? Set it equal to the table name
2344 $alias = $table;
2345 }
2346 // Is there a JOIN clause for this table?
2347 if ( isset( $join_conds[$alias] ) ) {
2348 list( $joinType, $conds ) = $join_conds[$alias];
2349 $tableClause = $joinType;
2350 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2351 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2352 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2353 if ( $use != '' ) {
2354 $tableClause .= ' ' . $use;
2355 }
2356 }
2357 $on = $this->makeList( (array)$conds, LIST_AND );
2358 if ( $on != '' ) {
2359 $tableClause .= ' ON (' . $on . ')';
2360 }
2361
2362 $retJOIN[] = $tableClause;
2363 // Is there an INDEX clause for this table?
2364 } elseif ( isset( $use_index[$alias] ) ) {
2365 $tableClause = $this->tableNameWithAlias( $table, $alias );
2366 $tableClause .= ' ' . $this->useIndexClause(
2367 implode( ',', (array)$use_index[$alias] ) );
2368
2369 $ret[] = $tableClause;
2370 } else {
2371 $tableClause = $this->tableNameWithAlias( $table, $alias );
2372
2373 $ret[] = $tableClause;
2374 }
2375 }
2376
2377 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2378 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2379 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2380
2381 // Compile our final table clause
2382 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2383 }
2384
2385 /**
2386 * Get the name of an index in a given table
2387 *
2388 * @param $index
2389 *
2390 * @return string
2391 */
2392 protected function indexName( $index ) {
2393 // Backwards-compatibility hack
2394 $renamed = array(
2395 'ar_usertext_timestamp' => 'usertext_timestamp',
2396 'un_user_id' => 'user_id',
2397 'un_user_ip' => 'user_ip',
2398 );
2399
2400 if ( isset( $renamed[$index] ) ) {
2401 return $renamed[$index];
2402 } else {
2403 return $index;
2404 }
2405 }
2406
2407 /**
2408 * Adds quotes and backslashes.
2409 *
2410 * @param $s string
2411 *
2412 * @return string
2413 */
2414 public function addQuotes( $s ) {
2415 if ( $s === null ) {
2416 return 'NULL';
2417 } else {
2418 # This will also quote numeric values. This should be harmless,
2419 # and protects against weird problems that occur when they really
2420 # _are_ strings such as article titles and string->number->string
2421 # conversion is not 1:1.
2422 return "'" . $this->strencode( $s ) . "'";
2423 }
2424 }
2425
2426 /**
2427 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2428 * MySQL uses `backticks` while basically everything else uses double quotes.
2429 * Since MySQL is the odd one out here the double quotes are our generic
2430 * and we implement backticks in DatabaseMysql.
2431 *
2432 * @param $s string
2433 *
2434 * @return string
2435 */
2436 public function addIdentifierQuotes( $s ) {
2437 return '"' . str_replace( '"', '""', $s ) . '"';
2438 }
2439
2440 /**
2441 * Returns if the given identifier looks quoted or not according to
2442 * the database convention for quoting identifiers .
2443 *
2444 * @param $name string
2445 *
2446 * @return boolean
2447 */
2448 public function isQuotedIdentifier( $name ) {
2449 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2450 }
2451
2452 /**
2453 * @param $s string
2454 * @return string
2455 */
2456 protected function escapeLikeInternal( $s ) {
2457 $s = str_replace( '\\', '\\\\', $s );
2458 $s = $this->strencode( $s );
2459 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2460
2461 return $s;
2462 }
2463
2464 /**
2465 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2466 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2467 * Alternatively, the function could be provided with an array of aforementioned parameters.
2468 *
2469 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2470 * for subpages of 'My page title'.
2471 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2472 *
2473 * @since 1.16
2474 * @return String: fully built LIKE statement
2475 */
2476 public function buildLike() {
2477 $params = func_get_args();
2478
2479 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2480 $params = $params[0];
2481 }
2482
2483 $s = '';
2484
2485 foreach ( $params as $value ) {
2486 if ( $value instanceof LikeMatch ) {
2487 $s .= $value->toString();
2488 } else {
2489 $s .= $this->escapeLikeInternal( $value );
2490 }
2491 }
2492
2493 return " LIKE '" . $s . "' ";
2494 }
2495
2496 /**
2497 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2498 *
2499 * @return LikeMatch
2500 */
2501 public function anyChar() {
2502 return new LikeMatch( '_' );
2503 }
2504
2505 /**
2506 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2507 *
2508 * @return LikeMatch
2509 */
2510 public function anyString() {
2511 return new LikeMatch( '%' );
2512 }
2513
2514 /**
2515 * Returns an appropriately quoted sequence value for inserting a new row.
2516 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2517 * subclass will return an integer, and save the value for insertId()
2518 *
2519 * Any implementation of this function should *not* involve reusing
2520 * sequence numbers created for rolled-back transactions.
2521 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2522 * @param $seqName string
2523 * @return null
2524 */
2525 public function nextSequenceValue( $seqName ) {
2526 return null;
2527 }
2528
2529 /**
2530 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2531 * is only needed because a) MySQL must be as efficient as possible due to
2532 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2533 * which index to pick. Anyway, other databases might have different
2534 * indexes on a given table. So don't bother overriding this unless you're
2535 * MySQL.
2536 * @param $index
2537 * @return string
2538 */
2539 public function useIndexClause( $index ) {
2540 return '';
2541 }
2542
2543 /**
2544 * REPLACE query wrapper.
2545 *
2546 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2547 * except that when there is a duplicate key error, the old row is deleted
2548 * and the new row is inserted in its place.
2549 *
2550 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2551 * perform the delete, we need to know what the unique indexes are so that
2552 * we know how to find the conflicting rows.
2553 *
2554 * It may be more efficient to leave off unique indexes which are unlikely
2555 * to collide. However if you do this, you run the risk of encountering
2556 * errors which wouldn't have occurred in MySQL.
2557 *
2558 * @param string $table The table to replace the row(s) in.
2559 * @param array $rows Can be either a single row to insert, or multiple rows,
2560 * in the same format as for DatabaseBase::insert()
2561 * @param array $uniqueIndexes is an array of indexes. Each element may be either
2562 * a field name or an array of field names
2563 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2564 */
2565 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2566 $quotedTable = $this->tableName( $table );
2567
2568 if ( count( $rows ) == 0 ) {
2569 return;
2570 }
2571
2572 # Single row case
2573 if ( !is_array( reset( $rows ) ) ) {
2574 $rows = array( $rows );
2575 }
2576
2577 foreach ( $rows as $row ) {
2578 # Delete rows which collide
2579 if ( $uniqueIndexes ) {
2580 $sql = "DELETE FROM $quotedTable WHERE ";
2581 $first = true;
2582 foreach ( $uniqueIndexes as $index ) {
2583 if ( $first ) {
2584 $first = false;
2585 $sql .= '( ';
2586 } else {
2587 $sql .= ' ) OR ( ';
2588 }
2589 if ( is_array( $index ) ) {
2590 $first2 = true;
2591 foreach ( $index as $col ) {
2592 if ( $first2 ) {
2593 $first2 = false;
2594 } else {
2595 $sql .= ' AND ';
2596 }
2597 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2598 }
2599 } else {
2600 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2601 }
2602 }
2603 $sql .= ' )';
2604 $this->query( $sql, $fname );
2605 }
2606
2607 # Now insert the row
2608 $this->insert( $table, $row, $fname );
2609 }
2610 }
2611
2612 /**
2613 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2614 * statement.
2615 *
2616 * @param string $table Table name
2617 * @param array $rows Rows to insert
2618 * @param string $fname Caller function name
2619 *
2620 * @return ResultWrapper
2621 */
2622 protected function nativeReplace( $table, $rows, $fname ) {
2623 $table = $this->tableName( $table );
2624
2625 # Single row case
2626 if ( !is_array( reset( $rows ) ) ) {
2627 $rows = array( $rows );
2628 }
2629
2630 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2631 $first = true;
2632
2633 foreach ( $rows as $row ) {
2634 if ( $first ) {
2635 $first = false;
2636 } else {
2637 $sql .= ',';
2638 }
2639
2640 $sql .= '(' . $this->makeList( $row ) . ')';
2641 }
2642
2643 return $this->query( $sql, $fname );
2644 }
2645
2646 /**
2647 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2648 *
2649 * This updates any conflicting rows (according to the unique indexes) using
2650 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2651 *
2652 * $rows may be either:
2653 * - A single associative array. The array keys are the field names, and
2654 * the values are the values to insert. The values are treated as data
2655 * and will be quoted appropriately. If NULL is inserted, this will be
2656 * converted to a database NULL.
2657 * - An array with numeric keys, holding a list of associative arrays.
2658 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2659 * each subarray must be identical to each other, and in the same order.
2660 *
2661 * It may be more efficient to leave off unique indexes which are unlikely
2662 * to collide. However if you do this, you run the risk of encountering
2663 * errors which wouldn't have occurred in MySQL.
2664 *
2665 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2666 * returns success.
2667 *
2668 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2669 * @param array $rows A single row or list of rows to insert
2670 * @param array $uniqueIndexes List of single field names or field name tuples
2671 * @param array $set An array of values to SET. For each array element,
2672 * the key gives the field name, and the value gives the data
2673 * to set that field to. The data will be quoted by
2674 * DatabaseBase::addQuotes().
2675 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2676 * @param array $options of options
2677 *
2678 * @return bool
2679 * @since 1.22
2680 */
2681 public function upsert(
2682 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
2683 ) {
2684 if ( !count( $rows ) ) {
2685 return true; // nothing to do
2686 }
2687 $rows = is_array( reset( $rows ) ) ? $rows : array( $rows );
2688
2689 if ( count( $uniqueIndexes ) ) {
2690 $clauses = array(); // list WHERE clauses that each identify a single row
2691 foreach ( $rows as $row ) {
2692 foreach ( $uniqueIndexes as $index ) {
2693 $index = is_array( $index ) ? $index : array( $index ); // columns
2694 $rowKey = array(); // unique key to this row
2695 foreach ( $index as $column ) {
2696 $rowKey[$column] = $row[$column];
2697 }
2698 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2699 }
2700 }
2701 $where = array( $this->makeList( $clauses, LIST_OR ) );
2702 } else {
2703 $where = false;
2704 }
2705
2706 $useTrx = !$this->mTrxLevel;
2707 if ( $useTrx ) {
2708 $this->begin( $fname );
2709 }
2710 try {
2711 # Update any existing conflicting row(s)
2712 if ( $where !== false ) {
2713 $ok = $this->update( $table, $set, $where, $fname );
2714 } else {
2715 $ok = true;
2716 }
2717 # Now insert any non-conflicting row(s)
2718 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2719 } catch ( Exception $e ) {
2720 if ( $useTrx ) {
2721 $this->rollback( $fname );
2722 }
2723 throw $e;
2724 }
2725 if ( $useTrx ) {
2726 $this->commit( $fname );
2727 }
2728
2729 return $ok;
2730 }
2731
2732 /**
2733 * DELETE where the condition is a join.
2734 *
2735 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2736 * we use sub-selects
2737 *
2738 * For safety, an empty $conds will not delete everything. If you want to
2739 * delete all rows where the join condition matches, set $conds='*'.
2740 *
2741 * DO NOT put the join condition in $conds.
2742 *
2743 * @param $delTable String: The table to delete from.
2744 * @param $joinTable String: The other table.
2745 * @param $delVar String: The variable to join on, in the first table.
2746 * @param $joinVar String: The variable to join on, in the second table.
2747 * @param $conds Array: Condition array of field names mapped to variables,
2748 * ANDed together in the WHERE clause
2749 * @param $fname String: Calling function name (use __METHOD__) for
2750 * logs/profiling
2751 * @throws DBUnexpectedError
2752 */
2753 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2754 $fname = __METHOD__ )
2755 {
2756 if ( !$conds ) {
2757 throw new DBUnexpectedError( $this,
2758 'DatabaseBase::deleteJoin() called with empty $conds' );
2759 }
2760
2761 $delTable = $this->tableName( $delTable );
2762 $joinTable = $this->tableName( $joinTable );
2763 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2764 if ( $conds != '*' ) {
2765 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2766 }
2767 $sql .= ')';
2768
2769 $this->query( $sql, $fname );
2770 }
2771
2772 /**
2773 * Returns the size of a text field, or -1 for "unlimited"
2774 *
2775 * @param $table string
2776 * @param $field string
2777 *
2778 * @return int
2779 */
2780 public function textFieldSize( $table, $field ) {
2781 $table = $this->tableName( $table );
2782 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2783 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2784 $row = $this->fetchObject( $res );
2785
2786 $m = array();
2787
2788 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2789 $size = $m[1];
2790 } else {
2791 $size = -1;
2792 }
2793
2794 return $size;
2795 }
2796
2797 /**
2798 * A string to insert into queries to show that they're low-priority, like
2799 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2800 * string and nothing bad should happen.
2801 *
2802 * @return string Returns the text of the low priority option if it is
2803 * supported, or a blank string otherwise
2804 */
2805 public function lowPriorityOption() {
2806 return '';
2807 }
2808
2809 /**
2810 * DELETE query wrapper.
2811 *
2812 * @param array $table Table name
2813 * @param string|array $conds of conditions. See $conds in DatabaseBase::select() for
2814 * the format. Use $conds == "*" to delete all rows
2815 * @param string $fname name of the calling function
2816 *
2817 * @throws DBUnexpectedError
2818 * @return bool|ResultWrapper
2819 */
2820 public function delete( $table, $conds, $fname = __METHOD__ ) {
2821 if ( !$conds ) {
2822 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2823 }
2824
2825 $table = $this->tableName( $table );
2826 $sql = "DELETE FROM $table";
2827
2828 if ( $conds != '*' ) {
2829 if ( is_array( $conds ) ) {
2830 $conds = $this->makeList( $conds, LIST_AND );
2831 }
2832 $sql .= ' WHERE ' . $conds;
2833 }
2834
2835 return $this->query( $sql, $fname );
2836 }
2837
2838 /**
2839 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2840 * into another table.
2841 *
2842 * @param string $destTable The table name to insert into
2843 * @param string|array $srcTable May be either a table name, or an array of table names
2844 * to include in a join.
2845 *
2846 * @param array $varMap must be an associative array of the form
2847 * array( 'dest1' => 'source1', ...). Source items may be literals
2848 * rather than field names, but strings should be quoted with
2849 * DatabaseBase::addQuotes()
2850 *
2851 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2852 * the details of the format of condition arrays. May be "*" to copy the
2853 * whole table.
2854 *
2855 * @param string $fname The function name of the caller, from __METHOD__
2856 *
2857 * @param array $insertOptions Options for the INSERT part of the query, see
2858 * DatabaseBase::insert() for details.
2859 * @param array $selectOptions Options for the SELECT part of the query, see
2860 * DatabaseBase::select() for details.
2861 *
2862 * @return ResultWrapper
2863 */
2864 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2865 $fname = __METHOD__,
2866 $insertOptions = array(), $selectOptions = array() )
2867 {
2868 $destTable = $this->tableName( $destTable );
2869
2870 if ( is_array( $insertOptions ) ) {
2871 $insertOptions = implode( ' ', $insertOptions );
2872 }
2873
2874 if ( !is_array( $selectOptions ) ) {
2875 $selectOptions = array( $selectOptions );
2876 }
2877
2878 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2879
2880 if ( is_array( $srcTable ) ) {
2881 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2882 } else {
2883 $srcTable = $this->tableName( $srcTable );
2884 }
2885
2886 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2887 " SELECT $startOpts " . implode( ',', $varMap ) .
2888 " FROM $srcTable $useIndex ";
2889
2890 if ( $conds != '*' ) {
2891 if ( is_array( $conds ) ) {
2892 $conds = $this->makeList( $conds, LIST_AND );
2893 }
2894 $sql .= " WHERE $conds";
2895 }
2896
2897 $sql .= " $tailOpts";
2898
2899 return $this->query( $sql, $fname );
2900 }
2901
2902 /**
2903 * Construct a LIMIT query with optional offset. This is used for query
2904 * pages. The SQL should be adjusted so that only the first $limit rows
2905 * are returned. If $offset is provided as well, then the first $offset
2906 * rows should be discarded, and the next $limit rows should be returned.
2907 * If the result of the query is not ordered, then the rows to be returned
2908 * are theoretically arbitrary.
2909 *
2910 * $sql is expected to be a SELECT, if that makes a difference.
2911 *
2912 * The version provided by default works in MySQL and SQLite. It will very
2913 * likely need to be overridden for most other DBMSes.
2914 *
2915 * @param string $sql SQL query we will append the limit too
2916 * @param $limit Integer the SQL limit
2917 * @param $offset Integer|bool the SQL offset (default false)
2918 *
2919 * @throws DBUnexpectedError
2920 * @return string
2921 */
2922 public function limitResult( $sql, $limit, $offset = false ) {
2923 if ( !is_numeric( $limit ) ) {
2924 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2925 }
2926 return "$sql LIMIT "
2927 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2928 . "{$limit} ";
2929 }
2930
2931 /**
2932 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2933 * within the UNION construct.
2934 * @return Boolean
2935 */
2936 public function unionSupportsOrderAndLimit() {
2937 return true; // True for almost every DB supported
2938 }
2939
2940 /**
2941 * Construct a UNION query
2942 * This is used for providing overload point for other DB abstractions
2943 * not compatible with the MySQL syntax.
2944 * @param array $sqls SQL statements to combine
2945 * @param $all Boolean: use UNION ALL
2946 * @return String: SQL fragment
2947 */
2948 public function unionQueries( $sqls, $all ) {
2949 $glue = $all ? ') UNION ALL (' : ') UNION (';
2950 return '(' . implode( $glue, $sqls ) . ')';
2951 }
2952
2953 /**
2954 * Returns an SQL expression for a simple conditional. This doesn't need
2955 * to be overridden unless CASE isn't supported in your DBMS.
2956 *
2957 * @param string|array $cond SQL expression which will result in a boolean value
2958 * @param string $trueVal SQL expression to return if true
2959 * @param string $falseVal SQL expression to return if false
2960 * @return String: SQL fragment
2961 */
2962 public function conditional( $cond, $trueVal, $falseVal ) {
2963 if ( is_array( $cond ) ) {
2964 $cond = $this->makeList( $cond, LIST_AND );
2965 }
2966 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2967 }
2968
2969 /**
2970 * Returns a comand for str_replace function in SQL query.
2971 * Uses REPLACE() in MySQL
2972 *
2973 * @param string $orig column to modify
2974 * @param string $old column to seek
2975 * @param string $new column to replace with
2976 *
2977 * @return string
2978 */
2979 public function strreplace( $orig, $old, $new ) {
2980 return "REPLACE({$orig}, {$old}, {$new})";
2981 }
2982
2983 /**
2984 * Determines how long the server has been up
2985 * STUB
2986 *
2987 * @return int
2988 */
2989 public function getServerUptime() {
2990 return 0;
2991 }
2992
2993 /**
2994 * Determines if the last failure was due to a deadlock
2995 * STUB
2996 *
2997 * @return bool
2998 */
2999 public function wasDeadlock() {
3000 return false;
3001 }
3002
3003 /**
3004 * Determines if the last failure was due to a lock timeout
3005 * STUB
3006 *
3007 * @return bool
3008 */
3009 public function wasLockTimeout() {
3010 return false;
3011 }
3012
3013 /**
3014 * Determines if the last query error was something that should be dealt
3015 * with by pinging the connection and reissuing the query.
3016 * STUB
3017 *
3018 * @return bool
3019 */
3020 public function wasErrorReissuable() {
3021 return false;
3022 }
3023
3024 /**
3025 * Determines if the last failure was due to the database being read-only.
3026 * STUB
3027 *
3028 * @return bool
3029 */
3030 public function wasReadOnlyError() {
3031 return false;
3032 }
3033
3034 /**
3035 * Perform a deadlock-prone transaction.
3036 *
3037 * This function invokes a callback function to perform a set of write
3038 * queries. If a deadlock occurs during the processing, the transaction
3039 * will be rolled back and the callback function will be called again.
3040 *
3041 * Usage:
3042 * $dbw->deadlockLoop( callback, ... );
3043 *
3044 * Extra arguments are passed through to the specified callback function.
3045 *
3046 * Returns whatever the callback function returned on its successful,
3047 * iteration, or false on error, for example if the retry limit was
3048 * reached.
3049 *
3050 * @return bool
3051 */
3052 public function deadlockLoop() {
3053 $this->begin( __METHOD__ );
3054 $args = func_get_args();
3055 $function = array_shift( $args );
3056 $oldIgnore = $this->ignoreErrors( true );
3057 $tries = self::DEADLOCK_TRIES;
3058
3059 if ( is_array( $function ) ) {
3060 $fname = $function[0];
3061 } else {
3062 $fname = $function;
3063 }
3064
3065 do {
3066 $retVal = call_user_func_array( $function, $args );
3067 $error = $this->lastError();
3068 $errno = $this->lastErrno();
3069 $sql = $this->lastQuery();
3070
3071 if ( $errno ) {
3072 if ( $this->wasDeadlock() ) {
3073 # Retry
3074 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3075 } else {
3076 $this->reportQueryError( $error, $errno, $sql, $fname );
3077 }
3078 }
3079 } while ( $this->wasDeadlock() && --$tries > 0 );
3080
3081 $this->ignoreErrors( $oldIgnore );
3082
3083 if ( $tries <= 0 ) {
3084 $this->rollback( __METHOD__ );
3085 $this->reportQueryError( $error, $errno, $sql, $fname );
3086 return false;
3087 } else {
3088 $this->commit( __METHOD__ );
3089 return $retVal;
3090 }
3091 }
3092
3093 /**
3094 * Wait for the slave to catch up to a given master position.
3095 *
3096 * @param $pos DBMasterPos object
3097 * @param $timeout Integer: the maximum number of seconds to wait for
3098 * synchronisation
3099 *
3100 * @return integer: zero if the slave was past that position already,
3101 * greater than zero if we waited for some period of time, less than
3102 * zero if we timed out.
3103 */
3104 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3105 wfProfileIn( __METHOD__ );
3106
3107 if ( !is_null( $this->mFakeSlaveLag ) ) {
3108 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
3109
3110 if ( $wait > $timeout * 1e6 ) {
3111 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
3112 wfProfileOut( __METHOD__ );
3113 return -1;
3114 } elseif ( $wait > 0 ) {
3115 wfDebug( "Fake slave waiting $wait us\n" );
3116 usleep( $wait );
3117 wfProfileOut( __METHOD__ );
3118 return 1;
3119 } else {
3120 wfDebug( "Fake slave up to date ($wait us)\n" );
3121 wfProfileOut( __METHOD__ );
3122 return 0;
3123 }
3124 }
3125
3126 wfProfileOut( __METHOD__ );
3127
3128 # Real waits are implemented in the subclass.
3129 return 0;
3130 }
3131
3132 /**
3133 * Get the replication position of this slave
3134 *
3135 * @return DBMasterPos, or false if this is not a slave.
3136 */
3137 public function getSlavePos() {
3138 if ( !is_null( $this->mFakeSlaveLag ) ) {
3139 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
3140 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
3141 return $pos;
3142 } else {
3143 # Stub
3144 return false;
3145 }
3146 }
3147
3148 /**
3149 * Get the position of this master
3150 *
3151 * @return DBMasterPos, or false if this is not a master
3152 */
3153 public function getMasterPos() {
3154 if ( $this->mFakeMaster ) {
3155 return new MySQLMasterPos( 'fake', microtime( true ) );
3156 } else {
3157 return false;
3158 }
3159 }
3160
3161 /**
3162 * Run an anonymous function as soon as there is no transaction pending.
3163 * If there is a transaction and it is rolled back, then the callback is cancelled.
3164 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3165 * Callbacks must commit any transactions that they begin.
3166 *
3167 * This is useful for updates to different systems or when separate transactions are needed.
3168 * For example, one might want to enqueue jobs into a system outside the database, but only
3169 * after the database is updated so that the jobs will see the data when they actually run.
3170 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3171 *
3172 * @param callable $callback
3173 * @since 1.20
3174 */
3175 final public function onTransactionIdle( $callback ) {
3176 $this->mTrxIdleCallbacks[] = array( $callback, wfGetCaller() );
3177 if ( !$this->mTrxLevel ) {
3178 $this->runOnTransactionIdleCallbacks();
3179 }
3180 }
3181
3182 /**
3183 * Run an anonymous function before the current transaction commits or now if there is none.
3184 * If there is a transaction and it is rolled back, then the callback is cancelled.
3185 * Callbacks must not start nor commit any transactions.
3186 *
3187 * This is useful for updates that easily cause deadlocks if locks are held too long
3188 * but where atomicity is strongly desired for these updates and some related updates.
3189 *
3190 * @param callable $callback
3191 * @since 1.22
3192 */
3193 final public function onTransactionPreCommitOrIdle( $callback ) {
3194 if ( $this->mTrxLevel ) {
3195 $this->mTrxPreCommitCallbacks[] = array( $callback, wfGetCaller() );
3196 } else {
3197 $this->onTransactionIdle( $callback ); // this will trigger immediately
3198 }
3199 }
3200
3201 /**
3202 * Actually any "on transaction idle" callbacks.
3203 *
3204 * @since 1.20
3205 */
3206 protected function runOnTransactionIdleCallbacks() {
3207 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
3208
3209 $e = null; // last exception
3210 do { // callbacks may add callbacks :)
3211 $callbacks = $this->mTrxIdleCallbacks;
3212 $this->mTrxIdleCallbacks = array(); // recursion guard
3213 foreach ( $callbacks as $callback ) {
3214 try {
3215 list( $phpCallback ) = $callback;
3216 $this->clearFlag( DBO_TRX ); // make each query its own transaction
3217 call_user_func( $phpCallback );
3218 $this->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
3219 } catch ( Exception $e ) {}
3220 }
3221 } while ( count( $this->mTrxIdleCallbacks ) );
3222
3223 if ( $e instanceof Exception ) {
3224 throw $e; // re-throw any last exception
3225 }
3226 }
3227
3228 /**
3229 * Actually any "on transaction pre-commit" callbacks.
3230 *
3231 * @since 1.22
3232 */
3233 protected function runOnTransactionPreCommitCallbacks() {
3234 $e = null; // last exception
3235 do { // callbacks may add callbacks :)
3236 $callbacks = $this->mTrxPreCommitCallbacks;
3237 $this->mTrxPreCommitCallbacks = array(); // recursion guard
3238 foreach ( $callbacks as $callback ) {
3239 try {
3240 list( $phpCallback ) = $callback;
3241 call_user_func( $phpCallback );
3242 } catch ( Exception $e ) {}
3243 }
3244 } while ( count( $this->mTrxPreCommitCallbacks ) );
3245
3246 if ( $e instanceof Exception ) {
3247 throw $e; // re-throw any last exception
3248 }
3249 }
3250
3251 /**
3252 * Begin an atomic section of statements
3253 *
3254 * If a transaction has been started already, just keep track of the given
3255 * section name to make sure the transaction is not committed pre-maturely.
3256 * This function can be used in layers (with sub-sections), so use a stack
3257 * to keep track of the different atomic sections. If there is no transaction,
3258 * start one implicitly.
3259 *
3260 * The goal of this function is to create an atomic section of SQL queries
3261 * without having to start a new transaction if it already exists.
3262 *
3263 * Atomic sections are more strict than transactions. With transactions,
3264 * attempting to begin a new transaction when one is already running results
3265 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3266 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3267 * and any database transactions cannot be began or committed until all atomic
3268 * levels are closed. There is no such thing as implicitly opening or closing
3269 * an atomic section.
3270 *
3271 * @since 1.23
3272 * @param string $fname
3273 * @throws DBError
3274 */
3275 final public function startAtomic( $fname = __METHOD__ ) {
3276 if ( !$this->mTrxLevel ) {
3277 $this->begin( $fname );
3278 $this->mTrxAutomatic = true;
3279 $this->mTrxAutomaticAtomic = true;
3280 }
3281
3282 $this->mTrxAtomicLevels->push( $fname );
3283 }
3284
3285 /**
3286 * Ends an atomic section of SQL statements
3287 *
3288 * Ends the next section of atomic SQL statements and commits the transaction
3289 * if necessary.
3290 *
3291 * @since 1.23
3292 * @see DatabaseBase::startAtomic
3293 * @param string $fname
3294 * @throws DBError
3295 */
3296 final public function endAtomic( $fname = __METHOD__ ) {
3297 if ( !$this->mTrxLevel ) {
3298 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3299 }
3300 if ( $this->mTrxAtomicLevels->isEmpty() ||
3301 $this->mTrxAtomicLevels->pop() !== $fname
3302 ) {
3303 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3304 }
3305
3306 if ( $this->mTrxAtomicLevels->isEmpty() && $this->mTrxAutomaticAtomic ) {
3307 $this->commit( $fname, 'flush' );
3308 }
3309 }
3310
3311 /**
3312 * Begin a transaction. If a transaction is already in progress, that transaction will be committed before the
3313 * new transaction is started.
3314 *
3315 * Note that when the DBO_TRX flag is set (which is usually the case for web requests, but not for maintenance scripts),
3316 * any previous database query will have started a transaction automatically.
3317 *
3318 * Nesting of transactions is not supported. Attempts to nest transactions will cause a warning, unless the current
3319 * transaction was started automatically because of the DBO_TRX flag.
3320 *
3321 * @param $fname string
3322 * @throws DBError
3323 */
3324 final public function begin( $fname = __METHOD__ ) {
3325 global $wgDebugDBTransactions;
3326
3327 if ( $this->mTrxLevel ) { // implicit commit
3328 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3329 // If the current transaction was an automatic atomic one, then we definitely have
3330 // a problem. Same if there is any unclosed atomic level.
3331 throw new DBUnexpectedError( $this,
3332 "Attempted to start explicit transaction when atomic levels are still open."
3333 );
3334 } elseif ( !$this->mTrxAutomatic ) {
3335 // We want to warn about inadvertently nested begin/commit pairs, but not about
3336 // auto-committing implicit transactions that were started by query() via DBO_TRX
3337 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3338 " performing implicit commit!";
3339 wfWarn( $msg );
3340 wfLogDBError( $msg );
3341 } else {
3342 // if the transaction was automatic and has done write operations,
3343 // log it if $wgDebugDBTransactions is enabled.
3344 if ( $this->mTrxDoneWrites && $wgDebugDBTransactions ) {
3345 wfDebug( "$fname: Automatic transaction with writes in progress" .
3346 " (from {$this->mTrxFname}), performing implicit commit!\n"
3347 );
3348 }
3349 }
3350
3351 $this->runOnTransactionPreCommitCallbacks();
3352 $this->doCommit( $fname );
3353 if ( $this->mTrxDoneWrites ) {
3354 Profiler::instance()->transactionWritingOut( $this->mServer, $this->mDBname );
3355 }
3356 $this->runOnTransactionIdleCallbacks();
3357 }
3358
3359 $this->doBegin( $fname );
3360 $this->mTrxFname = $fname;
3361 $this->mTrxDoneWrites = false;
3362 $this->mTrxAutomatic = false;
3363 $this->mTrxAutomaticAtomic = false;
3364 $this->mTrxAtomicLevels = new SplStack;
3365 $this->mTrxIdleCallbacks = array();
3366 $this->mTrxPreCommitCallbacks = array();
3367 }
3368
3369 /**
3370 * Issues the BEGIN command to the database server.
3371 *
3372 * @see DatabaseBase::begin()
3373 * @param type $fname
3374 */
3375 protected function doBegin( $fname ) {
3376 $this->query( 'BEGIN', $fname );
3377 $this->mTrxLevel = 1;
3378 }
3379
3380 /**
3381 * Commits a transaction previously started using begin().
3382 * If no transaction is in progress, a warning is issued.
3383 *
3384 * Nesting of transactions is not supported.
3385 *
3386 * @param $fname string
3387 * @param string $flush Flush flag, set to 'flush' to disable warnings about explicitly committing implicit
3388 * transactions, or calling commit when no transaction is in progress.
3389 * This will silently break any ongoing explicit transaction. Only set the flush flag if you are sure
3390 * that it is safe to ignore these warnings in your context.
3391 */
3392 final public function commit( $fname = __METHOD__, $flush = '' ) {
3393 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3394 // There are still atomic sections open. This cannot be ignored
3395 throw new DBUnexpectedError( $this, "Attempted to commit transaction while atomic sections are still open" );
3396 }
3397
3398 if ( $flush != 'flush' ) {
3399 if ( !$this->mTrxLevel ) {
3400 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3401 } elseif ( $this->mTrxAutomatic ) {
3402 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3403 }
3404 } else {
3405 if ( !$this->mTrxLevel ) {
3406 return; // nothing to do
3407 } elseif ( !$this->mTrxAutomatic ) {
3408 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3409 }
3410 }
3411
3412 $this->runOnTransactionPreCommitCallbacks();
3413 $this->doCommit( $fname );
3414 if ( $this->mTrxDoneWrites ) {
3415 Profiler::instance()->transactionWritingOut( $this->mServer, $this->mDBname );
3416 }
3417 $this->runOnTransactionIdleCallbacks();
3418 }
3419
3420 /**
3421 * Issues the COMMIT command to the database server.
3422 *
3423 * @see DatabaseBase::commit()
3424 * @param type $fname
3425 */
3426 protected function doCommit( $fname ) {
3427 if ( $this->mTrxLevel ) {
3428 $this->query( 'COMMIT', $fname );
3429 $this->mTrxLevel = 0;
3430 }
3431 }
3432
3433 /**
3434 * Rollback a transaction previously started using begin().
3435 * If no transaction is in progress, a warning is issued.
3436 *
3437 * No-op on non-transactional databases.
3438 *
3439 * @param $fname string
3440 */
3441 final public function rollback( $fname = __METHOD__ ) {
3442 if ( !$this->mTrxLevel ) {
3443 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3444 }
3445 $this->doRollback( $fname );
3446 $this->mTrxIdleCallbacks = array(); // cancel
3447 $this->mTrxPreCommitCallbacks = array(); // cancel
3448 $this->mTrxAtomicLevels = new SplStack;
3449 if ( $this->mTrxDoneWrites ) {
3450 Profiler::instance()->transactionWritingOut( $this->mServer, $this->mDBname );
3451 }
3452 }
3453
3454 /**
3455 * Issues the ROLLBACK command to the database server.
3456 *
3457 * @see DatabaseBase::rollback()
3458 * @param type $fname
3459 */
3460 protected function doRollback( $fname ) {
3461 if ( $this->mTrxLevel ) {
3462 $this->query( 'ROLLBACK', $fname, true );
3463 $this->mTrxLevel = 0;
3464 }
3465 }
3466
3467 /**
3468 * Creates a new table with structure copied from existing table
3469 * Note that unlike most database abstraction functions, this function does not
3470 * automatically append database prefix, because it works at a lower
3471 * abstraction level.
3472 * The table names passed to this function shall not be quoted (this
3473 * function calls addIdentifierQuotes when needed).
3474 *
3475 * @param string $oldName name of table whose structure should be copied
3476 * @param string $newName name of table to be created
3477 * @param $temporary Boolean: whether the new table should be temporary
3478 * @param string $fname calling function name
3479 * @throws MWException
3480 * @return Boolean: true if operation was successful
3481 */
3482 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3483 $fname = __METHOD__
3484 ) {
3485 throw new MWException(
3486 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3487 }
3488
3489 /**
3490 * List all tables on the database
3491 *
3492 * @param string $prefix Only show tables with this prefix, e.g. mw_
3493 * @param string $fname calling function name
3494 * @throws MWException
3495 */
3496 function listTables( $prefix = null, $fname = __METHOD__ ) {
3497 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3498 }
3499
3500 /**
3501 * Reset the views process cache set by listViews()
3502 * @since 1.22
3503 */
3504 final public function clearViewsCache() {
3505 $this->allViews = null;
3506 }
3507
3508 /**
3509 * Lists all the VIEWs in the database
3510 *
3511 * For caching purposes the list of all views should be stored in
3512 * $this->allViews. The process cache can be cleared with clearViewsCache()
3513 *
3514 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3515 * @param string $fname Name of calling function
3516 * @throws MWException
3517 * @since 1.22
3518 */
3519 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3520 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3521 }
3522
3523 /**
3524 * Differentiates between a TABLE and a VIEW
3525 *
3526 * @param $name string: Name of the database-structure to test.
3527 * @throws MWException
3528 * @since 1.22
3529 */
3530 public function isView( $name ) {
3531 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3532 }
3533
3534 /**
3535 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3536 * to the format used for inserting into timestamp fields in this DBMS.
3537 *
3538 * The result is unquoted, and needs to be passed through addQuotes()
3539 * before it can be included in raw SQL.
3540 *
3541 * @param $ts string|int
3542 *
3543 * @return string
3544 */
3545 public function timestamp( $ts = 0 ) {
3546 return wfTimestamp( TS_MW, $ts );
3547 }
3548
3549 /**
3550 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3551 * to the format used for inserting into timestamp fields in this DBMS. If
3552 * NULL is input, it is passed through, allowing NULL values to be inserted
3553 * into timestamp fields.
3554 *
3555 * The result is unquoted, and needs to be passed through addQuotes()
3556 * before it can be included in raw SQL.
3557 *
3558 * @param $ts string|int
3559 *
3560 * @return string
3561 */
3562 public function timestampOrNull( $ts = null ) {
3563 if ( is_null( $ts ) ) {
3564 return null;
3565 } else {
3566 return $this->timestamp( $ts );
3567 }
3568 }
3569
3570 /**
3571 * Take the result from a query, and wrap it in a ResultWrapper if
3572 * necessary. Boolean values are passed through as is, to indicate success
3573 * of write queries or failure.
3574 *
3575 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3576 * resource, and it was necessary to call this function to convert it to
3577 * a wrapper. Nowadays, raw database objects are never exposed to external
3578 * callers, so this is unnecessary in external code. For compatibility with
3579 * old code, ResultWrapper objects are passed through unaltered.
3580 *
3581 * @param $result bool|ResultWrapper
3582 *
3583 * @return bool|ResultWrapper
3584 */
3585 public function resultObject( $result ) {
3586 if ( empty( $result ) ) {
3587 return false;
3588 } elseif ( $result instanceof ResultWrapper ) {
3589 return $result;
3590 } elseif ( $result === true ) {
3591 // Successful write query
3592 return $result;
3593 } else {
3594 return new ResultWrapper( $this, $result );
3595 }
3596 }
3597
3598 /**
3599 * Ping the server and try to reconnect if it there is no connection
3600 *
3601 * @return bool Success or failure
3602 */
3603 public function ping() {
3604 # Stub. Not essential to override.
3605 return true;
3606 }
3607
3608 /**
3609 * Get slave lag. Currently supported only by MySQL.
3610 *
3611 * Note that this function will generate a fatal error on many
3612 * installations. Most callers should use LoadBalancer::safeGetLag()
3613 * instead.
3614 *
3615 * @return int Database replication lag in seconds
3616 */
3617 public function getLag() {
3618 return intval( $this->mFakeSlaveLag );
3619 }
3620
3621 /**
3622 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3623 *
3624 * @return int
3625 */
3626 function maxListLen() {
3627 return 0;
3628 }
3629
3630 /**
3631 * Some DBMSs have a special format for inserting into blob fields, they
3632 * don't allow simple quoted strings to be inserted. To insert into such
3633 * a field, pass the data through this function before passing it to
3634 * DatabaseBase::insert().
3635 * @param $b string
3636 * @return string
3637 */
3638 public function encodeBlob( $b ) {
3639 return $b;
3640 }
3641
3642 /**
3643 * Some DBMSs return a special placeholder object representing blob fields
3644 * in result objects. Pass the object through this function to return the
3645 * original string.
3646 * @param $b string
3647 * @return string
3648 */
3649 public function decodeBlob( $b ) {
3650 return $b;
3651 }
3652
3653 /**
3654 * Override database's default behavior. $options include:
3655 * 'connTimeout' : Set the connection timeout value in seconds.
3656 * May be useful for very long batch queries such as
3657 * full-wiki dumps, where a single query reads out over
3658 * hours or days.
3659 *
3660 * @param $options Array
3661 * @return void
3662 */
3663 public function setSessionOptions( array $options ) {
3664 }
3665
3666 /**
3667 * Read and execute SQL commands from a file.
3668 *
3669 * Returns true on success, error string or exception on failure (depending
3670 * on object's error ignore settings).
3671 *
3672 * @param string $filename File name to open
3673 * @param bool|callable $lineCallback Optional function called before reading each line
3674 * @param bool|callable $resultCallback Optional function called for each MySQL result
3675 * @param bool|string $fname Calling function name or false if name should be
3676 * generated dynamically using $filename
3677 * @param bool|callable $inputCallback Callback: Optional function called for each complete line sent
3678 * @throws MWException
3679 * @throws Exception|MWException
3680 * @return bool|string
3681 */
3682 public function sourceFile(
3683 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3684 ) {
3685 wfSuppressWarnings();
3686 $fp = fopen( $filename, 'r' );
3687 wfRestoreWarnings();
3688
3689 if ( false === $fp ) {
3690 throw new MWException( "Could not open \"{$filename}\".\n" );
3691 }
3692
3693 if ( !$fname ) {
3694 $fname = __METHOD__ . "( $filename )";
3695 }
3696
3697 try {
3698 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3699 }
3700 catch ( MWException $e ) {
3701 fclose( $fp );
3702 throw $e;
3703 }
3704
3705 fclose( $fp );
3706
3707 return $error;
3708 }
3709
3710 /**
3711 * Get the full path of a patch file. Originally based on archive()
3712 * from updaters.inc. Keep in mind this always returns a patch, as
3713 * it fails back to MySQL if no DB-specific patch can be found
3714 *
3715 * @param string $patch The name of the patch, like patch-something.sql
3716 * @return String Full path to patch file
3717 */
3718 public function patchPath( $patch ) {
3719 global $IP;
3720
3721 $dbType = $this->getType();
3722 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3723 return "$IP/maintenance/$dbType/archives/$patch";
3724 } else {
3725 return "$IP/maintenance/archives/$patch";
3726 }
3727 }
3728
3729 /**
3730 * Set variables to be used in sourceFile/sourceStream, in preference to the
3731 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3732 * all. If it's set to false, $GLOBALS will be used.
3733 *
3734 * @param bool|array $vars mapping variable name to value.
3735 */
3736 public function setSchemaVars( $vars ) {
3737 $this->mSchemaVars = $vars;
3738 }
3739
3740 /**
3741 * Read and execute commands from an open file handle.
3742 *
3743 * Returns true on success, error string or exception on failure (depending
3744 * on object's error ignore settings).
3745 *
3746 * @param $fp Resource: File handle
3747 * @param $lineCallback Callback: Optional function called before reading each query
3748 * @param $resultCallback Callback: Optional function called for each MySQL result
3749 * @param string $fname Calling function name
3750 * @param $inputCallback Callback: Optional function called for each complete query sent
3751 * @return bool|string
3752 */
3753 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3754 $fname = __METHOD__, $inputCallback = false )
3755 {
3756 $cmd = '';
3757
3758 while ( !feof( $fp ) ) {
3759 if ( $lineCallback ) {
3760 call_user_func( $lineCallback );
3761 }
3762
3763 $line = trim( fgets( $fp ) );
3764
3765 if ( $line == '' ) {
3766 continue;
3767 }
3768
3769 if ( '-' == $line[0] && '-' == $line[1] ) {
3770 continue;
3771 }
3772
3773 if ( $cmd != '' ) {
3774 $cmd .= ' ';
3775 }
3776
3777 $done = $this->streamStatementEnd( $cmd, $line );
3778
3779 $cmd .= "$line\n";
3780
3781 if ( $done || feof( $fp ) ) {
3782 $cmd = $this->replaceVars( $cmd );
3783
3784 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
3785 $res = $this->query( $cmd, $fname );
3786
3787 if ( $resultCallback ) {
3788 call_user_func( $resultCallback, $res, $this );
3789 }
3790
3791 if ( false === $res ) {
3792 $err = $this->lastError();
3793 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3794 }
3795 }
3796 $cmd = '';
3797 }
3798 }
3799
3800 return true;
3801 }
3802
3803 /**
3804 * Called by sourceStream() to check if we've reached a statement end
3805 *
3806 * @param string $sql SQL assembled so far
3807 * @param string $newLine New line about to be added to $sql
3808 * @return Bool Whether $newLine contains end of the statement
3809 */
3810 public function streamStatementEnd( &$sql, &$newLine ) {
3811 if ( $this->delimiter ) {
3812 $prev = $newLine;
3813 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3814 if ( $newLine != $prev ) {
3815 return true;
3816 }
3817 }
3818 return false;
3819 }
3820
3821 /**
3822 * Database independent variable replacement. Replaces a set of variables
3823 * in an SQL statement with their contents as given by $this->getSchemaVars().
3824 *
3825 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3826 *
3827 * - '{$var}' should be used for text and is passed through the database's
3828 * addQuotes method.
3829 * - `{$var}` should be used for identifiers (eg: table and database names),
3830 * it is passed through the database's addIdentifierQuotes method which
3831 * can be overridden if the database uses something other than backticks.
3832 * - / *$var* / is just encoded, besides traditional table prefix and
3833 * table options its use should be avoided.
3834 *
3835 * @param string $ins SQL statement to replace variables in
3836 * @return String The new SQL statement with variables replaced
3837 */
3838 protected function replaceSchemaVars( $ins ) {
3839 $vars = $this->getSchemaVars();
3840 foreach ( $vars as $var => $value ) {
3841 // replace '{$var}'
3842 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3843 // replace `{$var}`
3844 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3845 // replace /*$var*/
3846 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ), $ins );
3847 }
3848 return $ins;
3849 }
3850
3851 /**
3852 * Replace variables in sourced SQL
3853 *
3854 * @param $ins string
3855 *
3856 * @return string
3857 */
3858 protected function replaceVars( $ins ) {
3859 $ins = $this->replaceSchemaVars( $ins );
3860
3861 // Table prefixes
3862 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3863 array( $this, 'tableNameCallback' ), $ins );
3864
3865 // Index names
3866 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3867 array( $this, 'indexNameCallback' ), $ins );
3868
3869 return $ins;
3870 }
3871
3872 /**
3873 * Get schema variables. If none have been set via setSchemaVars(), then
3874 * use some defaults from the current object.
3875 *
3876 * @return array
3877 */
3878 protected function getSchemaVars() {
3879 if ( $this->mSchemaVars ) {
3880 return $this->mSchemaVars;
3881 } else {
3882 return $this->getDefaultSchemaVars();
3883 }
3884 }
3885
3886 /**
3887 * Get schema variables to use if none have been set via setSchemaVars().
3888 *
3889 * Override this in derived classes to provide variables for tables.sql
3890 * and SQL patch files.
3891 *
3892 * @return array
3893 */
3894 protected function getDefaultSchemaVars() {
3895 return array();
3896 }
3897
3898 /**
3899 * Table name callback
3900 *
3901 * @param $matches array
3902 *
3903 * @return string
3904 */
3905 protected function tableNameCallback( $matches ) {
3906 return $this->tableName( $matches[1] );
3907 }
3908
3909 /**
3910 * Index name callback
3911 *
3912 * @param $matches array
3913 *
3914 * @return string
3915 */
3916 protected function indexNameCallback( $matches ) {
3917 return $this->indexName( $matches[1] );
3918 }
3919
3920 /**
3921 * Check to see if a named lock is available. This is non-blocking.
3922 *
3923 * @param string $lockName name of lock to poll
3924 * @param string $method name of method calling us
3925 * @return Boolean
3926 * @since 1.20
3927 */
3928 public function lockIsFree( $lockName, $method ) {
3929 return true;
3930 }
3931
3932 /**
3933 * Acquire a named lock
3934 *
3935 * Abstracted from Filestore::lock() so child classes can implement for
3936 * their own needs.
3937 *
3938 * @param string $lockName name of lock to aquire
3939 * @param string $method name of method calling us
3940 * @param $timeout Integer: timeout
3941 * @return Boolean
3942 */
3943 public function lock( $lockName, $method, $timeout = 5 ) {
3944 return true;
3945 }
3946
3947 /**
3948 * Release a lock.
3949 *
3950 * @param string $lockName Name of lock to release
3951 * @param string $method Name of method calling us
3952 *
3953 * @return int Returns 1 if the lock was released, 0 if the lock was not established
3954 * by this thread (in which case the lock is not released), and NULL if the named
3955 * lock did not exist
3956 */
3957 public function unlock( $lockName, $method ) {
3958 return true;
3959 }
3960
3961 /**
3962 * Lock specific tables
3963 *
3964 * @param array $read of tables to lock for read access
3965 * @param array $write of tables to lock for write access
3966 * @param string $method name of caller
3967 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3968 *
3969 * @return bool
3970 */
3971 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3972 return true;
3973 }
3974
3975 /**
3976 * Unlock specific tables
3977 *
3978 * @param string $method the caller
3979 *
3980 * @return bool
3981 */
3982 public function unlockTables( $method ) {
3983 return true;
3984 }
3985
3986 /**
3987 * Delete a table
3988 * @param $tableName string
3989 * @param $fName string
3990 * @return bool|ResultWrapper
3991 * @since 1.18
3992 */
3993 public function dropTable( $tableName, $fName = __METHOD__ ) {
3994 if ( !$this->tableExists( $tableName, $fName ) ) {
3995 return false;
3996 }
3997 $sql = "DROP TABLE " . $this->tableName( $tableName );
3998 if ( $this->cascadingDeletes() ) {
3999 $sql .= " CASCADE";
4000 }
4001 return $this->query( $sql, $fName );
4002 }
4003
4004 /**
4005 * Get search engine class. All subclasses of this need to implement this
4006 * if they wish to use searching.
4007 *
4008 * @return String
4009 */
4010 public function getSearchEngine() {
4011 return 'SearchEngineDummy';
4012 }
4013
4014 /**
4015 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4016 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4017 * because "i" sorts after all numbers.
4018 *
4019 * @return String
4020 */
4021 public function getInfinity() {
4022 return 'infinity';
4023 }
4024
4025 /**
4026 * Encode an expiry time into the DBMS dependent format
4027 *
4028 * @param string $expiry timestamp for expiry, or the 'infinity' string
4029 * @return String
4030 */
4031 public function encodeExpiry( $expiry ) {
4032 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4033 ? $this->getInfinity()
4034 : $this->timestamp( $expiry );
4035 }
4036
4037 /**
4038 * Decode an expiry time into a DBMS independent format
4039 *
4040 * @param string $expiry DB timestamp field value for expiry
4041 * @param $format integer: TS_* constant, defaults to TS_MW
4042 * @return String
4043 */
4044 public function decodeExpiry( $expiry, $format = TS_MW ) {
4045 return ( $expiry == '' || $expiry == $this->getInfinity() )
4046 ? 'infinity'
4047 : wfTimestamp( $format, $expiry );
4048 }
4049
4050 /**
4051 * Allow or deny "big selects" for this session only. This is done by setting
4052 * the sql_big_selects session variable.
4053 *
4054 * This is a MySQL-specific feature.
4055 *
4056 * @param $value Mixed: true for allow, false for deny, or "default" to
4057 * restore the initial value
4058 */
4059 public function setBigSelects( $value = true ) {
4060 // no-op
4061 }
4062
4063 /**
4064 * @since 1.19
4065 */
4066 public function __toString() {
4067 return (string)$this->mConn;
4068 }
4069
4070 /**
4071 * Run a few simple sanity checks
4072 */
4073 public function __destruct() {
4074 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
4075 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4076 }
4077 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
4078 $callers = array();
4079 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
4080 $callers[] = $callbackInfo[1];
4081
4082 }
4083 $callers = implode( ', ', $callers );
4084 trigger_error( "DB transaction callbacks still pending (from $callers)." );
4085 }
4086 }
4087 }