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