MediaWiki master
sql.php
Go to the documentation of this file.
1<?php
25// @codeCoverageIgnoreStart
26require_once __DIR__ . '/Maintenance.php';
27// @codeCoverageIgnoreEnd
28
35
41class 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
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
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
237 public function getDbType() {
238 return Maintenance::DB_ADMIN;
239 }
240}
241
242// @codeCoverageIgnoreStart
243$maintClass = MwSql::class;
244require_once RUN_MAINTENANCE_IF_MAIN;
245// @codeCoverageIgnoreEnd
if(!defined( 'MEDIAWIKI')) if(ini_get('mbstring.func_overload')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
Definition Setup.php:105
Apply database changes after updating MediaWiki.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
getArg( $argId=0, $default=null)
Get an argument.
getBatchSize()
Returns batch size.
output( $out, $channel=null)
Throw some output to the user.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
waitForReplication()
Wait for replica DB servers to catch up.
hasOption( $name)
Checks to see if a particular option was set.
getOption( $name, $default=null)
Get an option, or return the default.
hasArg( $argId=0)
Does a given argument exist?
error( $err, $die=0)
Throw an error to the user.
getServiceContainer()
Returns the main service container.
addDescription( $text)
Set the description text.
Maintenance script that sends SQL queries from the specified file to the database.
Definition sql.php:41
sqlPrintResult( $res, $db)
Print the results, callback for $db->sourceStream()
Definition sql.php:205
__construct()
Default constructor.
Definition sql.php:42
sqlDoQuery(IDatabase $db, $line, $dieOnError)
Definition sql.php:185
execute()
Do the actual work.
Definition sql.php:59
getDbType()
Definition sql.php:237
Container for accessing information about the database servers in a database cluster.
Interface to a relational database.
Definition IDatabase.php:45
query( $sql, $fname=__METHOD__, $flags=0)
Run an SQL query statement and return the result.
Result wrapper for grabbing data queried from an IDatabase object.
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28
$maintClass
Definition sql.php:243