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