Merge "Add support for PHP7 random_bytes in favor of mcrypt_create_iv"
[lhc/web/wiklou.git] / maintenance / sql.php
1 <?php
2 /**
3 * Send SQL queries from the specified file to the database, performing
4 * variable replacement along the way.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Maintenance
23 */
24
25 require_once __DIR__ . '/Maintenance.php';
26
27 use Wikimedia\Rdbms\ResultWrapper;
28
29 /**
30 * Maintenance script that sends SQL queries from the specified file to the database.
31 *
32 * @ingroup Maintenance
33 */
34 class MwSql extends Maintenance {
35 public function __construct() {
36 parent::__construct();
37 $this->addDescription( 'Send SQL queries to a MediaWiki database. ' .
38 'Takes a file name containing SQL as argument or runs interactively.' );
39 $this->addOption( 'query',
40 'Run a single query instead of running interactively', false, true );
41 $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
42 $this->addOption( 'wikidb',
43 'The database wiki ID to use if not the current one', false, true );
44 $this->addOption( 'replicadb',
45 'Replica DB server to use instead of the master DB (can be "any")', false, true );
46 }
47
48 public function execute() {
49 global $IP;
50
51 // We wan't to allow "" for the wikidb, meaning don't call select_db()
52 $wiki = $this->hasOption( 'wikidb' ) ? $this->getOption( 'wikidb' ) : false;
53 // Get the appropriate load balancer (for this wiki)
54 if ( $this->hasOption( 'cluster' ) ) {
55 $lb = wfGetLBFactory()->getExternalLB( $this->getOption( 'cluster' ) );
56 } else {
57 $lb = wfGetLB( $wiki );
58 }
59 // Figure out which server to use
60 $replicaDB = $this->getOption( 'replicadb', $this->getOption( 'slave', '' ) );
61 if ( $replicaDB === 'any' ) {
62 $index = DB_REPLICA;
63 } elseif ( $replicaDB != '' ) {
64 $index = null;
65 $serverCount = $lb->getServerCount();
66 for ( $i = 0; $i < $serverCount; ++$i ) {
67 if ( $lb->getServerName( $i ) === $replicaDB ) {
68 $index = $i;
69 break;
70 }
71 }
72 if ( $index === null ) {
73 $this->error( "No replica DB server configured with the name '$replicaDB'.", 1 );
74 }
75 } else {
76 $index = DB_MASTER;
77 }
78
79 /** @var Database $db DB handle for the appropriate cluster/wiki */
80 $db = $lb->getConnection( $index, [], $wiki );
81 if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
82 $this->error( "The server selected ({$db->getServer()}) is not a replica DB.", 1 );
83 }
84
85 if ( $index === DB_MASTER ) {
86 $updater = DatabaseUpdater::newForDB( $db, true, $this );
87 $db->setSchemaVars( $updater->getSchemaVars() );
88 }
89
90 if ( $this->hasArg( 0 ) ) {
91 $file = fopen( $this->getArg( 0 ), 'r' );
92 if ( !$file ) {
93 $this->error( "Unable to open input file", true );
94 }
95
96 $error = $db->sourceStream( $file, null, [ $this, 'sqlPrintResult' ] );
97 if ( $error !== true ) {
98 $this->error( $error, true );
99 } else {
100 exit( 0 );
101 }
102 }
103
104 if ( $this->hasOption( 'query' ) ) {
105 $query = $this->getOption( 'query' );
106 $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
107 wfWaitForSlaves();
108 return;
109 }
110
111 if (
112 function_exists( 'readline_add_history' ) &&
113 Maintenance::posix_isatty( 0 /*STDIN*/ )
114 ) {
115 $historyFile = isset( $_ENV['HOME'] ) ?
116 "{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
117 readline_read_history( $historyFile );
118 } else {
119 $historyFile = null;
120 }
121
122 $wholeLine = '';
123 $newPrompt = '> ';
124 $prompt = $newPrompt;
125 $doDie = !Maintenance::posix_isatty( 0 );
126 while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
127 if ( !$line ) {
128 # User simply pressed return key
129 continue;
130 }
131 $done = $db->streamStatementEnd( $wholeLine, $line );
132
133 $wholeLine .= $line;
134
135 if ( !$done ) {
136 $wholeLine .= ' ';
137 $prompt = ' -> ';
138 continue;
139 }
140 if ( $historyFile ) {
141 # Delimiter is eated by streamStatementEnd, we add it
142 # up in the history (T39020)
143 readline_add_history( $wholeLine . ';' );
144 readline_write_history( $historyFile );
145 }
146 $this->sqlDoQuery( $db, $wholeLine, $doDie );
147 $prompt = $newPrompt;
148 $wholeLine = '';
149 }
150 wfWaitForSlaves();
151 }
152
153 protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
154 try {
155 $res = $db->query( $line );
156 $this->sqlPrintResult( $res, $db );
157 } catch ( DBQueryError $e ) {
158 $this->error( $e, $dieOnError );
159 }
160 }
161
162 /**
163 * Print the results, callback for $db->sourceStream()
164 * @param ResultWrapper|bool $res The results object
165 * @param IDatabase $db
166 */
167 public function sqlPrintResult( $res, $db ) {
168 if ( !$res ) {
169 // Do nothing
170 return;
171 } elseif ( is_object( $res ) && $res->numRows() ) {
172 foreach ( $res as $row ) {
173 $this->output( print_r( $row, true ) );
174 }
175 } else {
176 $affected = $db->affectedRows();
177 $this->output( "Query OK, $affected row(s) affected\n" );
178 }
179 }
180
181 /**
182 * @return int DB_TYPE constant
183 */
184 public function getDbType() {
185 return Maintenance::DB_ADMIN;
186 }
187 }
188
189 $maintClass = "MwSql";
190 require_once RUN_MAINTENANCE_IF_MAIN;