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