MediaWiki  1.27.2
sql.php
Go to the documentation of this file.
1 <?php
25 require_once __DIR__ . '/Maintenance.php';
26 
32 class MwSql extends Maintenance {
33  public function __construct() {
34  parent::__construct();
35  $this->addDescription( 'Send SQL queries to a MediaWiki database. ' .
36  'Takes a file name containing SQL as argument or runs interactively.' );
37  $this->addOption( 'query', 'Run a single query instead of running interactively', false, true );
38  $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
39  $this->addOption( 'wikidb', 'The database wiki ID to use if not the current one', false, true );
40  $this->addOption( 'slave', 'Use a slave server (either "any" or by name)', false, true );
41  }
42 
43  public function execute() {
44  // We wan't to allow "" for the wikidb, meaning don't call select_db()
45  $wiki = $this->hasOption( 'wikidb' ) ? $this->getOption( 'wikidb' ) : false;
46  // Get the appropriate load balancer (for this wiki)
47  if ( $this->hasOption( 'cluster' ) ) {
48  $lb = wfGetLBFactory()->getExternalLB( $this->getOption( 'cluster' ), $wiki );
49  } else {
50  $lb = wfGetLB( $wiki );
51  }
52  // Figure out which server to use
53  if ( $this->hasOption( 'slave' ) ) {
54  $server = $this->getOption( 'slave' );
55  if ( $server === 'any' ) {
56  $index = DB_SLAVE;
57  } else {
58  $index = null;
59  $serverCount = $lb->getServerCount();
60  for ( $i = 0; $i < $serverCount; ++$i ) {
61  if ( $lb->getServerName( $i ) === $server ) {
62  $index = $i;
63  break;
64  }
65  }
66  if ( $index === null ) {
67  $this->error( "No slave server configured with the name '$server'.", 1 );
68  }
69  }
70  } else {
71  $index = DB_MASTER;
72  }
73  // Get a DB handle (with this wiki's DB selected) from the appropriate load balancer
74  $db = $lb->getConnection( $index, [], $wiki );
75  if ( $this->hasOption( 'slave' ) && $db->getLBInfo( 'master' ) !== null ) {
76  $this->error( "The server selected ({$db->getServer()}) is not a slave.", 1 );
77  }
78 
79  if ( $this->hasArg( 0 ) ) {
80  $file = fopen( $this->getArg( 0 ), 'r' );
81  if ( !$file ) {
82  $this->error( "Unable to open input file", true );
83  }
84 
85  $error = $db->sourceStream( $file, false, [ $this, 'sqlPrintResult' ] );
86  if ( $error !== true ) {
87  $this->error( $error, true );
88  } else {
89  exit( 0 );
90  }
91  }
92 
93  if ( $this->hasOption( 'query' ) ) {
94  $query = $this->getOption( 'query' );
95  $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
97  return;
98  }
99 
100  $useReadline = function_exists( 'readline_add_history' )
101  && Maintenance::posix_isatty( 0 /*STDIN*/ );
102 
103  if ( $useReadline ) {
104  global $IP;
105  $historyFile = isset( $_ENV['HOME'] ) ?
106  "{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
107  readline_read_history( $historyFile );
108  }
109 
110  $wholeLine = '';
111  $newPrompt = '> ';
112  $prompt = $newPrompt;
113  $doDie = !Maintenance::posix_isatty( 0 );
114  while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
115  if ( !$line ) {
116  # User simply pressed return key
117  continue;
118  }
119  $done = $db->streamStatementEnd( $wholeLine, $line );
120 
121  $wholeLine .= $line;
122 
123  if ( !$done ) {
124  $wholeLine .= ' ';
125  $prompt = ' -> ';
126  continue;
127  }
128  if ( $useReadline ) {
129  # Delimiter is eated by streamStatementEnd, we add it
130  # up in the history (bug 37020)
131  readline_add_history( $wholeLine . $db->getDelimiter() );
132  readline_write_history( $historyFile );
133  }
134  $this->sqlDoQuery( $db, $wholeLine, $doDie );
135  $prompt = $newPrompt;
136  $wholeLine = '';
137  }
138  wfWaitForSlaves();
139  }
140 
141  protected function sqlDoQuery( $db, $line, $dieOnError ) {
142  try {
143  $res = $db->query( $line );
144  $this->sqlPrintResult( $res, $db );
145  } catch ( DBQueryError $e ) {
146  $this->error( $e, $dieOnError );
147  }
148  }
149 
155  public function sqlPrintResult( $res, $db ) {
156  if ( !$res ) {
157  // Do nothing
158  return;
159  } elseif ( is_object( $res ) && $res->numRows() ) {
160  foreach ( $res as $row ) {
161  $this->output( print_r( $row, true ) );
162  }
163  } else {
164  $affected = $db->affectedRows();
165  $this->output( "Query OK, $affected row(s) affected\n" );
166  }
167  }
168 
172  public function getDbType() {
173  return Maintenance::DB_ADMIN;
174  }
175 }
176 
177 $maintClass = "MwSql";
178 require_once RUN_MAINTENANCE_IF_MAIN;
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:1418
wfWaitForSlaves($ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the slaves to catch up to the master position.
$IP
Definition: WebStart.php:58
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
Maintenance script that sends SQL queries from the specified file to the database.
Definition: sql.php:32
hasOption($name)
Checks to see if a particular param exists.
__construct()
Definition: sql.php:33
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
static posix_isatty($fd)
Wrapper for posix_isatty() We default as considering stdin a tty (for nice readline methods) but trea...
execute()
Definition: sql.php:43
addOption($name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
wfGetLB($wiki=false)
Get a load balancer object.
sqlDoQuery($db, $line, $dieOnError)
Definition: sql.php:141
$res
Definition: database.txt:21
const DB_ADMIN
Definition: Maintenance.php:60
hasArg($argId=0)
Does a given argument exist?
const DB_SLAVE
Definition: Defines.php:46
addDescription($text)
Set the description text.
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
getOption($name, $default=null)
Get an option, or return the default.
output($out, $channel=null)
Throw some output to the user.
sqlPrintResult($res, $db)
Print the results, callback for $db->sourceStream()
Definition: sql.php:155
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
wfGetLBFactory()
Get the load balancer factory object.
static readconsole($prompt= '> ')
Prompt the console for input.
$line
Definition: cdb.php:59
error($err, $die=0)
Throw an error to the user.
$maintClass
Definition: sql.php:177
const DB_MASTER
Definition: Defines.php:47
getArg($argId=0, $default=null)
Get an argument.
getDbType()
Definition: sql.php:172