MediaWiki  1.32.5
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( 'cluster', 'Use an external cluster by name', false, true );
46  $this->addOption( 'wikidb',
47  'The database wiki ID to use if not the current one', false, true );
48  $this->addOption( 'replicadb',
49  'Replica DB server to use instead of the master DB (can be "any")', false, true );
50  }
51 
52  public function execute() {
53  global $IP;
54 
55  // We wan't to allow "" for the wikidb, meaning don't call select_db()
56  $wiki = $this->hasOption( 'wikidb' ) ? $this->getOption( 'wikidb' ) : false;
57  // Get the appropriate load balancer (for this wiki)
58  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
59  if ( $this->hasOption( 'cluster' ) ) {
60  $lb = $lbFactory->getExternalLB( $this->getOption( 'cluster' ) );
61  } else {
62  $lb = $lbFactory->getMainLB( $wiki );
63  }
64  // Figure out which server to use
65  $replicaDB = $this->getOption( 'replicadb', $this->getOption( 'slave', '' ) );
66  if ( $replicaDB === 'any' ) {
67  $index = DB_REPLICA;
68  } elseif ( $replicaDB != '' ) {
69  $index = null;
70  $serverCount = $lb->getServerCount();
71  for ( $i = 0; $i < $serverCount; ++$i ) {
72  if ( $lb->getServerName( $i ) === $replicaDB ) {
73  $index = $i;
74  break;
75  }
76  }
77  if ( $index === null ) {
78  $this->fatalError( "No replica DB server configured with the name '$replicaDB'." );
79  }
80  } else {
81  $index = DB_MASTER;
82  }
83 
85  $db = $lb->getConnection( $index, [], $wiki );
86  if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
87  $this->fatalError( "The server selected ({$db->getServer()}) is not a replica DB." );
88  }
89 
90  if ( $index === DB_MASTER ) {
91  $updater = DatabaseUpdater::newForDB( $db, true, $this );
92  $db->setSchemaVars( $updater->getSchemaVars() );
93  }
94 
95  if ( $this->hasArg( 0 ) ) {
96  $file = fopen( $this->getArg( 0 ), 'r' );
97  if ( !$file ) {
98  $this->fatalError( "Unable to open input file" );
99  }
100 
101  $error = $db->sourceStream( $file, null, [ $this, 'sqlPrintResult' ] );
102  if ( $error !== true ) {
103  $this->fatalError( $error );
104  } else {
105  exit( 0 );
106  }
107  }
108 
109  if ( $this->hasOption( 'query' ) ) {
110  $query = $this->getOption( 'query' );
111  $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
112  wfWaitForSlaves();
113  return;
114  }
115 
116  if (
117  function_exists( 'readline_add_history' ) &&
118  Maintenance::posix_isatty( 0 /*STDIN*/ )
119  ) {
120  $historyFile = isset( $_ENV['HOME'] ) ?
121  "{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
122  readline_read_history( $historyFile );
123  } else {
124  $historyFile = null;
125  }
126 
127  $wholeLine = '';
128  $newPrompt = '> ';
129  $prompt = $newPrompt;
130  $doDie = !Maintenance::posix_isatty( 0 );
131  while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
132  if ( !$line ) {
133  # User simply pressed return key
134  continue;
135  }
136  $done = $db->streamStatementEnd( $wholeLine, $line );
137 
138  $wholeLine .= $line;
139 
140  if ( !$done ) {
141  $wholeLine .= ' ';
142  $prompt = ' -> ';
143  continue;
144  }
145  if ( $historyFile ) {
146  # Delimiter is eated by streamStatementEnd, we add it
147  # up in the history (T39020)
148  readline_add_history( $wholeLine . ';' );
149  readline_write_history( $historyFile );
150  }
151  $this->sqlDoQuery( $db, $wholeLine, $doDie );
152  $prompt = $newPrompt;
153  $wholeLine = '';
154  }
155  wfWaitForSlaves();
156  }
157 
158  protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
159  try {
160  $res = $db->query( $line );
161  $this->sqlPrintResult( $res, $db );
162  } catch ( DBQueryError $e ) {
163  if ( $dieOnError ) {
164  $this->fatalError( $e );
165  } else {
166  $this->error( $e );
167  }
168  }
169  }
170 
176  public function sqlPrintResult( $res, $db ) {
177  if ( !$res ) {
178  // Do nothing
179  return;
180  } elseif ( is_object( $res ) && $res->numRows() ) {
181  $out = '';
182  foreach ( $res as $row ) {
183  $out .= print_r( $row, true );
184  $rows[] = $row;
185  }
186  if ( $this->hasOption( 'json' ) ) {
187  $out = json_encode( $rows, JSON_PRETTY_PRINT );
188  }
189  $this->output( $out . "\n" );
190  } else {
191  $affected = $db->affectedRows();
192  $this->output( "Query OK, $affected row(s) affected\n" );
193  }
194  }
195 
199  public function getDbType() {
200  return Maintenance::DB_ADMIN;
201  }
202 }
203 
205 require_once RUN_MAINTENANCE_IF_MAIN;
Wikimedia\Rdbms\IDatabase\query
query( $sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
MwSql\sqlDoQuery
sqlDoQuery(IDatabase $db, $line, $dieOnError)
Definition: sql.php:158
MwSql\__construct
__construct()
Default constructor.
Definition: sql.php:38
MwSql\sqlPrintResult
sqlPrintResult( $res, $db)
Print the results, callback for $db->sourceStream()
Definition: sql.php:176
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:465
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:317
Maintenance\readconsole
static readconsole( $prompt='> ')
Prompt the console for input.
Definition: Maintenance.php:1561
RUN_MAINTENANCE_IF_MAIN
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
Maintenance\hasArg
hasArg( $argId=0)
Does a given argument exist?
Definition: Maintenance.php:326
$res
$res
Definition: database.txt:21
Wikimedia\Rdbms\ResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: ResultWrapper.php:24
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
wfWaitForSlaves
wfWaitForSlaves( $ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the replica DBs to catch up to the master position.
Definition: GlobalFunctions.php:2847
php
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
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
$query
null for the 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:1627
MwSql\execute
execute()
Do the actual work.
Definition: sql.php:52
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:236
$IP
$IP
Definition: update.php:3
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
MwSql
Maintenance script that sends SQL queries from the specified file to the database.
Definition: sql.php:37
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
DB_MASTER
const DB_MASTER
Definition: defines.php:26
Maintenance\DB_ADMIN
const DB_ADMIN
Definition: Maintenance.php:67
Wikimedia\Rdbms\DBQueryError
Definition: DBQueryError.php:27
$line
$line
Definition: cdb.php:59
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2221
Maintenance\posix_isatty
static posix_isatty( $fd)
Wrapper for posix_isatty() We default as considering stdin a tty (for nice readline methods) but trea...
Definition: Maintenance.php:1548
MwSql\getDbType
getDbType()
Definition: sql.php:199
DatabaseUpdater\newForDB
static newForDB(Database $db, $shared=false, Maintenance $maintenance=null)
Definition: DatabaseUpdater.php:189
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:271
$rows
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:2683
$maintClass
$maintClass
Definition: sql.php:204
as
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
$updater
$page->newPageUpdater($user) $updater
Definition: pageupdater.txt:63
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:442
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:414
class
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
MediaWikiServices
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
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option exists.
Definition: Maintenance.php:257
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:336
$out
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub 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:813