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