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