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