registration: Improve duplicate config setting exception
[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( 'cluster', 'Use an external cluster by name', false, true );
46 $this->addOption( 'wikidb',
47 'The database wiki ID to use if not the current one', false, true );
48 $this->addOption( 'replicadb',
49 'Replica DB server to use instead of the master DB (can be "any")', false, true );
50 }
51
52 public function execute() {
53 global $IP;
54
55 // We wan't to allow "" for the wikidb, meaning don't call select_db()
56 $wiki = $this->hasOption( 'wikidb' ) ? $this->getOption( 'wikidb' ) : false;
57 // Get the appropriate load balancer (for this wiki)
58 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
59 if ( $this->hasOption( 'cluster' ) ) {
60 $lb = $lbFactory->getExternalLB( $this->getOption( 'cluster' ) );
61 } else {
62 $lb = $lbFactory->getMainLB( $wiki );
63 }
64 // Figure out which server to use
65 $replicaDB = $this->getOption( 'replicadb', $this->getOption( 'slave', '' ) );
66 if ( $replicaDB === 'any' ) {
67 $index = DB_REPLICA;
68 } elseif ( $replicaDB != '' ) {
69 $index = null;
70 $serverCount = $lb->getServerCount();
71 for ( $i = 0; $i < $serverCount; ++$i ) {
72 if ( $lb->getServerName( $i ) === $replicaDB ) {
73 $index = $i;
74 break;
75 }
76 }
77 if ( $index === null ) {
78 $this->fatalError( "No replica DB server configured with the name '$replicaDB'." );
79 }
80 } else {
81 $index = DB_MASTER;
82 }
83
84 /** @var IDatabase $db DB handle for the appropriate cluster/wiki */
85 $db = $lb->getConnection( $index, [], $wiki );
86 if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
87 $this->fatalError( "The server selected ({$db->getServer()}) is not a replica DB." );
88 }
89
90 if ( $index === DB_MASTER ) {
91 $updater = DatabaseUpdater::newForDB( $db, true, $this );
92 $db->setSchemaVars( $updater->getSchemaVars() );
93 }
94
95 if ( $this->hasArg( 0 ) ) {
96 $file = fopen( $this->getArg( 0 ), 'r' );
97 if ( !$file ) {
98 $this->fatalError( "Unable to open input file" );
99 }
100
101 $error = $db->sourceStream( $file, null, [ $this, 'sqlPrintResult' ] );
102 if ( $error !== true ) {
103 $this->fatalError( $error );
104 } else {
105 exit( 0 );
106 }
107 }
108
109 if ( $this->hasOption( 'query' ) ) {
110 $query = $this->getOption( 'query' );
111 $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
112 wfWaitForSlaves();
113 return;
114 }
115
116 if (
117 function_exists( 'readline_add_history' ) &&
118 Maintenance::posix_isatty( 0 /*STDIN*/ )
119 ) {
120 $historyFile = isset( $_ENV['HOME'] ) ?
121 "{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
122 readline_read_history( $historyFile );
123 } else {
124 $historyFile = null;
125 }
126
127 $wholeLine = '';
128 $newPrompt = '> ';
129 $prompt = $newPrompt;
130 $doDie = !Maintenance::posix_isatty( 0 );
131 while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
132 if ( !$line ) {
133 # User simply pressed return key
134 continue;
135 }
136 $done = $db->streamStatementEnd( $wholeLine, $line );
137
138 $wholeLine .= $line;
139
140 if ( !$done ) {
141 $wholeLine .= ' ';
142 $prompt = ' -> ';
143 continue;
144 }
145 if ( $historyFile ) {
146 # Delimiter is eated by streamStatementEnd, we add it
147 # up in the history (T39020)
148 readline_add_history( $wholeLine . ';' );
149 readline_write_history( $historyFile );
150 }
151 $this->sqlDoQuery( $db, $wholeLine, $doDie );
152 $prompt = $newPrompt;
153 $wholeLine = '';
154 }
155 wfWaitForSlaves();
156 }
157
158 protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
159 try {
160 $res = $db->query( $line );
161 $this->sqlPrintResult( $res, $db );
162 } catch ( DBQueryError $e ) {
163 if ( $dieOnError ) {
164 $this->fatalError( $e );
165 } else {
166 $this->error( $e );
167 }
168 }
169 }
170
171 /**
172 * Print the results, callback for $db->sourceStream()
173 * @param ResultWrapper|bool $res
174 * @param IDatabase $db
175 */
176 public function sqlPrintResult( $res, $db ) {
177 if ( !$res ) {
178 // Do nothing
179 return;
180 } elseif ( is_object( $res ) && $res->numRows() ) {
181 $out = '';
182 foreach ( $res as $row ) {
183 $out .= print_r( $row, true );
184 $rows[] = $row;
185 }
186 if ( $this->hasOption( 'json' ) ) {
187 $out = json_encode( $rows, JSON_PRETTY_PRINT );
188 }
189 $this->output( $out . "\n" );
190 } else {
191 $affected = $db->affectedRows();
192 $this->output( "Query OK, $affected row(s) affected\n" );
193 }
194 }
195
196 /**
197 * @return int DB_TYPE constant
198 */
199 public function getDbType() {
200 return Maintenance::DB_ADMIN;
201 }
202 }
203
204 $maintClass = MwSql::class;
205 require_once RUN_MAINTENANCE_IF_MAIN;