MediaWiki  1.30.0
sql.php
Go to the documentation of this file.
1 <?php
25 require_once __DIR__ . '/Maintenance.php';
26 
30 
36 class MwSql extends Maintenance {
37  public function __construct() {
38  parent::__construct();
39  $this->addDescription( 'Send SQL queries to a MediaWiki database. ' .
40  'Takes a file name containing SQL as argument or runs interactively.' );
41  $this->addOption( 'query',
42  'Run a single query instead of running interactively', false, true );
43  $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
44  $this->addOption( 'wikidb',
45  'The database wiki ID to use if not the current one', false, true );
46  $this->addOption( 'replicadb',
47  'Replica DB server to use instead of the master DB (can be "any")', false, true );
48  }
49 
50  public function execute() {
51  global $IP;
52 
53  // We wan't to allow "" for the wikidb, meaning don't call select_db()
54  $wiki = $this->hasOption( 'wikidb' ) ? $this->getOption( 'wikidb' ) : false;
55  // Get the appropriate load balancer (for this wiki)
56  if ( $this->hasOption( 'cluster' ) ) {
57  $lb = wfGetLBFactory()->getExternalLB( $this->getOption( 'cluster' ) );
58  } else {
59  $lb = wfGetLB( $wiki );
60  }
61  // Figure out which server to use
62  $replicaDB = $this->getOption( 'replicadb', $this->getOption( 'slave', '' ) );
63  if ( $replicaDB === 'any' ) {
64  $index = DB_REPLICA;
65  } elseif ( $replicaDB != '' ) {
66  $index = null;
67  $serverCount = $lb->getServerCount();
68  for ( $i = 0; $i < $serverCount; ++$i ) {
69  if ( $lb->getServerName( $i ) === $replicaDB ) {
70  $index = $i;
71  break;
72  }
73  }
74  if ( $index === null ) {
75  $this->error( "No replica DB server configured with the name '$replicaDB'.", 1 );
76  }
77  } else {
78  $index = DB_MASTER;
79  }
80 
82  $db = $lb->getConnection( $index, [], $wiki );
83  if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
84  $this->error( "The server selected ({$db->getServer()}) is not a replica DB.", 1 );
85  }
86 
87  if ( $index === DB_MASTER ) {
88  $updater = DatabaseUpdater::newForDB( $db, true, $this );
89  $db->setSchemaVars( $updater->getSchemaVars() );
90  }
91 
92  if ( $this->hasArg( 0 ) ) {
93  $file = fopen( $this->getArg( 0 ), 'r' );
94  if ( !$file ) {
95  $this->error( "Unable to open input file", true );
96  }
97 
98  $error = $db->sourceStream( $file, null, [ $this, 'sqlPrintResult' ] );
99  if ( $error !== true ) {
100  $this->error( $error, true );
101  } else {
102  exit( 0 );
103  }
104  }
105 
106  if ( $this->hasOption( 'query' ) ) {
107  $query = $this->getOption( 'query' );
108  $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
109  wfWaitForSlaves();
110  return;
111  }
112 
113  if (
114  function_exists( 'readline_add_history' ) &&
115  Maintenance::posix_isatty( 0 /*STDIN*/ )
116  ) {
117  $historyFile = isset( $_ENV['HOME'] ) ?
118  "{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
119  readline_read_history( $historyFile );
120  } else {
121  $historyFile = null;
122  }
123 
124  $wholeLine = '';
125  $newPrompt = '> ';
126  $prompt = $newPrompt;
127  $doDie = !Maintenance::posix_isatty( 0 );
128  while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
129  if ( !$line ) {
130  # User simply pressed return key
131  continue;
132  }
133  $done = $db->streamStatementEnd( $wholeLine, $line );
134 
135  $wholeLine .= $line;
136 
137  if ( !$done ) {
138  $wholeLine .= ' ';
139  $prompt = ' -> ';
140  continue;
141  }
142  if ( $historyFile ) {
143  # Delimiter is eated by streamStatementEnd, we add it
144  # up in the history (T39020)
145  readline_add_history( $wholeLine . ';' );
146  readline_write_history( $historyFile );
147  }
148  $this->sqlDoQuery( $db, $wholeLine, $doDie );
149  $prompt = $newPrompt;
150  $wholeLine = '';
151  }
152  wfWaitForSlaves();
153  }
154 
155  protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
156  try {
157  $res = $db->query( $line );
158  $this->sqlPrintResult( $res, $db );
159  } catch ( DBQueryError $e ) {
160  $this->error( $e, $dieOnError );
161  }
162  }
163 
169  public function sqlPrintResult( $res, $db ) {
170  if ( !$res ) {
171  // Do nothing
172  return;
173  } elseif ( is_object( $res ) && $res->numRows() ) {
174  foreach ( $res as $row ) {
175  $this->output( print_r( $row, true ) );
176  }
177  } else {
178  $affected = $db->affectedRows();
179  $this->output( "Query OK, $affected row(s) affected\n" );
180  }
181  }
182 
186  public function getDbType() {
187  return Maintenance::DB_ADMIN;
188  }
189 }
190 
191 $maintClass = "MwSql";
192 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:155
MwSql\__construct
__construct()
Default constructor.
Definition: sql.php:37
MwSql\sqlPrintResult
sqlPrintResult( $res, $db)
Print the results, callback for $db->sourceStream()
Definition: sql.php:169
wfGetLB
wfGetLB( $wiki=false)
Get a load balancer object.
Definition: GlobalFunctions.php:2869
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:287
Maintenance\readconsole
static readconsole( $prompt='> ')
Prompt the console for input.
Definition: Maintenance.php:1440
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
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:296
$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:3010
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:40
$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:1581
MwSql\execute
execute()
Do the actual work.
Definition: sql.php:50
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:215
$IP
$IP
Definition: update.php:3
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
MwSql
Maintenance script that sends SQL queries from the specified file to the database.
Definition: sql.php:36
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:64
Wikimedia\Rdbms\DBQueryError
Definition: DBQueryError.php:27
$line
$line
Definition: cdb.php:58
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2141
DatabaseUpdater\newForDB
static newForDB(Database $db, $shared=false, $maintenance=null)
Definition: DatabaseUpdater.php:187
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:1427
MwSql\getDbType
getDbType()
Definition: sql.php:186
wfGetLBFactory
wfGetLBFactory()
Get the load balancer factory object.
Definition: GlobalFunctions.php:2885
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:250
$maintClass
$maintClass
Definition: sql.php:191
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
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:392
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:373
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular param exists.
Definition: Maintenance.php:236
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:306