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