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