-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
349 lines (310 loc) · 8.9 KB
/
main.go
File metadata and controls
349 lines (310 loc) · 8.9 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"embed"
"encoding/json"
"flag"
"fmt"
"os"
"strings"
"dbml-tools/generator"
"dbml-tools/interpreter"
"dbml-tools/introspect"
"dbml-tools/lexer"
"dbml-tools/parser"
)
func usage() {
fmt.Fprintf(os.Stderr, "Usage: dbml-tools <command> [args]\n\n")
fmt.Fprintf(os.Stderr, "Commands:\n")
fmt.Fprintf(os.Stderr, " lex <file> Tokenize and output lexer JSON\n")
fmt.Fprintf(os.Stderr, " parse <file> Parse and output AST JSON\n")
fmt.Fprintf(os.Stderr, " interpret <file> Interpret and output database schema JSON\n")
fmt.Fprintf(os.Stderr, " check <file> Check for parse/semantic errors\n")
fmt.Fprintf(os.Stderr, " todbml [--normalize] <dsn> Connect to a database and output DBML\n")
fmt.Fprintf(os.Stderr, " tosql <file> Generate CREATE TABLE SQL\n")
fmt.Fprintf(os.Stderr, " todot <file> Generate Graphviz DOT diagram\n")
fmt.Fprintf(os.Stderr, " migrate [options] <old> <new> Generate migration SQL\n")
fmt.Fprintf(os.Stderr, "\nSQL dialect is determined by the database_type Project setting in DBML files.\n")
fmt.Fprintf(os.Stderr, "\nConnection string examples:\n")
fmt.Fprintf(os.Stderr, " mariadb://user:pass@host:3306/mydb\n")
fmt.Fprintf(os.Stderr, " postgres://user:pass@host:5432/mydb[?schema=public]\n")
fmt.Fprintf(os.Stderr, " sqlite:///path/to/file.db\n")
os.Exit(1)
}
func main() {
if len(os.Args) < 2 {
usage()
}
cmd := os.Args[1]
switch cmd {
case "todbml":
doToDBML(os.Args[2:])
case "tosql":
doToSQL(os.Args[2:])
case "todot":
doToDot(os.Args[2:])
case "migrate":
doMigrate(os.Args[2:])
case "check":
doCheck(os.Args[2:])
default:
if len(os.Args) < 3 {
usage()
}
file := os.Args[2]
src, err := os.ReadFile(file)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
source := string(src)
switch cmd {
case "lex":
doLex(source)
case "parse":
doParse(source)
case "interpret":
doInterpret(source)
default:
usage()
}
}
}
func readFile(path string) string {
src, err := os.ReadFile(path)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
return string(src)
}
func parseAndInterpret(source string) *interpreter.Database {
l := lexer.New(source)
tokens := l.Lex()
p := parser.New(tokens, source)
prog := p.Parse()
interp := interpreter.New()
return interp.Interpret(prog)
}
//go:embed sql
var sqlFiles embed.FS
func doToDBML(args []string) {
fs := flag.NewFlagSet("todbml", flag.ExitOnError)
normalize := fs.Bool("normalize", false, "normalize column types to database-agnostic DBML equivalents")
data := fs.Bool("data", false, "also export row data as DBML records blocks")
excludeStr := fs.String("exclude", "", "comma-separated table name patterns to exclude (supports * glob)")
includeStr := fs.String("include", "", "comma-separated table name patterns to include (all others excluded)")
fs.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: dbml-tools todbml [--normalize] [--data] [--exclude pattern,...] [--include pattern,...] <dsn>\n")
fs.PrintDefaults()
}
fs.Parse(args) //nolint:errcheck
if fs.NArg() < 1 {
fs.Usage()
os.Exit(1)
}
opts := introspect.Options{
Exclude: parseCSV(*excludeStr),
Include: parseCSV(*includeStr),
Data: *data,
}
dbml, err := introspect.Run(fs.Arg(0), sqlFiles, opts, *normalize)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
fmt.Print(dbml)
}
func parseCSV(s string) []string {
if s == "" {
return nil
}
parts := strings.Split(s, ",")
out := make([]string, 0, len(parts))
for _, p := range parts {
p = strings.TrimSpace(p)
if p != "" {
out = append(out, p)
}
}
return out
}
func doToDot(args []string) {
fs := flag.NewFlagSet("todot", flag.ExitOnError)
fs.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: dbml-tools todot <file>\n")
fs.PrintDefaults()
}
fs.Parse(args) //nolint:errcheck
if fs.NArg() < 1 {
fs.Usage()
os.Exit(1)
}
db := parseAndInterpret(readFile(fs.Arg(0)))
fmt.Print(generator.Dot(db))
}
func doToSQL(args []string) {
fs := flag.NewFlagSet("tosql", flag.ExitOnError)
fs.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: dbml-tools tosql <file>\n")
fmt.Fprintf(os.Stderr, " SQL dialect is determined by the database_type Project setting.\n")
fs.PrintDefaults()
}
fs.Parse(args) //nolint:errcheck
if fs.NArg() < 1 {
fs.Usage()
os.Exit(1)
}
db := parseAndInterpret(readFile(fs.Arg(0)))
d := resolveDialectDefault(generator.DialectFromDatabase(db))
fmt.Print(generator.Dump(db, d))
}
func doMigrate(args []string) {
fs := flag.NewFlagSet("migrate", flag.ExitOnError)
excludeStr := fs.String("exclude", "", "comma-separated table name patterns to exclude (supports * glob)")
includeStr := fs.String("include", "", "comma-separated table name patterns to include (all others excluded)")
fs.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: dbml-tools migrate [--exclude pattern,...] <old> <new>\n")
fmt.Fprintf(os.Stderr, " <old> and <new> may each be a .dbml file path or a connection string.\n")
fmt.Fprintf(os.Stderr, " SQL dialect is auto-detected from DSN or database_type Project setting.\n")
fs.PrintDefaults()
}
fs.Parse(args) //nolint:errcheck
if fs.NArg() < 2 {
fs.Usage()
os.Exit(1)
}
oldArg, newArg := fs.Arg(0), fs.Arg(1)
opts := introspect.Options{
Exclude: parseCSV(*excludeStr),
Include: parseCSV(*includeStr),
}
oldDB, err := loadSchema(oldArg, opts)
if err != nil {
fmt.Fprintf(os.Stderr, "error loading %s: %v\n", oldArg, err)
os.Exit(1)
}
newDB, err := loadSchema(newArg, opts)
if err != nil {
fmt.Fprintf(os.Stderr, "error loading %s: %v\n", newArg, err)
os.Exit(1)
}
d := resolveDialectDefault(resolveDialect(oldArg, newArg, oldDB, newDB))
fmt.Print(generator.Migrate(oldDB, newDB, d))
}
// loadSchema reads a schema from either a DBML file path or a live database DSN.
func loadSchema(arg string, opts introspect.Options) (*interpreter.Database, error) {
if _, err := introspect.ParseDSN(arg); err == nil {
dbml, err := introspect.Run(arg, sqlFiles, opts, false)
if err != nil {
return nil, err
}
return parseAndInterpret(dbml), nil
}
src, err := os.ReadFile(arg)
if err != nil {
return nil, err
}
return parseAndInterpret(string(src)), nil
}
// resolveDialectDefault falls back to MariaDB when the auto-detected dialect is Generic.
func resolveDialectDefault(d generator.Dialect) generator.Dialect {
if d == generator.Generic {
return generator.MariaDB
}
return d
}
// resolveDialect determines the dialect from DSN auto-detect or database_type Project setting.
func resolveDialect(arg1, arg2 string, db1, db2 *interpreter.Database) generator.Dialect {
// Auto-detect from first DSN found.
for _, arg := range []string{arg1, arg2} {
if parsed, err := introspect.ParseDSN(arg); err == nil {
switch parsed.Engine {
case introspect.EnginePostgres:
return generator.Postgres
case introspect.EngineMariaDB:
return generator.MariaDB
case introspect.EngineSQLite:
return generator.SQLite
}
}
}
// Fall back to database_type from DBML schemas.
for _, db := range []*interpreter.Database{db1, db2} {
if d := generator.DialectFromDatabase(db); d != generator.Generic {
return d
}
}
return generator.Generic
}
func doLex(source string) {
l := lexer.New(source)
tokens := l.Lex()
simple := lexer.ToSimpleTokens(tokens)
writeJSON(simple)
}
func doParse(source string) {
l := lexer.New(source)
tokens := l.Lex()
p := parser.New(tokens, source)
prog := p.Parse()
writeJSON(prog.ToJSON())
}
func doInterpret(source string) {
l := lexer.New(source)
tokens := l.Lex()
p := parser.New(tokens, source)
prog := p.Parse()
interp := interpreter.New()
db := interp.Interpret(prog)
writeJSON(db)
}
func doCheck(args []string) {
fs := flag.NewFlagSet("check", flag.ExitOnError)
fs.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: dbml-tools check <file>\n")
fs.PrintDefaults()
}
fs.Parse(args) //nolint:errcheck
if fs.NArg() < 1 {
fs.Usage()
os.Exit(1)
}
file := fs.Arg(0)
src, err := os.ReadFile(file)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
source := string(src)
l := lexer.New(source)
tokens := l.Lex()
p := parser.New(tokens, source)
prog := p.Parse()
interp := interpreter.New()
interp.Interpret(prog)
hasErrors := false
for _, e := range l.Errors {
fmt.Fprintf(os.Stderr, "%s:%s\n", file, e.Error())
hasErrors = true
}
for _, e := range p.Errors {
fmt.Fprintf(os.Stderr, "%s:%s\n", file, e.Error())
hasErrors = true
}
for _, e := range interp.Errors {
fmt.Fprintf(os.Stderr, "%s:%s\n", file, e.Error())
hasErrors = true
}
if hasErrors {
os.Exit(1)
}
}
func writeJSON(v interface{}) {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
fmt.Fprintf(os.Stderr, "json error: %v\n", err)
os.Exit(1)
}
}