SQL formatting support
authorChristian Weiske <cweiske@cweiske.de>
Wed, 16 Dec 2015 06:51:40 +0000 (07:51 +0100)
committerChristian Weiske <cweiske@cweiske.de>
Wed, 16 Dec 2015 06:51:40 +0000 (07:51 +0100)
README.rst
src/phpsqllint/Cli.php
tests/files/select-unformatted.sql [new file with mode: 0644]

index bca5a30c607df3c552f020b9569f31237fb987c8..ef9e165cb882a93c83bacc4b49c55db22daf30e4 100644 (file)
@@ -6,12 +6,15 @@ Command line tool to validate (syntax check) SQL files.
 Primarily for MySQL ``.sql`` files.
 
 Can be used in git pre-commit hooks to catch errors.
+Use it from your shell, offline and without any SQL server.
+
+You can also use it to format SQL queries.
 
 
 =====
 Usage
 =====
-::
+Syntax check::
 
     $ php-sqllint tests/files/create-missingcomma.sql 
     Checking SQL syntax of tests/files/create-missingcomma.sql
@@ -27,6 +30,23 @@ Emacs mode::
     tests/files/create-noname.sql:1.13:Error: At least one column definition was expected.
 
 
+Formatting::
+
+    $ php-sqllint --format tests/files/select-unformatted.sql
+    SELECT
+      id,
+      NAME,
+      url
+    FROM
+      users
+    WHERE
+      DATE > NOW() AND id != 0
+    ORDER BY NAME
+    LIMIT 10
+
+You can enable ANSI coloring by passing the ``--colors`` option.
+
+
 ====
 Bugs
 ====
index 5e4f6388435a2d0e3610e30441ef052c97bbd706..129a9257d736826bc43bfec9599c376b1e99f211 100644 (file)
@@ -28,6 +28,9 @@ class Cli
 {
     protected $renderer;
 
+    protected $format = false;
+    protected $colors = false;
+
     /**
      * Start processing.
      *
@@ -41,7 +44,11 @@ class Cli
 
             $allfine = true;
             foreach ($files as $filename) {
-                $allfine &= $this->checkFile($filename);
+                if ($this->format) {
+                    $allfine &= $this->formatFile($filename);
+                } else {
+                    $allfine &= $this->checkFile($filename);
+                }
             }
 
             if ($allfine == true) {
@@ -65,14 +72,8 @@ class Cli
     public function checkFile($filename)
     {
         $this->renderer->startRendering($filename);
-
-        if ($filename == '-') {
-            $sql = file_get_contents('php://stdin');
-        } else {
-            $sql = file_get_contents($filename);
-        }
-        if (trim($sql) == '') {
-            $this->renderer->displayError('SQL file empty', '', 0, 0);
+        $sql = $this->loadSql($filename);
+        if ($sql === false) {
             return false;
         }
 
@@ -110,6 +111,38 @@ class Cli
         return false;
     }
 
+    /**
+     * Reformat the given file
+     */
+    protected function formatFile($filename)
+    {
+        $this->renderer->startRendering($filename);
+        $sql = $this->loadSql($filename);
+        if ($sql === false) {
+            return false;
+        }
+
+        $options = array(
+            //FIXME: automatically detect if the shell/tool supports colors
+            'type' => $this->colors ? 'cli' : 'text'
+        );
+        echo \SqlParser\Utils\Formatter::format($sql, $options) . "\n";
+    }
+
+    protected function loadSql($filename)
+    {
+        if ($filename == '-') {
+            $sql = file_get_contents('php://stdin');
+        } else {
+            $sql = file_get_contents($filename);
+        }
+        if (trim($sql) == '') {
+            $this->renderer->displayError('SQL file empty', '', 0, 0);
+            return false;
+        }
+        return $sql;
+    }
+
     /**
      * Load parameters for the CLI option parser.
      *
@@ -122,6 +155,26 @@ class Cli
         $parser->version = '0.0.2';
         $parser->avoid_reading_stdin = true;
 
+        $parser->addOption(
+            'format',
+            array(
+                'short_name'  => '-f',
+                'long_name'   => '--format',
+                'description' => 'Reformat SQL instead of checking',
+                'action'      => 'StoreTrue',
+                'default'     => false,
+            )
+        );
+        $parser->addOption(
+            'colors',
+            array(
+                'short_name'  => '-c',
+                'long_name'   => '--colors',
+                'description' => 'Use colors in formatting output',
+                'action'      => 'StoreTrue',
+                'default'     => false,
+            )
+        );
         $parser->addOption(
             'renderer',
             array(
@@ -165,6 +218,9 @@ class Cli
                 . ucfirst($result->options['renderer']);
             $this->renderer = new $rendClass();
 
+            $this->format = $result->options['format'];
+            $this->colors = $result->options['colors'];
+
             foreach ($result->args['sql_files'] as $filename) {
                 if ($filename == '-') {
                     continue;
diff --git a/tests/files/select-unformatted.sql b/tests/files/select-unformatted.sql
new file mode 100644 (file)
index 0000000..c8fafca
--- /dev/null
@@ -0,0 +1 @@
+SELECT id, name, url FROM users WHERE date > NOW() and id != 0 ORDER BY name LIMIT 10