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