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