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