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