-
Notifications
You must be signed in to change notification settings - Fork 18
/
main.go
71 lines (64 loc) · 1.5 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"strings"
clickhouse "github.com/AfterShip/clickhouse-sql-parser/parser"
)
const VERSION = "0.3.8"
const help = `
Usage: clickhouse-sql-parser [YOUR SQL STRING] -f [YOUR SQL FILE] -format
`
var options struct {
help bool
file string
format bool
version bool
}
func init() {
flag.BoolVar(&options.format, "format", false, "Beautify print the ClickHouse SQL")
flag.StringVar(&options.file, "f", "", "Parse SQL from file")
flag.BoolVar(&options.help, "h", false, "Print help message")
flag.BoolVar(&options.version, "v", false, "Print version")
}
func main() {
flag.Parse()
if options.version {
fmt.Println("v" + VERSION)
os.Exit(0)
}
if len(os.Args) < 2 || options.help {
fmt.Print(help)
os.Exit(0)
}
var err error
var inputBytes []byte
if options.file != "" {
inputBytes, err = os.ReadFile(options.file)
if err != nil {
panic(fmt.Sprintf("read file error: %s", err.Error()))
}
} else {
if strings.HasPrefix(os.Args[len(os.Args)-1], "-") {
fmt.Print(help)
os.Exit(0)
}
inputBytes = []byte(os.Args[len(os.Args)-1])
}
parser := clickhouse.NewParser(string(inputBytes))
stmts, err := parser.ParseStmts()
if err != nil {
fmt.Printf("parse statements error: %s\n", err.Error())
os.Exit(1)
}
if !options.format { // print AST
bytes, _ := json.MarshalIndent(stmts, "", " ") // nolint
fmt.Println(string(bytes))
} else { // format SQL
for _, stmt := range stmts {
fmt.Println(stmt.String())
}
}
}