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