MwSql::sqlDoQuery()   A
last analyzed

Complexity

Conditions 2
Paths 3

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 3
nop 3
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 32 and the first side effect is on line 25.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
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
/**
28
 * Maintenance script that sends SQL queries from the specified file to the database.
29
 *
30
 * @ingroup Maintenance
31
 */
32
class MwSql extends Maintenance {
33
	public function __construct() {
34
		parent::__construct();
35
		$this->addDescription( 'Send SQL queries to a MediaWiki database. ' .
36
			'Takes a file name containing SQL as argument or runs interactively.' );
37
		$this->addOption( 'query',
38
			'Run a single query instead of running interactively', false, true );
39
		$this->addOption( 'cluster', 'Use an external cluster by name', false, true );
40
		$this->addOption( 'wikidb',
41
			'The database wiki ID to use if not the current one', false, true );
42
		$this->addOption( 'replicadb',
43
			'Replica DB server to use instead of the master DB (can be "any")', false, true );
44
	}
45
46
	public function execute() {
0 ignored issues
show
Coding Style introduced by
execute uses the super-global variable $_ENV which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
47
		global $IP;
48
49
		// We wan't to allow "" for the wikidb, meaning don't call select_db()
50
		$wiki = $this->hasOption( 'wikidb' ) ? $this->getOption( 'wikidb' ) : false;
51
		// Get the appropriate load balancer (for this wiki)
52
		if ( $this->hasOption( 'cluster' ) ) {
53
			$lb = wfGetLBFactory()->getExternalLB( $this->getOption( 'cluster' ), $wiki );
0 ignored issues
show
Deprecated Code introduced by
The function wfGetLBFactory() has been deprecated with message: since 1.27, use MediaWikiServices::getDBLoadBalancerFactory() instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
54
		} else {
55
			$lb = wfGetLB( $wiki );
0 ignored issues
show
Deprecated Code introduced by
The function wfGetLB() has been deprecated with message: since 1.27, use MediaWikiServices::getDBLoadBalancer() or MediaWikiServices::getDBLoadBalancerFactory() instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
56
		}
57
		// Figure out which server to use
58
		$replicaDB = $this->getOption( 'replicadb', $this->getOption( 'slave', '' ) );
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
			if ( $index === null ) {
71
				$this->error( "No replica DB server configured with the name '$replicaDB'.", 1 );
72
			}
73
		} else {
74
			$index = DB_MASTER;
75
		}
76
77
		/** @var Database $db DB handle for the appropriate cluster/wiki */
78
		$db = $lb->getConnection( $index, [], $wiki );
79
		if ( $replicaDB != '' && $db->getLBInfo( 'master' ) !== null ) {
80
			$this->error( "The server selected ({$db->getServer()}) is not a replica DB.", 1 );
81
		}
82
83
		if ( $index === DB_MASTER ) {
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->error( "Unable to open input file", true );
92
			}
93
94
			$error = $db->sourceStream( $file, null, [ $this, 'sqlPrintResult' ] );
95
			if ( $error !== true ) {
96
				$this->error( $error, true );
0 ignored issues
show
Bug introduced by
It seems like $error defined by $db->sourceStream($file,...his, 'sqlPrintResult')) on line 94 can also be of type boolean; however, Maintenance::error() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
97
			} else {
98
				exit( 0 );
0 ignored issues
show
Coding Style Compatibility introduced by
The method execute() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
99
			}
100
		}
101
102
		if ( $this->hasOption( 'query' ) ) {
103
			$query = $this->getOption( 'query' );
104
			$this->sqlDoQuery( $db, $query, /* dieOnError */ true );
105
			wfWaitForSlaves();
0 ignored issues
show
Deprecated Code introduced by
The function wfWaitForSlaves() has been deprecated with message: since 1.27 Use LBFactory::waitForReplication

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
106
			return;
107
		}
108
109
		if (
110
			function_exists( 'readline_add_history' ) &&
111
			Maintenance::posix_isatty( 0 /*STDIN*/ )
112
		) {
113
			$historyFile = isset( $_ENV['HOME'] ) ?
114
				"{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
115
			readline_read_history( $historyFile );
116
		} else {
117
			$historyFile = null;
118
		}
119
120
		$wholeLine = '';
121
		$newPrompt = '> ';
122
		$prompt = $newPrompt;
123
		$doDie = !Maintenance::posix_isatty( 0 );
124
		while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
125
			if ( !$line ) {
126
				# User simply pressed return key
127
				continue;
128
			}
129
			$done = $db->streamStatementEnd( $wholeLine, $line );
130
131
			$wholeLine .= $line;
132
133
			if ( !$done ) {
134
				$wholeLine .= ' ';
135
				$prompt = '    -> ';
136
				continue;
137
			}
138
			if ( $historyFile ) {
139
				# Delimiter is eated by streamStatementEnd, we add it
140
				# up in the history (bug 37020)
141
				readline_add_history( $wholeLine . ';' );
142
				readline_write_history( $historyFile );
143
			}
144
			$this->sqlDoQuery( $db, $wholeLine, $doDie );
145
			$prompt = $newPrompt;
146
			$wholeLine = '';
147
		}
148
		wfWaitForSlaves();
0 ignored issues
show
Deprecated Code introduced by
The function wfWaitForSlaves() has been deprecated with message: since 1.27 Use LBFactory::waitForReplication

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
149
	}
150
151
	protected function sqlDoQuery( IDatabase $db, $line, $dieOnError ) {
152
		try {
153
			$res = $db->query( $line );
154
			$this->sqlPrintResult( $res, $db );
0 ignored issues
show
Bug introduced by
It seems like $res defined by $db->query($line) on line 153 can also be of type boolean; however, MwSql::sqlPrintResult() does only seem to accept object<ResultWrapper>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
155
		} catch ( DBQueryError $e ) {
156
			$this->error( $e, $dieOnError );
157
		}
158
	}
159
160
	/**
161
	 * Print the results, callback for $db->sourceStream()
162
	 * @param ResultWrapper $res The results object
163
	 * @param IDatabase $db
164
	 */
165
	public function sqlPrintResult( $res, $db ) {
166
		if ( !$res ) {
167
			// Do nothing
168
			return;
169
		} elseif ( is_object( $res ) && $res->numRows() ) {
170
			foreach ( $res as $row ) {
171
				$this->output( print_r( $row, true ) );
172
			}
173
		} else {
174
			$affected = $db->affectedRows();
175
			$this->output( "Query OK, $affected row(s) affected\n" );
176
		}
177
	}
178
179
	/**
180
	 * @return int DB_TYPE constant
181
	 */
182
	public function getDbType() {
183
		return Maintenance::DB_ADMIN;
184
	}
185
}
186
187
$maintClass = "MwSql";
188
require_once RUN_MAINTENANCE_IF_MAIN;
189