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