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