Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 117
0.00% covered (danger)
0.00%
0 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
MwSql
0.00% covered (danger)
0.00%
0 / 114
0.00% covered (danger)
0.00%
0 / 5
1722
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 73
0.00% covered (danger)
0.00%
0 / 1
870
 sqlDoQuery
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 sqlPrintResult
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
56
 getDbType
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
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
25require_once __DIR__ . '/Maintenance.php';
26
27use MediaWiki\Installer\DatabaseUpdater;
28use Wikimedia\Rdbms\DBQueryError;
29use Wikimedia\Rdbms\IDatabase;
30use Wikimedia\Rdbms\IResultWrapper;
31
32/**
33 * Maintenance script that sends SQL queries from the specified file to the database.
34 *
35 * @ingroup Maintenance
36 */
37class 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( 'status', 'Return successful exit status only if the query succeeded '
46            . '(selected or altered rows), otherwise 1 for errors, 2 for no rows' );
47        $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
48        $this->addOption( 'wikidb',
49            'The database wiki ID to use if not the current one', false, true );
50        $this->addOption( 'replicadb',
51            'Replica DB server to use instead of the primary DB (can be "any")', false, true );
52        $this->setBatchSize( 100 );
53    }
54
55    public function execute() {
56        global $IP;
57
58        // We want to allow "" for the wikidb, meaning don't call select_db()
59        $wiki = $this->hasOption( 'wikidb' ) ? $this->getOption( 'wikidb' ) : false;
60        // Get the appropriate load balancer (for this wiki)
61        $lbFactory = $this->getServiceContainer()->getDBLoadBalancerFactory();
62        if ( $this->hasOption( 'cluster' ) ) {
63            $lb = $lbFactory->getExternalLB( $this->getOption( 'cluster' ) );
64        } else {
65            $lb = $lbFactory->getMainLB( $wiki );
66        }
67        // Figure out which server to use
68        $replicaDB = $this->getOption( 'replicadb', '' );
69        if ( $replicaDB === 'any' ) {
70            $index = DB_REPLICA;
71        } elseif ( $replicaDB !== '' ) {
72            $index = null;
73            $serverCount = $lb->getServerCount();
74            for ( $i = 0; $i < $serverCount; ++$i ) {
75                if ( $lb->getServerName( $i ) === $replicaDB ) {
76                    $index = $i;
77                    break;
78                }
79            }
80            if ( $index === null || $index === $lb->getWriterIndex() ) {
81                $this->fatalError( "No replica DB server configured with the name '$replicaDB'." );
82            }
83        } else {
84            $index = DB_PRIMARY;
85        }
86
87        $db = $lb->getMaintenanceConnectionRef( $index, [], $wiki );
88        if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
89            $this->fatalError( "Server {$db->getServerName()} is not a replica DB." );
90        }
91
92        if ( $index === DB_PRIMARY ) {
93            $updater = DatabaseUpdater::newForDB( $db, true, $this );
94            $db->setSchemaVars( $updater->getSchemaVars() );
95        }
96
97        if ( $this->hasArg( 0 ) ) {
98            $file = fopen( $this->getArg( 0 ), 'r' );
99            if ( !$file ) {
100                $this->fatalError( "Unable to open input file" );
101            }
102
103            $error = $db->sourceStream( $file, null, [ $this, 'sqlPrintResult' ], __METHOD__ );
104            if ( $error !== true ) {
105                $this->fatalError( $error );
106            }
107            return;
108        }
109
110        if ( $this->hasOption( 'query' ) ) {
111            $query = $this->getOption( 'query' );
112            $res = $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
113            $this->waitForReplication();
114            if ( $this->hasOption( 'status' ) && !$res ) {
115                $this->fatalError( 'Failed.', 2 );
116            }
117            return;
118        }
119
120        if (
121            function_exists( 'readline_add_history' ) &&
122            Maintenance::posix_isatty( 0 /*STDIN*/ )
123        ) {
124            $historyFile = isset( $_ENV['HOME'] ) ?
125                "{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
126            readline_read_history( $historyFile );
127        } else {
128            $historyFile = null;
129        }
130
131        $wholeLine = '';
132        $newPrompt = '> ';
133        $prompt = $newPrompt;
134        $doDie = !Maintenance::posix_isatty( 0 );
135        $res = 1;
136        $batchCount = 0;
137        while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
138            if ( !$line ) {
139                # User simply pressed return key
140                continue;
141            }
142            $done = $db->streamStatementEnd( $wholeLine, $line );
143
144            $wholeLine .= $line;
145
146            if ( !$done ) {
147                $wholeLine .= ' ';
148                $prompt = '    -> ';
149                continue;
150            }
151            if ( $historyFile ) {
152                # Delimiter is eaten by streamStatementEnd, we add it
153                # up in the history (T39020)
154                readline_add_history( $wholeLine . ';' );
155                readline_write_history( $historyFile );
156            }
157            // @phan-suppress-next-line SecurityCheck-SQLInjection
158            $res = $this->sqlDoQuery( $db, $wholeLine, $doDie );
159            if ( $this->getBatchSize() && ++$batchCount >= $this->getBatchSize() ) {
160                $batchCount = 0;
161                $this->waitForReplication();
162            }
163            $prompt = $newPrompt;
164            $wholeLine = '';
165        }
166        $this->waitForReplication();
167        if ( $this->hasOption( 'status' ) && !$res ) {
168            $this->fatalError( 'Failed.', 2 );
169        }
170    }
171
172    /**
173     * @param IDatabase $db
174     * @param string $line The SQL text of the query
175     * @param bool $dieOnError
176     * @return int|null Number of rows selected or updated, or null if the query was unsuccessful.
177     */
178    protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
179        try {
180            $res = $db->query( $line, __METHOD__ );
181            return $this->sqlPrintResult( $res, $db );
182        } catch ( DBQueryError $e ) {
183            if ( $dieOnError ) {
184                $this->fatalError( (string)$e );
185            } else {
186                $this->error( (string)$e );
187            }
188        }
189        return null;
190    }
191
192    /**
193     * Print the results, callback for $db->sourceStream()
194     * @param IResultWrapper|bool $res
195     * @param IDatabase $db
196     * @return int|null Number of rows selected or updated, or null if the query was unsuccessful.
197     */
198    public function sqlPrintResult( $res, $db ) {
199        if ( !$res ) {
200            // Do nothing
201            return null;
202        } elseif ( is_object( $res ) ) {
203            $out = '';
204            $rows = [];
205            foreach ( $res as $row ) {
206                $out .= print_r( $row, true );
207                $rows[] = $row;
208            }
209            if ( $this->hasOption( 'json' ) ) {
210                $out = json_encode( $rows, JSON_PRETTY_PRINT );
211            } elseif ( !$rows ) {
212                $out = 'Query OK, 0 row(s) affected';
213            }
214            $this->output( $out . "\n" );
215            return count( $rows );
216        } else {
217            $affected = $db->affectedRows();
218            if ( $this->hasOption( 'json' ) ) {
219                $this->output( json_encode( [ 'affected' => $affected ], JSON_PRETTY_PRINT ) . "\n" );
220            } else {
221                $this->output( "Query OK, $affected row(s) affected\n" );
222            }
223            return $affected;
224        }
225    }
226
227    /**
228     * @return int DB_TYPE constant
229     */
230    public function getDbType() {
231        return Maintenance::DB_ADMIN;
232    }
233}
234
235$maintClass = MwSql::class;
236require_once RUN_MAINTENANCE_IF_MAIN;