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