69372a01727f87c78a6111aa69e74390381ee522
[php-sqllint.git] / bin / php-sqllint
1 #!/usr/bin/env php
2 <?php
3 use SqlParser\Parser;
4
5 require_once __DIR__ . '/../vendor/autoload.php';
6
7 if ($argc < 2) {
8     echo "SQL file name missing\n";
9     exit(1);
10 }
11 $file = $argv[1];
12 if ($file == '') {
13     echo "SQL file name empty\n";
14     exit(1);
15 }
16 if (!file_exists($file)) {
17     echo "SQL file does not exist\n";
18     exit(1);
19 }
20
21 $sql = file_get_contents($file);
22 if (trim($sql) == '') {
23     echo "SQL file empty\n";
24     exit(1);
25 }
26
27 $parser = new Parser($sql);
28
29 if (count($parser->errors) == 0) {
30     echo "No syntax errors detected\n";
31     exit(0);
32 }
33
34 $lines = array(1 => 0);
35 $pos = -1;
36 $line = 1;
37 while (false !== $pos = strpos($sql, "\n", ++$pos)) {
38     $lines[++$line] = $pos;
39 }
40
41 echo "Syntax errors found\n";
42 foreach ($parser->errors as $error) {
43     reset($lines);
44     $line = 1;
45     while (next($lines) && $error->token->position >= current($lines)) {
46         ++$line;
47     }
48     $col = $error->token->position - $lines[$line];
49
50     /** @var SqlParser\Exceptions\ParserException $error) */
51     echo 'Line ' . $line
52         . ' col ' . $col
53         //FIXME: ->token or ->value?
54         . ' at "' . niceToken($error->token->token) . '":'
55         . ' ' . $error->getMessage()
56         . "\n";
57     //var_dump($error->token);
58 }
59
60 function niceToken($str)
61 {
62     return str_replace(
63         ["\n", "\r", "\t"],
64         ['\n', '\r', '\t'],
65         $str
66     );
67 }
68 ?>