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
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
====
{
protected $renderer;
+ protected $format = false;
+ protected $colors = false;
+
/**
* Start processing.
*
$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) {
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;
}
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.
*
$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(
. 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;