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