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