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