Merge "Print chained exceptions when maintenance script fails."
[lhc/web/wiklou.git] / maintenance / sql.php
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 require_once __DIR__ . '/Maintenance.php';
26
27 use MediaWiki\MediaWikiServices;
28 use Wikimedia\Rdbms\ResultWrapper;
29 use Wikimedia\Rdbms\IDatabase;
30 use Wikimedia\Rdbms\DBQueryError;
31
32 /**
33 * Maintenance script that sends SQL queries from the specified file to the database.
34 *
35 * @ingroup Maintenance
36 */
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 );
52 }
53
54 public function execute() {
55 global $IP;
56
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' ) );
63 } else {
64 $lb = $lbFactory->getMainLB( $wiki );
65 }
66 // Figure out which server to use
67 $replicaDB = $this->getOption( 'replicadb', $this->getOption( 'slave', '' ) );
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;
77 }
78 }
79 if ( $index === null ) {
80 $this->fatalError( "No replica DB server configured with the name '$replicaDB'." );
81 }
82 } else {
83 $index = DB_MASTER;
84 }
85
86 /** @var IDatabase $db DB handle for the appropriate cluster/wiki */
87 $db = $lb->getConnection( $index, [], $wiki );
88 if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
89 $this->fatalError( "The server selected ({$db->getServer()}) is not a replica DB." );
90 }
91
92 if ( $index === DB_MASTER ) {
93 $updater = DatabaseUpdater::newForDB( $db, true, $this );
94 $db->setSchemaVars( $updater->getSchemaVars() );
95 }
96
97 if ( $this->hasArg( 0 ) ) {
98 $file = fopen( $this->getArg( 0 ), 'r' );
99 if ( !$file ) {
100 $this->fatalError( "Unable to open input file" );
101 }
102
103 $error = $db->sourceStream( $file, null, [ $this, 'sqlPrintResult' ] );
104 if ( $error !== true ) {
105 $this->fatalError( $error );
106 } else {
107 exit( 0 );
108 }
109 }
110
111 if ( $this->hasOption( 'query' ) ) {
112 $query = $this->getOption( 'query' );
113 $res = $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
114 wfWaitForSlaves();
115 if ( $this->hasOption( 'status' ) ) {
116 exit( $res ? 0 : 2 );
117 }
118 return;
119 }
120
121 if (
122 function_exists( 'readline_add_history' ) &&
123 Maintenance::posix_isatty( 0 /*STDIN*/ )
124 ) {
125 $historyFile = isset( $_ENV['HOME'] ) ?
126 "{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
127 readline_read_history( $historyFile );
128 } else {
129 $historyFile = null;
130 }
131
132 $wholeLine = '';
133 $newPrompt = '> ';
134 $prompt = $newPrompt;
135 $doDie = !Maintenance::posix_isatty( 0 );
136 $res = 1;
137 while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
138 if ( !$line ) {
139 # User simply pressed return key
140 continue;
141 }
142 $done = $db->streamStatementEnd( $wholeLine, $line );
143
144 $wholeLine .= $line;
145
146 if ( !$done ) {
147 $wholeLine .= ' ';
148 $prompt = ' -> ';
149 continue;
150 }
151 if ( $historyFile ) {
152 # Delimiter is eated by streamStatementEnd, we add it
153 # up in the history (T39020)
154 readline_add_history( $wholeLine . ';' );
155 readline_write_history( $historyFile );
156 }
157 $res = $this->sqlDoQuery( $db, $wholeLine, $doDie );
158 $prompt = $newPrompt;
159 $wholeLine = '';
160 }
161 wfWaitForSlaves();
162 if ( $this->hasOption( 'status' ) ) {
163 exit( $res ? 0 : 2 );
164 }
165 }
166
167 /**
168 * @param IDatabase $db
169 * @param string $line The SQL text of the query
170 * @param bool $dieOnError
171 * @return int|null Number of rows selected or updated, or null if the query was unsuccessful.
172 */
173 protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
174 try {
175 $res = $db->query( $line );
176 return $this->sqlPrintResult( $res, $db );
177 } catch ( DBQueryError $e ) {
178 if ( $dieOnError ) {
179 $this->fatalError( $e );
180 } else {
181 $this->error( $e );
182 }
183 }
184 return null;
185 }
186
187 /**
188 * Print the results, callback for $db->sourceStream()
189 * @param ResultWrapper|bool $res
190 * @param IDatabase $db
191 * @return int|null Number of rows selected or updated, or null if the query was unsuccessful.
192 */
193 public function sqlPrintResult( $res, $db ) {
194 if ( !$res ) {
195 // Do nothing
196 return null;
197 } elseif ( is_object( $res ) ) {
198 $out = '';
199 $rows = [];
200 foreach ( $res as $row ) {
201 $out .= print_r( $row, true );
202 $rows[] = $row;
203 }
204 if ( $this->hasOption( 'json' ) ) {
205 $out = json_encode( $rows, JSON_PRETTY_PRINT );
206 } elseif ( !$rows ) {
207 $out = 'Query OK, 0 row(s) affected';
208 }
209 $this->output( $out . "\n" );
210 return count( $rows );
211 } else {
212 $affected = $db->affectedRows();
213 if ( $this->hasOption( 'json' ) ) {
214 $this->output( json_encode( [ 'affected' => $affected ], JSON_PRETTY_PRINT ) . "\n" );
215 } else {
216 $this->output( "Query OK, $affected row(s) affected\n" );
217 }
218 return $affected;
219 }
220 }
221
222 /**
223 * @return int DB_TYPE constant
224 */
225 public function getDbType() {
226 return Maintenance::DB_ADMIN;
227 }
228 }
229
230 $maintClass = MwSql::class;
231 require_once RUN_MAINTENANCE_IF_MAIN;