MediaWiki  1.28.0
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',
38  'Run a single query instead of running interactively', false, true );
39  $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
40  $this->addOption( 'wikidb',
41  'The database wiki ID to use if not the current one', false, true );
42  $this->addOption( 'replicadb',
43  'Replica DB server to use instead of the master DB (can be "any")', false, true );
44  }
45 
46  public function execute() {
47  global $IP;
48 
49  // We wan't to allow "" for the wikidb, meaning don't call select_db()
50  $wiki = $this->hasOption( 'wikidb' ) ? $this->getOption( 'wikidb' ) : false;
51  // Get the appropriate load balancer (for this wiki)
52  if ( $this->hasOption( 'cluster' ) ) {
53  $lb = wfGetLBFactory()->getExternalLB( $this->getOption( 'cluster' ), $wiki );
54  } else {
55  $lb = wfGetLB( $wiki );
56  }
57  // Figure out which server to use
58  $replicaDB = $this->getOption( 'replicadb', $this->getOption( 'slave', '' ) );
59  if ( $replicaDB === 'any' ) {
60  $index = DB_REPLICA;
61  } elseif ( $replicaDB != '' ) {
62  $index = null;
63  $serverCount = $lb->getServerCount();
64  for ( $i = 0; $i < $serverCount; ++$i ) {
65  if ( $lb->getServerName( $i ) === $replicaDB ) {
66  $index = $i;
67  break;
68  }
69  }
70  if ( $index === null ) {
71  $this->error( "No replica DB server configured with the name '$replicaDB'.", 1 );
72  }
73  } else {
74  $index = DB_MASTER;
75  }
76 
78  $db = $lb->getConnection( $index, [], $wiki );
79  if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
80  $this->error( "The server selected ({$db->getServer()}) is not a replica DB.", 1 );
81  }
82 
83  if ( $index === DB_MASTER ) {
84  $updater = DatabaseUpdater::newForDB( $db, true, $this );
85  $db->setSchemaVars( $updater->getSchemaVars() );
86  }
87 
88  if ( $this->hasArg( 0 ) ) {
89  $file = fopen( $this->getArg( 0 ), 'r' );
90  if ( !$file ) {
91  $this->error( "Unable to open input file", true );
92  }
93 
94  $error = $db->sourceStream( $file, null, [ $this, 'sqlPrintResult' ] );
95  if ( $error !== true ) {
96  $this->error( $error, true );
97  } else {
98  exit( 0 );
99  }
100  }
101 
102  if ( $this->hasOption( 'query' ) ) {
103  $query = $this->getOption( 'query' );
104  $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
105  wfWaitForSlaves();
106  return;
107  }
108 
109  if (
110  function_exists( 'readline_add_history' ) &&
111  Maintenance::posix_isatty( 0 /*STDIN*/ )
112  ) {
113  $historyFile = isset( $_ENV['HOME'] ) ?
114  "{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
115  readline_read_history( $historyFile );
116  } else {
117  $historyFile = null;
118  }
119 
120  $wholeLine = '';
121  $newPrompt = '> ';
122  $prompt = $newPrompt;
123  $doDie = !Maintenance::posix_isatty( 0 );
124  while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
125  if ( !$line ) {
126  # User simply pressed return key
127  continue;
128  }
129  $done = $db->streamStatementEnd( $wholeLine, $line );
130 
131  $wholeLine .= $line;
132 
133  if ( !$done ) {
134  $wholeLine .= ' ';
135  $prompt = ' -> ';
136  continue;
137  }
138  if ( $historyFile ) {
139  # Delimiter is eated by streamStatementEnd, we add it
140  # up in the history (bug 37020)
141  readline_add_history( $wholeLine . ';' );
142  readline_write_history( $historyFile );
143  }
144  $this->sqlDoQuery( $db, $wholeLine, $doDie );
145  $prompt = $newPrompt;
146  $wholeLine = '';
147  }
148  wfWaitForSlaves();
149  }
150 
151  protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
152  try {
153  $res = $db->query( $line );
154  $this->sqlPrintResult( $res, $db );
155  } catch ( DBQueryError $e ) {
156  $this->error( $e, $dieOnError );
157  }
158  }
159 
165  public function sqlPrintResult( $res, $db ) {
166  if ( !$res ) {
167  // Do nothing
168  return;
169  } elseif ( is_object( $res ) && $res->numRows() ) {
170  foreach ( $res as $row ) {
171  $this->output( print_r( $row, true ) );
172  }
173  } else {
174  $affected = $db->affectedRows();
175  $this->output( "Query OK, $affected row(s) affected\n" );
176  }
177  }
178 
182  public function getDbType() {
183  return Maintenance::DB_ADMIN;
184  }
185 }
186 
187 $maintClass = "MwSql";
188 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:1555
wfWaitForSlaves($ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
Waits for the replica DBs 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:2102
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
query($sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
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...
sqlDoQuery(IDatabase $db, $line, $dieOnError)
Definition: sql.php:151
execute()
Definition: sql.php:46
static newForDB(Database $db, $shared=false, $maintenance=null)
const DB_MASTER
Definition: defines.php:23
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.
$res
Definition: database.txt:21
const DB_ADMIN
Definition: Maintenance.php:59
hasArg($argId=0)
Does a given argument exist?
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:165
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:187
getArg($argId=0, $default=null)
Get an argument.
const DB_REPLICA
Definition: defines.php:22
getDbType()
Definition: sql.php:182
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:34