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