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