b26970eb0d240959f504fa10666750fd4e198f07
[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 /**
805 * Intended to be compatible with the PEAR::DB wrapper functions.
806 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
807 *
808 * ? = scalar value, quoted as necessary
809 * ! = raw SQL bit (a function for instance)
810 * & = filename; reads the file and inserts as a blob
811 * (we don't use this though...)
812 *
813 * @return array
814 */
815 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
816 /* MySQL doesn't support prepared statements (yet), so just
817 pack up the query for reference. We'll manually replace
818 the bits later. */
819 return array( 'query' => $sql, 'func' => $func );
820 }
821
822 function freePrepared( $prepared ) {
823 /* No-op by default */
824 }
825
826 /**
827 * Execute a prepared query with the various arguments
828 * @param $prepared String: the prepared sql
829 * @param $args Mixed: Either an array here, or put scalars as varargs
830 *
831 * @return ResultWrapper
832 */
833 function execute( $prepared, $args = null ) {
834 if ( !is_array( $args ) ) {
835 # Pull the var args
836 $args = func_get_args();
837 array_shift( $args );
838 }
839
840 $sql = $this->fillPrepared( $prepared['query'], $args );
841
842 return $this->query( $sql, $prepared['func'] );
843 }
844
845 /**
846 * Prepare & execute an SQL statement, quoting and inserting arguments
847 * in the appropriate places.
848 * @param $query String
849 * @param $args ...
850 *
851 * @return ResultWrapper
852 */
853 function safeQuery( $query, $args = null ) {
854 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
855
856 if ( !is_array( $args ) ) {
857 # Pull the var args
858 $args = func_get_args();
859 array_shift( $args );
860 }
861
862 $retval = $this->execute( $prepared, $args );
863 $this->freePrepared( $prepared );
864
865 return $retval;
866 }
867
868 /**
869 * For faking prepared SQL statements on DBs that don't support
870 * it directly.
871 * @param $preparedQuery String: a 'preparable' SQL statement
872 * @param $args Array of arguments to fill it with
873 * @return string executable SQL
874 */
875 function fillPrepared( $preparedQuery, $args ) {
876 reset( $args );
877 $this->preparedArgs =& $args;
878
879 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
880 array( &$this, 'fillPreparedArg' ), $preparedQuery );
881 }
882
883 /**
884 * preg_callback func for fillPrepared()
885 * The arguments should be in $this->preparedArgs and must not be touched
886 * while we're doing this.
887 *
888 * @param $matches Array
889 * @return String
890 * @private
891 */
892 function fillPreparedArg( $matches ) {
893 switch( $matches[1] ) {
894 case '\\?': return '?';
895 case '\\!': return '!';
896 case '\\&': return '&';
897 }
898
899 list( /* $n */ , $arg ) = each( $this->preparedArgs );
900
901 switch( $matches[1] ) {
902 case '?': return $this->addQuotes( $arg );
903 case '!': return $arg;
904 case '&':
905 # return $this->addQuotes( file_get_contents( $arg ) );
906 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
907 default:
908 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
909 }
910 }
911
912 /**
913 * Free a result object
914 * @param $res Mixed: A SQL result
915 */
916 function freeResult( $res ) {
917 # Stub. Might not really need to be overridden, since results should
918 # be freed by PHP when the variable goes out of scope anyway.
919 }
920
921 /**
922 * Simple UPDATE wrapper
923 * Usually aborts on failure
924 * If errors are explicitly ignored, returns success
925 *
926 * This function exists for historical reasons, DatabaseBase::update() has a more standard
927 * calling convention and feature set
928 *
929 * @return bool
930 */
931 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
932 $table = $this->tableName( $table );
933 $sql = "UPDATE $table SET $var = '" .
934 $this->strencode( $value ) . "' WHERE ($cond)";
935
936 return (bool)$this->query( $sql, $fname );
937 }
938
939 /**
940 * Simple SELECT wrapper, returns a single field, input must be encoded
941 * Usually aborts on failure
942 * If errors are explicitly ignored, returns FALSE on failure
943 */
944 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
945 if ( !is_array( $options ) ) {
946 $options = array( $options );
947 }
948
949 $options['LIMIT'] = 1;
950
951 $res = $this->select( $table, $var, $cond, $fname, $options );
952
953 if ( $res === false || !$this->numRows( $res ) ) {
954 return false;
955 }
956
957 $row = $this->fetchRow( $res );
958
959 if ( $row !== false ) {
960 return reset( $row );
961 } else {
962 return false;
963 }
964 }
965
966 /**
967 * Returns an optional USE INDEX clause to go after the table, and a
968 * string to go at the end of the query
969 *
970 * @private
971 *
972 * @param $options Array: associative array of options to be turned into
973 * an SQL query, valid keys are listed in the function.
974 * @return Array
975 */
976 function makeSelectOptions( $options ) {
977 $preLimitTail = $postLimitTail = '';
978 $startOpts = '';
979
980 $noKeyOptions = array();
981
982 foreach ( $options as $key => $option ) {
983 if ( is_numeric( $key ) ) {
984 $noKeyOptions[$option] = true;
985 }
986 }
987
988 if ( isset( $options['GROUP BY'] ) ) {
989 $gb = is_array( $options['GROUP BY'] )
990 ? implode( ',', $options['GROUP BY'] )
991 : $options['GROUP BY'];
992 $preLimitTail .= " GROUP BY {$gb}";
993 }
994
995 if ( isset( $options['HAVING'] ) ) {
996 $preLimitTail .= " HAVING {$options['HAVING']}";
997 }
998
999 if ( isset( $options['ORDER BY'] ) ) {
1000 $ob = is_array( $options['ORDER BY'] )
1001 ? implode( ',', $options['ORDER BY'] )
1002 : $options['ORDER BY'];
1003 $preLimitTail .= " ORDER BY {$ob}";
1004 }
1005
1006 // if (isset($options['LIMIT'])) {
1007 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1008 // isset($options['OFFSET']) ? $options['OFFSET']
1009 // : false);
1010 // }
1011
1012 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1013 $postLimitTail .= ' FOR UPDATE';
1014 }
1015
1016 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1017 $postLimitTail .= ' LOCK IN SHARE MODE';
1018 }
1019
1020 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1021 $startOpts .= 'DISTINCT';
1022 }
1023
1024 # Various MySQL extensions
1025 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1026 $startOpts .= ' /*! STRAIGHT_JOIN */';
1027 }
1028
1029 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1030 $startOpts .= ' HIGH_PRIORITY';
1031 }
1032
1033 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1034 $startOpts .= ' SQL_BIG_RESULT';
1035 }
1036
1037 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1038 $startOpts .= ' SQL_BUFFER_RESULT';
1039 }
1040
1041 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1042 $startOpts .= ' SQL_SMALL_RESULT';
1043 }
1044
1045 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1046 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1047 }
1048
1049 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1050 $startOpts .= ' SQL_CACHE';
1051 }
1052
1053 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1054 $startOpts .= ' SQL_NO_CACHE';
1055 }
1056
1057 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1058 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1059 } else {
1060 $useIndex = '';
1061 }
1062
1063 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1064 }
1065
1066 /**
1067 * SELECT wrapper
1068 *
1069 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1070 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1071 * @param $conds Mixed: Array or string, condition(s) for WHERE
1072 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1073 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1074 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1075 * @param $join_conds Array: Associative array of table join conditions (optional)
1076 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1077 * @return ResultWrapper|Bool Database result resource (feed to DatabaseBase::fetchObject
1078 * or whatever), or false on failure
1079 */
1080 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1081 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1082
1083 return $this->query( $sql, $fname );
1084 }
1085
1086 /**
1087 * SELECT wrapper
1088 *
1089 * @param $table Mixed: Array or string, table name(s) (prefix auto-added). Array keys are table aliases (optional)
1090 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1091 * @param $conds Mixed: Array or string, condition(s) for WHERE
1092 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1093 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1094 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1095 * @param $join_conds Array: Associative array of table join conditions (optional)
1096 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1097 * @return string, the SQL text
1098 */
1099 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1100 if ( is_array( $vars ) ) {
1101 $vars = implode( ',', $vars );
1102 }
1103
1104 if ( !is_array( $options ) ) {
1105 $options = array( $options );
1106 }
1107
1108 if ( is_array( $table ) ) {
1109 if ( !empty( $join_conds ) || ( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
1110 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1111 } else {
1112 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1113 }
1114 } elseif ( $table != '' ) {
1115 if ( $table { 0 } == ' ' ) {
1116 $from = ' FROM ' . $table;
1117 } else {
1118 $from = ' FROM ' . $this->tableName( $table );
1119 }
1120 } else {
1121 $from = '';
1122 }
1123
1124 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1125
1126 if ( !empty( $conds ) ) {
1127 if ( is_array( $conds ) ) {
1128 $conds = $this->makeList( $conds, LIST_AND );
1129 }
1130 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1131 } else {
1132 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1133 }
1134
1135 if ( isset( $options['LIMIT'] ) )
1136 $sql = $this->limitResult( $sql, $options['LIMIT'],
1137 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1138 $sql = "$sql $postLimitTail";
1139
1140 if ( isset( $options['EXPLAIN'] ) ) {
1141 $sql = 'EXPLAIN ' . $sql;
1142 }
1143
1144 return $sql;
1145 }
1146
1147 /**
1148 * Single row SELECT wrapper
1149 * Aborts or returns FALSE on error
1150 *
1151 * @param $table String: table name
1152 * @param $vars String: the selected variables
1153 * @param $conds Array: a condition map, terms are ANDed together.
1154 * Items with numeric keys are taken to be literal conditions
1155 * Takes an array of selected variables, and a condition map, which is ANDed
1156 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1157 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1158 * $obj- >page_id is the ID of the Astronomy article
1159 * @param $fname String: Calling function name
1160 * @param $options Array
1161 * @param $join_conds Array
1162 *
1163 * @return ResultWrapper|Bool
1164 */
1165 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
1166 $options['LIMIT'] = 1;
1167 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1168
1169 if ( $res === false ) {
1170 return false;
1171 }
1172
1173 if ( !$this->numRows( $res ) ) {
1174 return false;
1175 }
1176
1177 $obj = $this->fetchObject( $res );
1178
1179 return $obj;
1180 }
1181
1182 /**
1183 * Estimate rows in dataset
1184 * Returns estimated count - not necessarily an accurate estimate across different databases,
1185 * so use sparingly
1186 * Takes same arguments as DatabaseBase::select()
1187 *
1188 * @param $table String: table name
1189 * @param $vars Array: unused
1190 * @param $conds Array: filters on the table
1191 * @param $fname String: function name for profiling
1192 * @param $options Array: options for select
1193 * @return Integer: row count
1194 */
1195 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
1196 $rows = 0;
1197 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1198
1199 if ( $res ) {
1200 $row = $this->fetchRow( $res );
1201 $rows = ( isset( $row['rowcount'] ) ) ? $row['rowcount'] : 0;
1202 }
1203
1204 return $rows;
1205 }
1206
1207 /**
1208 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1209 * It's only slightly flawed. Don't use for anything important.
1210 *
1211 * @param $sql String: A SQL Query
1212 */
1213 static function generalizeSQL( $sql ) {
1214 # This does the same as the regexp below would do, but in such a way
1215 # as to avoid crashing php on some large strings.
1216 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1217
1218 $sql = str_replace ( "\\\\", '', $sql );
1219 $sql = str_replace ( "\\'", '', $sql );
1220 $sql = str_replace ( "\\\"", '', $sql );
1221 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1222 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1223
1224 # All newlines, tabs, etc replaced by single space
1225 $sql = preg_replace ( '/\s+/', ' ', $sql );
1226
1227 # All numbers => N
1228 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1229
1230 return $sql;
1231 }
1232
1233 /**
1234 * Determines whether a field exists in a table
1235 *
1236 * @param $table String: table name
1237 * @param $field String: filed to check on that table
1238 * @param $fname String: calling function name (optional)
1239 * @return Boolean: whether $table has filed $field
1240 */
1241 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1242 $info = $this->fieldInfo( $table, $field );
1243
1244 return (bool)$info;
1245 }
1246
1247 /**
1248 * Determines whether an index exists
1249 * Usually aborts on failure
1250 * If errors are explicitly ignored, returns NULL on failure
1251 *
1252 * @return bool|null
1253 */
1254 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1255 $info = $this->indexInfo( $table, $index, $fname );
1256 if ( is_null( $info ) ) {
1257 return null;
1258 } else {
1259 return $info !== false;
1260 }
1261 }
1262
1263 /**
1264 * Query whether a given table exists
1265 *
1266 * @string table
1267 *
1268 * @return bool
1269 */
1270 function tableExists( $table ) {
1271 $table = $this->tableName( $table );
1272 $old = $this->ignoreErrors( true );
1273 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__ );
1274 $this->ignoreErrors( $old );
1275
1276 return (bool)$res;
1277 }
1278
1279 /**
1280 * mysql_field_type() wrapper
1281 */
1282 function fieldType( $res, $index ) {
1283 if ( $res instanceof ResultWrapper ) {
1284 $res = $res->result;
1285 }
1286
1287 return mysql_field_type( $res, $index );
1288 }
1289
1290 /**
1291 * Determines if a given index is unique
1292 *
1293 * @param $table string
1294 * @param $index string
1295 *
1296 * @return bool
1297 */
1298 function indexUnique( $table, $index ) {
1299 $indexInfo = $this->indexInfo( $table, $index );
1300
1301 if ( !$indexInfo ) {
1302 return null;
1303 }
1304
1305 return !$indexInfo[0]->Non_unique;
1306 }
1307
1308 /**
1309 * @param $options array
1310 * @return string
1311 */
1312 function makeInsertOptions( $options ) {
1313 return implode( ' ', $options );
1314 }
1315
1316 /**
1317 * INSERT wrapper, inserts an array into a table
1318 *
1319 * $a may be a single associative array, or an array of these with numeric keys, for
1320 * multi-row insert.
1321 *
1322 * Usually aborts on failure
1323 * If errors are explicitly ignored, returns success
1324 *
1325 * @param $table String: table name (prefix auto-added)
1326 * @param $a Array: Array of rows to insert
1327 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1328 * @param $options Mixed: Associative array of options
1329 *
1330 * @return bool
1331 */
1332 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1333 # No rows to insert, easy just return now
1334 if ( !count( $a ) ) {
1335 return true;
1336 }
1337
1338 $table = $this->tableName( $table );
1339
1340 if ( !is_array( $options ) ) {
1341 $options = array( $options );
1342 }
1343
1344 $options = $this->makeInsertOptions( $options );
1345
1346 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1347 $multi = true;
1348 $keys = array_keys( $a[0] );
1349 } else {
1350 $multi = false;
1351 $keys = array_keys( $a );
1352 }
1353
1354 $sql = 'INSERT ' . $options .
1355 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1356
1357 if ( $multi ) {
1358 $first = true;
1359 foreach ( $a as $row ) {
1360 if ( $first ) {
1361 $first = false;
1362 } else {
1363 $sql .= ',';
1364 }
1365 $sql .= '(' . $this->makeList( $row ) . ')';
1366 }
1367 } else {
1368 $sql .= '(' . $this->makeList( $a ) . ')';
1369 }
1370
1371 return (bool)$this->query( $sql, $fname );
1372 }
1373
1374 /**
1375 * Make UPDATE options for the DatabaseBase::update function
1376 *
1377 * @private
1378 * @param $options Array: The options passed to DatabaseBase::update
1379 * @return string
1380 */
1381 function makeUpdateOptions( $options ) {
1382 if ( !is_array( $options ) ) {
1383 $options = array( $options );
1384 }
1385
1386 $opts = array();
1387
1388 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1389 $opts[] = $this->lowPriorityOption();
1390 }
1391
1392 if ( in_array( 'IGNORE', $options ) ) {
1393 $opts[] = 'IGNORE';
1394 }
1395
1396 return implode( ' ', $opts );
1397 }
1398
1399 /**
1400 * UPDATE wrapper, takes a condition array and a SET array
1401 *
1402 * @param $table String: The table to UPDATE
1403 * @param $values Array: An array of values to SET
1404 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1405 * @param $fname String: The Class::Function calling this function
1406 * (for the log)
1407 * @param $options Array: An array of UPDATE options, can be one or
1408 * more of IGNORE, LOW_PRIORITY
1409 * @return Boolean
1410 */
1411 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1412 $table = $this->tableName( $table );
1413 $opts = $this->makeUpdateOptions( $options );
1414 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1415
1416 if ( $conds != '*' ) {
1417 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1418 }
1419
1420 return $this->query( $sql, $fname );
1421 }
1422
1423 /**
1424 * Makes an encoded list of strings from an array
1425 * @param $a Array
1426 * @param $mode int
1427 * LIST_COMMA - comma separated, no field names
1428 * LIST_AND - ANDed WHERE clause (without the WHERE)
1429 * LIST_OR - ORed WHERE clause (without the WHERE)
1430 * LIST_SET - comma separated with field names, like a SET clause
1431 * LIST_NAMES - comma separated field names
1432 *
1433 * In LIST_AND or LIST_OR modes, you can suffix a field with an exclamation
1434 * mark to generate a 'NOT IN' structure.
1435 * Example:
1436 * $db->makeList( array( 'field!' => array( 1,2,3 ) );
1437 * outputs:
1438 * 'field' NOT IN ('1', '2', '3' );
1439
1440 * @return string
1441 */
1442 function makeList( $a, $mode = LIST_COMMA ) {
1443 if ( !is_array( $a ) ) {
1444 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1445 }
1446
1447 $first = true;
1448 $list = '';
1449
1450 foreach ( $a as $field => $value ) {
1451 if ( !$first ) {
1452 if ( $mode == LIST_AND ) {
1453 $list .= ' AND ';
1454 } elseif ( $mode == LIST_OR ) {
1455 $list .= ' OR ';
1456 } else {
1457 $list .= ',';
1458 }
1459 } else {
1460 $first = false;
1461 }
1462
1463 // Support 'NOT IN' by suffixing fieldname with an exclamation mark
1464 $not = false;
1465 if( substr($field,-1) == '!' ) {
1466 $not = true;
1467 $field = substr($field, 0, -1 );
1468 }
1469
1470 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1471 $list .= "($value)";
1472 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1473 $list .= "$value";
1474 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1475 if ( count( $value ) == 0 ) {
1476 throw new MWException( __METHOD__ . ': empty input' );
1477 } elseif ( count( $value ) == 1 ) {
1478 // Special-case single values, as IN isn't terribly efficient
1479 // Don't necessarily assume the single key is 0; we don't
1480 // enforce linear numeric ordering on other arrays here.
1481 $value = array_values( $value );
1482
1483 $operator = $not ? ' != ' : ' = ';
1484 $list .= $field . $operator . $this->addQuotes( $value[0] );
1485 } else {
1486 $operator = $not ? ' NOT IN ' : ' IN ';
1487 $list .= $field . $operator . "(" . $this->makeList( $value ) . ")";
1488 }
1489 } elseif ( $value === null ) {
1490 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1491 $list .= "$field IS ";
1492 } elseif ( $mode == LIST_SET ) {
1493 $list .= "$field = ";
1494 }
1495 $list .= 'NULL';
1496 } else {
1497 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1498 $list .= "$field = ";
1499 }
1500 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1501 }
1502 }
1503
1504 return $list;
1505 }
1506
1507 /**
1508 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1509 * The keys on each level may be either integers or strings.
1510 *
1511 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1512 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1513 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1514 * @return Mixed: string SQL fragment, or false if no items in array.
1515 */
1516 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1517 $conds = array();
1518
1519 foreach ( $data as $base => $sub ) {
1520 if ( count( $sub ) ) {
1521 $conds[] = $this->makeList(
1522 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1523 LIST_AND );
1524 }
1525 }
1526
1527 if ( $conds ) {
1528 return $this->makeList( $conds, LIST_OR );
1529 } else {
1530 // Nothing to search for...
1531 return false;
1532 }
1533 }
1534
1535 /**
1536 * Bitwise operations
1537 */
1538
1539 /**
1540 * @param $field
1541 * @return string
1542 */
1543 function bitNot( $field ) {
1544 return "(~$field)";
1545 }
1546
1547 /**
1548 * @param $fieldLeft
1549 * @param $fieldRight
1550 * @return string
1551 */
1552 function bitAnd( $fieldLeft, $fieldRight ) {
1553 return "($fieldLeft & $fieldRight)";
1554 }
1555
1556 /**
1557 * @param $fieldLeft
1558 * @param $fieldRight
1559 * @return string
1560 */
1561 function bitOr( $fieldLeft, $fieldRight ) {
1562 return "($fieldLeft | $fieldRight)";
1563 }
1564
1565 /**
1566 * Change the current database
1567 *
1568 * @todo Explain what exactly will fail if this is not overridden.
1569 * @return bool Success or failure
1570 */
1571 function selectDB( $db ) {
1572 # Stub. Shouldn't cause serious problems if it's not overridden, but
1573 # if your database engine supports a concept similar to MySQL's
1574 # databases you may as well.
1575 $this->mDBname = $db;
1576 return true;
1577 }
1578
1579 /**
1580 * Get the current DB name
1581 */
1582 function getDBname() {
1583 return $this->mDBname;
1584 }
1585
1586 /**
1587 * Get the server hostname or IP address
1588 */
1589 function getServer() {
1590 return $this->mServer;
1591 }
1592
1593 /**
1594 * Format a table name ready for use in constructing an SQL query
1595 *
1596 * This does two important things: it quotes the table names to clean them up,
1597 * and it adds a table prefix if only given a table name with no quotes.
1598 *
1599 * All functions of this object which require a table name call this function
1600 * themselves. Pass the canonical name to such functions. This is only needed
1601 * when calling query() directly.
1602 *
1603 * @param $name String: database table name
1604 * @param $quoted Boolean: Automatically pass the table name through
1605 * addIdentifierQuotes() so that it can be used in a query.
1606 * @return String: full database name
1607 */
1608 function tableName( $name, $quoted = true ) {
1609 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1610 # Skip the entire process when we have a string quoted on both ends.
1611 # Note that we check the end so that we will still quote any use of
1612 # use of `database`.table. But won't break things if someone wants
1613 # to query a database table with a dot in the name.
1614 if ( $this->isQuotedIdentifier( $name ) ) {
1615 return $name;
1616 }
1617
1618 # Lets test for any bits of text that should never show up in a table
1619 # name. Basically anything like JOIN or ON which are actually part of
1620 # SQL queries, but may end up inside of the table value to combine
1621 # sql. Such as how the API is doing.
1622 # Note that we use a whitespace test rather than a \b test to avoid
1623 # any remote case where a word like on may be inside of a table name
1624 # surrounded by symbols which may be considered word breaks.
1625 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1626 return $name;
1627 }
1628
1629 # Split database and table into proper variables.
1630 # We reverse the explode so that database.table and table both output
1631 # the correct table.
1632 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1633 if ( isset( $dbDetails[1] ) ) {
1634 @list( $table, $database ) = $dbDetails;
1635 } else {
1636 @list( $table ) = $dbDetails;
1637 }
1638 $prefix = $this->mTablePrefix; # Default prefix
1639
1640 # Note that we use the long format because php will complain in in_array if
1641 # the input is not an array, and will complain in is_array if it is not set.
1642 if ( !isset( $database ) # Don't use shared database if pre selected.
1643 && isset( $wgSharedDB ) # We have a shared database
1644 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1645 && isset( $wgSharedTables )
1646 && is_array( $wgSharedTables )
1647 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1648 $database = $wgSharedDB;
1649 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
1650 }
1651
1652 # Quote the $database and $table and apply the prefix if not quoted.
1653 if ( isset( $database ) ) {
1654 $database = ( !$quoted || $this->isQuotedIdentifier( $database ) ? $database : $this->addIdentifierQuotes( $database ) );
1655 $prefix = '';
1656 }
1657
1658 $table = "{$prefix}{$table}";
1659 if ( $quoted && !$this->isQuotedIdentifier( $table ) ) {
1660 $table = $this->addIdentifierQuotes( "{$table}" );
1661 }
1662
1663 # Merge our database and table into our final table name.
1664 $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
1665
1666 return $tableName;
1667 }
1668
1669 /**
1670 * Fetch a number of table names into an array
1671 * This is handy when you need to construct SQL for joins
1672 *
1673 * Example:
1674 * extract($dbr->tableNames('user','watchlist'));
1675 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1676 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1677 */
1678 public function tableNames() {
1679 $inArray = func_get_args();
1680 $retVal = array();
1681
1682 foreach ( $inArray as $name ) {
1683 $retVal[$name] = $this->tableName( $name );
1684 }
1685
1686 return $retVal;
1687 }
1688
1689 /**
1690 * Fetch a number of table names into an zero-indexed numerical array
1691 * This is handy when you need to construct SQL for joins
1692 *
1693 * Example:
1694 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1695 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1696 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1697 */
1698 public function tableNamesN() {
1699 $inArray = func_get_args();
1700 $retVal = array();
1701
1702 foreach ( $inArray as $name ) {
1703 $retVal[] = $this->tableName( $name );
1704 }
1705
1706 return $retVal;
1707 }
1708
1709 /**
1710 * Get an aliased table name
1711 * e.g. tableName AS newTableName
1712 *
1713 * @param $name string Table name, see tableName()
1714 * @param $alias string Alias (optional)
1715 * @return string SQL name for aliased table. Will not alias a table to its own name
1716 */
1717 public function tableNameWithAlias( $name, $alias = false ) {
1718 if ( !$alias || $alias == $name ) {
1719 return $this->tableName( $name );
1720 } else {
1721 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1722 }
1723 }
1724
1725 /**
1726 * Gets an array of aliased table names
1727 *
1728 * @param $tables array( [alias] => table )
1729 * @return array of strings, see tableNameWithAlias()
1730 */
1731 public function tableNamesWithAlias( $tables ) {
1732 $retval = array();
1733 foreach ( $tables as $alias => $table ) {
1734 if ( is_numeric( $alias ) ) {
1735 $alias = $table;
1736 }
1737 $retval[] = $this->tableNameWithAlias( $table, $alias );
1738 }
1739 return $retval;
1740 }
1741
1742 /**
1743 * @return string
1744 */
1745 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1746 $ret = array();
1747 $retJOIN = array();
1748 $use_index_safe = is_array( $use_index ) ? $use_index : array();
1749 $join_conds_safe = is_array( $join_conds ) ? $join_conds : array();
1750
1751 foreach ( $tables as $alias => $table ) {
1752 if ( !is_string( $alias ) ) {
1753 // No alias? Set it equal to the table name
1754 $alias = $table;
1755 }
1756 // Is there a JOIN and INDEX clause for this table?
1757 if ( isset( $join_conds_safe[$alias] ) && isset( $use_index_safe[$alias] ) ) {
1758 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1759 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1760 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND );
1761 if ( $on != '' ) {
1762 $tableClause .= ' ON (' . $on . ')';
1763 }
1764
1765 $retJOIN[] = $tableClause;
1766 // Is there an INDEX clause?
1767 } else if ( isset( $use_index_safe[$alias] ) ) {
1768 $tableClause = $this->tableNameWithAlias( $table, $alias );
1769 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1770 $ret[] = $tableClause;
1771 // Is there a JOIN clause?
1772 } else if ( isset( $join_conds_safe[$alias] ) ) {
1773 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1774 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND );
1775 if ( $on != '' ) {
1776 $tableClause .= ' ON (' . $on . ')';
1777 }
1778
1779 $retJOIN[] = $tableClause;
1780 } else {
1781 $tableClause = $this->tableNameWithAlias( $table, $alias );
1782 $ret[] = $tableClause;
1783 }
1784 }
1785
1786 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1787 $straightJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
1788 $otherJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
1789
1790 // Compile our final table clause
1791 return implode( ' ', array( $straightJoins, $otherJoins ) );
1792 }
1793
1794 /**
1795 * Get the name of an index in a given table
1796 *
1797 * @param $index
1798 *
1799 * @return string
1800 */
1801 function indexName( $index ) {
1802 // Backwards-compatibility hack
1803 $renamed = array(
1804 'ar_usertext_timestamp' => 'usertext_timestamp',
1805 'un_user_id' => 'user_id',
1806 'un_user_ip' => 'user_ip',
1807 );
1808
1809 if ( isset( $renamed[$index] ) ) {
1810 return $renamed[$index];
1811 } else {
1812 return $index;
1813 }
1814 }
1815
1816 /**
1817 * If it's a string, adds quotes and backslashes
1818 * Otherwise returns as-is
1819 *
1820 * @param $s string
1821 *
1822 * @return string
1823 */
1824 function addQuotes( $s ) {
1825 if ( $s === null ) {
1826 return 'NULL';
1827 } else {
1828 # This will also quote numeric values. This should be harmless,
1829 # and protects against weird problems that occur when they really
1830 # _are_ strings such as article titles and string->number->string
1831 # conversion is not 1:1.
1832 return "'" . $this->strencode( $s ) . "'";
1833 }
1834 }
1835
1836 /**
1837 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1838 * MySQL uses `backticks` while basically everything else uses double quotes.
1839 * Since MySQL is the odd one out here the double quotes are our generic
1840 * and we implement backticks in DatabaseMysql.
1841 *
1842 * @return string
1843 */
1844 public function addIdentifierQuotes( $s ) {
1845 return '"' . str_replace( '"', '""', $s ) . '"';
1846 }
1847
1848 /**
1849 * Returns if the given identifier looks quoted or not according to
1850 * the database convention for quoting identifiers .
1851 *
1852 * @param $name string
1853 *
1854 * @return boolean
1855 */
1856 public function isQuotedIdentifier( $name ) {
1857 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1858 }
1859
1860 /**
1861 * Backwards compatibility, identifier quoting originated in DatabasePostgres
1862 * which used quote_ident which does not follow our naming conventions
1863 * was renamed to addIdentifierQuotes.
1864 * @deprecated since 1.18 use addIdentifierQuotes
1865 *
1866 * @return string
1867 */
1868 function quote_ident( $s ) {
1869 wfDeprecated( __METHOD__ );
1870 return $this->addIdentifierQuotes( $s );
1871 }
1872
1873 /**
1874 * Escape string for safe LIKE usage.
1875 * WARNING: you should almost never use this function directly,
1876 * instead use buildLike() that escapes everything automatically
1877 * @deprecated since 1.17, warnings in 1.17, removed in ???
1878 */
1879 public function escapeLike( $s ) {
1880 wfDeprecated( __METHOD__ );
1881 return $this->escapeLikeInternal( $s );
1882 }
1883
1884 protected function escapeLikeInternal( $s ) {
1885 $s = str_replace( '\\', '\\\\', $s );
1886 $s = $this->strencode( $s );
1887 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1888
1889 return $s;
1890 }
1891
1892 /**
1893 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1894 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1895 * Alternatively, the function could be provided with an array of aforementioned parameters.
1896 *
1897 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1898 * for subpages of 'My page title'.
1899 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1900 *
1901 * @since 1.16
1902 * @return String: fully built LIKE statement
1903 */
1904 function buildLike() {
1905 $params = func_get_args();
1906
1907 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1908 $params = $params[0];
1909 }
1910
1911 $s = '';
1912
1913 foreach ( $params as $value ) {
1914 if ( $value instanceof LikeMatch ) {
1915 $s .= $value->toString();
1916 } else {
1917 $s .= $this->escapeLikeInternal( $value );
1918 }
1919 }
1920
1921 return " LIKE '" . $s . "' ";
1922 }
1923
1924 /**
1925 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1926 *
1927 * @return LikeMatch
1928 */
1929 function anyChar() {
1930 return new LikeMatch( '_' );
1931 }
1932
1933 /**
1934 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1935 *
1936 * @rerturn LikeMatch
1937 */
1938 function anyString() {
1939 return new LikeMatch( '%' );
1940 }
1941
1942 /**
1943 * Returns an appropriately quoted sequence value for inserting a new row.
1944 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1945 * subclass will return an integer, and save the value for insertId()
1946 */
1947 function nextSequenceValue( $seqName ) {
1948 return null;
1949 }
1950
1951 /**
1952 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1953 * is only needed because a) MySQL must be as efficient as possible due to
1954 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1955 * which index to pick. Anyway, other databases might have different
1956 * indexes on a given table. So don't bother overriding this unless you're
1957 * MySQL.
1958 */
1959 function useIndexClause( $index ) {
1960 return '';
1961 }
1962
1963 /**
1964 * REPLACE query wrapper
1965 * PostgreSQL simulates this with a DELETE followed by INSERT
1966 * $row is the row to insert, an associative array
1967 * $uniqueIndexes is an array of indexes. Each element may be either a
1968 * field name or an array of field names
1969 *
1970 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1971 * However if you do this, you run the risk of encountering errors which wouldn't have
1972 * occurred in MySQL
1973 *
1974 * @param $table String: The table to replace the row(s) in.
1975 * @param $uniqueIndexes Array: An associative array of indexes
1976 * @param $rows Array: Array of rows to replace
1977 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1978 */
1979 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1980 $table = $this->tableName( $table );
1981
1982 # Single row case
1983 if ( !is_array( reset( $rows ) ) ) {
1984 $rows = array( $rows );
1985 }
1986
1987 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1988 $first = true;
1989
1990 foreach ( $rows as $row ) {
1991 if ( $first ) {
1992 $first = false;
1993 } else {
1994 $sql .= ',';
1995 }
1996
1997 $sql .= '(' . $this->makeList( $row ) . ')';
1998 }
1999
2000 return $this->query( $sql, $fname );
2001 }
2002
2003 /**
2004 * DELETE where the condition is a join
2005 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
2006 *
2007 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
2008 * join condition matches, set $conds='*'
2009 *
2010 * DO NOT put the join condition in $conds
2011 *
2012 * @param $delTable String: The table to delete from.
2013 * @param $joinTable String: The other table.
2014 * @param $delVar String: The variable to join on, in the first table.
2015 * @param $joinVar String: The variable to join on, in the second table.
2016 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
2017 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2018 */
2019 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
2020 if ( !$conds ) {
2021 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
2022 }
2023
2024 $delTable = $this->tableName( $delTable );
2025 $joinTable = $this->tableName( $joinTable );
2026 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
2027
2028 if ( $conds != '*' ) {
2029 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
2030 }
2031
2032 return $this->query( $sql, $fname );
2033 }
2034
2035 /**
2036 * Returns the size of a text field, or -1 for "unlimited"
2037 */
2038 function textFieldSize( $table, $field ) {
2039 $table = $this->tableName( $table );
2040 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2041 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2042 $row = $this->fetchObject( $res );
2043
2044 $m = array();
2045
2046 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2047 $size = $m[1];
2048 } else {
2049 $size = -1;
2050 }
2051
2052 return $size;
2053 }
2054
2055 /**
2056 * A string to insert into queries to show that they're low-priority, like
2057 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2058 * string and nothing bad should happen.
2059 *
2060 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
2061 */
2062 function lowPriorityOption() {
2063 return '';
2064 }
2065
2066 /**
2067 * DELETE query wrapper
2068 *
2069 * Use $conds == "*" to delete all rows
2070 */
2071 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2072 if ( !$conds ) {
2073 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2074 }
2075
2076 $table = $this->tableName( $table );
2077 $sql = "DELETE FROM $table";
2078
2079 if ( $conds != '*' ) {
2080 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
2081 }
2082
2083 return $this->query( $sql, $fname );
2084 }
2085
2086 /**
2087 * INSERT SELECT wrapper
2088 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
2089 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
2090 * $conds may be "*" to copy the whole table
2091 * srcTable may be an array of tables.
2092 *
2093 * @return ResultWrapper
2094 */
2095 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
2096 $insertOptions = array(), $selectOptions = array() )
2097 {
2098 $destTable = $this->tableName( $destTable );
2099
2100 if ( is_array( $insertOptions ) ) {
2101 $insertOptions = implode( ' ', $insertOptions );
2102 }
2103
2104 if ( !is_array( $selectOptions ) ) {
2105 $selectOptions = array( $selectOptions );
2106 }
2107
2108 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2109
2110 if ( is_array( $srcTable ) ) {
2111 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2112 } else {
2113 $srcTable = $this->tableName( $srcTable );
2114 }
2115
2116 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2117 " SELECT $startOpts " . implode( ',', $varMap ) .
2118 " FROM $srcTable $useIndex ";
2119
2120 if ( $conds != '*' ) {
2121 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
2122 }
2123
2124 $sql .= " $tailOpts";
2125
2126 return $this->query( $sql, $fname );
2127 }
2128
2129 /**
2130 * Construct a LIMIT query with optional offset. This is used for query
2131 * pages. The SQL should be adjusted so that only the first $limit rows
2132 * are returned. If $offset is provided as well, then the first $offset
2133 * rows should be discarded, and the next $limit rows should be returned.
2134 * If the result of the query is not ordered, then the rows to be returned
2135 * are theoretically arbitrary.
2136 *
2137 * $sql is expected to be a SELECT, if that makes a difference. For
2138 * UPDATE, limitResultForUpdate should be used.
2139 *
2140 * The version provided by default works in MySQL and SQLite. It will very
2141 * likely need to be overridden for most other DBMSes.
2142 *
2143 * @param $sql String: SQL query we will append the limit too
2144 * @param $limit Integer: the SQL limit
2145 * @param $offset Integer the SQL offset (default false)
2146 *
2147 * @return string
2148 */
2149 function limitResult( $sql, $limit, $offset = false ) {
2150 if ( !is_numeric( $limit ) ) {
2151 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2152 }
2153
2154 return "$sql LIMIT "
2155 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2156 . "{$limit} ";
2157 }
2158
2159 function limitResultForUpdate( $sql, $num ) {
2160 return $this->limitResult( $sql, $num, 0 );
2161 }
2162
2163 /**
2164 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2165 * within the UNION construct.
2166 * @return Boolean
2167 */
2168 function unionSupportsOrderAndLimit() {
2169 return true; // True for almost every DB supported
2170 }
2171
2172 /**
2173 * Construct a UNION query
2174 * This is used for providing overload point for other DB abstractions
2175 * not compatible with the MySQL syntax.
2176 * @param $sqls Array: SQL statements to combine
2177 * @param $all Boolean: use UNION ALL
2178 * @return String: SQL fragment
2179 */
2180 function unionQueries( $sqls, $all ) {
2181 $glue = $all ? ') UNION ALL (' : ') UNION (';
2182 return '(' . implode( $glue, $sqls ) . ')';
2183 }
2184
2185 /**
2186 * Returns an SQL expression for a simple conditional. This doesn't need
2187 * to be overridden unless CASE isn't supported in your DBMS.
2188 *
2189 * @param $cond String: SQL expression which will result in a boolean value
2190 * @param $trueVal String: SQL expression to return if true
2191 * @param $falseVal String: SQL expression to return if false
2192 * @return String: SQL fragment
2193 */
2194 function conditional( $cond, $trueVal, $falseVal ) {
2195 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2196 }
2197
2198 /**
2199 * Returns a comand for str_replace function in SQL query.
2200 * Uses REPLACE() in MySQL
2201 *
2202 * @param $orig String: column to modify
2203 * @param $old String: column to seek
2204 * @param $new String: column to replace with
2205 *
2206 * @return string
2207 */
2208 function strreplace( $orig, $old, $new ) {
2209 return "REPLACE({$orig}, {$old}, {$new})";
2210 }
2211
2212 /**
2213 * Determines if the last failure was due to a deadlock
2214 * STUB
2215 *
2216 * @return bool
2217 */
2218 function wasDeadlock() {
2219 return false;
2220 }
2221
2222 /**
2223 * Determines if the last query error was something that should be dealt
2224 * with by pinging the connection and reissuing the query.
2225 * STUB
2226 *
2227 * @return bool
2228 */
2229 function wasErrorReissuable() {
2230 return false;
2231 }
2232
2233 /**
2234 * Determines if the last failure was due to the database being read-only.
2235 * STUB
2236 *
2237 * @return bool
2238 */
2239 function wasReadOnlyError() {
2240 return false;
2241 }
2242
2243 /**
2244 * Perform a deadlock-prone transaction.
2245 *
2246 * This function invokes a callback function to perform a set of write
2247 * queries. If a deadlock occurs during the processing, the transaction
2248 * will be rolled back and the callback function will be called again.
2249 *
2250 * Usage:
2251 * $dbw->deadlockLoop( callback, ... );
2252 *
2253 * Extra arguments are passed through to the specified callback function.
2254 *
2255 * Returns whatever the callback function returned on its successful,
2256 * iteration, or false on error, for example if the retry limit was
2257 * reached.
2258 */
2259 function deadlockLoop() {
2260 $myFname = 'DatabaseBase::deadlockLoop';
2261
2262 $this->begin();
2263 $args = func_get_args();
2264 $function = array_shift( $args );
2265 $oldIgnore = $this->ignoreErrors( true );
2266 $tries = DEADLOCK_TRIES;
2267
2268 if ( is_array( $function ) ) {
2269 $fname = $function[0];
2270 } else {
2271 $fname = $function;
2272 }
2273
2274 do {
2275 $retVal = call_user_func_array( $function, $args );
2276 $error = $this->lastError();
2277 $errno = $this->lastErrno();
2278 $sql = $this->lastQuery();
2279
2280 if ( $errno ) {
2281 if ( $this->wasDeadlock() ) {
2282 # Retry
2283 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
2284 } else {
2285 $this->reportQueryError( $error, $errno, $sql, $fname );
2286 }
2287 }
2288 } while ( $this->wasDeadlock() && --$tries > 0 );
2289
2290 $this->ignoreErrors( $oldIgnore );
2291
2292 if ( $tries <= 0 ) {
2293 $this->rollback( $myFname );
2294 $this->reportQueryError( $error, $errno, $sql, $fname );
2295 return false;
2296 } else {
2297 $this->commit( $myFname );
2298 return $retVal;
2299 }
2300 }
2301
2302 /**
2303 * Do a SELECT MASTER_POS_WAIT()
2304 *
2305 * @param $pos MySQLMasterPos object
2306 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2307 */
2308 function masterPosWait( MySQLMasterPos $pos, $timeout ) {
2309 $fname = 'DatabaseBase::masterPosWait';
2310 wfProfileIn( $fname );
2311
2312 # Commit any open transactions
2313 if ( $this->mTrxLevel ) {
2314 $this->commit();
2315 }
2316
2317 if ( !is_null( $this->mFakeSlaveLag ) ) {
2318 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
2319
2320 if ( $wait > $timeout * 1e6 ) {
2321 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2322 wfProfileOut( $fname );
2323 return -1;
2324 } elseif ( $wait > 0 ) {
2325 wfDebug( "Fake slave waiting $wait us\n" );
2326 usleep( $wait );
2327 wfProfileOut( $fname );
2328 return 1;
2329 } else {
2330 wfDebug( "Fake slave up to date ($wait us)\n" );
2331 wfProfileOut( $fname );
2332 return 0;
2333 }
2334 }
2335
2336 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2337 $encFile = $this->addQuotes( $pos->file );
2338 $encPos = intval( $pos->pos );
2339 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2340 $res = $this->doQuery( $sql );
2341
2342 if ( $res && $row = $this->fetchRow( $res ) ) {
2343 wfProfileOut( $fname );
2344 return $row[0];
2345 } else {
2346 wfProfileOut( $fname );
2347 return false;
2348 }
2349 }
2350
2351 /**
2352 * Get the position of the master from SHOW SLAVE STATUS
2353 *
2354 * @return MySQLMasterPos|false
2355 */
2356 function getSlavePos() {
2357 if ( !is_null( $this->mFakeSlaveLag ) ) {
2358 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
2359 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
2360 return $pos;
2361 }
2362
2363 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2364 $row = $this->fetchObject( $res );
2365
2366 if ( $row ) {
2367 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
2368 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
2369 } else {
2370 return false;
2371 }
2372 }
2373
2374 /**
2375 * Get the position of the master from SHOW MASTER STATUS
2376 *
2377 * @return MySQLMasterPos|false
2378 */
2379 function getMasterPos() {
2380 if ( $this->mFakeMaster ) {
2381 return new MySQLMasterPos( 'fake', microtime( true ) );
2382 }
2383
2384 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2385 $row = $this->fetchObject( $res );
2386
2387 if ( $row ) {
2388 return new MySQLMasterPos( $row->File, $row->Position );
2389 } else {
2390 return false;
2391 }
2392 }
2393
2394 /**
2395 * Begin a transaction, committing any previously open transaction
2396 */
2397 function begin( $fname = 'DatabaseBase::begin' ) {
2398 $this->query( 'BEGIN', $fname );
2399 $this->mTrxLevel = 1;
2400 }
2401
2402 /**
2403 * End a transaction
2404 */
2405 function commit( $fname = 'DatabaseBase::commit' ) {
2406 if ( $this->mTrxLevel ) {
2407 $this->query( 'COMMIT', $fname );
2408 $this->mTrxLevel = 0;
2409 }
2410 }
2411
2412 /**
2413 * Rollback a transaction.
2414 * No-op on non-transactional databases.
2415 */
2416 function rollback( $fname = 'DatabaseBase::rollback' ) {
2417 if ( $this->mTrxLevel ) {
2418 $this->query( 'ROLLBACK', $fname, true );
2419 $this->mTrxLevel = 0;
2420 }
2421 }
2422
2423 /**
2424 * Creates a new table with structure copied from existing table
2425 * Note that unlike most database abstraction functions, this function does not
2426 * automatically append database prefix, because it works at a lower
2427 * abstraction level.
2428 * The table names passed to this function shall not be quoted (this
2429 * function calls addIdentifierQuotes when needed).
2430 *
2431 * @param $oldName String: name of table whose structure should be copied
2432 * @param $newName String: name of table to be created
2433 * @param $temporary Boolean: whether the new table should be temporary
2434 * @param $fname String: calling function name
2435 * @return Boolean: true if operation was successful
2436 */
2437 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2438 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2439 }
2440
2441 /**
2442 * List all tables on the database
2443 *
2444 * @param $prefix Only show tables with this prefix, e.g. mw_
2445 * @param $fname String: calling function name
2446 */
2447 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2448 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2449 }
2450
2451 /**
2452 * Return MW-style timestamp used for MySQL schema
2453 *
2454 * @return string
2455 */
2456 function timestamp( $ts = 0 ) {
2457 return wfTimestamp( TS_MW, $ts );
2458 }
2459
2460 /**
2461 * Local database timestamp format or null
2462 *
2463 * @return string
2464 */
2465 function timestampOrNull( $ts = null ) {
2466 if ( is_null( $ts ) ) {
2467 return null;
2468 } else {
2469 return $this->timestamp( $ts );
2470 }
2471 }
2472
2473 /**
2474 * @todo document
2475 *
2476 * @return ResultWrapper
2477 */
2478 function resultObject( $result ) {
2479 if ( empty( $result ) ) {
2480 return false;
2481 } elseif ( $result instanceof ResultWrapper ) {
2482 return $result;
2483 } elseif ( $result === true ) {
2484 // Successful write query
2485 return $result;
2486 } else {
2487 return new ResultWrapper( $this, $result );
2488 }
2489 }
2490
2491 /**
2492 * Return aggregated value alias
2493 */
2494 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2495 return $valuename;
2496 }
2497
2498 /**
2499 * Ping the server and try to reconnect if it there is no connection
2500 *
2501 * @return bool Success or failure
2502 */
2503 function ping() {
2504 # Stub. Not essential to override.
2505 return true;
2506 }
2507
2508 /**
2509 * Get slave lag.
2510 * Currently supported only by MySQL
2511 * @return Database replication lag in seconds
2512 */
2513 function getLag() {
2514 return intval( $this->mFakeSlaveLag );
2515 }
2516
2517 /**
2518 * Get status information from SHOW STATUS in an associative array
2519 *
2520 * @return array
2521 */
2522 function getStatus( $which = "%" ) {
2523 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2524 $status = array();
2525
2526 foreach ( $res as $row ) {
2527 $status[$row->Variable_name] = $row->Value;
2528 }
2529
2530 return $status;
2531 }
2532
2533 /**
2534 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2535 *
2536 * return int
2537 */
2538 function maxListLen() {
2539 return 0;
2540 }
2541
2542 function encodeBlob( $b ) {
2543 return $b;
2544 }
2545
2546 function decodeBlob( $b ) {
2547 return $b;
2548 }
2549
2550 /**
2551 * Override database's default connection timeout. May be useful for very
2552 * long batch queries such as full-wiki dumps, where a single query reads
2553 * out over hours or days. May or may not be necessary for non-MySQL
2554 * databases. For most purposes, leaving it as a no-op should be fine.
2555 *
2556 * @param $timeout Integer in seconds
2557 */
2558 public function setTimeout( $timeout ) {}
2559
2560 /**
2561 * Read and execute SQL commands from a file.
2562 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2563 * @param $filename String: File name to open
2564 * @param $lineCallback Callback: Optional function called before reading each line
2565 * @param $resultCallback Callback: Optional function called for each MySQL result
2566 * @param $fname String: Calling function name or false if name should be generated dynamically
2567 * using $filename
2568 */
2569 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2570 wfSuppressWarnings();
2571 $fp = fopen( $filename, 'r' );
2572 wfRestoreWarnings();
2573
2574 if ( false === $fp ) {
2575 throw new MWException( "Could not open \"{$filename}\".\n" );
2576 }
2577
2578 if ( !$fname ) {
2579 $fname = __METHOD__ . "( $filename )";
2580 }
2581
2582 try {
2583 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2584 }
2585 catch ( MWException $e ) {
2586 fclose( $fp );
2587 throw $e;
2588 }
2589
2590 fclose( $fp );
2591
2592 return $error;
2593 }
2594
2595 /**
2596 * Get the full path of a patch file. Originally based on archive()
2597 * from updaters.inc. Keep in mind this always returns a patch, as
2598 * it fails back to MySQL if no DB-specific patch can be found
2599 *
2600 * @param $patch String The name of the patch, like patch-something.sql
2601 * @return String Full path to patch file
2602 */
2603 public function patchPath( $patch ) {
2604 global $IP;
2605
2606 $dbType = $this->getType();
2607 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2608 return "$IP/maintenance/$dbType/archives/$patch";
2609 } else {
2610 return "$IP/maintenance/archives/$patch";
2611 }
2612 }
2613
2614 /**
2615 * Set variables to be used in sourceFile/sourceStream, in preference to the
2616 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
2617 * all. If it's set to false, $GLOBALS will be used.
2618 *
2619 * @param $vars False, or array mapping variable name to value.
2620 */
2621 function setSchemaVars( $vars ) {
2622 $this->mSchemaVars = $vars;
2623 }
2624
2625 /**
2626 * Read and execute commands from an open file handle
2627 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2628 * @param $fp Resource: File handle
2629 * @param $lineCallback Callback: Optional function called before reading each line
2630 * @param $resultCallback Callback: Optional function called for each MySQL result
2631 * @param $fname String: Calling function name
2632 */
2633 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2634 $cmd = "";
2635 $done = false;
2636 $dollarquote = false;
2637
2638 while ( ! feof( $fp ) ) {
2639 if ( $lineCallback ) {
2640 call_user_func( $lineCallback );
2641 }
2642
2643 $line = trim( fgets( $fp ) );
2644 $sl = strlen( $line ) - 1;
2645
2646 if ( $sl < 0 ) {
2647 continue;
2648 }
2649
2650 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2651 continue;
2652 }
2653
2654 # # Allow dollar quoting for function declarations
2655 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2656 if ( $dollarquote ) {
2657 $dollarquote = false;
2658 $done = true;
2659 }
2660 else {
2661 $dollarquote = true;
2662 }
2663 }
2664 else if ( !$dollarquote ) {
2665 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
2666 $done = true;
2667 $line = substr( $line, 0, $sl );
2668 }
2669 }
2670
2671 if ( $cmd != '' ) {
2672 $cmd .= ' ';
2673 }
2674
2675 $cmd .= "$line\n";
2676
2677 if ( $done ) {
2678 $cmd = str_replace( ';;', ";", $cmd );
2679 $cmd = $this->replaceVars( $cmd );
2680 $res = $this->query( $cmd, $fname );
2681
2682 if ( $resultCallback ) {
2683 call_user_func( $resultCallback, $res, $this );
2684 }
2685
2686 if ( false === $res ) {
2687 $err = $this->lastError();
2688 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2689 }
2690
2691 $cmd = '';
2692 $done = false;
2693 }
2694 }
2695
2696 return true;
2697 }
2698
2699 /**
2700 * Database independent variable replacement, replaces a set of variables
2701 * in a sql statement with their contents as given by $this->getSchemaVars().
2702 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables
2703 *
2704 * '{$var}' should be used for text and is passed through the database's addQuotes method
2705 * `{$var}` should be used for identifiers (eg: table and database names), it is passed through
2706 * the database's addIdentifierQuotes method which can be overridden if the database
2707 * uses something other than backticks.
2708 * / *$var* / is just encoded, besides traditional dbprefix and tableoptions it's use should be avoided
2709 *
2710 * @param $ins String: SQL statement to replace variables in
2711 * @return String The new SQL statement with variables replaced
2712 */
2713 protected function replaceSchemaVars( $ins ) {
2714 $vars = $this->getSchemaVars();
2715 foreach ( $vars as $var => $value ) {
2716 // replace '{$var}'
2717 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
2718 // replace `{$var}`
2719 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
2720 // replace /*$var*/
2721 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
2722 }
2723 return $ins;
2724 }
2725
2726 /**
2727 * Replace variables in sourced SQL
2728 */
2729 protected function replaceVars( $ins ) {
2730 $ins = $this->replaceSchemaVars( $ins );
2731
2732 // Table prefixes
2733 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2734 array( $this, 'tableNameCallback' ), $ins );
2735
2736 // Index names
2737 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2738 array( $this, 'indexNameCallback' ), $ins );
2739
2740 return $ins;
2741 }
2742
2743 /**
2744 * Get schema variables. If none have been set via setSchemaVars(), then
2745 * use some defaults from the current object.
2746 */
2747 protected function getSchemaVars() {
2748 if ( $this->mSchemaVars ) {
2749 return $this->mSchemaVars;
2750 } else {
2751 return $this->getDefaultSchemaVars();
2752 }
2753 }
2754
2755 /**
2756 * Get schema variables to use if none have been set via setSchemaVars().
2757 * Override this in derived classes to provide variables for tables.sql
2758 * and SQL patch files.
2759 */
2760 protected function getDefaultSchemaVars() {
2761 return array();
2762 }
2763
2764 /**
2765 * Table name callback
2766 * @private
2767 */
2768 protected function tableNameCallback( $matches ) {
2769 return $this->tableName( $matches[1] );
2770 }
2771
2772 /**
2773 * Index name callback
2774 */
2775 protected function indexNameCallback( $matches ) {
2776 return $this->indexName( $matches[1] );
2777 }
2778
2779 /**
2780 * Build a concatenation list to feed into a SQL query
2781 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2782 * @return String
2783 */
2784 function buildConcat( $stringList ) {
2785 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2786 }
2787
2788 /**
2789 * Acquire a named lock
2790 *
2791 * Abstracted from Filestore::lock() so child classes can implement for
2792 * their own needs.
2793 *
2794 * @param $lockName String: name of lock to aquire
2795 * @param $method String: name of method calling us
2796 * @param $timeout Integer: timeout
2797 * @return Boolean
2798 */
2799 public function lock( $lockName, $method, $timeout = 5 ) {
2800 return true;
2801 }
2802
2803 /**
2804 * Release a lock.
2805 *
2806 * @param $lockName String: Name of lock to release
2807 * @param $method String: Name of method calling us
2808 *
2809 * @return Returns 1 if the lock was released, 0 if the lock was not established
2810 * by this thread (in which case the lock is not released), and NULL if the named
2811 * lock did not exist
2812 */
2813 public function unlock( $lockName, $method ) {
2814 return true;
2815 }
2816
2817 /**
2818 * Lock specific tables
2819 *
2820 * @param $read Array of tables to lock for read access
2821 * @param $write Array of tables to lock for write access
2822 * @param $method String name of caller
2823 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2824 */
2825 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2826 return true;
2827 }
2828
2829 /**
2830 * Unlock specific tables
2831 *
2832 * @param $method String the caller
2833 */
2834 public function unlockTables( $method ) {
2835 return true;
2836 }
2837
2838 /**
2839 * Delete a table
2840 */
2841 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
2842 if( !$this->tableExists( $tableName ) ) {
2843 return false;
2844 }
2845 $sql = "DROP TABLE " . $this->tableName( $tableName );
2846 if( $this->cascadingDeletes() ) {
2847 $sql .= " CASCADE";
2848 }
2849 return $this->query( $sql, $fName );
2850 }
2851
2852 /**
2853 * Get search engine class. All subclasses of this need to implement this
2854 * if they wish to use searching.
2855 *
2856 * @return String
2857 */
2858 public function getSearchEngine() {
2859 return 'SearchEngineDummy';
2860 }
2861
2862 /**
2863 * Find out when 'infinity' is. Most DBMSes support this. This is a special
2864 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
2865 * because "i" sorts after all numbers.
2866 *
2867 * @return String
2868 */
2869 public function getInfinity() {
2870 return 'infinity';
2871 }
2872
2873 /**
2874 * Encode an expiry time
2875 *
2876 * @param $expiry String: timestamp for expiry, or the 'infinity' string
2877 * @return String
2878 */
2879 public function encodeExpiry( $expiry ) {
2880 if ( $expiry == '' || $expiry == $this->getInfinity() ) {
2881 return $this->getInfinity();
2882 } else {
2883 return $this->timestamp( $expiry );
2884 }
2885 }
2886
2887 /**
2888 * Allow or deny "big selects" for this session only. This is done by setting
2889 * the sql_big_selects session variable.
2890 *
2891 * This is a MySQL-specific feature.
2892 *
2893 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2894 */
2895 public function setBigSelects( $value = true ) {
2896 // no-op
2897 }
2898 }