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