3 * Send SQL queries from the specified file to the database, performing
4 * variable replacement along the way.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
22 * @ingroup Maintenance
25 require_once __DIR__
. '/Maintenance.php';
27 use Wikimedia\Rdbms\ResultWrapper
;
28 use Wikimedia\Rdbms\IDatabase
;
29 use Wikimedia\Rdbms\DBQueryError
;
32 * Maintenance script that sends SQL queries from the specified file to the database.
34 * @ingroup Maintenance
36 class MwSql
extends Maintenance
{
37 public function __construct() {
38 parent
::__construct();
39 $this->addDescription( 'Send SQL queries to a MediaWiki database. ' .
40 'Takes a file name containing SQL as argument or runs interactively.' );
41 $this->addOption( 'query',
42 'Run a single query instead of running interactively', false, true );
43 $this->addOption( 'json', 'Output the results as JSON instead of PHP objects' );
44 $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
45 $this->addOption( 'wikidb',
46 'The database wiki ID to use if not the current one', false, true );
47 $this->addOption( 'replicadb',
48 'Replica DB server to use instead of the master DB (can be "any")', false, true );
51 public function execute() {
54 // We wan't to allow "" for the wikidb, meaning don't call select_db()
55 $wiki = $this->hasOption( 'wikidb' ) ?
$this->getOption( 'wikidb' ) : false;
56 // Get the appropriate load balancer (for this wiki)
57 if ( $this->hasOption( 'cluster' ) ) {
58 $lb = wfGetLBFactory()->getExternalLB( $this->getOption( 'cluster' ) );
60 $lb = wfGetLB( $wiki );
62 // Figure out which server to use
63 $replicaDB = $this->getOption( 'replicadb', $this->getOption( 'slave', '' ) );
64 if ( $replicaDB === 'any' ) {
66 } elseif ( $replicaDB != '' ) {
68 $serverCount = $lb->getServerCount();
69 for ( $i = 0; $i < $serverCount; ++
$i ) {
70 if ( $lb->getServerName( $i ) === $replicaDB ) {
75 if ( $index === null ) {
76 $this->fatalError( "No replica DB server configured with the name '$replicaDB'." );
82 /** @var IDatabase $db DB handle for the appropriate cluster/wiki */
83 $db = $lb->getConnection( $index, [], $wiki );
84 if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
85 $this->fatalError( "The server selected ({$db->getServer()}) is not a replica DB." );
88 if ( $index === DB_MASTER
) {
89 $updater = DatabaseUpdater
::newForDB( $db, true, $this );
90 $db->setSchemaVars( $updater->getSchemaVars() );
93 if ( $this->hasArg( 0 ) ) {
94 $file = fopen( $this->getArg( 0 ), 'r' );
96 $this->fatalError( "Unable to open input file" );
99 $error = $db->sourceStream( $file, null, [ $this, 'sqlPrintResult' ] );
100 if ( $error !== true ) {
101 $this->fatalError( $error );
107 if ( $this->hasOption( 'query' ) ) {
108 $query = $this->getOption( 'query' );
109 $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
115 function_exists( 'readline_add_history' ) &&
116 Maintenance
::posix_isatty( 0 /*STDIN*/ )
118 $historyFile = isset( $_ENV['HOME'] ) ?
119 "{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
120 readline_read_history( $historyFile );
127 $prompt = $newPrompt;
128 $doDie = !Maintenance
::posix_isatty( 0 );
129 while ( ( $line = Maintenance
::readconsole( $prompt ) ) !== false ) {
131 # User simply pressed return key
134 $done = $db->streamStatementEnd( $wholeLine, $line );
143 if ( $historyFile ) {
144 # Delimiter is eated by streamStatementEnd, we add it
145 # up in the history (T39020)
146 readline_add_history( $wholeLine . ';' );
147 readline_write_history( $historyFile );
149 $this->sqlDoQuery( $db, $wholeLine, $doDie );
150 $prompt = $newPrompt;
156 protected function sqlDoQuery( IDatabase
$db, $line, $dieOnError ) {
158 $res = $db->query( $line );
159 $this->sqlPrintResult( $res, $db );
160 } catch ( DBQueryError
$e ) {
162 $this->fatalError( $e );
170 * Print the results, callback for $db->sourceStream()
171 * @param ResultWrapper|bool $res
172 * @param IDatabase $db
174 public function sqlPrintResult( $res, $db ) {
178 } elseif ( is_object( $res ) && $res->numRows() ) {
180 foreach ( $res as $row ) {
181 $out .= print_r( $row, true );
184 if ( $this->hasOption( 'json' ) ) {
185 $out = json_encode( $rows, JSON_PRETTY_PRINT
);
187 $this->output( $out . "\n" );
189 $affected = $db->affectedRows();
190 $this->output( "Query OK, $affected row(s) affected\n" );
195 * @return int DB_TYPE constant
197 public function getDbType() {
198 return Maintenance
::DB_ADMIN
;
202 $maintClass = MwSql
::class;
203 require_once RUN_MAINTENANCE_IF_MAIN
;