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