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