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