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