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