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