MediaWiki master
sql.php
Go to the documentation of this file.
1<?php
25require_once __DIR__ . '/Maintenance.php';
26
32
38class MwSql extends Maintenance {
39 public function __construct() {
40 parent::__construct();
41 $this->addDescription( 'Send SQL queries to a MediaWiki database. ' .
42 'Takes a file name containing SQL as argument or runs interactively.' );
43 $this->addOption( 'query',
44 'Run a single query instead of running interactively', false, true );
45 $this->addOption( 'json', 'Output the results as JSON instead of PHP objects' );
46 $this->addOption( 'status', 'Return successful exit status only if the query succeeded '
47 . '(selected or altered rows), otherwise 1 for errors, 2 for no rows' );
48 $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
49 $this->addOption( 'wikidb',
50 'The database wiki ID to use if not the current one', false, true );
51 $this->addOption( 'replicadb',
52 'Replica DB server to use instead of the primary DB (can be "any")', false, true );
53 $this->setBatchSize( 100 );
54 }
55
56 public function execute() {
57 global $IP;
58
59 // We want to allow "" for the wikidb, meaning don't call select_db()
60 $wiki = $this->hasOption( 'wikidb' ) ? $this->getOption( 'wikidb' ) : false;
61 // Get the appropriate load balancer (for this wiki)
62 $lbFactory = $this->getServiceContainer()->getDBLoadBalancerFactory();
63 if ( $this->hasOption( 'cluster' ) ) {
64 $lb = $lbFactory->getExternalLB( $this->getOption( 'cluster' ) );
65 } else {
66 $lb = $lbFactory->getMainLB( $wiki );
67 }
68 // Figure out which server to use
69 $replicaDB = $this->getOption( 'replicadb', '' );
70 if ( $replicaDB === 'any' ) {
71 $index = DB_REPLICA;
72 } elseif ( $replicaDB !== '' ) {
73 $index = null;
74 $serverCount = $lb->getServerCount();
75 for ( $i = 0; $i < $serverCount; ++$i ) {
76 if ( $lb->getServerName( $i ) === $replicaDB ) {
77 $index = $i;
78 break;
79 }
80 }
81 // @phan-suppress-next-line PhanSuspiciousValueComparison
82 if ( $index === null || $index === ServerInfo::WRITER_INDEX ) {
83 $this->fatalError( "No replica DB server configured with the name '$replicaDB'." );
84 }
85 } else {
86 $index = DB_PRIMARY;
87 }
88
89 $db = $lb->getMaintenanceConnectionRef( $index, [], $wiki );
90 if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
91 $this->fatalError( "Server {$db->getServerName()} is not a replica DB." );
92 }
93
94 if ( $index === DB_PRIMARY ) {
95 $updater = DatabaseUpdater::newForDB( $db, true, $this );
96 $db->setSchemaVars( $updater->getSchemaVars() );
97 }
98
99 if ( $this->hasArg( 0 ) ) {
100 $file = fopen( $this->getArg( 0 ), 'r' );
101 if ( !$file ) {
102 $this->fatalError( "Unable to open input file" );
103 }
104
105 $error = $db->sourceStream( $file, null, [ $this, 'sqlPrintResult' ], __METHOD__ );
106 if ( $error !== true ) {
107 $this->fatalError( $error );
108 }
109 return;
110 }
111
112 if ( $this->hasOption( 'query' ) ) {
113 $query = $this->getOption( 'query' );
114 $res = $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
115 $this->waitForReplication();
116 if ( $this->hasOption( 'status' ) && !$res ) {
117 $this->fatalError( 'Failed.', 2 );
118 }
119 return;
120 }
121
122 if (
123 function_exists( 'readline_add_history' ) &&
124 Maintenance::posix_isatty( 0 /*STDIN*/ )
125 ) {
126 $historyFile = isset( $_ENV['HOME'] ) ?
127 "{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
128 readline_read_history( $historyFile );
129 } else {
130 $historyFile = null;
131 }
132
133 $wholeLine = '';
134 $newPrompt = '> ';
135 $prompt = $newPrompt;
136 $doDie = !Maintenance::posix_isatty( 0 );
137 $res = 1;
138 $batchCount = 0;
139 while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
140 if ( !$line ) {
141 # User simply pressed return key
142 continue;
143 }
144 $done = $db->streamStatementEnd( $wholeLine, $line );
145
146 $wholeLine .= $line;
147
148 if ( !$done ) {
149 $wholeLine .= ' ';
150 $prompt = ' -> ';
151 continue;
152 }
153 if ( $historyFile ) {
154 # Delimiter is eaten by streamStatementEnd, we add it
155 # up in the history (T39020)
156 readline_add_history( $wholeLine . ';' );
157 readline_write_history( $historyFile );
158 }
159 // @phan-suppress-next-line SecurityCheck-SQLInjection
160 $res = $this->sqlDoQuery( $db, $wholeLine, $doDie );
161 if ( $this->getBatchSize() && ++$batchCount >= $this->getBatchSize() ) {
162 $batchCount = 0;
163 $this->waitForReplication();
164 }
165 $prompt = $newPrompt;
166 $wholeLine = '';
167 }
168 $this->waitForReplication();
169 if ( $this->hasOption( 'status' ) && !$res ) {
170 $this->fatalError( 'Failed.', 2 );
171 }
172 }
173
180 protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
181 try {
182 $res = $db->query( $line, __METHOD__ );
183 return $this->sqlPrintResult( $res, $db );
184 } catch ( DBQueryError $e ) {
185 if ( $dieOnError ) {
186 $this->fatalError( (string)$e );
187 } else {
188 $this->error( (string)$e );
189 }
190 }
191 return null;
192 }
193
200 public function sqlPrintResult( $res, $db ) {
201 if ( !$res ) {
202 // Do nothing
203 return null;
204 } elseif ( is_object( $res ) ) {
205 $out = '';
206 $rows = [];
207 foreach ( $res as $row ) {
208 $out .= print_r( $row, true );
209 $rows[] = $row;
210 }
211 if ( $this->hasOption( 'json' ) ) {
212 $out = json_encode( $rows, JSON_PRETTY_PRINT );
213 } elseif ( !$rows ) {
214 $out = 'Query OK, 0 row(s) affected';
215 }
216 $this->output( $out . "\n" );
217 return count( $rows );
218 } else {
219 $affected = $db->affectedRows();
220 if ( $this->hasOption( 'json' ) ) {
221 $this->output( json_encode( [ 'affected' => $affected ], JSON_PRETTY_PRINT ) . "\n" );
222 } else {
223 $this->output( "Query OK, $affected row(s) affected\n" );
224 }
225 return $affected;
226 }
227 }
228
232 public function getDbType() {
234 }
235}
236
237$maintClass = MwSql::class;
238require_once RUN_MAINTENANCE_IF_MAIN;
if(!defined( 'MEDIAWIKI')) if(ini_get('mbstring.func_overload')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
Definition Setup.php:100
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
error( $err, $die=0)
Throw an error to the user.
output( $out, $channel=null)
Throw some output to the user.
hasArg( $argId=0)
Does a given argument exist?
waitForReplication()
Wait for replica DBs to catch up.
hasOption( $name)
Checks to see if a particular option was set.
static readconsole( $prompt='> ')
Prompt the console for input.
static posix_isatty( $fd)
Wrapper for posix_isatty() We default as considering stdin a tty (for nice readline methods) but trea...
getServiceContainer()
Returns the main service container.
getBatchSize()
Returns batch size.
getArg( $argId=0, $default=null)
Get an argument.
addDescription( $text)
Set the description text.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
setBatchSize( $s=0)
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Class for handling database updates.
Maintenance script that sends SQL queries from the specified file to the database.
Definition sql.php:38
sqlPrintResult( $res, $db)
Print the results, callback for $db->sourceStream()
Definition sql.php:200
__construct()
Default constructor.
Definition sql.php:39
sqlDoQuery(IDatabase $db, $line, $dieOnError)
Definition sql.php:180
execute()
Do the actual work.
Definition sql.php:56
getDbType()
Definition sql.php:232
Information about an individual database host.
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:39
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:237