This repository was archived by the owner on Mar 27, 2026. It is now read-only.
forked from AfterShip/clickhouse-sql-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
81 lines (74 loc) · 1.85 KB
/
main.go
File metadata and controls
81 lines (74 loc) · 1.85 KB
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
72
73
74
75
76
77
78
79
80
81
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"strings"
clickhouse "github.com/AfterShip/clickhouse-sql-parser/parser"
)
const VERSION = "0.4.17"
const help = `
Usage: clickhouse-sql-parser [YOUR SQL STRING] -f [YOUR SQL FILE] -format -beautify
`
var options struct {
help bool
file string
format bool
beautify bool
version bool
}
func init() {
flag.BoolVar(&options.format, "format", false, "Print formatted ClickHouse SQL")
flag.BoolVar(&options.beautify, "beautify", 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 {
fmt.Fprintf(os.Stderr, "read file error: %s\n", err.Error())
os.Exit(1)
}
} 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.Fprintf(os.Stderr, "parse statements error: %s\n", err.Error())
os.Exit(1)
}
if !options.format && !options.beautify { // print AST
bytes, _ := json.MarshalIndent(stmts, "", " ") // nolint
fmt.Println(string(bytes))
} else { // format SQL
for _, stmt := range stmts {
if options.beautify {
formatter := clickhouse.NewFormatter()
formatter.WithBeautify()
formatter.WriteExpr(stmt)
fmt.Println(formatter.String())
} else {
fmt.Println(clickhouse.Format(stmt))
}
}
}
}