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