Movatterモバイル変換


[0]ホーム

URL:


MediaWiki master
sql.php
Go to the documentation of this file.
1<?php
25// @codeCoverageIgnoreStart
26require_once __DIR__ .'/Maintenance.php';
27// @codeCoverageIgnoreEnd
28
29useMediaWiki\Installer\DatabaseUpdater;
30useMediaWiki\Maintenance\Maintenance;
31useWikimedia\Rdbms\DBQueryError;
32useWikimedia\Rdbms\IDatabase;
33useWikimedia\Rdbms\IResultWrapper;
34useWikimedia\Rdbms\ServerInfo;
35
41classMwSqlextendsMaintenance {
42publicfunction__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
59publicfunctionexecute() {
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();
66if ( $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','' );
73if ( $replicaDB ==='any' ) {
74 $index =DB_REPLICA;
75 } elseif ( $replicaDB !=='' ) {
76 $index =null;
77 $serverCount = $lb->getServerCount();
78for ( $i = 0; $i < $serverCount; ++$i ) {
79if ( $lb->getServerName( $i ) === $replicaDB ) {
80 $index = $i;
81break;
82 }
83 }
84// @phan-suppress-next-line PhanSuspiciousValueComparison
85if ( $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 );
93if ( $replicaDB !='' && $db->getLBInfo('master' ) !==null ) {
94 $this->fatalError("Server {$db->getServerName()} is not a replica DB." );
95 }
96
97if ( $index ===DB_PRIMARY ) {
98 $updater = DatabaseUpdater::newForDB( $db,true, $this );
99 $db->setSchemaVars( $updater->getSchemaVars() );
100 }
101
102if ( $this->hasArg( 0 ) ) {
103 $file = fopen( $this->getArg( 0 ),'r' );
104if ( !$file ) {
105 $this->fatalError("Unable to open input file" );
106 }
107
108 $error = $db->sourceStream( $file,null, $this->sqlPrintResult( ... ), __METHOD__ );
109if ( $error !==true ) {
110 $this->fatalError( $error );
111 }
112return;
113 }
114
115if ( $this->hasOption('query' ) ) {
116 $query = $this->getOption('query' );
117 $res = $this->sqlDoQuery( $db, $query,/* dieOnError */true );
118 $this->waitForReplication();
119if ( $this->hasOption('status' ) && !$res ) {
120 $this->fatalError('Failed.', 2 );
121 }
122return;
123 }
124
125if (
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
144while ( ( $line = Maintenance::readconsole( $prompt ) ) !==false ) {
145if ( !$line ) {
146 # User simply pressed return key
147continue;
148 }
149 $done = $db->streamStatementEnd( $wholeLine, $line );
150
151 $wholeLine .= $line;
152
153if ( !$done ) {
154 $wholeLine .=' ';
155 $prompt =' -> ';
156continue;
157 }
158if ( $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 );
166if ( $this->getBatchSize() && ++$batchCount >= $this->getBatchSize() ) {
167 $batchCount = 0;
168 $this->waitForReplication();
169 }
170 $prompt = $newPrompt;
171 $wholeLine ='';
172 }
173 $this->waitForReplication();
174if ( $this->hasOption('status' ) && !$res ) {
175 $this->fatalError('Failed.', 2 );
176 }
177 }
178
185protectedfunctionsqlDoQuery(IDatabase $db, $line, $dieOnError ) {
186try {
187 $res = $db->query( $line, __METHOD__ );
188return $this->sqlPrintResult( $res, $db );
189 }catch (DBQueryError $e ) {
190if ( $dieOnError ) {
191 $this->fatalError( (string)$e );
192 }else {
193 $this->error( (string)$e );
194 }
195 }
196returnnull;
197 }
198
205privatefunction sqlPrintResult( $res, $db ) {
206if ( !$res ) {
207// Do nothing
208returnnull;
209 } elseif ( is_object( $res ) ) {
210 $out ='';
211 $rows = [];
212foreach ( $res as $row ) {
213 $out .= print_r( $row,true );
214 $rows[] = $row;
215 }
216if ( $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" );
222return count( $rows );
223 }else {
224 $affected = $db->affectedRows();
225if ( $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 }
230return $affected;
231 }
232 }
233
237publicfunctiongetDbType() {
238return Maintenance::DB_ADMIN;
239 }
240}
241
242// @codeCoverageIgnoreStart
243$maintClass = MwSql::class;
244require_once RUN_MAINTENANCE_IF_MAIN;
245// @codeCoverageIgnoreEnd
$IP
if(!defined('MEDIAWIKI')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
DefinitionSetup.php:103
MediaWiki\Installer\DatabaseUpdater
Apply database changes after updating MediaWiki.
DefinitionDatabaseUpdater.php:52
MediaWiki\Maintenance\Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
DefinitionMaintenance.php:78
MediaWiki\Maintenance\Maintenance\setBatchSize
setBatchSize( $s=0)
DefinitionMaintenance.php:433
MediaWiki\Maintenance\Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
DefinitionMaintenance.php:365
MediaWiki\Maintenance\Maintenance\getBatchSize
getBatchSize()
Returns batch size.
DefinitionMaintenance.php:426
MediaWiki\Maintenance\Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
DefinitionMaintenance.php:493
MediaWiki\Maintenance\Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
DefinitionMaintenance.php:558
MediaWiki\Maintenance\Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
DefinitionMaintenance.php:273
MediaWiki\Maintenance\Maintenance\waitForReplication
waitForReplication()
Wait for replica DB servers to catch up.
DefinitionMaintenance.php:1261
MediaWiki\Maintenance\Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option was set.
DefinitionMaintenance.php:292
MediaWiki\Maintenance\Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
DefinitionMaintenance.php:307
MediaWiki\Maintenance\Maintenance\hasArg
hasArg( $argId=0)
Does a given argument exist?
DefinitionMaintenance.php:353
MediaWiki\Maintenance\Maintenance\error
error( $err, $die=0)
Throw an error to the user.
DefinitionMaintenance.php:520
MediaWiki\Maintenance\Maintenance\getServiceContainer
getServiceContainer()
Returns the main service container.
DefinitionMaintenance.php:687
MediaWiki\Maintenance\Maintenance\addDescription
addDescription( $text)
Set the description text.
DefinitionMaintenance.php:343
MwSql
Maintenance script that sends SQL queries from the specified file to the database.
Definitionsql.php:41
MwSql\__construct
__construct()
Default constructor.
Definitionsql.php:42
MwSql\sqlDoQuery
sqlDoQuery(IDatabase $db, $line, $dieOnError)
Definitionsql.php:185
MwSql\execute
execute()
Do the actual work.
Definitionsql.php:59
MwSql\getDbType
getDbType()
Definitionsql.php:237
Wikimedia\Rdbms\DBQueryError
DefinitionDBQueryError.php:26
Wikimedia\Rdbms\ServerInfo
Container for accessing information about the database servers in a database cluster.
DefinitionServerInfo.php:14
Wikimedia\Rdbms\IDatabase
Interface to a relational database.
DefinitionIDatabase.php:45
Wikimedia\Rdbms\IDatabase\query
query( $sql, $fname=__METHOD__, $flags=0)
Run an SQL query statement and return the result.
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
DefinitionIResultWrapper.php:26
DB_REPLICA
const DB_REPLICA
Definitiondefines.php:26
DB_PRIMARY
const DB_PRIMARY
Definitiondefines.php:28
$maintClass
$maintClass
Definitionsql.php:243

[8]ページ先頭

©2009-2025 Movatter.jp