sql.php: Provide --json output mode
authorChad Horohoe <chadh@wikimedia.org>
Fri, 16 Feb 2018 21:21:38 +0000 (13:21 -0800)
committerChad Horohoe <chadh@wikimedia.org>
Fri, 16 Feb 2018 21:22:31 +0000 (13:22 -0800)
stdObject is a pretty useless format unless you're working with PHP

Change-Id: I7549347a630768223fba5b282a930361dfe6f2d3

maintenance/sql.php

index dd05bbe..2c8bdb6 100644 (file)
@@ -40,6 +40,7 @@ class MwSql extends Maintenance {
                        'Takes a file name containing SQL as argument or runs interactively.' );
                $this->addOption( 'query',
                        'Run a single query instead of running interactively', false, true );
+               $this->addOption( 'json', 'Output the results as JSON instead of PHP objects' );
                $this->addOption( 'cluster', 'Use an external cluster by name', false, true );
                $this->addOption( 'wikidb',
                        'The database wiki ID to use if not the current one', false, true );
@@ -175,9 +176,15 @@ class MwSql extends Maintenance {
                        // Do nothing
                        return;
                } elseif ( is_object( $res ) && $res->numRows() ) {
+                       $out = '';
                        foreach ( $res as $row ) {
-                               $this->output( print_r( $row, true ) );
+                               $out .= print_r( $row, true );
+                               $rows[] = $row;
                        }
+                       if ( $this->hasOption( 'json' ) ) {
+                               $out = json_encode( $rows, JSON_PRETTY_PRINT );
+                       }
+                       $this->output( $out . "\n" );
                } else {
                        $affected = $db->affectedRows();
                        $this->output( "Query OK, $affected row(s) affected\n" );