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 MediaWiki\MediaWikiServices
;
28 use Wikimedia\Rdbms\IResultWrapper
;
29 use Wikimedia\Rdbms\IDatabase
;
30 use Wikimedia\Rdbms\DBQueryError
;
33 * Maintenance script that sends SQL queries from the specified file to the database.
35 * @ingroup Maintenance
37 class MwSql
extends Maintenance
{
38 public function __construct() {
39 parent
::__construct();
40 $this->addDescription( 'Send SQL queries to a MediaWiki database. ' .
41 'Takes a file name containing SQL as argument or runs interactively.' );
42 $this->addOption( 'query',
43 'Run a single query instead of running interactively', false, true );
44 $this->addOption( 'json', 'Output the results as JSON instead of PHP objects' );
45 $this->addOption( 'status', 'Return successful exit status only if the query succeeded '
46 . '(selected or altered rows), otherwise 1 for errors, 2 for no rows' );
47 $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
48 $this->addOption( 'wikidb',
49 'The database wiki ID to use if not the current one', false, true );
50 $this->addOption( 'replicadb',
51 'Replica DB server to use instead of the master DB (can be "any")', false, true );
54 public function execute() {
57 // We wan't to allow "" for the wikidb, meaning don't call select_db()
58 $wiki = $this->hasOption( 'wikidb' ) ?
$this->getOption( 'wikidb' ) : false;
59 // Get the appropriate load balancer (for this wiki)
60 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
61 if ( $this->hasOption( 'cluster' ) ) {
62 $lb = $lbFactory->getExternalLB( $this->getOption( 'cluster' ) );
64 $lb = $lbFactory->getMainLB( $wiki );
66 // Figure out which server to use
67 $replicaDB = $this->getOption( 'replicadb', $this->getOption( 'slave', '' ) );
68 if ( $replicaDB === 'any' ) {
70 } elseif ( $replicaDB !== '' ) {
72 $serverCount = $lb->getServerCount();
73 for ( $i = 0; $i < $serverCount; ++
$i ) {
74 if ( $lb->getServerName( $i ) === $replicaDB ) {
79 if ( $index === null ||
$index === $lb->getWriterIndex() ) {
80 $this->fatalError( "No replica DB server configured with the name '$replicaDB'." );
86 $db = $lb->getMaintenanceConnectionRef( $index, [], $wiki );
87 if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
88 $this->fatalError( "The server selected ({$db->getServer()}) is not a replica DB." );
91 if ( $index === DB_MASTER
) {
92 $updater = DatabaseUpdater
::newForDB( $db, true, $this );
93 $db->setSchemaVars( $updater->getSchemaVars() );
96 if ( $this->hasArg( 0 ) ) {
97 $file = fopen( $this->getArg( 0 ), 'r' );
99 $this->fatalError( "Unable to open input file" );
102 $error = $db->sourceStream( $file, null, [ $this, 'sqlPrintResult' ] );
103 if ( $error !== true ) {
104 $this->fatalError( $error );
110 if ( $this->hasOption( 'query' ) ) {
111 $query = $this->getOption( 'query' );
112 $res = $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
114 if ( $this->hasOption( 'status' ) ) {
115 exit( $res ?
0 : 2 );
121 function_exists( 'readline_add_history' ) &&
122 Maintenance
::posix_isatty( 0 /*STDIN*/ )
124 $historyFile = isset( $_ENV['HOME'] ) ?
125 "{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
126 readline_read_history( $historyFile );
133 $prompt = $newPrompt;
134 $doDie = !Maintenance
::posix_isatty( 0 );
136 while ( ( $line = Maintenance
::readconsole( $prompt ) ) !== false ) {
138 # User simply pressed return key
141 $done = $db->streamStatementEnd( $wholeLine, $line );
150 if ( $historyFile ) {
151 # Delimiter is eated by streamStatementEnd, we add it
152 # up in the history (T39020)
153 readline_add_history( $wholeLine . ';' );
154 readline_write_history( $historyFile );
156 $res = $this->sqlDoQuery( $db, $wholeLine, $doDie );
157 $prompt = $newPrompt;
161 if ( $this->hasOption( 'status' ) ) {
162 exit( $res ?
0 : 2 );
167 * @param IDatabase $db
168 * @param string $line The SQL text of the query
169 * @param bool $dieOnError
170 * @return int|null Number of rows selected or updated, or null if the query was unsuccessful.
172 protected function sqlDoQuery( IDatabase
$db, $line, $dieOnError ) {
174 $res = $db->query( $line );
175 return $this->sqlPrintResult( $res, $db );
176 } catch ( DBQueryError
$e ) {
178 $this->fatalError( $e );
187 * Print the results, callback for $db->sourceStream()
188 * @param IResultWrapper|bool $res
189 * @param IDatabase $db
190 * @return int|null Number of rows selected or updated, or null if the query was unsuccessful.
192 public function sqlPrintResult( $res, $db ) {
196 } elseif ( is_object( $res ) ) {
199 foreach ( $res as $row ) {
200 $out .= print_r( $row, true );
203 if ( $this->hasOption( 'json' ) ) {
204 $out = json_encode( $rows, JSON_PRETTY_PRINT
);
205 } elseif ( !$rows ) {
206 $out = 'Query OK, 0 row(s) affected';
208 $this->output( $out . "\n" );
209 return count( $rows );
211 $affected = $db->affectedRows();
212 if ( $this->hasOption( 'json' ) ) {
213 $this->output( json_encode( [ 'affected' => $affected ], JSON_PRETTY_PRINT
) . "\n" );
215 $this->output( "Query OK, $affected row(s) affected\n" );
222 * @return int DB_TYPE constant
224 public function getDbType() {
225 return Maintenance
::DB_ADMIN
;
229 $maintClass = MwSql
::class;
230 require_once RUN_MAINTENANCE_IF_MAIN
;