(bug 27283) SqlBagOStuff breaks PostgreSQL txns
[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 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 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 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 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 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 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 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 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 function setFakeSlaveLag( $lag ) {
397 $this->mFakeSlaveLag = $lag;
398 }
399
400 /**
401 * Make this connection a fake master
402 *
403 * @param $enabled bool
404 */
405 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 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 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 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 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 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 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 function searchableIPs() {
482 return false;
483 }
484
485 /**
486 * Returns true if this database can use functional indexes
487 *
488 * @return bool
489 */
490 function functionalIndexes() {
491 return false;
492 }
493
494 /**
495 * Return the last query that went through DatabaseBase::query()
496 * @return String
497 */
498 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 function doneWrites() {
509 return $this->mDoneWrites;
510 }
511
512 /**
513 * Is a connection to the database open?
514 * @return Boolean
515 */
516 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 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 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 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 function getProperty( $name ) {
571 return $this->$name;
572 }
573
574 /**
575 * @return string
576 */
577 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 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 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 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 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 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 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 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 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1430 if ( is_array( $vars ) ) {
1431 $vars = implode( ',', $vars );
1432 }
1433
1434 $options = (array)$options;
1435
1436 if ( is_array( $table ) ) {
1437 $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1438 ? $options['USE INDEX']
1439 : array();
1440 if ( count( $join_conds ) || count( $useIndex ) ) {
1441 $from = ' FROM ' .
1442 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
1443 } else {
1444 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1445 }
1446 } elseif ( $table != '' ) {
1447 if ( $table[0] == ' ' ) {
1448 $from = ' FROM ' . $table;
1449 } else {
1450 $from = ' FROM ' . $this->tableName( $table );
1451 }
1452 } else {
1453 $from = '';
1454 }
1455
1456 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1457
1458 if ( !empty( $conds ) ) {
1459 if ( is_array( $conds ) ) {
1460 $conds = $this->makeList( $conds, LIST_AND );
1461 }
1462 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1463 } else {
1464 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1465 }
1466
1467 if ( isset( $options['LIMIT'] ) ) {
1468 $sql = $this->limitResult( $sql, $options['LIMIT'],
1469 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1470 }
1471 $sql = "$sql $postLimitTail";
1472
1473 if ( isset( $options['EXPLAIN'] ) ) {
1474 $sql = 'EXPLAIN ' . $sql;
1475 }
1476
1477 return $sql;
1478 }
1479
1480 /**
1481 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1482 * that a single row object is returned. If the query returns no rows,
1483 * false is returned.
1484 *
1485 * @param $table string|array Table name
1486 * @param $vars string|array Field names
1487 * @param $conds array Conditions
1488 * @param $fname string Caller function name
1489 * @param $options string|array Query options
1490 * @param $join_conds array|string Join conditions
1491 *
1492 * @return object|bool
1493 */
1494 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
1495 $options = array(), $join_conds = array() )
1496 {
1497 $options = (array)$options;
1498 $options['LIMIT'] = 1;
1499 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1500
1501 if ( $res === false ) {
1502 return false;
1503 }
1504
1505 if ( !$this->numRows( $res ) ) {
1506 return false;
1507 }
1508
1509 $obj = $this->fetchObject( $res );
1510
1511 return $obj;
1512 }
1513
1514 /**
1515 * Estimate rows in dataset.
1516 *
1517 * MySQL allows you to estimate the number of rows that would be returned
1518 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1519 * index cardinality statistics, and is notoriously inaccurate, especially
1520 * when large numbers of rows have recently been added or deleted.
1521 *
1522 * For DBMSs that don't support fast result size estimation, this function
1523 * will actually perform the SELECT COUNT(*).
1524 *
1525 * Takes the same arguments as DatabaseBase::select().
1526 *
1527 * @param $table String: table name
1528 * @param Array|string $vars : unused
1529 * @param Array|string $conds : filters on the table
1530 * @param $fname String: function name for profiling
1531 * @param $options Array: options for select
1532 * @return Integer: row count
1533 */
1534 public function estimateRowCount( $table, $vars = '*', $conds = '',
1535 $fname = 'DatabaseBase::estimateRowCount', $options = array() )
1536 {
1537 $rows = 0;
1538 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1539
1540 if ( $res ) {
1541 $row = $this->fetchRow( $res );
1542 $rows = ( isset( $row['rowcount'] ) ) ? $row['rowcount'] : 0;
1543 }
1544
1545 return $rows;
1546 }
1547
1548 /**
1549 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1550 * It's only slightly flawed. Don't use for anything important.
1551 *
1552 * @param $sql String A SQL Query
1553 *
1554 * @return string
1555 */
1556 static function generalizeSQL( $sql ) {
1557 # This does the same as the regexp below would do, but in such a way
1558 # as to avoid crashing php on some large strings.
1559 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1560
1561 $sql = str_replace ( "\\\\", '', $sql );
1562 $sql = str_replace ( "\\'", '', $sql );
1563 $sql = str_replace ( "\\\"", '', $sql );
1564 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1565 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1566
1567 # All newlines, tabs, etc replaced by single space
1568 $sql = preg_replace ( '/\s+/', ' ', $sql );
1569
1570 # All numbers => N
1571 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1572
1573 return $sql;
1574 }
1575
1576 /**
1577 * Determines whether a field exists in a table
1578 *
1579 * @param $table String: table name
1580 * @param $field String: filed to check on that table
1581 * @param $fname String: calling function name (optional)
1582 * @return Boolean: whether $table has filed $field
1583 */
1584 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1585 $info = $this->fieldInfo( $table, $field );
1586
1587 return (bool)$info;
1588 }
1589
1590 /**
1591 * Determines whether an index exists
1592 * Usually throws a DBQueryError on failure
1593 * If errors are explicitly ignored, returns NULL on failure
1594 *
1595 * @param $table
1596 * @param $index
1597 * @param $fname string
1598 *
1599 * @return bool|null
1600 */
1601 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1602 $info = $this->indexInfo( $table, $index, $fname );
1603 if ( is_null( $info ) ) {
1604 return null;
1605 } else {
1606 return $info !== false;
1607 }
1608 }
1609
1610 /**
1611 * Query whether a given table exists
1612 *
1613 * @param $table string
1614 * @param $fname string
1615 *
1616 * @return bool
1617 */
1618 function tableExists( $table, $fname = __METHOD__ ) {
1619 $table = $this->tableName( $table );
1620 $old = $this->ignoreErrors( true );
1621 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1622 $this->ignoreErrors( $old );
1623
1624 return (bool)$res;
1625 }
1626
1627 /**
1628 * mysql_field_type() wrapper
1629 * @param $res
1630 * @param $index
1631 * @return string
1632 */
1633 function fieldType( $res, $index ) {
1634 if ( $res instanceof ResultWrapper ) {
1635 $res = $res->result;
1636 }
1637
1638 return mysql_field_type( $res, $index );
1639 }
1640
1641 /**
1642 * Determines if a given index is unique
1643 *
1644 * @param $table string
1645 * @param $index string
1646 *
1647 * @return bool
1648 */
1649 function indexUnique( $table, $index ) {
1650 $indexInfo = $this->indexInfo( $table, $index );
1651
1652 if ( !$indexInfo ) {
1653 return null;
1654 }
1655
1656 return !$indexInfo[0]->Non_unique;
1657 }
1658
1659 /**
1660 * Helper for DatabaseBase::insert().
1661 *
1662 * @param $options array
1663 * @return string
1664 */
1665 function makeInsertOptions( $options ) {
1666 return implode( ' ', $options );
1667 }
1668
1669 /**
1670 * INSERT wrapper, inserts an array into a table.
1671 *
1672 * $a may be either:
1673 *
1674 * - A single associative array. The array keys are the field names, and
1675 * the values are the values to insert. The values are treated as data
1676 * and will be quoted appropriately. If NULL is inserted, this will be
1677 * converted to a database NULL.
1678 * - An array with numeric keys, holding a list of associative arrays.
1679 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1680 * each subarray must be identical to each other, and in the same order.
1681 *
1682 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1683 * returns success.
1684 *
1685 * $options is an array of options, with boolean options encoded as values
1686 * with numeric keys, in the same style as $options in
1687 * DatabaseBase::select(). Supported options are:
1688 *
1689 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1690 * any rows which cause duplicate key errors are not inserted. It's
1691 * possible to determine how many rows were successfully inserted using
1692 * DatabaseBase::affectedRows().
1693 *
1694 * @param $table String Table name. This will be passed through
1695 * DatabaseBase::tableName().
1696 * @param $a Array of rows to insert
1697 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1698 * @param $options Array of options
1699 *
1700 * @return bool
1701 */
1702 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1703 # No rows to insert, easy just return now
1704 if ( !count( $a ) ) {
1705 return true;
1706 }
1707
1708 $table = $this->tableName( $table );
1709
1710 if ( !is_array( $options ) ) {
1711 $options = array( $options );
1712 }
1713
1714 $options = $this->makeInsertOptions( $options );
1715
1716 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1717 $multi = true;
1718 $keys = array_keys( $a[0] );
1719 } else {
1720 $multi = false;
1721 $keys = array_keys( $a );
1722 }
1723
1724 $sql = 'INSERT ' . $options .
1725 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1726
1727 if ( $multi ) {
1728 $first = true;
1729 foreach ( $a as $row ) {
1730 if ( $first ) {
1731 $first = false;
1732 } else {
1733 $sql .= ',';
1734 }
1735 $sql .= '(' . $this->makeList( $row ) . ')';
1736 }
1737 } else {
1738 $sql .= '(' . $this->makeList( $a ) . ')';
1739 }
1740
1741 return (bool)$this->query( $sql, $fname );
1742 }
1743
1744 /**
1745 * Make UPDATE options for the DatabaseBase::update function
1746 *
1747 * @param $options Array: The options passed to DatabaseBase::update
1748 * @return string
1749 */
1750 function makeUpdateOptions( $options ) {
1751 if ( !is_array( $options ) ) {
1752 $options = array( $options );
1753 }
1754
1755 $opts = array();
1756
1757 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1758 $opts[] = $this->lowPriorityOption();
1759 }
1760
1761 if ( in_array( 'IGNORE', $options ) ) {
1762 $opts[] = 'IGNORE';
1763 }
1764
1765 return implode( ' ', $opts );
1766 }
1767
1768 /**
1769 * UPDATE wrapper. Takes a condition array and a SET array.
1770 *
1771 * @param $table String name of the table to UPDATE. This will be passed through
1772 * DatabaseBase::tableName().
1773 *
1774 * @param $values Array: An array of values to SET. For each array element,
1775 * the key gives the field name, and the value gives the data
1776 * to set that field to. The data will be quoted by
1777 * DatabaseBase::addQuotes().
1778 *
1779 * @param $conds Array: An array of conditions (WHERE). See
1780 * DatabaseBase::select() for the details of the format of
1781 * condition arrays. Use '*' to update all rows.
1782 *
1783 * @param $fname String: The function name of the caller (from __METHOD__),
1784 * for logging and profiling.
1785 *
1786 * @param $options Array: An array of UPDATE options, can be:
1787 * - IGNORE: Ignore unique key conflicts
1788 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1789 * @return Boolean
1790 */
1791 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1792 $table = $this->tableName( $table );
1793 $opts = $this->makeUpdateOptions( $options );
1794 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1795
1796 if ( $conds !== array() && $conds !== '*' ) {
1797 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1798 }
1799
1800 return $this->query( $sql, $fname );
1801 }
1802
1803 /**
1804 * Makes an encoded list of strings from an array
1805 * @param $a Array containing the data
1806 * @param $mode int Constant
1807 * - LIST_COMMA: comma separated, no field names
1808 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1809 * the documentation for $conds in DatabaseBase::select().
1810 * - LIST_OR: ORed WHERE clause (without the WHERE)
1811 * - LIST_SET: comma separated with field names, like a SET clause
1812 * - LIST_NAMES: comma separated field names
1813 *
1814 * @return string
1815 */
1816 function makeList( $a, $mode = LIST_COMMA ) {
1817 if ( !is_array( $a ) ) {
1818 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1819 }
1820
1821 $first = true;
1822 $list = '';
1823
1824 foreach ( $a as $field => $value ) {
1825 if ( !$first ) {
1826 if ( $mode == LIST_AND ) {
1827 $list .= ' AND ';
1828 } elseif ( $mode == LIST_OR ) {
1829 $list .= ' OR ';
1830 } else {
1831 $list .= ',';
1832 }
1833 } else {
1834 $first = false;
1835 }
1836
1837 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1838 $list .= "($value)";
1839 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1840 $list .= "$value";
1841 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1842 if ( count( $value ) == 0 ) {
1843 throw new MWException( __METHOD__ . ': empty input' );
1844 } elseif ( count( $value ) == 1 ) {
1845 // Special-case single values, as IN isn't terribly efficient
1846 // Don't necessarily assume the single key is 0; we don't
1847 // enforce linear numeric ordering on other arrays here.
1848 $value = array_values( $value );
1849 $list .= $field . " = " . $this->addQuotes( $value[0] );
1850 } else {
1851 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1852 }
1853 } elseif ( $value === null ) {
1854 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1855 $list .= "$field IS ";
1856 } elseif ( $mode == LIST_SET ) {
1857 $list .= "$field = ";
1858 }
1859 $list .= 'NULL';
1860 } else {
1861 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1862 $list .= "$field = ";
1863 }
1864 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1865 }
1866 }
1867
1868 return $list;
1869 }
1870
1871 /**
1872 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1873 * The keys on each level may be either integers or strings.
1874 *
1875 * @param $data Array: organized as 2-d
1876 * array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1877 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1878 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1879 * @return Mixed: string SQL fragment, or false if no items in array.
1880 */
1881 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1882 $conds = array();
1883
1884 foreach ( $data as $base => $sub ) {
1885 if ( count( $sub ) ) {
1886 $conds[] = $this->makeList(
1887 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1888 LIST_AND );
1889 }
1890 }
1891
1892 if ( $conds ) {
1893 return $this->makeList( $conds, LIST_OR );
1894 } else {
1895 // Nothing to search for...
1896 return false;
1897 }
1898 }
1899
1900 /**
1901 * Bitwise operations
1902 */
1903
1904 /**
1905 * @param $field
1906 * @return string
1907 */
1908 function bitNot( $field ) {
1909 return "(~$field)";
1910 }
1911
1912 /**
1913 * @param $fieldLeft
1914 * @param $fieldRight
1915 * @return string
1916 */
1917 function bitAnd( $fieldLeft, $fieldRight ) {
1918 return "($fieldLeft & $fieldRight)";
1919 }
1920
1921 /**
1922 * @param $fieldLeft
1923 * @param $fieldRight
1924 * @return string
1925 */
1926 function bitOr( $fieldLeft, $fieldRight ) {
1927 return "($fieldLeft | $fieldRight)";
1928 }
1929
1930 /**
1931 * Change the current database
1932 *
1933 * @todo Explain what exactly will fail if this is not overridden.
1934 *
1935 * @param $db
1936 *
1937 * @return bool Success or failure
1938 */
1939 function selectDB( $db ) {
1940 # Stub. Shouldn't cause serious problems if it's not overridden, but
1941 # if your database engine supports a concept similar to MySQL's
1942 # databases you may as well.
1943 $this->mDBname = $db;
1944 return true;
1945 }
1946
1947 /**
1948 * Get the current DB name
1949 */
1950 function getDBname() {
1951 return $this->mDBname;
1952 }
1953
1954 /**
1955 * Get the server hostname or IP address
1956 */
1957 function getServer() {
1958 return $this->mServer;
1959 }
1960
1961 /**
1962 * Format a table name ready for use in constructing an SQL query
1963 *
1964 * This does two important things: it quotes the table names to clean them up,
1965 * and it adds a table prefix if only given a table name with no quotes.
1966 *
1967 * All functions of this object which require a table name call this function
1968 * themselves. Pass the canonical name to such functions. This is only needed
1969 * when calling query() directly.
1970 *
1971 * @param $name String: database table name
1972 * @param $format String One of:
1973 * quoted - Automatically pass the table name through addIdentifierQuotes()
1974 * so that it can be used in a query.
1975 * raw - Do not add identifier quotes to the table name
1976 * @return String: full database name
1977 */
1978 function tableName( $name, $format = 'quoted' ) {
1979 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1980 # Skip the entire process when we have a string quoted on both ends.
1981 # Note that we check the end so that we will still quote any use of
1982 # use of `database`.table. But won't break things if someone wants
1983 # to query a database table with a dot in the name.
1984 if ( $this->isQuotedIdentifier( $name ) ) {
1985 return $name;
1986 }
1987
1988 # Lets test for any bits of text that should never show up in a table
1989 # name. Basically anything like JOIN or ON which are actually part of
1990 # SQL queries, but may end up inside of the table value to combine
1991 # sql. Such as how the API is doing.
1992 # Note that we use a whitespace test rather than a \b test to avoid
1993 # any remote case where a word like on may be inside of a table name
1994 # surrounded by symbols which may be considered word breaks.
1995 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1996 return $name;
1997 }
1998
1999 # Split database and table into proper variables.
2000 # We reverse the explode so that database.table and table both output
2001 # the correct table.
2002 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
2003 if ( isset( $dbDetails[1] ) ) {
2004 list( $table, $database ) = $dbDetails;
2005 } else {
2006 list( $table ) = $dbDetails;
2007 }
2008 $prefix = $this->mTablePrefix; # Default prefix
2009
2010 # A database name has been specified in input. We don't want any
2011 # prefixes added.
2012 if ( isset( $database ) ) {
2013 $prefix = '';
2014 }
2015
2016 # Note that we use the long format because php will complain in in_array if
2017 # the input is not an array, and will complain in is_array if it is not set.
2018 if ( !isset( $database ) # Don't use shared database if pre selected.
2019 && isset( $wgSharedDB ) # We have a shared database
2020 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
2021 && isset( $wgSharedTables )
2022 && is_array( $wgSharedTables )
2023 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
2024 $database = $wgSharedDB;
2025 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
2026 }
2027
2028 # Quote the $database and $table and apply the prefix if not quoted.
2029 if ( isset( $database ) ) {
2030 $database = ( $format == 'quoted' || $this->isQuotedIdentifier( $database ) ? $database : $this->addIdentifierQuotes( $database ) );
2031 }
2032
2033 $table = "{$prefix}{$table}";
2034 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $table ) ) {
2035 $table = $this->addIdentifierQuotes( "{$table}" );
2036 }
2037
2038 # Merge our database and table into our final table name.
2039 $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
2040
2041 return $tableName;
2042 }
2043
2044 /**
2045 * Fetch a number of table names into an array
2046 * This is handy when you need to construct SQL for joins
2047 *
2048 * Example:
2049 * extract($dbr->tableNames('user','watchlist'));
2050 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2051 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2052 *
2053 * @return array
2054 */
2055 public function tableNames() {
2056 $inArray = func_get_args();
2057 $retVal = array();
2058
2059 foreach ( $inArray as $name ) {
2060 $retVal[$name] = $this->tableName( $name );
2061 }
2062
2063 return $retVal;
2064 }
2065
2066 /**
2067 * Fetch a number of table names into an zero-indexed numerical array
2068 * This is handy when you need to construct SQL for joins
2069 *
2070 * Example:
2071 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
2072 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2073 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2074 *
2075 * @return array
2076 */
2077 public function tableNamesN() {
2078 $inArray = func_get_args();
2079 $retVal = array();
2080
2081 foreach ( $inArray as $name ) {
2082 $retVal[] = $this->tableName( $name );
2083 }
2084
2085 return $retVal;
2086 }
2087
2088 /**
2089 * Get an aliased table name
2090 * e.g. tableName AS newTableName
2091 *
2092 * @param $name string Table name, see tableName()
2093 * @param $alias string|bool Alias (optional)
2094 * @return string SQL name for aliased table. Will not alias a table to its own name
2095 */
2096 public function tableNameWithAlias( $name, $alias = false ) {
2097 if ( !$alias || $alias == $name ) {
2098 return $this->tableName( $name );
2099 } else {
2100 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2101 }
2102 }
2103
2104 /**
2105 * Gets an array of aliased table names
2106 *
2107 * @param $tables array( [alias] => table )
2108 * @return array of strings, see tableNameWithAlias()
2109 */
2110 public function tableNamesWithAlias( $tables ) {
2111 $retval = array();
2112 foreach ( $tables as $alias => $table ) {
2113 if ( is_numeric( $alias ) ) {
2114 $alias = $table;
2115 }
2116 $retval[] = $this->tableNameWithAlias( $table, $alias );
2117 }
2118 return $retval;
2119 }
2120
2121 /**
2122 * Get the aliased table name clause for a FROM clause
2123 * which might have a JOIN and/or USE INDEX clause
2124 *
2125 * @param $tables array ( [alias] => table )
2126 * @param $use_index array Same as for select()
2127 * @param $join_conds array Same as for select()
2128 * @return string
2129 */
2130 protected function tableNamesWithUseIndexOrJOIN(
2131 $tables, $use_index = array(), $join_conds = array()
2132 ) {
2133 $ret = array();
2134 $retJOIN = array();
2135 $use_index = (array)$use_index;
2136 $join_conds = (array)$join_conds;
2137
2138 foreach ( $tables as $alias => $table ) {
2139 if ( !is_string( $alias ) ) {
2140 // No alias? Set it equal to the table name
2141 $alias = $table;
2142 }
2143 // Is there a JOIN clause for this table?
2144 if ( isset( $join_conds[$alias] ) ) {
2145 list( $joinType, $conds ) = $join_conds[$alias];
2146 $tableClause = $joinType;
2147 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2148 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2149 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2150 if ( $use != '' ) {
2151 $tableClause .= ' ' . $use;
2152 }
2153 }
2154 $on = $this->makeList( (array)$conds, LIST_AND );
2155 if ( $on != '' ) {
2156 $tableClause .= ' ON (' . $on . ')';
2157 }
2158
2159 $retJOIN[] = $tableClause;
2160 // Is there an INDEX clause for this table?
2161 } elseif ( isset( $use_index[$alias] ) ) {
2162 $tableClause = $this->tableNameWithAlias( $table, $alias );
2163 $tableClause .= ' ' . $this->useIndexClause(
2164 implode( ',', (array)$use_index[$alias] ) );
2165
2166 $ret[] = $tableClause;
2167 } else {
2168 $tableClause = $this->tableNameWithAlias( $table, $alias );
2169
2170 $ret[] = $tableClause;
2171 }
2172 }
2173
2174 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2175 $straightJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2176 $otherJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2177
2178 // Compile our final table clause
2179 return implode( ' ', array( $straightJoins, $otherJoins ) );
2180 }
2181
2182 /**
2183 * Get the name of an index in a given table
2184 *
2185 * @param $index
2186 *
2187 * @return string
2188 */
2189 function indexName( $index ) {
2190 // Backwards-compatibility hack
2191 $renamed = array(
2192 'ar_usertext_timestamp' => 'usertext_timestamp',
2193 'un_user_id' => 'user_id',
2194 'un_user_ip' => 'user_ip',
2195 );
2196
2197 if ( isset( $renamed[$index] ) ) {
2198 return $renamed[$index];
2199 } else {
2200 return $index;
2201 }
2202 }
2203
2204 /**
2205 * If it's a string, adds quotes and backslashes
2206 * Otherwise returns as-is
2207 *
2208 * @param $s string
2209 *
2210 * @return string
2211 */
2212 function addQuotes( $s ) {
2213 if ( $s === null ) {
2214 return 'NULL';
2215 } else {
2216 # This will also quote numeric values. This should be harmless,
2217 # and protects against weird problems that occur when they really
2218 # _are_ strings such as article titles and string->number->string
2219 # conversion is not 1:1.
2220 return "'" . $this->strencode( $s ) . "'";
2221 }
2222 }
2223
2224 /**
2225 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2226 * MySQL uses `backticks` while basically everything else uses double quotes.
2227 * Since MySQL is the odd one out here the double quotes are our generic
2228 * and we implement backticks in DatabaseMysql.
2229 *
2230 * @param $s string
2231 *
2232 * @return string
2233 */
2234 public function addIdentifierQuotes( $s ) {
2235 return '"' . str_replace( '"', '""', $s ) . '"';
2236 }
2237
2238 /**
2239 * Returns if the given identifier looks quoted or not according to
2240 * the database convention for quoting identifiers .
2241 *
2242 * @param $name string
2243 *
2244 * @return boolean
2245 */
2246 public function isQuotedIdentifier( $name ) {
2247 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2248 }
2249
2250 /**
2251 * Backwards compatibility, identifier quoting originated in DatabasePostgres
2252 * which used quote_ident which does not follow our naming conventions
2253 * was renamed to addIdentifierQuotes.
2254 * @deprecated since 1.18 use addIdentifierQuotes
2255 *
2256 * @param $s string
2257 *
2258 * @return string
2259 */
2260 function quote_ident( $s ) {
2261 wfDeprecated( __METHOD__, '1.18' );
2262 return $this->addIdentifierQuotes( $s );
2263 }
2264
2265 /**
2266 * Escape string for safe LIKE usage.
2267 * WARNING: you should almost never use this function directly,
2268 * instead use buildLike() that escapes everything automatically
2269 * @deprecated since 1.17, warnings in 1.17, removed in ???
2270 *
2271 * @param $s string
2272 *
2273 * @return string
2274 */
2275 public function escapeLike( $s ) {
2276 wfDeprecated( __METHOD__, '1.17' );
2277 return $this->escapeLikeInternal( $s );
2278 }
2279
2280 /**
2281 * @param $s string
2282 * @return string
2283 */
2284 protected function escapeLikeInternal( $s ) {
2285 $s = str_replace( '\\', '\\\\', $s );
2286 $s = $this->strencode( $s );
2287 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2288
2289 return $s;
2290 }
2291
2292 /**
2293 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2294 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2295 * Alternatively, the function could be provided with an array of aforementioned parameters.
2296 *
2297 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2298 * for subpages of 'My page title'.
2299 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2300 *
2301 * @since 1.16
2302 * @return String: fully built LIKE statement
2303 */
2304 function buildLike() {
2305 $params = func_get_args();
2306
2307 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2308 $params = $params[0];
2309 }
2310
2311 $s = '';
2312
2313 foreach ( $params as $value ) {
2314 if ( $value instanceof LikeMatch ) {
2315 $s .= $value->toString();
2316 } else {
2317 $s .= $this->escapeLikeInternal( $value );
2318 }
2319 }
2320
2321 return " LIKE '" . $s . "' ";
2322 }
2323
2324 /**
2325 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2326 *
2327 * @return LikeMatch
2328 */
2329 function anyChar() {
2330 return new LikeMatch( '_' );
2331 }
2332
2333 /**
2334 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2335 *
2336 * @return LikeMatch
2337 */
2338 function anyString() {
2339 return new LikeMatch( '%' );
2340 }
2341
2342 /**
2343 * Returns an appropriately quoted sequence value for inserting a new row.
2344 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2345 * subclass will return an integer, and save the value for insertId()
2346 *
2347 * Any implementation of this function should *not* involve reusing
2348 * sequence numbers created for rolled-back transactions.
2349 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2350 * @param $seqName string
2351 * @return null
2352 */
2353 function nextSequenceValue( $seqName ) {
2354 return null;
2355 }
2356
2357 /**
2358 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2359 * is only needed because a) MySQL must be as efficient as possible due to
2360 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2361 * which index to pick. Anyway, other databases might have different
2362 * indexes on a given table. So don't bother overriding this unless you're
2363 * MySQL.
2364 * @param $index
2365 * @return string
2366 */
2367 function useIndexClause( $index ) {
2368 return '';
2369 }
2370
2371 /**
2372 * REPLACE query wrapper.
2373 *
2374 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2375 * except that when there is a duplicate key error, the old row is deleted
2376 * and the new row is inserted in its place.
2377 *
2378 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2379 * perform the delete, we need to know what the unique indexes are so that
2380 * we know how to find the conflicting rows.
2381 *
2382 * It may be more efficient to leave off unique indexes which are unlikely
2383 * to collide. However if you do this, you run the risk of encountering
2384 * errors which wouldn't have occurred in MySQL.
2385 *
2386 * @param $table String: The table to replace the row(s) in.
2387 * @param $rows array Can be either a single row to insert, or multiple rows,
2388 * in the same format as for DatabaseBase::insert()
2389 * @param $uniqueIndexes array is an array of indexes. Each element may be either
2390 * a field name or an array of field names
2391 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2392 */
2393 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
2394 $quotedTable = $this->tableName( $table );
2395
2396 if ( count( $rows ) == 0 ) {
2397 return;
2398 }
2399
2400 # Single row case
2401 if ( !is_array( reset( $rows ) ) ) {
2402 $rows = array( $rows );
2403 }
2404
2405 foreach( $rows as $row ) {
2406 # Delete rows which collide
2407 if ( $uniqueIndexes ) {
2408 $sql = "DELETE FROM $quotedTable WHERE ";
2409 $first = true;
2410 foreach ( $uniqueIndexes as $index ) {
2411 if ( $first ) {
2412 $first = false;
2413 $sql .= '( ';
2414 } else {
2415 $sql .= ' ) OR ( ';
2416 }
2417 if ( is_array( $index ) ) {
2418 $first2 = true;
2419 foreach ( $index as $col ) {
2420 if ( $first2 ) {
2421 $first2 = false;
2422 } else {
2423 $sql .= ' AND ';
2424 }
2425 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2426 }
2427 } else {
2428 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2429 }
2430 }
2431 $sql .= ' )';
2432 $this->query( $sql, $fname );
2433 }
2434
2435 # Now insert the row
2436 $this->insert( $table, $row );
2437 }
2438 }
2439
2440 /**
2441 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2442 * statement.
2443 *
2444 * @param $table string Table name
2445 * @param $rows array Rows to insert
2446 * @param $fname string Caller function name
2447 *
2448 * @return ResultWrapper
2449 */
2450 protected function nativeReplace( $table, $rows, $fname ) {
2451 $table = $this->tableName( $table );
2452
2453 # Single row case
2454 if ( !is_array( reset( $rows ) ) ) {
2455 $rows = array( $rows );
2456 }
2457
2458 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2459 $first = true;
2460
2461 foreach ( $rows as $row ) {
2462 if ( $first ) {
2463 $first = false;
2464 } else {
2465 $sql .= ',';
2466 }
2467
2468 $sql .= '(' . $this->makeList( $row ) . ')';
2469 }
2470
2471 return $this->query( $sql, $fname );
2472 }
2473
2474 /**
2475 * DELETE where the condition is a join.
2476 *
2477 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2478 * we use sub-selects
2479 *
2480 * For safety, an empty $conds will not delete everything. If you want to
2481 * delete all rows where the join condition matches, set $conds='*'.
2482 *
2483 * DO NOT put the join condition in $conds.
2484 *
2485 * @param $delTable String: The table to delete from.
2486 * @param $joinTable String: The other table.
2487 * @param $delVar String: The variable to join on, in the first table.
2488 * @param $joinVar String: The variable to join on, in the second table.
2489 * @param $conds Array: Condition array of field names mapped to variables,
2490 * ANDed together in the WHERE clause
2491 * @param $fname String: Calling function name (use __METHOD__) for
2492 * logs/profiling
2493 */
2494 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2495 $fname = 'DatabaseBase::deleteJoin' )
2496 {
2497 if ( !$conds ) {
2498 throw new DBUnexpectedError( $this,
2499 'DatabaseBase::deleteJoin() called with empty $conds' );
2500 }
2501
2502 $delTable = $this->tableName( $delTable );
2503 $joinTable = $this->tableName( $joinTable );
2504 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2505 if ( $conds != '*' ) {
2506 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2507 }
2508 $sql .= ')';
2509
2510 $this->query( $sql, $fname );
2511 }
2512
2513 /**
2514 * Returns the size of a text field, or -1 for "unlimited"
2515 *
2516 * @param $table string
2517 * @param $field string
2518 *
2519 * @return int
2520 */
2521 function textFieldSize( $table, $field ) {
2522 $table = $this->tableName( $table );
2523 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2524 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2525 $row = $this->fetchObject( $res );
2526
2527 $m = array();
2528
2529 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2530 $size = $m[1];
2531 } else {
2532 $size = -1;
2533 }
2534
2535 return $size;
2536 }
2537
2538 /**
2539 * A string to insert into queries to show that they're low-priority, like
2540 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2541 * string and nothing bad should happen.
2542 *
2543 * @return string Returns the text of the low priority option if it is
2544 * supported, or a blank string otherwise
2545 */
2546 function lowPriorityOption() {
2547 return '';
2548 }
2549
2550 /**
2551 * DELETE query wrapper.
2552 *
2553 * @param $table Array Table name
2554 * @param $conds String|Array of conditions. See $conds in DatabaseBase::select() for
2555 * the format. Use $conds == "*" to delete all rows
2556 * @param $fname String name of the calling function
2557 *
2558 * @return bool
2559 */
2560 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2561 if ( !$conds ) {
2562 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2563 }
2564
2565 $table = $this->tableName( $table );
2566 $sql = "DELETE FROM $table";
2567
2568 if ( $conds != '*' ) {
2569 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
2570 }
2571
2572 return $this->query( $sql, $fname );
2573 }
2574
2575 /**
2576 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2577 * into another table.
2578 *
2579 * @param $destTable string The table name to insert into
2580 * @param $srcTable string|array May be either a table name, or an array of table names
2581 * to include in a join.
2582 *
2583 * @param $varMap array must be an associative array of the form
2584 * array( 'dest1' => 'source1', ...). Source items may be literals
2585 * rather than field names, but strings should be quoted with
2586 * DatabaseBase::addQuotes()
2587 *
2588 * @param $conds array Condition array. See $conds in DatabaseBase::select() for
2589 * the details of the format of condition arrays. May be "*" to copy the
2590 * whole table.
2591 *
2592 * @param $fname string The function name of the caller, from __METHOD__
2593 *
2594 * @param $insertOptions array Options for the INSERT part of the query, see
2595 * DatabaseBase::insert() for details.
2596 * @param $selectOptions array Options for the SELECT part of the query, see
2597 * DatabaseBase::select() for details.
2598 *
2599 * @return ResultWrapper
2600 */
2601 function insertSelect( $destTable, $srcTable, $varMap, $conds,
2602 $fname = 'DatabaseBase::insertSelect',
2603 $insertOptions = array(), $selectOptions = array() )
2604 {
2605 $destTable = $this->tableName( $destTable );
2606
2607 if ( is_array( $insertOptions ) ) {
2608 $insertOptions = implode( ' ', $insertOptions );
2609 }
2610
2611 if ( !is_array( $selectOptions ) ) {
2612 $selectOptions = array( $selectOptions );
2613 }
2614
2615 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2616
2617 if ( is_array( $srcTable ) ) {
2618 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2619 } else {
2620 $srcTable = $this->tableName( $srcTable );
2621 }
2622
2623 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2624 " SELECT $startOpts " . implode( ',', $varMap ) .
2625 " FROM $srcTable $useIndex ";
2626
2627 if ( $conds != '*' ) {
2628 if ( is_array( $conds ) ) {
2629 $conds = $this->makeList( $conds, LIST_AND );
2630 }
2631 $sql .= " WHERE $conds";
2632 }
2633
2634 $sql .= " $tailOpts";
2635
2636 return $this->query( $sql, $fname );
2637 }
2638
2639 /**
2640 * Construct a LIMIT query with optional offset. This is used for query
2641 * pages. The SQL should be adjusted so that only the first $limit rows
2642 * are returned. If $offset is provided as well, then the first $offset
2643 * rows should be discarded, and the next $limit rows should be returned.
2644 * If the result of the query is not ordered, then the rows to be returned
2645 * are theoretically arbitrary.
2646 *
2647 * $sql is expected to be a SELECT, if that makes a difference. For
2648 * UPDATE, limitResultForUpdate should be used.
2649 *
2650 * The version provided by default works in MySQL and SQLite. It will very
2651 * likely need to be overridden for most other DBMSes.
2652 *
2653 * @param $sql String SQL query we will append the limit too
2654 * @param $limit Integer the SQL limit
2655 * @param $offset Integer|bool the SQL offset (default false)
2656 *
2657 * @return string
2658 */
2659 function limitResult( $sql, $limit, $offset = false ) {
2660 if ( !is_numeric( $limit ) ) {
2661 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2662 }
2663
2664 return "$sql LIMIT "
2665 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2666 . "{$limit} ";
2667 }
2668
2669 /**
2670 * @param $sql
2671 * @param $num
2672 * @return string
2673 */
2674 function limitResultForUpdate( $sql, $num ) {
2675 return $this->limitResult( $sql, $num, 0 );
2676 }
2677
2678 /**
2679 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2680 * within the UNION construct.
2681 * @return Boolean
2682 */
2683 function unionSupportsOrderAndLimit() {
2684 return true; // True for almost every DB supported
2685 }
2686
2687 /**
2688 * Construct a UNION query
2689 * This is used for providing overload point for other DB abstractions
2690 * not compatible with the MySQL syntax.
2691 * @param $sqls Array: SQL statements to combine
2692 * @param $all Boolean: use UNION ALL
2693 * @return String: SQL fragment
2694 */
2695 function unionQueries( $sqls, $all ) {
2696 $glue = $all ? ') UNION ALL (' : ') UNION (';
2697 return '(' . implode( $glue, $sqls ) . ')';
2698 }
2699
2700 /**
2701 * Returns an SQL expression for a simple conditional. This doesn't need
2702 * to be overridden unless CASE isn't supported in your DBMS.
2703 *
2704 * @param $cond String: SQL expression which will result in a boolean value
2705 * @param $trueVal String: SQL expression to return if true
2706 * @param $falseVal String: SQL expression to return if false
2707 * @return String: SQL fragment
2708 */
2709 function conditional( $cond, $trueVal, $falseVal ) {
2710 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2711 }
2712
2713 /**
2714 * Returns a comand for str_replace function in SQL query.
2715 * Uses REPLACE() in MySQL
2716 *
2717 * @param $orig String: column to modify
2718 * @param $old String: column to seek
2719 * @param $new String: column to replace with
2720 *
2721 * @return string
2722 */
2723 function strreplace( $orig, $old, $new ) {
2724 return "REPLACE({$orig}, {$old}, {$new})";
2725 }
2726
2727 /**
2728 * Determines how long the server has been up
2729 * STUB
2730 *
2731 * @return int
2732 */
2733 function getServerUptime() {
2734 return 0;
2735 }
2736
2737 /**
2738 * Determines if the last failure was due to a deadlock
2739 * STUB
2740 *
2741 * @return bool
2742 */
2743 function wasDeadlock() {
2744 return false;
2745 }
2746
2747 /**
2748 * Determines if the last failure was due to a lock timeout
2749 * STUB
2750 *
2751 * @return bool
2752 */
2753 function wasLockTimeout() {
2754 return false;
2755 }
2756
2757 /**
2758 * Determines if the last query error was something that should be dealt
2759 * with by pinging the connection and reissuing the query.
2760 * STUB
2761 *
2762 * @return bool
2763 */
2764 function wasErrorReissuable() {
2765 return false;
2766 }
2767
2768 /**
2769 * Determines if the last failure was due to the database being read-only.
2770 * STUB
2771 *
2772 * @return bool
2773 */
2774 function wasReadOnlyError() {
2775 return false;
2776 }
2777
2778 /**
2779 * Perform a deadlock-prone transaction.
2780 *
2781 * This function invokes a callback function to perform a set of write
2782 * queries. If a deadlock occurs during the processing, the transaction
2783 * will be rolled back and the callback function will be called again.
2784 *
2785 * Usage:
2786 * $dbw->deadlockLoop( callback, ... );
2787 *
2788 * Extra arguments are passed through to the specified callback function.
2789 *
2790 * Returns whatever the callback function returned on its successful,
2791 * iteration, or false on error, for example if the retry limit was
2792 * reached.
2793 *
2794 * @return bool
2795 */
2796 function deadlockLoop() {
2797
2798 $this->begin( __METHOD__ );
2799 $args = func_get_args();
2800 $function = array_shift( $args );
2801 $oldIgnore = $this->ignoreErrors( true );
2802 $tries = DEADLOCK_TRIES;
2803
2804 if ( is_array( $function ) ) {
2805 $fname = $function[0];
2806 } else {
2807 $fname = $function;
2808 }
2809
2810 do {
2811 $retVal = call_user_func_array( $function, $args );
2812 $error = $this->lastError();
2813 $errno = $this->lastErrno();
2814 $sql = $this->lastQuery();
2815
2816 if ( $errno ) {
2817 if ( $this->wasDeadlock() ) {
2818 # Retry
2819 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
2820 } else {
2821 $this->reportQueryError( $error, $errno, $sql, $fname );
2822 }
2823 }
2824 } while ( $this->wasDeadlock() && --$tries > 0 );
2825
2826 $this->ignoreErrors( $oldIgnore );
2827
2828 if ( $tries <= 0 ) {
2829 $this->rollback( __METHOD__ );
2830 $this->reportQueryError( $error, $errno, $sql, $fname );
2831 return false;
2832 } else {
2833 $this->commit( __METHOD__ );
2834 return $retVal;
2835 }
2836 }
2837
2838 /**
2839 * Wait for the slave to catch up to a given master position.
2840 *
2841 * @param $pos DBMasterPos object
2842 * @param $timeout Integer: the maximum number of seconds to wait for
2843 * synchronisation
2844 *
2845 * @return integer: zero if the slave was past that position already,
2846 * greater than zero if we waited for some period of time, less than
2847 * zero if we timed out.
2848 */
2849 function masterPosWait( DBMasterPos $pos, $timeout ) {
2850 wfProfileIn( __METHOD__ );
2851
2852 if ( !is_null( $this->mFakeSlaveLag ) ) {
2853 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
2854
2855 if ( $wait > $timeout * 1e6 ) {
2856 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2857 wfProfileOut( __METHOD__ );
2858 return -1;
2859 } elseif ( $wait > 0 ) {
2860 wfDebug( "Fake slave waiting $wait us\n" );
2861 usleep( $wait );
2862 wfProfileOut( __METHOD__ );
2863 return 1;
2864 } else {
2865 wfDebug( "Fake slave up to date ($wait us)\n" );
2866 wfProfileOut( __METHOD__ );
2867 return 0;
2868 }
2869 }
2870
2871 wfProfileOut( __METHOD__ );
2872
2873 # Real waits are implemented in the subclass.
2874 return 0;
2875 }
2876
2877 /**
2878 * Get the replication position of this slave
2879 *
2880 * @return DBMasterPos, or false if this is not a slave.
2881 */
2882 function getSlavePos() {
2883 if ( !is_null( $this->mFakeSlaveLag ) ) {
2884 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
2885 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
2886 return $pos;
2887 } else {
2888 # Stub
2889 return false;
2890 }
2891 }
2892
2893 /**
2894 * Get the position of this master
2895 *
2896 * @return DBMasterPos, or false if this is not a master
2897 */
2898 function getMasterPos() {
2899 if ( $this->mFakeMaster ) {
2900 return new MySQLMasterPos( 'fake', microtime( true ) );
2901 } else {
2902 return false;
2903 }
2904 }
2905
2906 /**
2907 * Begin a transaction
2908 *
2909 * @param $fname string
2910 */
2911 function begin( $fname = 'DatabaseBase::begin' ) {
2912 $this->query( 'BEGIN', $fname );
2913 $this->mTrxLevel = 1;
2914 }
2915
2916 /**
2917 * End a transaction
2918 *
2919 * @param $fname string
2920 */
2921 function commit( $fname = 'DatabaseBase::commit' ) {
2922 if ( $this->mTrxLevel ) {
2923 $this->query( 'COMMIT', $fname );
2924 $this->mTrxLevel = 0;
2925 }
2926 }
2927
2928 /**
2929 * Rollback a transaction.
2930 * No-op on non-transactional databases.
2931 *
2932 * @param $fname string
2933 */
2934 function rollback( $fname = 'DatabaseBase::rollback' ) {
2935 if ( $this->mTrxLevel ) {
2936 $this->query( 'ROLLBACK', $fname, true );
2937 $this->mTrxLevel = 0;
2938 }
2939 }
2940
2941 /**
2942 * Creates a new table with structure copied from existing table
2943 * Note that unlike most database abstraction functions, this function does not
2944 * automatically append database prefix, because it works at a lower
2945 * abstraction level.
2946 * The table names passed to this function shall not be quoted (this
2947 * function calls addIdentifierQuotes when needed).
2948 *
2949 * @param $oldName String: name of table whose structure should be copied
2950 * @param $newName String: name of table to be created
2951 * @param $temporary Boolean: whether the new table should be temporary
2952 * @param $fname String: calling function name
2953 * @return Boolean: true if operation was successful
2954 */
2955 function duplicateTableStructure( $oldName, $newName, $temporary = false,
2956 $fname = 'DatabaseBase::duplicateTableStructure' )
2957 {
2958 throw new MWException(
2959 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2960 }
2961
2962 /**
2963 * List all tables on the database
2964 *
2965 * @param $prefix string Only show tables with this prefix, e.g. mw_
2966 * @param $fname String: calling function name
2967 */
2968 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2969 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2970 }
2971
2972 /**
2973 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2974 * to the format used for inserting into timestamp fields in this DBMS.
2975 *
2976 * The result is unquoted, and needs to be passed through addQuotes()
2977 * before it can be included in raw SQL.
2978 *
2979 * @param $ts string|int
2980 *
2981 * @return string
2982 */
2983 function timestamp( $ts = 0 ) {
2984 return wfTimestamp( TS_MW, $ts );
2985 }
2986
2987 /**
2988 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2989 * to the format used for inserting into timestamp fields in this DBMS. If
2990 * NULL is input, it is passed through, allowing NULL values to be inserted
2991 * into timestamp fields.
2992 *
2993 * The result is unquoted, and needs to be passed through addQuotes()
2994 * before it can be included in raw SQL.
2995 *
2996 * @param $ts string|int
2997 *
2998 * @return string
2999 */
3000 function timestampOrNull( $ts = null ) {
3001 if ( is_null( $ts ) ) {
3002 return null;
3003 } else {
3004 return $this->timestamp( $ts );
3005 }
3006 }
3007
3008 /**
3009 * Take the result from a query, and wrap it in a ResultWrapper if
3010 * necessary. Boolean values are passed through as is, to indicate success
3011 * of write queries or failure.
3012 *
3013 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3014 * resource, and it was necessary to call this function to convert it to
3015 * a wrapper. Nowadays, raw database objects are never exposed to external
3016 * callers, so this is unnecessary in external code. For compatibility with
3017 * old code, ResultWrapper objects are passed through unaltered.
3018 *
3019 * @param $result bool|ResultWrapper
3020 *
3021 * @return bool|ResultWrapper
3022 */
3023 function resultObject( $result ) {
3024 if ( empty( $result ) ) {
3025 return false;
3026 } elseif ( $result instanceof ResultWrapper ) {
3027 return $result;
3028 } elseif ( $result === true ) {
3029 // Successful write query
3030 return $result;
3031 } else {
3032 return new ResultWrapper( $this, $result );
3033 }
3034 }
3035
3036 /**
3037 * Return aggregated value alias
3038 *
3039 * @param $valuedata
3040 * @param $valuename string
3041 *
3042 * @return string
3043 */
3044 function aggregateValue ( $valuedata, $valuename = 'value' ) {
3045 return $valuename;
3046 }
3047
3048 /**
3049 * Ping the server and try to reconnect if it there is no connection
3050 *
3051 * @return bool Success or failure
3052 */
3053 function ping() {
3054 # Stub. Not essential to override.
3055 return true;
3056 }
3057
3058 /**
3059 * Get slave lag. Currently supported only by MySQL.
3060 *
3061 * Note that this function will generate a fatal error on many
3062 * installations. Most callers should use LoadBalancer::safeGetLag()
3063 * instead.
3064 *
3065 * @return int Database replication lag in seconds
3066 */
3067 function getLag() {
3068 return intval( $this->mFakeSlaveLag );
3069 }
3070
3071 /**
3072 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3073 *
3074 * @return int
3075 */
3076 function maxListLen() {
3077 return 0;
3078 }
3079
3080 /**
3081 * Some DBMSs have a special format for inserting into blob fields, they
3082 * don't allow simple quoted strings to be inserted. To insert into such
3083 * a field, pass the data through this function before passing it to
3084 * DatabaseBase::insert().
3085 * @param $b string
3086 * @return string
3087 */
3088 function encodeBlob( $b ) {
3089 return $b;
3090 }
3091
3092 /**
3093 * Some DBMSs return a special placeholder object representing blob fields
3094 * in result objects. Pass the object through this function to return the
3095 * original string.
3096 * @param $b string
3097 * @return string
3098 */
3099 function decodeBlob( $b ) {
3100 return $b;
3101 }
3102
3103 /**
3104 * Override database's default connection timeout
3105 *
3106 * @param $timeout Integer in seconds
3107 * @return void
3108 * @deprecated since 1.19; use setSessionOptions()
3109 */
3110 public function setTimeout( $timeout ) {
3111 wfDeprecated( __METHOD__, '1.19' );
3112 $this->setSessionOptions( array( 'connTimeout' => $timeout ) );
3113 }
3114
3115 /**
3116 * Override database's default behavior. $options include:
3117 * 'connTimeout' : Set the connection timeout value in seconds.
3118 * May be useful for very long batch queries such as
3119 * full-wiki dumps, where a single query reads out over
3120 * hours or days.
3121 *
3122 * @param $options Array
3123 * @return void
3124 */
3125 public function setSessionOptions( array $options ) {}
3126
3127 /**
3128 * Read and execute SQL commands from a file.
3129 *
3130 * Returns true on success, error string or exception on failure (depending
3131 * on object's error ignore settings).
3132 *
3133 * @param $filename String: File name to open
3134 * @param $lineCallback Callback: Optional function called before reading each line
3135 * @param $resultCallback Callback: Optional function called for each MySQL result
3136 * @param $fname String: Calling function name or false if name should be
3137 * generated dynamically using $filename
3138 * @return bool|string
3139 */
3140 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
3141 wfSuppressWarnings();
3142 $fp = fopen( $filename, 'r' );
3143 wfRestoreWarnings();
3144
3145 if ( false === $fp ) {
3146 throw new MWException( "Could not open \"{$filename}\".\n" );
3147 }
3148
3149 if ( !$fname ) {
3150 $fname = __METHOD__ . "( $filename )";
3151 }
3152
3153 try {
3154 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
3155 }
3156 catch ( MWException $e ) {
3157 fclose( $fp );
3158 throw $e;
3159 }
3160
3161 fclose( $fp );
3162
3163 return $error;
3164 }
3165
3166 /**
3167 * Get the full path of a patch file. Originally based on archive()
3168 * from updaters.inc. Keep in mind this always returns a patch, as
3169 * it fails back to MySQL if no DB-specific patch can be found
3170 *
3171 * @param $patch String The name of the patch, like patch-something.sql
3172 * @return String Full path to patch file
3173 */
3174 public function patchPath( $patch ) {
3175 global $IP;
3176
3177 $dbType = $this->getType();
3178 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3179 return "$IP/maintenance/$dbType/archives/$patch";
3180 } else {
3181 return "$IP/maintenance/archives/$patch";
3182 }
3183 }
3184
3185 /**
3186 * Set variables to be used in sourceFile/sourceStream, in preference to the
3187 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3188 * all. If it's set to false, $GLOBALS will be used.
3189 *
3190 * @param $vars bool|array mapping variable name to value.
3191 */
3192 function setSchemaVars( $vars ) {
3193 $this->mSchemaVars = $vars;
3194 }
3195
3196 /**
3197 * Read and execute commands from an open file handle.
3198 *
3199 * Returns true on success, error string or exception on failure (depending
3200 * on object's error ignore settings).
3201 *
3202 * @param $fp Resource: File handle
3203 * @param $lineCallback Callback: Optional function called before reading each line
3204 * @param $resultCallback Callback: Optional function called for each MySQL result
3205 * @param $fname String: Calling function name
3206 * @param $inputCallback Callback: Optional function called for each complete line (ended with ;) sent
3207 * @return bool|string
3208 */
3209 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3210 $fname = 'DatabaseBase::sourceStream', $inputCallback = false )
3211 {
3212 $cmd = '';
3213
3214 while ( !feof( $fp ) ) {
3215 if ( $lineCallback ) {
3216 call_user_func( $lineCallback );
3217 }
3218
3219 $line = trim( fgets( $fp ) );
3220
3221 if ( $line == '' ) {
3222 continue;
3223 }
3224
3225 if ( '-' == $line[0] && '-' == $line[1] ) {
3226 continue;
3227 }
3228
3229 if ( $cmd != '' ) {
3230 $cmd .= ' ';
3231 }
3232
3233 $done = $this->streamStatementEnd( $cmd, $line );
3234
3235 $cmd .= "$line\n";
3236
3237 if ( $done || feof( $fp ) ) {
3238 $cmd = $this->replaceVars( $cmd );
3239 if ( $inputCallback ) {
3240 call_user_func( $inputCallback, $cmd );
3241 }
3242 $res = $this->query( $cmd, $fname );
3243
3244 if ( $resultCallback ) {
3245 call_user_func( $resultCallback, $res, $this );
3246 }
3247
3248 if ( false === $res ) {
3249 $err = $this->lastError();
3250 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3251 }
3252
3253 $cmd = '';
3254 }
3255 }
3256
3257 return true;
3258 }
3259
3260 /**
3261 * Called by sourceStream() to check if we've reached a statement end
3262 *
3263 * @param $sql String SQL assembled so far
3264 * @param $newLine String New line about to be added to $sql
3265 * @return Bool Whether $newLine contains end of the statement
3266 */
3267 public function streamStatementEnd( &$sql, &$newLine ) {
3268 if ( $this->delimiter ) {
3269 $prev = $newLine;
3270 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3271 if ( $newLine != $prev ) {
3272 return true;
3273 }
3274 }
3275 return false;
3276 }
3277
3278 /**
3279 * Database independent variable replacement. Replaces a set of variables
3280 * in an SQL statement with their contents as given by $this->getSchemaVars().
3281 *
3282 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3283 *
3284 * - '{$var}' should be used for text and is passed through the database's
3285 * addQuotes method.
3286 * - `{$var}` should be used for identifiers (eg: table and database names),
3287 * it is passed through the database's addIdentifierQuotes method which
3288 * can be overridden if the database uses something other than backticks.
3289 * - / *$var* / is just encoded, besides traditional table prefix and
3290 * table options its use should be avoided.
3291 *
3292 * @param $ins String: SQL statement to replace variables in
3293 * @return String The new SQL statement with variables replaced
3294 */
3295 protected function replaceSchemaVars( $ins ) {
3296 $vars = $this->getSchemaVars();
3297 foreach ( $vars as $var => $value ) {
3298 // replace '{$var}'
3299 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3300 // replace `{$var}`
3301 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3302 // replace /*$var*/
3303 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
3304 }
3305 return $ins;
3306 }
3307
3308 /**
3309 * Replace variables in sourced SQL
3310 *
3311 * @param $ins string
3312 *
3313 * @return string
3314 */
3315 protected function replaceVars( $ins ) {
3316 $ins = $this->replaceSchemaVars( $ins );
3317
3318 // Table prefixes
3319 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3320 array( $this, 'tableNameCallback' ), $ins );
3321
3322 // Index names
3323 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3324 array( $this, 'indexNameCallback' ), $ins );
3325
3326 return $ins;
3327 }
3328
3329 /**
3330 * Get schema variables. If none have been set via setSchemaVars(), then
3331 * use some defaults from the current object.
3332 *
3333 * @return array
3334 */
3335 protected function getSchemaVars() {
3336 if ( $this->mSchemaVars ) {
3337 return $this->mSchemaVars;
3338 } else {
3339 return $this->getDefaultSchemaVars();
3340 }
3341 }
3342
3343 /**
3344 * Get schema variables to use if none have been set via setSchemaVars().
3345 *
3346 * Override this in derived classes to provide variables for tables.sql
3347 * and SQL patch files.
3348 *
3349 * @return array
3350 */
3351 protected function getDefaultSchemaVars() {
3352 return array();
3353 }
3354
3355 /**
3356 * Table name callback
3357 *
3358 * @param $matches array
3359 *
3360 * @return string
3361 */
3362 protected function tableNameCallback( $matches ) {
3363 return $this->tableName( $matches[1] );
3364 }
3365
3366 /**
3367 * Index name callback
3368 *
3369 * @param $matches array
3370 *
3371 * @return string
3372 */
3373 protected function indexNameCallback( $matches ) {
3374 return $this->indexName( $matches[1] );
3375 }
3376
3377 /**
3378 * Build a concatenation list to feed into a SQL query
3379 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
3380 * @return String
3381 */
3382 function buildConcat( $stringList ) {
3383 return 'CONCAT(' . implode( ',', $stringList ) . ')';
3384 }
3385
3386 /**
3387 * Check to see if a named lock is available. This is non-blocking.
3388 *
3389 * @param $lockName String: name of lock to poll
3390 * @param $method String: name of method calling us
3391 * @return Boolean
3392 * @since 1.20
3393 */
3394 public function lockIsFree( $lockName, $method ) {
3395 return true;
3396 }
3397
3398 /**
3399 * Acquire a named lock
3400 *
3401 * Abstracted from Filestore::lock() so child classes can implement for
3402 * their own needs.
3403 *
3404 * @param $lockName String: name of lock to aquire
3405 * @param $method String: name of method calling us
3406 * @param $timeout Integer: timeout
3407 * @return Boolean
3408 */
3409 public function lock( $lockName, $method, $timeout = 5 ) {
3410 return true;
3411 }
3412
3413 /**
3414 * Release a lock.
3415 *
3416 * @param $lockName String: Name of lock to release
3417 * @param $method String: Name of method calling us
3418 *
3419 * @return int Returns 1 if the lock was released, 0 if the lock was not established
3420 * by this thread (in which case the lock is not released), and NULL if the named
3421 * lock did not exist
3422 */
3423 public function unlock( $lockName, $method ) {
3424 return true;
3425 }
3426
3427 /**
3428 * Lock specific tables
3429 *
3430 * @param $read Array of tables to lock for read access
3431 * @param $write Array of tables to lock for write access
3432 * @param $method String name of caller
3433 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
3434 *
3435 * @return bool
3436 */
3437 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3438 return true;
3439 }
3440
3441 /**
3442 * Unlock specific tables
3443 *
3444 * @param $method String the caller
3445 *
3446 * @return bool
3447 */
3448 public function unlockTables( $method ) {
3449 return true;
3450 }
3451
3452 /**
3453 * Delete a table
3454 * @param $tableName string
3455 * @param $fName string
3456 * @return bool|ResultWrapper
3457 * @since 1.18
3458 */
3459 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
3460 if( !$this->tableExists( $tableName, $fName ) ) {
3461 return false;
3462 }
3463 $sql = "DROP TABLE " . $this->tableName( $tableName );
3464 if( $this->cascadingDeletes() ) {
3465 $sql .= " CASCADE";
3466 }
3467 return $this->query( $sql, $fName );
3468 }
3469
3470 /**
3471 * Get search engine class. All subclasses of this need to implement this
3472 * if they wish to use searching.
3473 *
3474 * @return String
3475 */
3476 public function getSearchEngine() {
3477 return 'SearchEngineDummy';
3478 }
3479
3480 /**
3481 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3482 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3483 * because "i" sorts after all numbers.
3484 *
3485 * @return String
3486 */
3487 public function getInfinity() {
3488 return 'infinity';
3489 }
3490
3491 /**
3492 * Encode an expiry time into the DBMS dependent format
3493 *
3494 * @param $expiry String: timestamp for expiry, or the 'infinity' string
3495 * @return String
3496 */
3497 public function encodeExpiry( $expiry ) {
3498 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3499 ? $this->getInfinity()
3500 : $this->timestamp( $expiry );
3501 }
3502
3503 /**
3504 * Decode an expiry time into a DBMS independent format
3505 *
3506 * @param $expiry String: DB timestamp field value for expiry
3507 * @param $format integer: TS_* constant, defaults to TS_MW
3508 * @return String
3509 */
3510 public function decodeExpiry( $expiry, $format = TS_MW ) {
3511 return ( $expiry == '' || $expiry == $this->getInfinity() )
3512 ? 'infinity'
3513 : wfTimestamp( $format, $expiry );
3514 }
3515
3516 /**
3517 * Allow or deny "big selects" for this session only. This is done by setting
3518 * the sql_big_selects session variable.
3519 *
3520 * This is a MySQL-specific feature.
3521 *
3522 * @param $value Mixed: true for allow, false for deny, or "default" to
3523 * restore the initial value
3524 */
3525 public function setBigSelects( $value = true ) {
3526 // no-op
3527 }
3528
3529 /**
3530 * @since 1.19
3531 */
3532 public function __toString() {
3533 return (string)$this->mConn;
3534 }
3535 }