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