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