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 master DB (can be "any")', false, true );
52  }
53 
54  public function execute() {
55  global $IP;
56 
57  // We wan't 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 = MediaWikiServices::getInstance()->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', $this->getOption( 'slave', '' ) );
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 ) {
80  $this->fatalError( "No replica DB server configured with the name '$replicaDB'." );
81  }
82  } else {
83  $index = DB_MASTER;
84  }
85 
86  $db = $lb->getMaintenanceConnectionRef( $index, [], $wiki );
87  if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
88  $this->fatalError( "The server selected ({$db->getServer()}) is not a replica DB." );
89  }
90 
91  if ( $index === DB_MASTER ) {
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' ] );
103  if ( $error !== true ) {
104  $this->fatalError( $error );
105  } else {
106  exit( 0 );
107  }
108  }
109 
110  if ( $this->hasOption( 'query' ) ) {
111  $query = $this->getOption( 'query' );
112  $res = $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
113  wfWaitForSlaves();
114  if ( $this->hasOption( 'status' ) ) {
115  exit( $res ? 0 : 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  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 eated by streamStatementEnd, we add it
152  # up in the history (T39020)
153  readline_add_history( $wholeLine . ';' );
154  readline_write_history( $historyFile );
155  }
156  $res = $this->sqlDoQuery( $db, $wholeLine, $doDie );
157  $prompt = $newPrompt;
158  $wholeLine = '';
159  }
160  wfWaitForSlaves();
161  if ( $this->hasOption( 'status' ) ) {
162  exit( $res ? 0 : 2 );
163  }
164  }
165 
172  protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
173  try {
174  $res = $db->query( $line );
175  return $this->sqlPrintResult( $res, $db );
176  } catch ( DBQueryError $e ) {
177  if ( $dieOnError ) {
178  $this->fatalError( $e );
179  } else {
180  $this->error( $e );
181  }
182  }
183  return null;
184  }
185 
192  public function sqlPrintResult( $res, $db ) {
193  if ( !$res ) {
194  // Do nothing
195  return null;
196  } elseif ( is_object( $res ) ) {
197  $out = '';
198  $rows = [];
199  foreach ( $res as $row ) {
200  $out .= print_r( $row, true );
201  $rows[] = $row;
202  }
203  if ( $this->hasOption( 'json' ) ) {
204  $out = json_encode( $rows, JSON_PRETTY_PRINT );
205  } elseif ( !$rows ) {
206  $out = 'Query OK, 0 row(s) affected';
207  }
208  $this->output( $out . "\n" );
209  return count( $rows );
210  } else {
211  $affected = $db->affectedRows();
212  if ( $this->hasOption( 'json' ) ) {
213  $this->output( json_encode( [ 'affected' => $affected ], JSON_PRETTY_PRINT ) . "\n" );
214  } else {
215  $this->output( "Query OK, $affected row(s) affected\n" );
216  }
217  return $affected;
218  }
219  }
220 
224  public function getDbType() {
225  return Maintenance::DB_ADMIN;
226  }
227 }
228 
230 require_once RUN_MAINTENANCE_IF_MAIN;
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition: hooks.txt:2621
getArg( $argId=0, $default=null)
Get an argument.
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers change it to an object instance and return false override the list derivative used $groups Array of ChangesListFilterGroup objects(added in 1.34) 'FileDeleteComplete' null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1529
error( $err, $die=0)
Throw an error to the user.
$IP
Definition: WebStart.php:41
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getOption( $name, $default=null)
Get an option, or return the default.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2147
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
static readconsole( $prompt='> ')
Prompt the console for input.
Maintenance script that sends SQL queries from the specified file to the database.
Definition: sql.php:37
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
__construct()
Definition: sql.php:38
hasOption( $name)
Checks to see if a particular option exists.
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
sqlDoQuery(IDatabase $db, $line, $dieOnError)
Definition: sql.php:172
execute()
Definition: sql.php:54
const DB_MASTER
Definition: defines.php:26
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:767
hasArg( $argId=0)
Does a given argument exist?
$res
Definition: database.txt:21
wfWaitForSlaves( $ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the replica DBs to catch up to the master position.
addDescription( $text)
Set the description text.
const DB_ADMIN
Definition: Maintenance.php:87
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
output( $out, $channel=null)
Throw some output to the user.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
static posix_isatty( $fd)
Wrapper for posix_isatty() We default as considering stdin a tty (for nice readline methods) but trea...
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
$line
Definition: cdb.php:59
$page->newPageUpdater($user) $updater
Definition: pageupdater.txt:63
static newForDB(IMaintainableDatabase $db, $shared=false, Maintenance $maintenance=null)
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
$maintClass
Definition: sql.php:229
const DB_REPLICA
Definition: defines.php:25
sqlPrintResult( $res, $db)
Print the results, callback for $db->sourceStream()
Definition: sql.php:192
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
query( $sql, $fname=__METHOD__, $flags=0)
Run an SQL query and return the result.
getDbType()
Definition: sql.php:224