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