Debian Codegraph @

maintenance/sql.php

raw symbols SCIP
1 <?php
2 /**
3 * Send SQL queries from the specified file to the database, performing
4 * variable replacement along the way.
5 *
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.
10 *
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.
15 *
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
20 *
21 * @file
22 * @ingroup Maintenance
23 */
24
25 // @codeCoverageIgnoreStart
26 require_once __DIR__ . '/Maintenance.php';
27 // @codeCoverageIgnoreEnd
28
29 use MediaWiki\Installer\DatabaseUpdater;
30 use Wikimedia\Rdbms\DBQueryError;
31 use Wikimedia\Rdbms\IDatabase;
32 use Wikimedia\Rdbms\IResultWrapper;
33 use Wikimedia\Rdbms\ServerInfo;
34
35 /**
36 * Maintenance script that sends SQL queries from the specified file to the database.
37 *
38 * @ingroup Maintenance
39 */
40 class MwSql extends Maintenance {
41 public function __construct() {
42 parent::__construct();
43 $this->addDescription( 'Send SQL queries to a MediaWiki database. ' .
44 'Takes a file name containing SQL as argument or runs interactively.' );
45 $this->addOption( 'query',
46 'Run a single query instead of running interactively', false, true );
47 $this->addOption( 'json', 'Output the results as JSON instead of PHP objects' );
48 $this->addOption( 'status', 'Return successful exit status only if the query succeeded '
49 . '(selected or altered rows), otherwise 1 for errors, 2 for no rows' );
50 $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
51 $this->addOption( 'wikidb',
52 'The database wiki ID to use if not the current one', false, true );
53 $this->addOption( 'replicadb',
54 'Replica DB server to use instead of the primary DB (can be "any")', false, true );
55 $this->setBatchSize( 100 );
56 }
57
58 public function execute() {
59 global $IP;
60
61 // We want to allow "" for the wikidb, meaning don't call select_db()
62 $wiki = $this->hasOption( 'wikidb' ) ? $this->getOption( 'wikidb' ) : false;
63 // Get the appropriate load balancer (for this wiki)
64 $lbFactory = $this->getServiceContainer()->getDBLoadBalancerFactory();
65 if ( $this->hasOption( 'cluster' ) ) {
66 $lb = $lbFactory->getExternalLB( $this->getOption( 'cluster' ) );
67 } else {
68 $lb = $lbFactory->getMainLB( $wiki );
69 }
70 // Figure out which server to use
71 $replicaDB = $this->getOption( 'replicadb', '' );
72 if ( $replicaDB === 'any' ) {
73 $index = DB_REPLICA;
74 } elseif ( $replicaDB !== '' ) {
75 $index = null;
76 $serverCount = $lb->getServerCount();
77 for ( $i = 0; $i < $serverCount; ++$i ) {
78 if ( $lb->getServerName( $i ) === $replicaDB ) {
79 $index = $i;
80 break;
81 }
82 }
83 // @phan-suppress-next-line PhanSuspiciousValueComparison
84 if ( $index === null || $index === ServerInfo::WRITER_INDEX ) {
85 $this->fatalError( "No replica DB server configured with the name '$replicaDB'." );
86 }
87 } else {
88 $index = DB_PRIMARY;
89 }
90
91 $db = $lb->getMaintenanceConnectionRef( $index, [], $wiki );
92 if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
93 $this->fatalError( "Server {$db->getServerName()} is not a replica DB." );
94 }
95
96 if ( $index === DB_PRIMARY ) {
97 $updater = DatabaseUpdater::newForDB( $db, true, $this );
98 $db->setSchemaVars( $updater->getSchemaVars() );
99 }
100
101 if ( $this->hasArg( 0 ) ) {
102 $file = fopen( $this->getArg( 0 ), 'r' );
103 if ( !$file ) {
104 $this->fatalError( "Unable to open input file" );
105 }
106
107 $error = $db->sourceStream( $file, null, [ $this, 'sqlPrintResult' ], __METHOD__ );
108 if ( $error !== true ) {
109 $this->fatalError( $error );
110 }
111 return;
112 }
113
114 if ( $this->hasOption( 'query' ) ) {
115 $query = $this->getOption( 'query' );
116 $res = $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
117 $this->waitForReplication();
118 if ( $this->hasOption( 'status' ) && !$res ) {
119 $this->fatalError( 'Failed.', 2 );
120 }
121 return;
122 }
123
124 if (
125 function_exists( 'readline_add_history' ) &&
126 Maintenance::posix_isatty( 0 /*STDIN*/ )
127 ) {
128 $home = getenv( 'HOME' );
129 $historyFile = $home ?
130 "$home/.mwsql_history" : "$IP/maintenance/.mwsql_history";
131 readline_read_history( $historyFile );
132 } else {
133 $historyFile = null;
134 }
135
136 $wholeLine = '';
137 $newPrompt = '> ';
138 $prompt = $newPrompt;
139 $doDie = !Maintenance::posix_isatty( 0 );
140 $res = 1;
141 $batchCount = 0;
142 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
143 while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
144 if ( !$line ) {
145 # User simply pressed return key
146 continue;
147 }
148 $done = $db->streamStatementEnd( $wholeLine, $line );
149
150 $wholeLine .= $line;
151
152 if ( !$done ) {
153 $wholeLine .= ' ';
154 $prompt = ' -> ';
155 continue;
156 }
157 if ( $historyFile ) {
158 # Delimiter is eaten by streamStatementEnd, we add it
159 # up in the history (T39020)
160 readline_add_history( $wholeLine . ';' );
161 readline_write_history( $historyFile );
162 }
163 // @phan-suppress-next-line SecurityCheck-SQLInjection
164 $res = $this->sqlDoQuery( $db, $wholeLine, $doDie );
165 if ( $this->getBatchSize() && ++$batchCount >= $this->getBatchSize() ) {
166 $batchCount = 0;
167 $this->waitForReplication();
168 }
169 $prompt = $newPrompt;
170 $wholeLine = '';
171 }
172 $this->waitForReplication();
173 if ( $this->hasOption( 'status' ) && !$res ) {
174 $this->fatalError( 'Failed.', 2 );
175 }
176 }
177
178 /**
179 * @param IDatabase $db
180 * @param string $line The SQL text of the query
181 * @param bool $dieOnError
182 * @return int|null Number of rows selected or updated, or null if the query was unsuccessful.
183 */
184 protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
185 try {
186 $res = $db->query( $line, __METHOD__ );
187 return $this->sqlPrintResult( $res, $db );
188 } catch ( DBQueryError $e ) {
189 if ( $dieOnError ) {
190 $this->fatalError( (string)$e );
191 } else {
192 $this->error( (string)$e );
193 }
194 }
195 return null;
196 }
197
198 /**
199 * Print the results, callback for $db->sourceStream()
200 * @param IResultWrapper|bool $res
201 * @param IDatabase $db
202 * @return int|null Number of rows selected or updated, or null if the query was unsuccessful.
203 */
204 public function sqlPrintResult( $res, $db ) {
205 if ( !$res ) {
206 // Do nothing
207 return null;
208 } elseif ( is_object( $res ) ) {
209 $out = '';
210 $rows = [];
211 foreach ( $res as $row ) {
212 $out .= print_r( $row, true );
213 $rows[] = $row;
214 }
215 if ( $this->hasOption( 'json' ) ) {
216 $out = json_encode( $rows, JSON_PRETTY_PRINT );
217 } elseif ( !$rows ) {
218 $out = 'Query OK, 0 row(s) affected';
219 }
220 $this->output( $out . "\n" );
221 return count( $rows );
222 } else {
223 $affected = $db->affectedRows();
224 if ( $this->hasOption( 'json' ) ) {
225 $this->output( json_encode( [ 'affected' => $affected ], JSON_PRETTY_PRINT ) . "\n" );
226 } else {
227 $this->output( "Query OK, $affected row(s) affected\n" );
228 }
229 return $affected;
230 }
231 }
232
233 /**
234 * @return int DB_TYPE constant
235 */
236 public function getDbType() {
237 return Maintenance::DB_ADMIN;
238 }
239 }
240
241 // @codeCoverageIgnoreStart
242 $maintClass = MwSql::class;
243 require_once RUN_MAINTENANCE_IF_MAIN;
244 // @codeCoverageIgnoreEnd