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