maintenance/version: Namespace and rename
[mediawiki.git] / maintenance / sql.php
blob66e9d16b807083ef92f5576ada6d1899fa7d21dd
1 <?php
2 /**
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
21 * @file
22 * @ingroup Maintenance
25 require_once __DIR__ . '/Maintenance.php';
27 use Wikimedia\Rdbms\DBQueryError;
28 use Wikimedia\Rdbms\IDatabase;
29 use Wikimedia\Rdbms\IResultWrapper;
31 /**
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( 'status', 'Return successful exit status only if the query succeeded '
45 . '(selected or altered rows), otherwise 1 for errors, 2 for no rows' );
46 $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
47 $this->addOption( 'wikidb',
48 'The database wiki ID to use if not the current one', false, true );
49 $this->addOption( 'replicadb',
50 'Replica DB server to use instead of the primary DB (can be "any")', false, true );
51 $this->setBatchSize( 100 );
54 public function execute() {
55 global $IP;
57 // We want 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 = $this->getServiceContainer()->getDBLoadBalancerFactory();
61 if ( $this->hasOption( 'cluster' ) ) {
62 $lb = $lbFactory->getExternalLB( $this->getOption( 'cluster' ) );
63 } else {
64 $lb = $lbFactory->getMainLB( $wiki );
66 // Figure out which server to use
67 $replicaDB = $this->getOption( 'replicadb', '' );
68 if ( $replicaDB === 'any' ) {
69 $index = DB_REPLICA;
70 } elseif ( $replicaDB !== '' ) {
71 $index = null;
72 $serverCount = $lb->getServerCount();
73 for ( $i = 0; $i < $serverCount; ++$i ) {
74 if ( $lb->getServerName( $i ) === $replicaDB ) {
75 $index = $i;
76 break;
79 if ( $index === null || $index === $lb->getWriterIndex() ) {
80 $this->fatalError( "No replica DB server configured with the name '$replicaDB'." );
82 } else {
83 $index = DB_PRIMARY;
86 $db = $lb->getMaintenanceConnectionRef( $index, [], $wiki );
87 if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
88 $this->fatalError( "Server {$db->getServerName()} is not a replica DB." );
91 if ( $index === DB_PRIMARY ) {
92 $updater = DatabaseUpdater::newForDB( $db, true, $this );
93 $db->setSchemaVars( $updater->getSchemaVars() );
96 if ( $this->hasArg( 0 ) ) {
97 $file = fopen( $this->getArg( 0 ), 'r' );
98 if ( !$file ) {
99 $this->fatalError( "Unable to open input file" );
102 $error = $db->sourceStream( $file, null, [ $this, 'sqlPrintResult' ], __METHOD__ );
103 if ( $error !== true ) {
104 $this->fatalError( $error );
106 return;
109 if ( $this->hasOption( 'query' ) ) {
110 $query = $this->getOption( 'query' );
111 $res = $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
112 $this->waitForReplication();
113 if ( $this->hasOption( 'status' ) && !$res ) {
114 $this->fatalError( 'Failed.', 2 );
116 return;
119 if (
120 function_exists( 'readline_add_history' ) &&
121 Maintenance::posix_isatty( 0 /*STDIN*/ )
123 $historyFile = isset( $_ENV['HOME'] ) ?
124 "{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
125 readline_read_history( $historyFile );
126 } else {
127 $historyFile = null;
130 $wholeLine = '';
131 $newPrompt = '> ';
132 $prompt = $newPrompt;
133 $doDie = !Maintenance::posix_isatty( 0 );
134 $res = 1;
135 $batchCount = 0;
136 while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
137 if ( !$line ) {
138 # User simply pressed return key
139 continue;
141 $done = $db->streamStatementEnd( $wholeLine, $line );
143 $wholeLine .= $line;
145 if ( !$done ) {
146 $wholeLine .= ' ';
147 $prompt = ' -> ';
148 continue;
150 if ( $historyFile ) {
151 # Delimiter is eaten by streamStatementEnd, we add it
152 # up in the history (T39020)
153 readline_add_history( $wholeLine . ';' );
154 readline_write_history( $historyFile );
156 // @phan-suppress-next-line SecurityCheck-SQLInjection
157 $res = $this->sqlDoQuery( $db, $wholeLine, $doDie );
158 if ( $this->getBatchSize() && ++$batchCount >= $this->getBatchSize() ) {
159 $batchCount = 0;
160 $this->waitForReplication();
162 $prompt = $newPrompt;
163 $wholeLine = '';
165 $this->waitForReplication();
166 if ( $this->hasOption( 'status' ) && !$res ) {
167 $this->fatalError( 'Failed.', 2 );
172 * @param IDatabase $db
173 * @param string $line The SQL text of the query
174 * @param bool $dieOnError
175 * @return int|null Number of rows selected or updated, or null if the query was unsuccessful.
177 protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
178 try {
179 $res = $db->query( $line, __METHOD__ );
180 return $this->sqlPrintResult( $res, $db );
181 } catch ( DBQueryError $e ) {
182 if ( $dieOnError ) {
183 $this->fatalError( (string)$e );
184 } else {
185 $this->error( (string)$e );
188 return null;
192 * Print the results, callback for $db->sourceStream()
193 * @param IResultWrapper|bool $res
194 * @param IDatabase $db
195 * @return int|null Number of rows selected or updated, or null if the query was unsuccessful.
197 public function sqlPrintResult( $res, $db ) {
198 if ( !$res ) {
199 // Do nothing
200 return null;
201 } elseif ( is_object( $res ) ) {
202 $out = '';
203 $rows = [];
204 foreach ( $res as $row ) {
205 $out .= print_r( $row, true );
206 $rows[] = $row;
208 if ( $this->hasOption( 'json' ) ) {
209 $out = json_encode( $rows, JSON_PRETTY_PRINT );
210 } elseif ( !$rows ) {
211 $out = 'Query OK, 0 row(s) affected';
213 $this->output( $out . "\n" );
214 return count( $rows );
215 } else {
216 $affected = $db->affectedRows();
217 if ( $this->hasOption( 'json' ) ) {
218 $this->output( json_encode( [ 'affected' => $affected ], JSON_PRETTY_PRINT ) . "\n" );
219 } else {
220 $this->output( "Query OK, $affected row(s) affected\n" );
222 return $affected;
227 * @return int DB_TYPE constant
229 public function getDbType() {
230 return Maintenance::DB_ADMIN;
234 $maintClass = MwSql::class;
235 require_once RUN_MAINTENANCE_IF_MAIN;