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