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