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 global $IP;
47
48 // We want to allow "" for the wikidb, meaning don't call select_db()
49 $wiki = $this->hasOption( 'wikidb' ) ? $this->getOption( 'wikidb' ) : false;
50 // Get the appropriate load balancer (for this wiki)
51 $lbFactory = $this->getServiceContainer()->getDBLoadBalancerFactory();
52 if ( $this->hasOption( 'cluster' ) ) {
53 $lb = $lbFactory->getExternalLB( $this->getOption( 'cluster' ) );
54 } else {
55 $lb = $lbFactory->getMainLB( $wiki );
56 }
57 // Figure out which server to use
58 $replicaDB = $this->getOption( 'replicadb', '' );
59 if ( $replicaDB === 'any' ) {
60 $index = DB_REPLICA;
61 } elseif ( $replicaDB !== '' ) {
62 $index = null;
63 $serverCount = $lb->getServerCount();
64 for ( $i = 0; $i < $serverCount; ++$i ) {
65 if ( $lb->getServerName( $i ) === $replicaDB ) {
66 $index = $i;
67 break;
68 }
69 }
70 // @phan-suppress-next-line PhanSuspiciousValueComparison
71 if ( $index === null || $index === ServerInfo::WRITER_INDEX ) {
72 $this->fatalError( "No replica DB server configured with the name '$replicaDB'." );
73 }
74 } else {
75 $index = DB_PRIMARY;
76 }
77
78 $db = $lb->getMaintenanceConnectionRef( $index, [], $wiki );
79 if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
80 $this->fatalError( "Server {$db->getServerName()} is not a replica DB." );
81 }
82
83 if ( $index === DB_PRIMARY ) {
84 $updater = DatabaseUpdater::newForDB( $db, true, $this );
85 $db->setSchemaVars( $updater->getSchemaVars() );
86 }
87
88 if ( $this->hasArg( 0 ) ) {
89 $file = fopen( $this->getArg( 0 ), 'r' );
90 if ( !$file ) {
91 $this->fatalError( "Unable to open input file" );
92 }
93
94 $error = $db->sourceStream( $file, null, $this->sqlPrintResult( ... ), __METHOD__ );
95 if ( $error !== true ) {
96 $this->fatalError( $error );
97 }
98 return;
99 }
100
101 if ( $this->hasOption( 'query' ) ) {
102 $query = $this->getOption( 'query' );
103 $res = $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
104 $this->waitForReplication();
105 if ( $this->hasOption( 'status' ) && !$res ) {
106 $this->fatalError( 'Failed.', 2 );
107 }
108 return;
109 }
110
111 if (
112 function_exists( 'readline_add_history' ) &&
113 Maintenance::posix_isatty( 0 /*STDIN*/ )
114 ) {
115 $home = getenv( 'HOME' );
116 $historyFile = $home ?
117 "$home/.mwsql_history" : "$IP/maintenance/.mwsql_history";
118 readline_read_history( $historyFile );
119 } else {
120 $historyFile = null;
121 }
122
123 $wholeLine = '';
124 $newPrompt = '> ';
125 $prompt = $newPrompt;
126 $doDie = !Maintenance::posix_isatty( 0 );
127 $res = 1;
128 $batchCount = 0;
129 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
130 while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
131 if ( !$line ) {
132 # User simply pressed return key
133 continue;
134 }
135 $done = $db->streamStatementEnd( $wholeLine, $line );
136
137 $wholeLine .= $line;
138
139 if ( !$done ) {
140 $wholeLine .= ' ';
141 $prompt = ' -> ';
142 continue;
143 }
144 if ( $historyFile ) {
145 # Delimiter is eaten by streamStatementEnd, we add it
146 # up in the history (T39020)
147 readline_add_history( $wholeLine . ';' );
148 readline_write_history( $historyFile );
149 }
150 // @phan-suppress-next-line SecurityCheck-SQLInjection
151 $res = $this->sqlDoQuery( $db, $wholeLine, $doDie );
152 if ( $this->getBatchSize() && ++$batchCount >= $this->getBatchSize() ) {
153 $batchCount = 0;
154 $this->waitForReplication();
155 }
156 $prompt = $newPrompt;
157 $wholeLine = '';
158 }
159 $this->waitForReplication();
160 if ( $this->hasOption( 'status' ) && !$res ) {
161 $this->fatalError( 'Failed.', 2 );
162 }
163 }
164
171 protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
172 try {
173 $res = $db->query( $line, __METHOD__ );
174 return $this->sqlPrintResult( $res, $db );
175 } catch ( DBQueryError $e ) {
176 if ( $dieOnError ) {
177 $this->fatalError( (string)$e );
178 } else {
179 $this->error( (string)$e );
180 }
181 }
182 return null;
183 }
184
191 private function sqlPrintResult( $res, $db ) {
192 if ( !$res ) {
193 // Do nothing
194 return null;
195 } elseif ( is_object( $res ) ) {
196 $out = '';
197 $rows = [];
198 foreach ( $res as $row ) {
199 $out .= print_r( $row, true );
200 $rows[] = $row;
201 }
202 if ( $this->hasOption( 'json' ) ) {
203 $out = json_encode( $rows, JSON_PRETTY_PRINT );
204 } elseif ( !$rows ) {
205 $out = 'Query OK, 0 row(s) affected';
206 }
207 $this->output( $out . "\n" );
208 return count( $rows );
209 } else {
210 $affected = $db->affectedRows();
211 if ( $this->hasOption( 'json' ) ) {
212 $this->output( json_encode( [ 'affected' => $affected ], JSON_PRETTY_PRINT ) . "\n" );
213 } else {
214 $this->output( "Query OK, $affected row(s) affected\n" );
215 }
216 return $affected;
217 }
218 }
219
223 public function getDbType() {
224 return Maintenance::DB_ADMIN;
225 }
226}
227
228// @codeCoverageIgnoreStart
229$maintClass = MwSql::class;
230require_once RUN_MAINTENANCE_IF_MAIN;
231// @codeCoverageIgnoreEnd
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28
if(!defined('MEDIAWIKI')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
Definition Setup.php:90
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:171
execute()
Do the actual work.
Definition sql.php:45
getDbType()
Definition sql.php:223
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:229