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