-
Notifications
You must be signed in to change notification settings - Fork 3
/
wipe_cmd.go
293 lines (272 loc) · 7.59 KB
/
wipe_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
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
package ddl
import (
"bytes"
"context"
"database/sql"
"flag"
"fmt"
"io"
"os"
)
// WipeCmd implements the `sqddl wipe` subcommand.
type WipeCmd struct {
// (Required) DB is the database to wipe.
DB *sql.DB
// (Required) Dialect is the database dialect.
Dialect string
// If DryRun is true, the SQL queries will be written to Stdout instead of
// being run against the database.
DryRun bool
// Stdout is the command's standard out. If nil, the command writes to
// os.Stdout.
Stdout io.Writer
// Ctx is the command's context.
Ctx context.Context
db string // -db flag.
buf *bytes.Buffer // Reusable buffer. Make sure to Reset() before use.
}
// WipeCommand creates a new WipeCmd with the given arguments. E.g.
// sqddl wipe -db <DATABASE_URL> [FLAGS]
//
// WipeCommand("-db", "postgres://user:pass@localhost:5432/sakila")
func WipeCommand(args ...string) (*WipeCmd, error) {
var cmd WipeCmd
var historyTable string
flagset := flag.NewFlagSet("", flag.ContinueOnError)
flagset.StringVar(&cmd.db, "db", "", "(required) Database URL/DSN.")
flagset.StringVar(&historyTable, "history-table", "", "(ignored)")
flagset.BoolVar(&cmd.DryRun, "dry-run", false, "Print the generated SQL statements without running them.")
flagset.Usage = func() {
fmt.Fprint(flagset.Output(), `Usage:
sqddl wipe -db <DATABASE_URL> [FLAGS]
sqddl wipe -db 'postgres://username:password@localhost:5432/sakila' -dry-run
sqddl wipe -db 'postgres://username:password@localhost:5432/sakila'
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")
}
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
}
// Run runs the WipeCmd.
func (cmd *WipeCmd) 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.db != "" {
defer cmd.DB.Close()
}
if cmd.Ctx == nil {
cmd.Ctx = context.Background()
}
cmd.buf = bufpool.Get().(*bytes.Buffer)
cmd.buf.Reset()
defer bufpool.Put(cmd.buf)
dbi := NewDatabaseIntrospector(cmd.Dialect, cmd.DB)
currentSchema, err := dbi.GetCurrentSchema()
if err != nil {
return err
}
// DROP VIEW.
views, err := dbi.GetViews()
if err != nil {
return err
}
for _, view := range views {
if cmd.buf.Len() > 0 {
cmd.buf.WriteString("\n")
}
cmd.buf.WriteString("DROP ")
if view.IsMaterialized {
cmd.buf.WriteString("MATERIALIZED ")
}
cmd.buf.WriteString("VIEW IF EXISTS ")
if view.ViewSchema != "" && view.ViewSchema != currentSchema {
cmd.buf.WriteString(QuoteIdentifier(cmd.Dialect, view.ViewSchema) + ".")
}
cmd.buf.WriteString(QuoteIdentifier(cmd.Dialect, view.ViewName))
if cmd.Dialect == DialectPostgres || cmd.Dialect == DialectMySQL {
cmd.buf.WriteString(" CASCADE")
}
cmd.buf.WriteString(";\n")
}
// ALTER TABLE DROP CONSTRAINT (Foreign keys). We drop all foreign keys
// first before dropping tables so that we don't get tripped by by circular
// table dependencies later.
if cmd.Dialect != DialectSQLite {
dbi.ConstraintTypes = []string{FOREIGN_KEY}
constraints, err := dbi.GetConstraints()
if err != nil {
return err
}
for _, constraint := range constraints {
if cmd.buf.Len() > 0 {
cmd.buf.WriteString("\n")
}
cmd.buf.WriteString("ALTER TABLE ")
if constraint.TableSchema != "" && constraint.TableSchema != currentSchema {
cmd.buf.WriteString(QuoteIdentifier(cmd.Dialect, constraint.TableSchema) + ".")
}
cmd.buf.WriteString(QuoteIdentifier(cmd.Dialect, constraint.TableName) + " DROP CONSTRAINT " + QuoteIdentifier(cmd.Dialect, constraint.ConstraintName))
if cmd.Dialect == DialectPostgres {
cmd.buf.WriteString(" CASCADE")
}
cmd.buf.WriteString(";\n")
}
}
// DROP TABLE.
tables, err := dbi.GetTables()
if err != nil {
return err
}
if cmd.Dialect == DialectSQLite && len(tables) > 0 {
if cmd.buf.Len() > 0 {
cmd.buf.WriteString("\n")
}
cmd.buf.WriteString("PRAGMA defer_foreign_keys = 1;\n")
}
for _, table := range tables {
if cmd.buf.Len() > 0 {
cmd.buf.WriteString("\n")
}
cmd.buf.WriteString("DROP TABLE IF EXISTS ")
if table.TableSchema != "" && table.TableSchema != currentSchema {
cmd.buf.WriteString(QuoteIdentifier(cmd.Dialect, table.TableSchema) + ".")
}
cmd.buf.WriteString(QuoteIdentifier(cmd.Dialect, table.TableName))
if cmd.Dialect == DialectPostgres || cmd.Dialect == DialectMySQL {
cmd.buf.WriteString(" CASCADE")
}
cmd.buf.WriteString(";\n")
}
// DROP PROCEDURE and DROP FUNCTION.
if cmd.Dialect != DialectSQLite {
routines, err := dbi.GetRoutines()
if err != nil {
return err
}
for _, routine := range routines {
if cmd.buf.Len() > 0 {
cmd.buf.WriteString("\n")
}
cmd.buf.WriteString("DROP ")
if routine.RoutineType == "PROCEDURE" {
cmd.buf.WriteString("PROCEDURE ")
} else {
cmd.buf.WriteString("FUNCTION ")
}
cmd.buf.WriteString("IF EXISTS ")
if routine.RoutineSchema != "" && routine.RoutineSchema != currentSchema {
cmd.buf.WriteString(QuoteIdentifier(cmd.Dialect, routine.RoutineSchema) + ".")
}
cmd.buf.WriteString(QuoteIdentifier(cmd.Dialect, routine.RoutineName))
if cmd.Dialect == DialectPostgres {
cmd.buf.WriteString(" CASCADE")
}
cmd.buf.WriteString(";\n")
}
}
if cmd.Dialect == DialectPostgres {
// DROP TYPE.
enums, err := dbi.GetEnums()
if err != nil {
return err
}
for _, enum := range enums {
if cmd.buf.Len() > 0 {
cmd.buf.WriteString("\n")
}
cmd.buf.WriteString("DROP TYPE IF EXISTS ")
if enum.EnumSchema != "" && enum.EnumSchema != currentSchema {
cmd.buf.WriteString(QuoteIdentifier(cmd.Dialect, enum.EnumSchema) + ".")
}
cmd.buf.WriteString(QuoteIdentifier(cmd.Dialect, enum.EnumName) + " CASCADE;\n")
}
// DROP DOMAIN.
domains, err := dbi.GetDomains()
if err != nil {
return err
}
for _, domain := range domains {
if cmd.buf.Len() > 0 {
cmd.buf.WriteString("\n")
}
cmd.buf.WriteString("DROP DOMAIN IF EXISTS ")
if domain.DomainSchema != "" && domain.DomainSchema != currentSchema {
cmd.buf.WriteString(QuoteIdentifier(cmd.Dialect, domain.DomainSchema) + ".")
}
cmd.buf.WriteString(QuoteIdentifier(cmd.Dialect, domain.DomainName) + " CASCADE;\n")
}
// DROP EXTENSION.
extensions, err := dbi.GetExtensions()
if err != nil {
return err
}
for _, extension := range extensions {
if extension == "plpgsql" {
continue
}
if cmd.buf.Len() > 0 {
cmd.buf.WriteString("\n")
}
cmd.buf.WriteString("DROP EXTENSION IF EXISTS " + QuoteIdentifier(cmd.Dialect, extension) + " CASCADE;\n")
}
}
// If DryRun, write the SQL queries to Stdout instead.
if cmd.DryRun {
_, err = cmd.buf.WriteTo(cmd.Stdout)
if err != nil {
return err
}
return nil
}
queries := cmd.buf.String()
if queries == "" {
return nil
}
// If MySQL, run the queries using DB.Exec because MySQL doesn't support
// running DDL in transactions.
if cmd.Dialect == DialectMySQL {
_, err = cmd.DB.ExecContext(cmd.Ctx, queries)
if err != nil {
return err
}
return nil
}
// Otherwise, run the queries in a transaction.
tx, err := cmd.DB.BeginTx(cmd.Ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
_, err = tx.ExecContext(cmd.Ctx, queries)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}