wfProfileOut() for new return added in c6396 (c4e407c)
[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|\(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['LIMIT'] = 1;
1479 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1480
1481 if ( $res === false ) {
1482 return false;
1483 }
1484
1485 if ( !$this->numRows( $res ) ) {
1486 return false;
1487 }
1488
1489 $obj = $this->fetchObject( $res );
1490
1491 return $obj;
1492 }
1493
1494 /**
1495 * Estimate rows in dataset.
1496 *
1497 * MySQL allows you to estimate the number of rows that would be returned
1498 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1499 * index cardinality statistics, and is notoriously inaccurate, especially
1500 * when large numbers of rows have recently been added or deleted.
1501 *
1502 * For DBMSs that don't support fast result size estimation, this function
1503 * will actually perform the SELECT COUNT(*).
1504 *
1505 * Takes the same arguments as DatabaseBase::select().
1506 *
1507 * @param $table String: table name
1508 * @param Array|string $vars : unused
1509 * @param Array|string $conds : filters on the table
1510 * @param $fname String: function name for profiling
1511 * @param $options Array: options for select
1512 * @return Integer: row count
1513 */
1514 public function estimateRowCount( $table, $vars = '*', $conds = '',
1515 $fname = 'DatabaseBase::estimateRowCount', $options = array() )
1516 {
1517 $rows = 0;
1518 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1519
1520 if ( $res ) {
1521 $row = $this->fetchRow( $res );
1522 $rows = ( isset( $row['rowcount'] ) ) ? $row['rowcount'] : 0;
1523 }
1524
1525 return $rows;
1526 }
1527
1528 /**
1529 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1530 * It's only slightly flawed. Don't use for anything important.
1531 *
1532 * @param $sql String A SQL Query
1533 *
1534 * @return string
1535 */
1536 static function generalizeSQL( $sql ) {
1537 # This does the same as the regexp below would do, but in such a way
1538 # as to avoid crashing php on some large strings.
1539 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1540
1541 $sql = str_replace ( "\\\\", '', $sql );
1542 $sql = str_replace ( "\\'", '', $sql );
1543 $sql = str_replace ( "\\\"", '', $sql );
1544 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1545 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1546
1547 # All newlines, tabs, etc replaced by single space
1548 $sql = preg_replace ( '/\s+/', ' ', $sql );
1549
1550 # All numbers => N
1551 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1552
1553 return $sql;
1554 }
1555
1556 /**
1557 * Determines whether a field exists in a table
1558 *
1559 * @param $table String: table name
1560 * @param $field String: filed to check on that table
1561 * @param $fname String: calling function name (optional)
1562 * @return Boolean: whether $table has filed $field
1563 */
1564 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1565 $info = $this->fieldInfo( $table, $field );
1566
1567 return (bool)$info;
1568 }
1569
1570 /**
1571 * Determines whether an index exists
1572 * Usually throws a DBQueryError on failure
1573 * If errors are explicitly ignored, returns NULL on failure
1574 *
1575 * @param $table
1576 * @param $index
1577 * @param $fname string
1578 *
1579 * @return bool|null
1580 */
1581 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1582 $info = $this->indexInfo( $table, $index, $fname );
1583 if ( is_null( $info ) ) {
1584 return null;
1585 } else {
1586 return $info !== false;
1587 }
1588 }
1589
1590 /**
1591 * Query whether a given table exists
1592 *
1593 * @param $table string
1594 * @param $fname string
1595 *
1596 * @return bool
1597 */
1598 function tableExists( $table, $fname = __METHOD__ ) {
1599 $table = $this->tableName( $table );
1600 $old = $this->ignoreErrors( true );
1601 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1602 $this->ignoreErrors( $old );
1603
1604 return (bool)$res;
1605 }
1606
1607 /**
1608 * mysql_field_type() wrapper
1609 * @param $res
1610 * @param $index
1611 * @return string
1612 */
1613 function fieldType( $res, $index ) {
1614 if ( $res instanceof ResultWrapper ) {
1615 $res = $res->result;
1616 }
1617
1618 return mysql_field_type( $res, $index );
1619 }
1620
1621 /**
1622 * Determines if a given index is unique
1623 *
1624 * @param $table string
1625 * @param $index string
1626 *
1627 * @return bool
1628 */
1629 function indexUnique( $table, $index ) {
1630 $indexInfo = $this->indexInfo( $table, $index );
1631
1632 if ( !$indexInfo ) {
1633 return null;
1634 }
1635
1636 return !$indexInfo[0]->Non_unique;
1637 }
1638
1639 /**
1640 * Helper for DatabaseBase::insert().
1641 *
1642 * @param $options array
1643 * @return string
1644 */
1645 function makeInsertOptions( $options ) {
1646 return implode( ' ', $options );
1647 }
1648
1649 /**
1650 * INSERT wrapper, inserts an array into a table.
1651 *
1652 * $a may be either:
1653 *
1654 * - A single associative array. The array keys are the field names, and
1655 * the values are the values to insert. The values are treated as data
1656 * and will be quoted appropriately. If NULL is inserted, this will be
1657 * converted to a database NULL.
1658 * - An array with numeric keys, holding a list of associative arrays.
1659 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1660 * each subarray must be identical to each other, and in the same order.
1661 *
1662 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1663 * returns success.
1664 *
1665 * $options is an array of options, with boolean options encoded as values
1666 * with numeric keys, in the same style as $options in
1667 * DatabaseBase::select(). Supported options are:
1668 *
1669 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1670 * any rows which cause duplicate key errors are not inserted. It's
1671 * possible to determine how many rows were successfully inserted using
1672 * DatabaseBase::affectedRows().
1673 *
1674 * @param $table String Table name. This will be passed through
1675 * DatabaseBase::tableName().
1676 * @param $a Array of rows to insert
1677 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1678 * @param $options Array of options
1679 *
1680 * @return bool
1681 */
1682 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1683 # No rows to insert, easy just return now
1684 if ( !count( $a ) ) {
1685 return true;
1686 }
1687
1688 $table = $this->tableName( $table );
1689
1690 if ( !is_array( $options ) ) {
1691 $options = array( $options );
1692 }
1693
1694 $options = $this->makeInsertOptions( $options );
1695
1696 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1697 $multi = true;
1698 $keys = array_keys( $a[0] );
1699 } else {
1700 $multi = false;
1701 $keys = array_keys( $a );
1702 }
1703
1704 $sql = 'INSERT ' . $options .
1705 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1706
1707 if ( $multi ) {
1708 $first = true;
1709 foreach ( $a as $row ) {
1710 if ( $first ) {
1711 $first = false;
1712 } else {
1713 $sql .= ',';
1714 }
1715 $sql .= '(' . $this->makeList( $row ) . ')';
1716 }
1717 } else {
1718 $sql .= '(' . $this->makeList( $a ) . ')';
1719 }
1720
1721 return (bool)$this->query( $sql, $fname );
1722 }
1723
1724 /**
1725 * Make UPDATE options for the DatabaseBase::update function
1726 *
1727 * @param $options Array: The options passed to DatabaseBase::update
1728 * @return string
1729 */
1730 function makeUpdateOptions( $options ) {
1731 if ( !is_array( $options ) ) {
1732 $options = array( $options );
1733 }
1734
1735 $opts = array();
1736
1737 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1738 $opts[] = $this->lowPriorityOption();
1739 }
1740
1741 if ( in_array( 'IGNORE', $options ) ) {
1742 $opts[] = 'IGNORE';
1743 }
1744
1745 return implode( ' ', $opts );
1746 }
1747
1748 /**
1749 * UPDATE wrapper. Takes a condition array and a SET array.
1750 *
1751 * @param $table String name of the table to UPDATE. This will be passed through
1752 * DatabaseBase::tableName().
1753 *
1754 * @param $values Array: An array of values to SET. For each array element,
1755 * the key gives the field name, and the value gives the data
1756 * to set that field to. The data will be quoted by
1757 * DatabaseBase::addQuotes().
1758 *
1759 * @param $conds Array: An array of conditions (WHERE). See
1760 * DatabaseBase::select() for the details of the format of
1761 * condition arrays. Use '*' to update all rows.
1762 *
1763 * @param $fname String: The function name of the caller (from __METHOD__),
1764 * for logging and profiling.
1765 *
1766 * @param $options Array: An array of UPDATE options, can be:
1767 * - IGNORE: Ignore unique key conflicts
1768 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1769 * @return Boolean
1770 */
1771 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1772 $table = $this->tableName( $table );
1773 $opts = $this->makeUpdateOptions( $options );
1774 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1775
1776 if ( $conds !== array() && $conds !== '*' ) {
1777 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1778 }
1779
1780 return $this->query( $sql, $fname );
1781 }
1782
1783 /**
1784 * Makes an encoded list of strings from an array
1785 * @param $a Array containing the data
1786 * @param $mode int Constant
1787 * - LIST_COMMA: comma separated, no field names
1788 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1789 * the documentation for $conds in DatabaseBase::select().
1790 * - LIST_OR: ORed WHERE clause (without the WHERE)
1791 * - LIST_SET: comma separated with field names, like a SET clause
1792 * - LIST_NAMES: comma separated field names
1793 *
1794 * @return string
1795 */
1796 function makeList( $a, $mode = LIST_COMMA ) {
1797 if ( !is_array( $a ) ) {
1798 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1799 }
1800
1801 $first = true;
1802 $list = '';
1803
1804 foreach ( $a as $field => $value ) {
1805 if ( !$first ) {
1806 if ( $mode == LIST_AND ) {
1807 $list .= ' AND ';
1808 } elseif ( $mode == LIST_OR ) {
1809 $list .= ' OR ';
1810 } else {
1811 $list .= ',';
1812 }
1813 } else {
1814 $first = false;
1815 }
1816
1817 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1818 $list .= "($value)";
1819 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1820 $list .= "$value";
1821 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1822 if ( count( $value ) == 0 ) {
1823 throw new MWException( __METHOD__ . ': empty input' );
1824 } elseif ( count( $value ) == 1 ) {
1825 // Special-case single values, as IN isn't terribly efficient
1826 // Don't necessarily assume the single key is 0; we don't
1827 // enforce linear numeric ordering on other arrays here.
1828 $value = array_values( $value );
1829 $list .= $field . " = " . $this->addQuotes( $value[0] );
1830 } else {
1831 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1832 }
1833 } elseif ( $value === null ) {
1834 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1835 $list .= "$field IS ";
1836 } elseif ( $mode == LIST_SET ) {
1837 $list .= "$field = ";
1838 }
1839 $list .= 'NULL';
1840 } else {
1841 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1842 $list .= "$field = ";
1843 }
1844 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1845 }
1846 }
1847
1848 return $list;
1849 }
1850
1851 /**
1852 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1853 * The keys on each level may be either integers or strings.
1854 *
1855 * @param $data Array: organized as 2-d
1856 * array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1857 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1858 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1859 * @return Mixed: string SQL fragment, or false if no items in array.
1860 */
1861 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1862 $conds = array();
1863
1864 foreach ( $data as $base => $sub ) {
1865 if ( count( $sub ) ) {
1866 $conds[] = $this->makeList(
1867 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1868 LIST_AND );
1869 }
1870 }
1871
1872 if ( $conds ) {
1873 return $this->makeList( $conds, LIST_OR );
1874 } else {
1875 // Nothing to search for...
1876 return false;
1877 }
1878 }
1879
1880 /**
1881 * Bitwise operations
1882 */
1883
1884 /**
1885 * @param $field
1886 * @return string
1887 */
1888 function bitNot( $field ) {
1889 return "(~$field)";
1890 }
1891
1892 /**
1893 * @param $fieldLeft
1894 * @param $fieldRight
1895 * @return string
1896 */
1897 function bitAnd( $fieldLeft, $fieldRight ) {
1898 return "($fieldLeft & $fieldRight)";
1899 }
1900
1901 /**
1902 * @param $fieldLeft
1903 * @param $fieldRight
1904 * @return string
1905 */
1906 function bitOr( $fieldLeft, $fieldRight ) {
1907 return "($fieldLeft | $fieldRight)";
1908 }
1909
1910 /**
1911 * Change the current database
1912 *
1913 * @todo Explain what exactly will fail if this is not overridden.
1914 *
1915 * @param $db
1916 *
1917 * @return bool Success or failure
1918 */
1919 function selectDB( $db ) {
1920 # Stub. Shouldn't cause serious problems if it's not overridden, but
1921 # if your database engine supports a concept similar to MySQL's
1922 # databases you may as well.
1923 $this->mDBname = $db;
1924 return true;
1925 }
1926
1927 /**
1928 * Get the current DB name
1929 */
1930 function getDBname() {
1931 return $this->mDBname;
1932 }
1933
1934 /**
1935 * Get the server hostname or IP address
1936 */
1937 function getServer() {
1938 return $this->mServer;
1939 }
1940
1941 /**
1942 * Format a table name ready for use in constructing an SQL query
1943 *
1944 * This does two important things: it quotes the table names to clean them up,
1945 * and it adds a table prefix if only given a table name with no quotes.
1946 *
1947 * All functions of this object which require a table name call this function
1948 * themselves. Pass the canonical name to such functions. This is only needed
1949 * when calling query() directly.
1950 *
1951 * @param $name String: database table name
1952 * @param $format String One of:
1953 * quoted - Automatically pass the table name through addIdentifierQuotes()
1954 * so that it can be used in a query.
1955 * raw - Do not add identifier quotes to the table name
1956 * @return String: full database name
1957 */
1958 function tableName( $name, $format = 'quoted' ) {
1959 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1960 # Skip the entire process when we have a string quoted on both ends.
1961 # Note that we check the end so that we will still quote any use of
1962 # use of `database`.table. But won't break things if someone wants
1963 # to query a database table with a dot in the name.
1964 if ( $this->isQuotedIdentifier( $name ) ) {
1965 return $name;
1966 }
1967
1968 # Lets test for any bits of text that should never show up in a table
1969 # name. Basically anything like JOIN or ON which are actually part of
1970 # SQL queries, but may end up inside of the table value to combine
1971 # sql. Such as how the API is doing.
1972 # Note that we use a whitespace test rather than a \b test to avoid
1973 # any remote case where a word like on may be inside of a table name
1974 # surrounded by symbols which may be considered word breaks.
1975 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1976 return $name;
1977 }
1978
1979 # Split database and table into proper variables.
1980 # We reverse the explode so that database.table and table both output
1981 # the correct table.
1982 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1983 if ( isset( $dbDetails[1] ) ) {
1984 list( $table, $database ) = $dbDetails;
1985 } else {
1986 list( $table ) = $dbDetails;
1987 }
1988 $prefix = $this->mTablePrefix; # Default prefix
1989
1990 # A database name has been specified in input. We don't want any
1991 # prefixes added.
1992 if ( isset( $database ) ) {
1993 $prefix = '';
1994 }
1995
1996 # Note that we use the long format because php will complain in in_array if
1997 # the input is not an array, and will complain in is_array if it is not set.
1998 if ( !isset( $database ) # Don't use shared database if pre selected.
1999 && isset( $wgSharedDB ) # We have a shared database
2000 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
2001 && isset( $wgSharedTables )
2002 && is_array( $wgSharedTables )
2003 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
2004 $database = $wgSharedDB;
2005 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
2006 }
2007
2008 # Quote the $database and $table and apply the prefix if not quoted.
2009 if ( isset( $database ) ) {
2010 $database = ( $format == 'quoted' || $this->isQuotedIdentifier( $database ) ? $database : $this->addIdentifierQuotes( $database ) );
2011 }
2012
2013 $table = "{$prefix}{$table}";
2014 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $table ) ) {
2015 $table = $this->addIdentifierQuotes( "{$table}" );
2016 }
2017
2018 # Merge our database and table into our final table name.
2019 $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
2020
2021 return $tableName;
2022 }
2023
2024 /**
2025 * Fetch a number of table names into an array
2026 * This is handy when you need to construct SQL for joins
2027 *
2028 * Example:
2029 * extract($dbr->tableNames('user','watchlist'));
2030 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2031 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2032 *
2033 * @return array
2034 */
2035 public function tableNames() {
2036 $inArray = func_get_args();
2037 $retVal = array();
2038
2039 foreach ( $inArray as $name ) {
2040 $retVal[$name] = $this->tableName( $name );
2041 }
2042
2043 return $retVal;
2044 }
2045
2046 /**
2047 * Fetch a number of table names into an zero-indexed numerical array
2048 * This is handy when you need to construct SQL for joins
2049 *
2050 * Example:
2051 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
2052 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2053 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2054 *
2055 * @return array
2056 */
2057 public function tableNamesN() {
2058 $inArray = func_get_args();
2059 $retVal = array();
2060
2061 foreach ( $inArray as $name ) {
2062 $retVal[] = $this->tableName( $name );
2063 }
2064
2065 return $retVal;
2066 }
2067
2068 /**
2069 * Get an aliased table name
2070 * e.g. tableName AS newTableName
2071 *
2072 * @param $name string Table name, see tableName()
2073 * @param $alias string|bool Alias (optional)
2074 * @return string SQL name for aliased table. Will not alias a table to its own name
2075 */
2076 public function tableNameWithAlias( $name, $alias = false ) {
2077 if ( !$alias || $alias == $name ) {
2078 return $this->tableName( $name );
2079 } else {
2080 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2081 }
2082 }
2083
2084 /**
2085 * Gets an array of aliased table names
2086 *
2087 * @param $tables array( [alias] => table )
2088 * @return array of strings, see tableNameWithAlias()
2089 */
2090 public function tableNamesWithAlias( $tables ) {
2091 $retval = array();
2092 foreach ( $tables as $alias => $table ) {
2093 if ( is_numeric( $alias ) ) {
2094 $alias = $table;
2095 }
2096 $retval[] = $this->tableNameWithAlias( $table, $alias );
2097 }
2098 return $retval;
2099 }
2100
2101 /**
2102 * Get the aliased table name clause for a FROM clause
2103 * which might have a JOIN and/or USE INDEX clause
2104 *
2105 * @param $tables array ( [alias] => table )
2106 * @param $use_index array Same as for select()
2107 * @param $join_conds array Same as for select()
2108 * @return string
2109 */
2110 protected function tableNamesWithUseIndexOrJOIN(
2111 $tables, $use_index = array(), $join_conds = array()
2112 ) {
2113 $ret = array();
2114 $retJOIN = array();
2115 $use_index = (array)$use_index;
2116 $join_conds = (array)$join_conds;
2117
2118 foreach ( $tables as $alias => $table ) {
2119 if ( !is_string( $alias ) ) {
2120 // No alias? Set it equal to the table name
2121 $alias = $table;
2122 }
2123 // Is there a JOIN clause for this table?
2124 if ( isset( $join_conds[$alias] ) ) {
2125 list( $joinType, $conds ) = $join_conds[$alias];
2126 $tableClause = $joinType;
2127 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2128 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2129 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2130 if ( $use != '' ) {
2131 $tableClause .= ' ' . $use;
2132 }
2133 }
2134 $on = $this->makeList( (array)$conds, LIST_AND );
2135 if ( $on != '' ) {
2136 $tableClause .= ' ON (' . $on . ')';
2137 }
2138
2139 $retJOIN[] = $tableClause;
2140 // Is there an INDEX clause for this table?
2141 } elseif ( isset( $use_index[$alias] ) ) {
2142 $tableClause = $this->tableNameWithAlias( $table, $alias );
2143 $tableClause .= ' ' . $this->useIndexClause(
2144 implode( ',', (array)$use_index[$alias] ) );
2145
2146 $ret[] = $tableClause;
2147 } else {
2148 $tableClause = $this->tableNameWithAlias( $table, $alias );
2149
2150 $ret[] = $tableClause;
2151 }
2152 }
2153
2154 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2155 $straightJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2156 $otherJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2157
2158 // Compile our final table clause
2159 return implode( ' ', array( $straightJoins, $otherJoins ) );
2160 }
2161
2162 /**
2163 * Get the name of an index in a given table
2164 *
2165 * @param $index
2166 *
2167 * @return string
2168 */
2169 function indexName( $index ) {
2170 // Backwards-compatibility hack
2171 $renamed = array(
2172 'ar_usertext_timestamp' => 'usertext_timestamp',
2173 'un_user_id' => 'user_id',
2174 'un_user_ip' => 'user_ip',
2175 );
2176
2177 if ( isset( $renamed[$index] ) ) {
2178 return $renamed[$index];
2179 } else {
2180 return $index;
2181 }
2182 }
2183
2184 /**
2185 * If it's a string, adds quotes and backslashes
2186 * Otherwise returns as-is
2187 *
2188 * @param $s string
2189 *
2190 * @return string
2191 */
2192 function addQuotes( $s ) {
2193 if ( $s === null ) {
2194 return 'NULL';
2195 } else {
2196 # This will also quote numeric values. This should be harmless,
2197 # and protects against weird problems that occur when they really
2198 # _are_ strings such as article titles and string->number->string
2199 # conversion is not 1:1.
2200 return "'" . $this->strencode( $s ) . "'";
2201 }
2202 }
2203
2204 /**
2205 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2206 * MySQL uses `backticks` while basically everything else uses double quotes.
2207 * Since MySQL is the odd one out here the double quotes are our generic
2208 * and we implement backticks in DatabaseMysql.
2209 *
2210 * @param $s string
2211 *
2212 * @return string
2213 */
2214 public function addIdentifierQuotes( $s ) {
2215 return '"' . str_replace( '"', '""', $s ) . '"';
2216 }
2217
2218 /**
2219 * Returns if the given identifier looks quoted or not according to
2220 * the database convention for quoting identifiers .
2221 *
2222 * @param $name string
2223 *
2224 * @return boolean
2225 */
2226 public function isQuotedIdentifier( $name ) {
2227 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2228 }
2229
2230 /**
2231 * Backwards compatibility, identifier quoting originated in DatabasePostgres
2232 * which used quote_ident which does not follow our naming conventions
2233 * was renamed to addIdentifierQuotes.
2234 * @deprecated since 1.18 use addIdentifierQuotes
2235 *
2236 * @param $s string
2237 *
2238 * @return string
2239 */
2240 function quote_ident( $s ) {
2241 wfDeprecated( __METHOD__, '1.18' );
2242 return $this->addIdentifierQuotes( $s );
2243 }
2244
2245 /**
2246 * Escape string for safe LIKE usage.
2247 * WARNING: you should almost never use this function directly,
2248 * instead use buildLike() that escapes everything automatically
2249 * @deprecated since 1.17, warnings in 1.17, removed in ???
2250 *
2251 * @param $s string
2252 *
2253 * @return string
2254 */
2255 public function escapeLike( $s ) {
2256 wfDeprecated( __METHOD__, '1.17' );
2257 return $this->escapeLikeInternal( $s );
2258 }
2259
2260 /**
2261 * @param $s string
2262 * @return string
2263 */
2264 protected function escapeLikeInternal( $s ) {
2265 $s = str_replace( '\\', '\\\\', $s );
2266 $s = $this->strencode( $s );
2267 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2268
2269 return $s;
2270 }
2271
2272 /**
2273 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2274 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2275 * Alternatively, the function could be provided with an array of aforementioned parameters.
2276 *
2277 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2278 * for subpages of 'My page title'.
2279 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2280 *
2281 * @since 1.16
2282 * @return String: fully built LIKE statement
2283 */
2284 function buildLike() {
2285 $params = func_get_args();
2286
2287 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2288 $params = $params[0];
2289 }
2290
2291 $s = '';
2292
2293 foreach ( $params as $value ) {
2294 if ( $value instanceof LikeMatch ) {
2295 $s .= $value->toString();
2296 } else {
2297 $s .= $this->escapeLikeInternal( $value );
2298 }
2299 }
2300
2301 return " LIKE '" . $s . "' ";
2302 }
2303
2304 /**
2305 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2306 *
2307 * @return LikeMatch
2308 */
2309 function anyChar() {
2310 return new LikeMatch( '_' );
2311 }
2312
2313 /**
2314 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2315 *
2316 * @return LikeMatch
2317 */
2318 function anyString() {
2319 return new LikeMatch( '%' );
2320 }
2321
2322 /**
2323 * Returns an appropriately quoted sequence value for inserting a new row.
2324 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2325 * subclass will return an integer, and save the value for insertId()
2326 *
2327 * Any implementation of this function should *not* involve reusing
2328 * sequence numbers created for rolled-back transactions.
2329 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2330 * @param $seqName string
2331 * @return null
2332 */
2333 function nextSequenceValue( $seqName ) {
2334 return null;
2335 }
2336
2337 /**
2338 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2339 * is only needed because a) MySQL must be as efficient as possible due to
2340 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2341 * which index to pick. Anyway, other databases might have different
2342 * indexes on a given table. So don't bother overriding this unless you're
2343 * MySQL.
2344 * @param $index
2345 * @return string
2346 */
2347 function useIndexClause( $index ) {
2348 return '';
2349 }
2350
2351 /**
2352 * REPLACE query wrapper.
2353 *
2354 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2355 * except that when there is a duplicate key error, the old row is deleted
2356 * and the new row is inserted in its place.
2357 *
2358 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2359 * perform the delete, we need to know what the unique indexes are so that
2360 * we know how to find the conflicting rows.
2361 *
2362 * It may be more efficient to leave off unique indexes which are unlikely
2363 * to collide. However if you do this, you run the risk of encountering
2364 * errors which wouldn't have occurred in MySQL.
2365 *
2366 * @param $table String: The table to replace the row(s) in.
2367 * @param $rows array Can be either a single row to insert, or multiple rows,
2368 * in the same format as for DatabaseBase::insert()
2369 * @param $uniqueIndexes array is an array of indexes. Each element may be either
2370 * a field name or an array of field names
2371 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2372 */
2373 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
2374 $quotedTable = $this->tableName( $table );
2375
2376 if ( count( $rows ) == 0 ) {
2377 return;
2378 }
2379
2380 # Single row case
2381 if ( !is_array( reset( $rows ) ) ) {
2382 $rows = array( $rows );
2383 }
2384
2385 foreach( $rows as $row ) {
2386 # Delete rows which collide
2387 if ( $uniqueIndexes ) {
2388 $sql = "DELETE FROM $quotedTable WHERE ";
2389 $first = true;
2390 foreach ( $uniqueIndexes as $index ) {
2391 if ( $first ) {
2392 $first = false;
2393 $sql .= '( ';
2394 } else {
2395 $sql .= ' ) OR ( ';
2396 }
2397 if ( is_array( $index ) ) {
2398 $first2 = true;
2399 foreach ( $index as $col ) {
2400 if ( $first2 ) {
2401 $first2 = false;
2402 } else {
2403 $sql .= ' AND ';
2404 }
2405 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2406 }
2407 } else {
2408 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2409 }
2410 }
2411 $sql .= ' )';
2412 $this->query( $sql, $fname );
2413 }
2414
2415 # Now insert the row
2416 $this->insert( $table, $row );
2417 }
2418 }
2419
2420 /**
2421 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2422 * statement.
2423 *
2424 * @param $table string Table name
2425 * @param $rows array Rows to insert
2426 * @param $fname string Caller function name
2427 *
2428 * @return ResultWrapper
2429 */
2430 protected function nativeReplace( $table, $rows, $fname ) {
2431 $table = $this->tableName( $table );
2432
2433 # Single row case
2434 if ( !is_array( reset( $rows ) ) ) {
2435 $rows = array( $rows );
2436 }
2437
2438 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2439 $first = true;
2440
2441 foreach ( $rows as $row ) {
2442 if ( $first ) {
2443 $first = false;
2444 } else {
2445 $sql .= ',';
2446 }
2447
2448 $sql .= '(' . $this->makeList( $row ) . ')';
2449 }
2450
2451 return $this->query( $sql, $fname );
2452 }
2453
2454 /**
2455 * DELETE where the condition is a join.
2456 *
2457 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2458 * we use sub-selects
2459 *
2460 * For safety, an empty $conds will not delete everything. If you want to
2461 * delete all rows where the join condition matches, set $conds='*'.
2462 *
2463 * DO NOT put the join condition in $conds.
2464 *
2465 * @param $delTable String: The table to delete from.
2466 * @param $joinTable String: The other table.
2467 * @param $delVar String: The variable to join on, in the first table.
2468 * @param $joinVar String: The variable to join on, in the second table.
2469 * @param $conds Array: Condition array of field names mapped to variables,
2470 * ANDed together in the WHERE clause
2471 * @param $fname String: Calling function name (use __METHOD__) for
2472 * logs/profiling
2473 */
2474 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2475 $fname = 'DatabaseBase::deleteJoin' )
2476 {
2477 if ( !$conds ) {
2478 throw new DBUnexpectedError( $this,
2479 'DatabaseBase::deleteJoin() called with empty $conds' );
2480 }
2481
2482 $delTable = $this->tableName( $delTable );
2483 $joinTable = $this->tableName( $joinTable );
2484 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2485 if ( $conds != '*' ) {
2486 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2487 }
2488 $sql .= ')';
2489
2490 $this->query( $sql, $fname );
2491 }
2492
2493 /**
2494 * Returns the size of a text field, or -1 for "unlimited"
2495 *
2496 * @param $table string
2497 * @param $field string
2498 *
2499 * @return int
2500 */
2501 function textFieldSize( $table, $field ) {
2502 $table = $this->tableName( $table );
2503 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2504 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2505 $row = $this->fetchObject( $res );
2506
2507 $m = array();
2508
2509 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2510 $size = $m[1];
2511 } else {
2512 $size = -1;
2513 }
2514
2515 return $size;
2516 }
2517
2518 /**
2519 * A string to insert into queries to show that they're low-priority, like
2520 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2521 * string and nothing bad should happen.
2522 *
2523 * @return string Returns the text of the low priority option if it is
2524 * supported, or a blank string otherwise
2525 */
2526 function lowPriorityOption() {
2527 return '';
2528 }
2529
2530 /**
2531 * DELETE query wrapper.
2532 *
2533 * @param $table Array Table name
2534 * @param $conds String|Array of conditions. See $conds in DatabaseBase::select() for
2535 * the format. Use $conds == "*" to delete all rows
2536 * @param $fname String name of the calling function
2537 *
2538 * @return bool
2539 */
2540 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2541 if ( !$conds ) {
2542 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2543 }
2544
2545 $table = $this->tableName( $table );
2546 $sql = "DELETE FROM $table";
2547
2548 if ( $conds != '*' ) {
2549 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
2550 }
2551
2552 return $this->query( $sql, $fname );
2553 }
2554
2555 /**
2556 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2557 * into another table.
2558 *
2559 * @param $destTable string The table name to insert into
2560 * @param $srcTable string|array May be either a table name, or an array of table names
2561 * to include in a join.
2562 *
2563 * @param $varMap array must be an associative array of the form
2564 * array( 'dest1' => 'source1', ...). Source items may be literals
2565 * rather than field names, but strings should be quoted with
2566 * DatabaseBase::addQuotes()
2567 *
2568 * @param $conds array Condition array. See $conds in DatabaseBase::select() for
2569 * the details of the format of condition arrays. May be "*" to copy the
2570 * whole table.
2571 *
2572 * @param $fname string The function name of the caller, from __METHOD__
2573 *
2574 * @param $insertOptions array Options for the INSERT part of the query, see
2575 * DatabaseBase::insert() for details.
2576 * @param $selectOptions array Options for the SELECT part of the query, see
2577 * DatabaseBase::select() for details.
2578 *
2579 * @return ResultWrapper
2580 */
2581 function insertSelect( $destTable, $srcTable, $varMap, $conds,
2582 $fname = 'DatabaseBase::insertSelect',
2583 $insertOptions = array(), $selectOptions = array() )
2584 {
2585 $destTable = $this->tableName( $destTable );
2586
2587 if ( is_array( $insertOptions ) ) {
2588 $insertOptions = implode( ' ', $insertOptions );
2589 }
2590
2591 if ( !is_array( $selectOptions ) ) {
2592 $selectOptions = array( $selectOptions );
2593 }
2594
2595 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2596
2597 if ( is_array( $srcTable ) ) {
2598 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2599 } else {
2600 $srcTable = $this->tableName( $srcTable );
2601 }
2602
2603 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2604 " SELECT $startOpts " . implode( ',', $varMap ) .
2605 " FROM $srcTable $useIndex ";
2606
2607 if ( $conds != '*' ) {
2608 if ( is_array( $conds ) ) {
2609 $conds = $this->makeList( $conds, LIST_AND );
2610 }
2611 $sql .= " WHERE $conds";
2612 }
2613
2614 $sql .= " $tailOpts";
2615
2616 return $this->query( $sql, $fname );
2617 }
2618
2619 /**
2620 * Construct a LIMIT query with optional offset. This is used for query
2621 * pages. The SQL should be adjusted so that only the first $limit rows
2622 * are returned. If $offset is provided as well, then the first $offset
2623 * rows should be discarded, and the next $limit rows should be returned.
2624 * If the result of the query is not ordered, then the rows to be returned
2625 * are theoretically arbitrary.
2626 *
2627 * $sql is expected to be a SELECT, if that makes a difference. For
2628 * UPDATE, limitResultForUpdate should be used.
2629 *
2630 * The version provided by default works in MySQL and SQLite. It will very
2631 * likely need to be overridden for most other DBMSes.
2632 *
2633 * @param $sql String SQL query we will append the limit too
2634 * @param $limit Integer the SQL limit
2635 * @param $offset Integer|bool the SQL offset (default false)
2636 *
2637 * @return string
2638 */
2639 function limitResult( $sql, $limit, $offset = false ) {
2640 if ( !is_numeric( $limit ) ) {
2641 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2642 }
2643
2644 return "$sql LIMIT "
2645 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2646 . "{$limit} ";
2647 }
2648
2649 /**
2650 * @param $sql
2651 * @param $num
2652 * @return string
2653 */
2654 function limitResultForUpdate( $sql, $num ) {
2655 return $this->limitResult( $sql, $num, 0 );
2656 }
2657
2658 /**
2659 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2660 * within the UNION construct.
2661 * @return Boolean
2662 */
2663 function unionSupportsOrderAndLimit() {
2664 return true; // True for almost every DB supported
2665 }
2666
2667 /**
2668 * Construct a UNION query
2669 * This is used for providing overload point for other DB abstractions
2670 * not compatible with the MySQL syntax.
2671 * @param $sqls Array: SQL statements to combine
2672 * @param $all Boolean: use UNION ALL
2673 * @return String: SQL fragment
2674 */
2675 function unionQueries( $sqls, $all ) {
2676 $glue = $all ? ') UNION ALL (' : ') UNION (';
2677 return '(' . implode( $glue, $sqls ) . ')';
2678 }
2679
2680 /**
2681 * Returns an SQL expression for a simple conditional. This doesn't need
2682 * to be overridden unless CASE isn't supported in your DBMS.
2683 *
2684 * @param $cond String: SQL expression which will result in a boolean value
2685 * @param $trueVal String: SQL expression to return if true
2686 * @param $falseVal String: SQL expression to return if false
2687 * @return String: SQL fragment
2688 */
2689 function conditional( $cond, $trueVal, $falseVal ) {
2690 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2691 }
2692
2693 /**
2694 * Returns a comand for str_replace function in SQL query.
2695 * Uses REPLACE() in MySQL
2696 *
2697 * @param $orig String: column to modify
2698 * @param $old String: column to seek
2699 * @param $new String: column to replace with
2700 *
2701 * @return string
2702 */
2703 function strreplace( $orig, $old, $new ) {
2704 return "REPLACE({$orig}, {$old}, {$new})";
2705 }
2706
2707 /**
2708 * Determines how long the server has been up
2709 * STUB
2710 *
2711 * @return int
2712 */
2713 function getServerUptime() {
2714 return 0;
2715 }
2716
2717 /**
2718 * Determines if the last failure was due to a deadlock
2719 * STUB
2720 *
2721 * @return bool
2722 */
2723 function wasDeadlock() {
2724 return false;
2725 }
2726
2727 /**
2728 * Determines if the last failure was due to a lock timeout
2729 * STUB
2730 *
2731 * @return bool
2732 */
2733 function wasLockTimeout() {
2734 return false;
2735 }
2736
2737 /**
2738 * Determines if the last query error was something that should be dealt
2739 * with by pinging the connection and reissuing the query.
2740 * STUB
2741 *
2742 * @return bool
2743 */
2744 function wasErrorReissuable() {
2745 return false;
2746 }
2747
2748 /**
2749 * Determines if the last failure was due to the database being read-only.
2750 * STUB
2751 *
2752 * @return bool
2753 */
2754 function wasReadOnlyError() {
2755 return false;
2756 }
2757
2758 /**
2759 * Perform a deadlock-prone transaction.
2760 *
2761 * This function invokes a callback function to perform a set of write
2762 * queries. If a deadlock occurs during the processing, the transaction
2763 * will be rolled back and the callback function will be called again.
2764 *
2765 * Usage:
2766 * $dbw->deadlockLoop( callback, ... );
2767 *
2768 * Extra arguments are passed through to the specified callback function.
2769 *
2770 * Returns whatever the callback function returned on its successful,
2771 * iteration, or false on error, for example if the retry limit was
2772 * reached.
2773 *
2774 * @return bool
2775 */
2776 function deadlockLoop() {
2777
2778 $this->begin( __METHOD__ );
2779 $args = func_get_args();
2780 $function = array_shift( $args );
2781 $oldIgnore = $this->ignoreErrors( true );
2782 $tries = DEADLOCK_TRIES;
2783
2784 if ( is_array( $function ) ) {
2785 $fname = $function[0];
2786 } else {
2787 $fname = $function;
2788 }
2789
2790 do {
2791 $retVal = call_user_func_array( $function, $args );
2792 $error = $this->lastError();
2793 $errno = $this->lastErrno();
2794 $sql = $this->lastQuery();
2795
2796 if ( $errno ) {
2797 if ( $this->wasDeadlock() ) {
2798 # Retry
2799 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
2800 } else {
2801 $this->reportQueryError( $error, $errno, $sql, $fname );
2802 }
2803 }
2804 } while ( $this->wasDeadlock() && --$tries > 0 );
2805
2806 $this->ignoreErrors( $oldIgnore );
2807
2808 if ( $tries <= 0 ) {
2809 $this->rollback( __METHOD__ );
2810 $this->reportQueryError( $error, $errno, $sql, $fname );
2811 return false;
2812 } else {
2813 $this->commit( __METHOD__ );
2814 return $retVal;
2815 }
2816 }
2817
2818 /**
2819 * Wait for the slave to catch up to a given master position.
2820 *
2821 * @param $pos DBMasterPos object
2822 * @param $timeout Integer: the maximum number of seconds to wait for
2823 * synchronisation
2824 *
2825 * @return integer: zero if the slave was past that position already,
2826 * greater than zero if we waited for some period of time, less than
2827 * zero if we timed out.
2828 */
2829 function masterPosWait( DBMasterPos $pos, $timeout ) {
2830 wfProfileIn( __METHOD__ );
2831
2832 if ( !is_null( $this->mFakeSlaveLag ) ) {
2833 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
2834
2835 if ( $wait > $timeout * 1e6 ) {
2836 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2837 wfProfileOut( __METHOD__ );
2838 return -1;
2839 } elseif ( $wait > 0 ) {
2840 wfDebug( "Fake slave waiting $wait us\n" );
2841 usleep( $wait );
2842 wfProfileOut( __METHOD__ );
2843 return 1;
2844 } else {
2845 wfDebug( "Fake slave up to date ($wait us)\n" );
2846 wfProfileOut( __METHOD__ );
2847 return 0;
2848 }
2849 }
2850
2851 wfProfileOut( __METHOD__ );
2852
2853 # Real waits are implemented in the subclass.
2854 return 0;
2855 }
2856
2857 /**
2858 * Get the replication position of this slave
2859 *
2860 * @return DBMasterPos, or false if this is not a slave.
2861 */
2862 function getSlavePos() {
2863 if ( !is_null( $this->mFakeSlaveLag ) ) {
2864 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
2865 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
2866 return $pos;
2867 } else {
2868 # Stub
2869 return false;
2870 }
2871 }
2872
2873 /**
2874 * Get the position of this master
2875 *
2876 * @return DBMasterPos, or false if this is not a master
2877 */
2878 function getMasterPos() {
2879 if ( $this->mFakeMaster ) {
2880 return new MySQLMasterPos( 'fake', microtime( true ) );
2881 } else {
2882 return false;
2883 }
2884 }
2885
2886 /**
2887 * Begin a transaction, committing any previously open transaction
2888 *
2889 * @param $fname string
2890 */
2891 function begin( $fname = 'DatabaseBase::begin' ) {
2892 $this->query( 'BEGIN', $fname );
2893 $this->mTrxLevel = 1;
2894 }
2895
2896 /**
2897 * End a transaction
2898 *
2899 * @param $fname string
2900 */
2901 function commit( $fname = 'DatabaseBase::commit' ) {
2902 if ( $this->mTrxLevel ) {
2903 $this->query( 'COMMIT', $fname );
2904 $this->mTrxLevel = 0;
2905 }
2906 }
2907
2908 /**
2909 * Rollback a transaction.
2910 * No-op on non-transactional databases.
2911 *
2912 * @param $fname string
2913 */
2914 function rollback( $fname = 'DatabaseBase::rollback' ) {
2915 if ( $this->mTrxLevel ) {
2916 $this->query( 'ROLLBACK', $fname, true );
2917 $this->mTrxLevel = 0;
2918 }
2919 }
2920
2921 /**
2922 * Creates a new table with structure copied from existing table
2923 * Note that unlike most database abstraction functions, this function does not
2924 * automatically append database prefix, because it works at a lower
2925 * abstraction level.
2926 * The table names passed to this function shall not be quoted (this
2927 * function calls addIdentifierQuotes when needed).
2928 *
2929 * @param $oldName String: name of table whose structure should be copied
2930 * @param $newName String: name of table to be created
2931 * @param $temporary Boolean: whether the new table should be temporary
2932 * @param $fname String: calling function name
2933 * @return Boolean: true if operation was successful
2934 */
2935 function duplicateTableStructure( $oldName, $newName, $temporary = false,
2936 $fname = 'DatabaseBase::duplicateTableStructure' )
2937 {
2938 throw new MWException(
2939 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2940 }
2941
2942 /**
2943 * List all tables on the database
2944 *
2945 * @param $prefix string Only show tables with this prefix, e.g. mw_
2946 * @param $fname String: calling function name
2947 */
2948 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2949 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2950 }
2951
2952 /**
2953 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2954 * to the format used for inserting into timestamp fields in this DBMS.
2955 *
2956 * The result is unquoted, and needs to be passed through addQuotes()
2957 * before it can be included in raw SQL.
2958 *
2959 * @param $ts string|int
2960 *
2961 * @return string
2962 */
2963 function timestamp( $ts = 0 ) {
2964 return wfTimestamp( TS_MW, $ts );
2965 }
2966
2967 /**
2968 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2969 * to the format used for inserting into timestamp fields in this DBMS. If
2970 * NULL is input, it is passed through, allowing NULL values to be inserted
2971 * into timestamp fields.
2972 *
2973 * The result is unquoted, and needs to be passed through addQuotes()
2974 * before it can be included in raw SQL.
2975 *
2976 * @param $ts string|int
2977 *
2978 * @return string
2979 */
2980 function timestampOrNull( $ts = null ) {
2981 if ( is_null( $ts ) ) {
2982 return null;
2983 } else {
2984 return $this->timestamp( $ts );
2985 }
2986 }
2987
2988 /**
2989 * Take the result from a query, and wrap it in a ResultWrapper if
2990 * necessary. Boolean values are passed through as is, to indicate success
2991 * of write queries or failure.
2992 *
2993 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2994 * resource, and it was necessary to call this function to convert it to
2995 * a wrapper. Nowadays, raw database objects are never exposed to external
2996 * callers, so this is unnecessary in external code. For compatibility with
2997 * old code, ResultWrapper objects are passed through unaltered.
2998 *
2999 * @param $result bool|ResultWrapper
3000 *
3001 * @return bool|ResultWrapper
3002 */
3003 function resultObject( $result ) {
3004 if ( empty( $result ) ) {
3005 return false;
3006 } elseif ( $result instanceof ResultWrapper ) {
3007 return $result;
3008 } elseif ( $result === true ) {
3009 // Successful write query
3010 return $result;
3011 } else {
3012 return new ResultWrapper( $this, $result );
3013 }
3014 }
3015
3016 /**
3017 * Return aggregated value alias
3018 *
3019 * @param $valuedata
3020 * @param $valuename string
3021 *
3022 * @return string
3023 */
3024 function aggregateValue ( $valuedata, $valuename = 'value' ) {
3025 return $valuename;
3026 }
3027
3028 /**
3029 * Ping the server and try to reconnect if it there is no connection
3030 *
3031 * @return bool Success or failure
3032 */
3033 function ping() {
3034 # Stub. Not essential to override.
3035 return true;
3036 }
3037
3038 /**
3039 * Get slave lag. Currently supported only by MySQL.
3040 *
3041 * Note that this function will generate a fatal error on many
3042 * installations. Most callers should use LoadBalancer::safeGetLag()
3043 * instead.
3044 *
3045 * @return int Database replication lag in seconds
3046 */
3047 function getLag() {
3048 return intval( $this->mFakeSlaveLag );
3049 }
3050
3051 /**
3052 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3053 *
3054 * @return int
3055 */
3056 function maxListLen() {
3057 return 0;
3058 }
3059
3060 /**
3061 * Some DBMSs have a special format for inserting into blob fields, they
3062 * don't allow simple quoted strings to be inserted. To insert into such
3063 * a field, pass the data through this function before passing it to
3064 * DatabaseBase::insert().
3065 * @param $b string
3066 * @return string
3067 */
3068 function encodeBlob( $b ) {
3069 return $b;
3070 }
3071
3072 /**
3073 * Some DBMSs return a special placeholder object representing blob fields
3074 * in result objects. Pass the object through this function to return the
3075 * original string.
3076 * @param $b string
3077 * @return string
3078 */
3079 function decodeBlob( $b ) {
3080 return $b;
3081 }
3082
3083 /**
3084 * Override database's default connection timeout
3085 *
3086 * @param $timeout Integer in seconds
3087 * @return void
3088 * @deprecated since 1.19; use setSessionOptions()
3089 */
3090 public function setTimeout( $timeout ) {
3091 wfDeprecated( __METHOD__, '1.19' );
3092 $this->setSessionOptions( array( 'connTimeout' => $timeout ) );
3093 }
3094
3095 /**
3096 * Override database's default behavior. $options include:
3097 * 'connTimeout' : Set the connection timeout value in seconds.
3098 * May be useful for very long batch queries such as
3099 * full-wiki dumps, where a single query reads out over
3100 * hours or days.
3101 *
3102 * @param $options Array
3103 * @return void
3104 */
3105 public function setSessionOptions( array $options ) {}
3106
3107 /**
3108 * Read and execute SQL commands from a file.
3109 *
3110 * Returns true on success, error string or exception on failure (depending
3111 * on object's error ignore settings).
3112 *
3113 * @param $filename String: File name to open
3114 * @param $lineCallback Callback: Optional function called before reading each line
3115 * @param $resultCallback Callback: Optional function called for each MySQL result
3116 * @param $fname String: Calling function name or false if name should be
3117 * generated dynamically using $filename
3118 * @return bool|string
3119 */
3120 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
3121 wfSuppressWarnings();
3122 $fp = fopen( $filename, 'r' );
3123 wfRestoreWarnings();
3124
3125 if ( false === $fp ) {
3126 throw new MWException( "Could not open \"{$filename}\".\n" );
3127 }
3128
3129 if ( !$fname ) {
3130 $fname = __METHOD__ . "( $filename )";
3131 }
3132
3133 try {
3134 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
3135 }
3136 catch ( MWException $e ) {
3137 fclose( $fp );
3138 throw $e;
3139 }
3140
3141 fclose( $fp );
3142
3143 return $error;
3144 }
3145
3146 /**
3147 * Get the full path of a patch file. Originally based on archive()
3148 * from updaters.inc. Keep in mind this always returns a patch, as
3149 * it fails back to MySQL if no DB-specific patch can be found
3150 *
3151 * @param $patch String The name of the patch, like patch-something.sql
3152 * @return String Full path to patch file
3153 */
3154 public function patchPath( $patch ) {
3155 global $IP;
3156
3157 $dbType = $this->getType();
3158 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3159 return "$IP/maintenance/$dbType/archives/$patch";
3160 } else {
3161 return "$IP/maintenance/archives/$patch";
3162 }
3163 }
3164
3165 /**
3166 * Set variables to be used in sourceFile/sourceStream, in preference to the
3167 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3168 * all. If it's set to false, $GLOBALS will be used.
3169 *
3170 * @param $vars bool|array mapping variable name to value.
3171 */
3172 function setSchemaVars( $vars ) {
3173 $this->mSchemaVars = $vars;
3174 }
3175
3176 /**
3177 * Read and execute commands from an open file handle.
3178 *
3179 * Returns true on success, error string or exception on failure (depending
3180 * on object's error ignore settings).
3181 *
3182 * @param $fp Resource: File handle
3183 * @param $lineCallback Callback: Optional function called before reading each line
3184 * @param $resultCallback Callback: Optional function called for each MySQL result
3185 * @param $fname String: Calling function name
3186 * @param $inputCallback Callback: Optional function called for each complete line (ended with ;) sent
3187 * @return bool|string
3188 */
3189 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3190 $fname = 'DatabaseBase::sourceStream', $inputCallback = false )
3191 {
3192 $cmd = '';
3193
3194 while ( !feof( $fp ) ) {
3195 if ( $lineCallback ) {
3196 call_user_func( $lineCallback );
3197 }
3198
3199 $line = trim( fgets( $fp ) );
3200
3201 if ( $line == '' ) {
3202 continue;
3203 }
3204
3205 if ( '-' == $line[0] && '-' == $line[1] ) {
3206 continue;
3207 }
3208
3209 if ( $cmd != '' ) {
3210 $cmd .= ' ';
3211 }
3212
3213 $done = $this->streamStatementEnd( $cmd, $line );
3214
3215 $cmd .= "$line\n";
3216
3217 if ( $done || feof( $fp ) ) {
3218 $cmd = $this->replaceVars( $cmd );
3219 if ( $inputCallback ) {
3220 call_user_func( $inputCallback, $cmd );
3221 }
3222 $res = $this->query( $cmd, $fname );
3223
3224 if ( $resultCallback ) {
3225 call_user_func( $resultCallback, $res, $this );
3226 }
3227
3228 if ( false === $res ) {
3229 $err = $this->lastError();
3230 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3231 }
3232
3233 $cmd = '';
3234 }
3235 }
3236
3237 return true;
3238 }
3239
3240 /**
3241 * Called by sourceStream() to check if we've reached a statement end
3242 *
3243 * @param $sql String SQL assembled so far
3244 * @param $newLine String New line about to be added to $sql
3245 * @return Bool Whether $newLine contains end of the statement
3246 */
3247 public function streamStatementEnd( &$sql, &$newLine ) {
3248 if ( $this->delimiter ) {
3249 $prev = $newLine;
3250 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3251 if ( $newLine != $prev ) {
3252 return true;
3253 }
3254 }
3255 return false;
3256 }
3257
3258 /**
3259 * Database independent variable replacement. Replaces a set of variables
3260 * in an SQL statement with their contents as given by $this->getSchemaVars().
3261 *
3262 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3263 *
3264 * - '{$var}' should be used for text and is passed through the database's
3265 * addQuotes method.
3266 * - `{$var}` should be used for identifiers (eg: table and database names),
3267 * it is passed through the database's addIdentifierQuotes method which
3268 * can be overridden if the database uses something other than backticks.
3269 * - / *$var* / is just encoded, besides traditional table prefix and
3270 * table options its use should be avoided.
3271 *
3272 * @param $ins String: SQL statement to replace variables in
3273 * @return String The new SQL statement with variables replaced
3274 */
3275 protected function replaceSchemaVars( $ins ) {
3276 $vars = $this->getSchemaVars();
3277 foreach ( $vars as $var => $value ) {
3278 // replace '{$var}'
3279 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3280 // replace `{$var}`
3281 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3282 // replace /*$var*/
3283 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
3284 }
3285 return $ins;
3286 }
3287
3288 /**
3289 * Replace variables in sourced SQL
3290 *
3291 * @param $ins string
3292 *
3293 * @return string
3294 */
3295 protected function replaceVars( $ins ) {
3296 $ins = $this->replaceSchemaVars( $ins );
3297
3298 // Table prefixes
3299 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3300 array( $this, 'tableNameCallback' ), $ins );
3301
3302 // Index names
3303 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3304 array( $this, 'indexNameCallback' ), $ins );
3305
3306 return $ins;
3307 }
3308
3309 /**
3310 * Get schema variables. If none have been set via setSchemaVars(), then
3311 * use some defaults from the current object.
3312 *
3313 * @return array
3314 */
3315 protected function getSchemaVars() {
3316 if ( $this->mSchemaVars ) {
3317 return $this->mSchemaVars;
3318 } else {
3319 return $this->getDefaultSchemaVars();
3320 }
3321 }
3322
3323 /**
3324 * Get schema variables to use if none have been set via setSchemaVars().
3325 *
3326 * Override this in derived classes to provide variables for tables.sql
3327 * and SQL patch files.
3328 *
3329 * @return array
3330 */
3331 protected function getDefaultSchemaVars() {
3332 return array();
3333 }
3334
3335 /**
3336 * Table name callback
3337 *
3338 * @param $matches array
3339 *
3340 * @return string
3341 */
3342 protected function tableNameCallback( $matches ) {
3343 return $this->tableName( $matches[1] );
3344 }
3345
3346 /**
3347 * Index name callback
3348 *
3349 * @param $matches array
3350 *
3351 * @return string
3352 */
3353 protected function indexNameCallback( $matches ) {
3354 return $this->indexName( $matches[1] );
3355 }
3356
3357 /**
3358 * Build a concatenation list to feed into a SQL query
3359 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
3360 * @return String
3361 */
3362 function buildConcat( $stringList ) {
3363 return 'CONCAT(' . implode( ',', $stringList ) . ')';
3364 }
3365
3366 /**
3367 * Acquire a named lock
3368 *
3369 * Abstracted from Filestore::lock() so child classes can implement for
3370 * their own needs.
3371 *
3372 * @param $lockName String: name of lock to aquire
3373 * @param $method String: name of method calling us
3374 * @param $timeout Integer: timeout
3375 * @return Boolean
3376 */
3377 public function lock( $lockName, $method, $timeout = 5 ) {
3378 return true;
3379 }
3380
3381 /**
3382 * Release a lock.
3383 *
3384 * @param $lockName String: Name of lock to release
3385 * @param $method String: Name of method calling us
3386 *
3387 * @return int Returns 1 if the lock was released, 0 if the lock was not established
3388 * by this thread (in which case the lock is not released), and NULL if the named
3389 * lock did not exist
3390 */
3391 public function unlock( $lockName, $method ) {
3392 return true;
3393 }
3394
3395 /**
3396 * Lock specific tables
3397 *
3398 * @param $read Array of tables to lock for read access
3399 * @param $write Array of tables to lock for write access
3400 * @param $method String name of caller
3401 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
3402 *
3403 * @return bool
3404 */
3405 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3406 return true;
3407 }
3408
3409 /**
3410 * Unlock specific tables
3411 *
3412 * @param $method String the caller
3413 *
3414 * @return bool
3415 */
3416 public function unlockTables( $method ) {
3417 return true;
3418 }
3419
3420 /**
3421 * Delete a table
3422 * @param $tableName string
3423 * @param $fName string
3424 * @return bool|ResultWrapper
3425 * @since 1.18
3426 */
3427 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
3428 if( !$this->tableExists( $tableName, $fName ) ) {
3429 return false;
3430 }
3431 $sql = "DROP TABLE " . $this->tableName( $tableName );
3432 if( $this->cascadingDeletes() ) {
3433 $sql .= " CASCADE";
3434 }
3435 return $this->query( $sql, $fName );
3436 }
3437
3438 /**
3439 * Get search engine class. All subclasses of this need to implement this
3440 * if they wish to use searching.
3441 *
3442 * @return String
3443 */
3444 public function getSearchEngine() {
3445 return 'SearchEngineDummy';
3446 }
3447
3448 /**
3449 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3450 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3451 * because "i" sorts after all numbers.
3452 *
3453 * @return String
3454 */
3455 public function getInfinity() {
3456 return 'infinity';
3457 }
3458
3459 /**
3460 * Encode an expiry time into the DBMS dependent format
3461 *
3462 * @param $expiry String: timestamp for expiry, or the 'infinity' string
3463 * @return String
3464 */
3465 public function encodeExpiry( $expiry ) {
3466 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3467 ? $this->getInfinity()
3468 : $this->timestamp( $expiry );
3469 }
3470
3471 /**
3472 * Decode an expiry time into a DBMS independent format
3473 *
3474 * @param $expiry String: DB timestamp field value for expiry
3475 * @param $format integer: TS_* constant, defaults to TS_MW
3476 * @return String
3477 */
3478 public function decodeExpiry( $expiry, $format = TS_MW ) {
3479 return ( $expiry == '' || $expiry == $this->getInfinity() )
3480 ? 'infinity'
3481 : wfTimestamp( $format, $expiry );
3482 }
3483
3484 /**
3485 * Allow or deny "big selects" for this session only. This is done by setting
3486 * the sql_big_selects session variable.
3487 *
3488 * This is a MySQL-specific feature.
3489 *
3490 * @param $value Mixed: true for allow, false for deny, or "default" to
3491 * restore the initial value
3492 */
3493 public function setBigSelects( $value = true ) {
3494 // no-op
3495 }
3496 }