Merge maintenance-work branch (now with less errors!):
[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 * @ingroup Maintenance
22 */
23
24 require_once( "Maintenance.php" );
25
26 class MwSql extends Maintenance {
27 public function __construct() {
28 parent::__construct();
29 $this->mDescription = "Send SQL queries to a MediaWiki database";
30 }
31
32 public function execute() {
33 if ( $this->hasArg() ) {
34 $fileName = $this->getArg();
35 $file = fopen( $fileName, 'r' );
36 $promptCallback = false;
37 } else {
38 $file = $this->getStdin();
39 $promptObject = new SqlPromptPrinter( "> " );
40 $promptCallback = $promptObject->cb();
41 }
42
43 if ( !$file )
44 $this->error( "Unable to open input file\n", true );
45
46 $dbw = wfGetDB( DB_MASTER );
47 $error = $dbw->sourceStream( $file, $promptCallback, array( $this, 'sqlPrintResult' ) );
48 if ( $error !== true ) {
49 $this->error( $error, true );
50 } else {
51 exit( 0 );
52 }
53 }
54
55 /**
56 * Print the results, callback for $db->sourceStream()
57 * @param $res The results object
58 * @param $db Database object
59 */
60 public function sqlPrintResult( $res, $db ) {
61 if ( !$res ) {
62 // Do nothing
63 } elseif ( is_object( $res ) && $res->numRows() ) {
64 while ( $row = $res->fetchObject() ) {
65 $this->output( print_r( $row, true ) );
66 }
67 } else {
68 $affected = $db->affectedRows();
69 $this->output( "Query OK, $affected row(s) affected\n" );
70 }
71 }
72 }
73
74 class SqlPromptPrinter {
75 function __construct( $prompt ) {
76 $this->prompt = $prompt;
77 }
78
79 function cb() {
80 return array( $this, 'printPrompt' );
81 }
82
83 function printPrompt() {
84 echo $this->prompt;
85 }
86 }
87
88 $maintClass = "MwSql";
89 require_once( DO_MAINTENANCE );