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