summaryrefslogtreecommitdiff
path: root/maintenance/sql.php
blob: 5ec1d8d33f348625f7bbf5eac69a5caf857dfe66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php

/**
 * Send SQL queries from the specified file to the database, performing
 * variable replacement along the way.
 * 
 * @addtogroup Database
 */

require_once( dirname(__FILE__) . '/' . 'commandLine.inc' );

if ( isset( $options['help'] ) ) {
	echo "Send SQL queries to a MediaWiki database.\nUsage: php sql.php [<file>]\n";
	exit( 1 );
}

if ( isset( $args[0] ) ) {
	$fileName = $args[0];
	$file = fopen( $fileName, 'r' );
	$promptCallback = false;
} else {
	$file = STDIN;
	$promptObject = new SqlPromptPrinter( "> " );
	$promptCallback = $promptObject->cb();
}

if ( !$file  ) {
	echo "Unable to open input file\n";
	exit( 1 );
}

$dbw =& wfGetDB( DB_MASTER );
$error = $dbw->sourceStream( $file, $promptCallback, 'sqlPrintResult' );
if ( $error !== true ) {
	echo $error;
	exit( 1 );
} else {
	exit( 0 );
}

//-----------------------------------------------------------------------------
class SqlPromptPrinter {
	function __construct( $prompt ) {
		$this->prompt = $prompt;
	}

	function cb() {
		return array( $this, 'printPrompt' );
	}

	function printPrompt() {
		echo $this->prompt;
	}
}

function sqlPrintResult( $res ) {
	if ( !$res ) {
		// Do nothing
	} elseif ( $res->numRows() ) {
		while ( $row = $res->fetchObject() ) {
			print_r( $row );
		}
	} else {
		$affected = $res->db->affectedRows();
		echo "Query OK, $affected row(s) affected\n";
	}
}