Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
51.75% covered (warning)
51.75%
59 / 114
40.00% covered (danger)
40.00%
2 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
MwSql
51.75% covered (warning)
51.75%
59 / 114
40.00% covered (danger)
40.00%
2 / 5
229.77
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
1
 execute
42.47% covered (danger)
42.47%
31 / 73
0.00% covered (danger)
0.00%
0 / 1
189.17
 sqlDoQuery
28.57% covered (danger)
28.57%
2 / 7
0.00% covered (danger)
0.00%
0 / 1
6.28
 sqlPrintResult
57.89% covered (warning)
57.89%
11 / 19
0.00% covered (danger)
0.00%
0 / 1
10.66
 getDbType
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Send SQL queries from the specified file to the database, performing
4 * variable replacement along the way.
5 *
6 * @license GPL-2.0-or-later
7 * @file
8 * @ingroup Maintenance
9 */
10
11// @codeCoverageIgnoreStart
12require_once __DIR__ . '/Maintenance.php';
13// @codeCoverageIgnoreEnd
14
15use MediaWiki\Installer\DatabaseUpdater;
16use MediaWiki\Maintenance\Maintenance;
17use Wikimedia\Rdbms\DBQueryError;
18use Wikimedia\Rdbms\IDatabase;
19use Wikimedia\Rdbms\IResultWrapper;
20use Wikimedia\Rdbms\ServerInfo;
21
22/**
23 * Maintenance script that sends SQL queries from the specified file to the database.
24 *
25 * @ingroup Maintenance
26 */
27class MwSql extends Maintenance {
28    public function __construct() {
29        parent::__construct();
30        $this->addDescription( 'Send SQL queries to a MediaWiki database. ' .
31            'Takes a file name containing SQL as argument or runs interactively.' );
32        $this->addOption( 'query',
33            'Run a single query instead of running interactively', false, true );
34        $this->addOption( 'json', 'Output the results as JSON instead of PHP objects' );
35        $this->addOption( 'status', 'Return successful exit status only if the query succeeded '
36            . '(selected or altered rows), otherwise 1 for errors, 2 for no rows' );
37        $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
38        $this->addOption( 'wikidb',
39            'The database wiki ID to use if not the current one', false, true );
40        $this->addOption( 'replicadb',
41            'Replica DB server to use instead of the primary DB (can be "any")', false, true );
42        $this->setBatchSize( 100 );
43    }
44
45    public function execute() {
46        global $IP;
47
48        // We want to allow "" for the wikidb, meaning don't call select_db()
49        $wiki = $this->hasOption( 'wikidb' ) ? $this->getOption( 'wikidb' ) : false;
50        // Get the appropriate load balancer (for this wiki)
51        $lbFactory = $this->getServiceContainer()->getDBLoadBalancerFactory();
52        if ( $this->hasOption( 'cluster' ) ) {
53            $lb = $lbFactory->getExternalLB( $this->getOption( 'cluster' ) );
54        } else {
55            $lb = $lbFactory->getMainLB( $wiki );
56        }
57        // Figure out which server to use
58        $replicaDB = $this->getOption( 'replicadb', '' );
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            // @phan-suppress-next-line PhanSuspiciousValueComparison
71            if ( $index === null || $index === ServerInfo::WRITER_INDEX ) {
72                $this->fatalError( "No replica DB server configured with the name '$replicaDB'." );
73            }
74        } else {
75            $index = DB_PRIMARY;
76        }
77
78        $db = $lb->getMaintenanceConnectionRef( $index, [], $wiki );
79        if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
80            $this->fatalError( "Server {$db->getServerName()} is not a replica DB." );
81        }
82
83        if ( $index === DB_PRIMARY ) {
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->fatalError( "Unable to open input file" );
92            }
93
94            $error = $db->sourceStream( $file, null, $this->sqlPrintResult( ... ), __METHOD__ );
95            if ( $error !== true ) {
96                $this->fatalError( $error );
97            }
98            return;
99        }
100
101        if ( $this->hasOption( 'query' ) ) {
102            $query = $this->getOption( 'query' );
103            $res = $this->sqlDoQuery( $db, $query, /* dieOnError */ true );
104            $this->waitForReplication();
105            if ( $this->hasOption( 'status' ) && !$res ) {
106                $this->fatalError( 'Failed.', 2 );
107            }
108            return;
109        }
110
111        if (
112            function_exists( 'readline_add_history' ) &&
113            Maintenance::posix_isatty( 0 /*STDIN*/ )
114        ) {
115            $home = getenv( 'HOME' );
116            $historyFile = $home ?
117                "$home/.mwsql_history" : "$IP/maintenance/.mwsql_history";
118            readline_read_history( $historyFile );
119        } else {
120            $historyFile = null;
121        }
122
123        $wholeLine = '';
124        $newPrompt = '> ';
125        $prompt = $newPrompt;
126        $doDie = !Maintenance::posix_isatty( 0 );
127        $res = 1;
128        $batchCount = 0;
129        // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
130        while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
131            if ( !$line ) {
132                # User simply pressed return key
133                continue;
134            }
135            $done = $db->streamStatementEnd( $wholeLine, $line );
136
137            $wholeLine .= $line;
138
139            if ( !$done ) {
140                $wholeLine .= ' ';
141                $prompt = '    -> ';
142                continue;
143            }
144            if ( $historyFile ) {
145                # Delimiter is eaten by streamStatementEnd, we add it
146                # up in the history (T39020)
147                readline_add_history( $wholeLine . ';' );
148                readline_write_history( $historyFile );
149            }
150            // @phan-suppress-next-line SecurityCheck-SQLInjection
151            $res = $this->sqlDoQuery( $db, $wholeLine, $doDie );
152            if ( $this->getBatchSize() && ++$batchCount >= $this->getBatchSize() ) {
153                $batchCount = 0;
154                $this->waitForReplication();
155            }
156            $prompt = $newPrompt;
157            $wholeLine = '';
158        }
159        $this->waitForReplication();
160        if ( $this->hasOption( 'status' ) && !$res ) {
161            $this->fatalError( 'Failed.', 2 );
162        }
163    }
164
165    /**
166     * @param IDatabase $db
167     * @param string $line The SQL text of the query
168     * @param bool $dieOnError
169     * @return int|null Number of rows selected or updated, or null if the query was unsuccessful.
170     */
171    protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
172        try {
173            $res = $db->query( $line, __METHOD__ );
174            return $this->sqlPrintResult( $res, $db );
175        } catch ( DBQueryError $e ) {
176            if ( $dieOnError ) {
177                $this->fatalError( (string)$e );
178            } else {
179                $this->error( (string)$e );
180            }
181        }
182        return null;
183    }
184
185    /**
186     * Print the results, callback for $db->sourceStream()
187     * @param IResultWrapper|bool $res
188     * @param IDatabase $db
189     * @return int|null Number of rows selected or updated, or null if the query was unsuccessful.
190     */
191    private function sqlPrintResult( $res, $db ) {
192        if ( !$res ) {
193            // Do nothing
194            return null;
195        } elseif ( is_object( $res ) ) {
196            $out = '';
197            $rows = [];
198            foreach ( $res as $row ) {
199                $out .= print_r( $row, true );
200                $rows[] = $row;
201            }
202            if ( $this->hasOption( 'json' ) ) {
203                $out = json_encode( $rows, JSON_PRETTY_PRINT );
204            } elseif ( !$rows ) {
205                $out = 'Query OK, 0 row(s) affected';
206            }
207            $this->output( $out . "\n" );
208            return count( $rows );
209        } else {
210            $affected = $db->affectedRows();
211            if ( $this->hasOption( 'json' ) ) {
212                $this->output( json_encode( [ 'affected' => $affected ], JSON_PRETTY_PRINT ) . "\n" );
213            } else {
214                $this->output( "Query OK, $affected row(s) affected\n" );
215            }
216            return $affected;
217        }
218    }
219
220    /**
221     * @return int DB_TYPE constant
222     */
223    public function getDbType() {
224        return Maintenance::DB_ADMIN;
225    }
226}
227
228// @codeCoverageIgnoreStart
229$maintClass = MwSql::class;
230require_once RUN_MAINTENANCE_IF_MAIN;
231// @codeCoverageIgnoreEnd