-
Notifications
You must be signed in to change notification settings - Fork 4
/
tables_cmd.go
213 lines (196 loc) · 6.01 KB
/
tables_cmd.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
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
package ddl
import (
"database/sql"
"flag"
"fmt"
"go/format"
"io"
"os"
"path/filepath"
"strings"
)
// TablesCmd implements the `sqddl tables` subcommand.
type TablesCmd struct {
// (Required) DB is the database.
DB *sql.DB
// (Required) Dialect is the database dialect.
Dialect string
// PackageName is the name of the package for the generated go code. Leave
// blank to use "_".
PackageName string
// Filename is the name of the file to write the table structs into. Leave
// blank to write to Stdout instead.
Filename string
// SchemaQualifiedStructs controls whether the generated struct names are
// schema qualified e.g. `type SCHEMA_TABLE struct` instead of `type TABLE
// struct`.
SchemaQualifiedStructs bool
// Stdout specifies the command's standard out to write to if no Filename
// is provided. If nil, the command writes to os.Stdout.
Stdout io.Writer
// HistoryTable is the name of the migration history table. If empty, the
// default history table name will be "sqddl_history".
HistoryTable string
// Schemas is the list of schemas that will be included.
Schemas []string
// ExcludeSchemas is the list of schemas that will be excluded.
ExcludeSchemas []string
// Tables is the list of tables that will be included.
Tables []string
// ExcludeTables is the list of tables that will be excluded.
ExcludeTables []string
db string // -db flag.
}
func TablesCommand(args ...string) (*TablesCmd, error) {
var cmd TablesCmd
var schemas, excludeSchemas, tables, excludeTables string
flagset := flag.NewFlagSet("", flag.ContinueOnError)
flagset.StringVar(&cmd.db, "db", "", "(required) Database URL/DSN.")
flagset.StringVar(&cmd.HistoryTable, "history-table", "sqddl_history", "Name of migration history table.")
flagset.StringVar(&cmd.PackageName, "pkg", "_", "Package name used in the generated code.")
flagset.StringVar(&cmd.Filename, "file", "", "Name of the file to write the generated code into. Leave blank to write to stdout.")
flagset.BoolVar(&cmd.SchemaQualifiedStructs, "schema-qualified-structs", false, "Schema-qualify the generated struct names.")
flagset.StringVar(&schemas, "schemas", "", "Comma-separated list of schemas to be included.")
flagset.StringVar(&excludeSchemas, "exclude-schemas", "", "Comma-separated list of schemas to be excluded.")
flagset.StringVar(&tables, "tables", "", "Comma-separated list of tables to be included.")
flagset.StringVar(&excludeTables, "exclude-tables", "", "Comma-separated list of tables to be excluded.")
flagset.Usage = func() {
fmt.Fprint(flagset.Output(), `Usage:
sqddl tables -db <DATABASE_URL> [FLAGS]
sqddl tables -db 'postgres://user:pass@localhost:5432/sakila'
sqddl tables -db 'postgres://user:pass@localhost:5432/sakila' -pkg tables -file tables/tables.go
sqddl tables -db 'postgres://user:pass@localhost:5432/sakila' -schemas schema1,schema2,schema3 -exclude-tables table1,table2,table3
Flags:
`)
flagset.PrintDefaults()
}
err := flagset.Parse(args)
if err != nil {
return nil, err
}
if cmd.db == "" {
return nil, fmt.Errorf("-db empty or not provided")
}
if schemas != "" {
cmd.Schemas = strings.Split(schemas, ",")
}
if excludeSchemas != "" {
cmd.ExcludeSchemas = strings.Split(excludeSchemas, ",")
}
if tables != "" {
cmd.Tables = strings.Split(tables, ",")
}
if excludeTables != "" {
cmd.ExcludeTables = strings.Split(excludeTables, ",")
}
var driverName, dsn string
cmd.Dialect, driverName, dsn = NormalizeDSN(cmd.db)
if cmd.Dialect == "" {
return nil, fmt.Errorf("could not identity dialect for -db %q", cmd.db)
}
cmd.DB, err = sql.Open(driverName, dsn)
if err != nil {
return nil, err
}
return &cmd, nil
}
func (cmd *TablesCmd) Run() error {
if cmd.DB == nil {
return fmt.Errorf("nil DB")
}
if cmd.Dialect == "" {
return fmt.Errorf("empty Dialect")
}
if cmd.Stdout == nil {
cmd.Stdout = os.Stdout
}
if cmd.HistoryTable == "" {
cmd.HistoryTable = "sqddl_history"
}
if cmd.db != "" {
defer cmd.DB.Close()
}
var tableStructs TableStructs
var catalog Catalog
dbi := &DatabaseIntrospector{
Dialect: cmd.Dialect,
DB: cmd.DB,
Filter: Filter{
Schemas: cmd.Schemas,
ExcludeSchemas: cmd.ExcludeSchemas,
Tables: cmd.Tables,
ExcludeTables: append(cmd.ExcludeTables, cmd.HistoryTable),
},
}
dbi.ObjectTypes = []string{"TABLES"}
err := dbi.WriteCatalog(&catalog)
if err != nil {
return err
}
err = tableStructs.ReadCatalog(&catalog)
if err != nil {
return err
}
if cmd.SchemaQualifiedStructs {
for i := range tableStructs {
tableStruct := &tableStructs[i]
tableName := strings.ToLower(tableStruct.Name)
if tableStruct.Fields[0].NameTag != "" {
tableName = tableStruct.Fields[0].NameTag
}
tableSchema, tableName, _ := strings.Cut(tableName, ".")
if tableName == "" {
tableSchema, tableName = tableName, tableSchema
}
if tableSchema == "" && catalog.CurrentSchema != "" {
tableSchema = catalog.CurrentSchema
}
if tableSchema != "" {
tableStruct.Name = strings.ToUpper(strings.ReplaceAll(tableSchema+"_"+tableName, " ", "_"))
tableStruct.Fields[0].NameTag = tableSchema + "." + tableName
}
}
}
text, err := tableStructs.MarshalText()
if err != nil {
return err
}
if len(text) == 0 {
return nil
}
if cmd.PackageName == "" && cmd.Filename != "" {
err = os.MkdirAll(filepath.Dir(cmd.Filename), 0755)
if err != nil {
return err
}
dirname := filepath.Base(filepath.Dir(cmd.Filename))
if dirname != "" && dirname != "." {
cmd.PackageName = strings.ReplaceAll(dirname, " ", "_")
}
}
if cmd.PackageName == "" {
cmd.PackageName = "_"
}
text, err = format.Source(text)
if err != nil {
return err
}
out := cmd.Stdout
if cmd.Filename != "" {
file, err := os.OpenFile(cmd.Filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer file.Close()
out = file
}
_, err = io.WriteString(out, "package "+cmd.PackageName+"\n\nimport \"github.com/bokwoon95/sq\"\n\n")
if err != nil {
return err
}
_, err = out.Write(text)
if err != nil {
return err
}
return nil
}