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