-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathhelpers.go
433 lines (399 loc) · 12.6 KB
/
helpers.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
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
package helpers
import (
"context"
"database/sql"
"errors"
"fmt"
"io/fs"
"net"
"os"
"path"
"runtime/debug"
"strings"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/confmap"
"github.com/knadh/koanf/providers/env"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/v2"
"github.com/stephenafamo/bob/gen"
"github.com/stephenafamo/bob/gen/drivers"
"github.com/stephenafamo/bob/gen/importers"
)
const DefaultConfigPath = "./bobgen.yaml"
func Version() string {
if info, ok := debug.ReadBuildInfo(); ok {
return info.Main.Version
}
return ""
}
type Templates struct {
Models []fs.FS
Factory []fs.FS
Queries []fs.FS
}
func DefaultOutputs(destination, pkgname string, noFactory bool, templates *Templates) []*gen.Output {
if templates == nil {
templates = &Templates{}
}
if destination == "" {
destination = "models"
}
if pkgname == "" {
pkgname = "models"
}
outputs := []*gen.Output{
{
Key: "models",
OutFolder: destination,
PkgName: pkgname,
Templates: append(templates.Models, gen.ModelTemplates),
},
{
Key: "queries",
Templates: append(templates.Queries, gen.QueriesTemplates),
},
}
if !noFactory {
outputs = append(outputs, &gen.Output{
Key: "factory",
OutFolder: path.Join(destination, "factory"),
PkgName: "factory",
Templates: append(templates.Factory, gen.FactoryTemplates),
})
}
return outputs
}
func GetConfigFromFile[ConstraintExtra, DriverConfig any](configPath, driverConfigKey string) (gen.Config[ConstraintExtra], DriverConfig, error) {
var provider koanf.Provider
var config gen.Config[ConstraintExtra]
var driverConfig DriverConfig
_, err := os.Stat(configPath)
if err == nil {
// set the provider if provided
provider = file.Provider(configPath)
}
if err != nil && !(configPath == DefaultConfigPath && errors.Is(err, os.ErrNotExist)) {
return config, driverConfig, err
}
return GetConfigFromProvider[ConstraintExtra, DriverConfig](provider, driverConfigKey)
}
func GetConfigFromProvider[ConstraintExtra, DriverConfig any](provider koanf.Provider, driverConfigKey string) (gen.Config[ConstraintExtra], DriverConfig, error) {
var config gen.Config[ConstraintExtra]
var driverConfig DriverConfig
k := koanf.New(".")
// Add some defaults
err := k.Load(confmap.Provider(map[string]any{
"wipe": true,
"struct_tag_casing": "snake",
"relation_tag": "-",
"generator": fmt.Sprintf("BobGen %s %s", driverConfigKey, Version()),
}, "."), nil)
if err != nil {
return config, driverConfig, err
}
if provider != nil {
// Load YAML config and merge into the previously loaded config (because we can).
err := k.Load(provider, yaml.Parser())
if err != nil {
return config, driverConfig, err
}
}
// Load env variables for ONLY driver config
envKey := strings.ToUpper(driverConfigKey) + "_"
err = k.Load(env.Provider(envKey, ".", func(s string) string {
// replace only the first underscore to make it a flat map[string]any
return strings.Replace(strings.ToLower(s), "_", ".", 1)
}), nil)
if err != nil {
return config, driverConfig, err
}
err = k.UnmarshalWithConf("", &config, koanf.UnmarshalConf{Tag: "yaml"})
if err != nil {
return config, driverConfig, err
}
err = k.UnmarshalWithConf(driverConfigKey, &driverConfig, koanf.UnmarshalConf{Tag: "yaml"})
if err != nil {
return config, driverConfig, err
}
return config, driverConfig, nil
}
func EnumType(types drivers.Types, enum string) string {
types[enum] = drivers.Type{
NoRandomizationTest: true, // enums are often not random enough
RandomExpr: fmt.Sprintf(`all := all%s()
return all[f.IntBetween(0, len(all)-1)]`, enum),
}
return enum
}
func Types() drivers.Types {
return drivers.Types{
"bool": {
NoRandomizationTest: true,
RandomExpr: `return f.Bool()`,
},
"int": {
RandomExpr: `return f.Int()`,
},
"int8": {
RandomExpr: `return f.Int8()`,
},
"int16": {
RandomExpr: `return f.Int16()`,
},
"int32": {
RandomExpr: `return f.Int32()`,
},
"int64": {
RandomExpr: `return f.Int64()`,
},
"uint": {
RandomExpr: `return f.UInt()`,
},
"uint8": {
RandomExpr: `return f.UInt8()`,
},
"uint16": {
RandomExpr: `return f.UInt16()`,
},
"uint32": {
RandomExpr: `return f.UInt32()`,
},
"uint64": {
RandomExpr: `return f.UInt64()`,
},
"float32": {
RandomExpr: `return f.Float32(10, -1_000_000, 1_000_000)`,
},
"float64": {
RandomExpr: `return f.Float64(10, -1_000_000, 1_000_000)`,
},
"string": {
RandomExpr: `return strings.Join(f.Lorem().Words(f.IntBetween(1, 5)), " ")`,
RandomExprImports: importers.List{`"strings"`},
},
"[]byte": {
DependsOn: []string{"string"},
RandomExpr: `return []byte(random_string(f))`,
CompareExpr: `bytes.Equal(AAA, BBB)`,
CompareExprImports: importers.List{`"bytes"`},
NoScannerValuerTest: true,
},
"time.Time": {
Imports: importers.List{`"time"`},
RandomExpr: `year := time.Hour * 24 * 365
min := time.Now().Add(-year)
max := time.Now().Add(year)
return f.Time().TimeBetween(min, max)`,
CompareExpr: `AAA.Equal(BBB)`,
NoScannerValuerTest: true,
},
"types.Text[netip.Addr, *netip.Addr]": {
Imports: importers.List{
`"net/netip"`,
`"github.com/stephenafamo/bob/types"`,
},
RandomExpr: `var addr [4]byte
rand.Read(addr[:])
ipAddr := netip.AddrFrom4(addr)
return types.Text[netip.Addr, *netip.Addr]{Val: ipAddr}`,
RandomExprImports: importers.List{`"crypto/rand"`},
},
"pgtypes.Inet": {
Imports: importers.List{
`"github.com/stephenafamo/bob/types/pgtypes"`,
},
RandomExpr: `var addr [4]byte
rand.Read(addr[:])
ipAddr := netip.AddrFrom4(addr)
ipPrefix := netip.PrefixFrom(ipAddr, f.IntBetween(0, ipAddr.BitLen()))
return pgtypes.Inet{Prefix: ipPrefix}`,
RandomExprImports: importers.List{`"crypto/rand"`, `"net/netip"`},
},
"pgtypes.Macaddr": {
Imports: importers.List{`"github.com/stephenafamo/bob/types/pgtypes"`},
RandomExpr: `addr, _ := net.ParseMAC(f.Internet().MacAddress())
return pgtypes.Macaddr{Addr: addr}`,
RandomExprImports: importers.List{`"net"`},
CompareExpr: `slices.Equal(AAA.Addr, BBB.Addr)`,
CompareExprImports: importers.List{`"slices"`},
},
"pq.BoolArray": {
Imports: importers.List{`"github.com/lib/pq"`},
RandomExpr: `arr := make(pq.BoolArray, f.IntBetween(1, 5))
for i := range arr {
arr[i] = f.Bool()
}
return arr`,
NoRandomizationTest: true,
},
"pq.Int64Array": {
Imports: importers.List{`"github.com/lib/pq"`},
RandomExpr: `arr := make(pq.Int64Array, f.IntBetween(1, 5))
for i := range arr {
arr[i] = f.Int64()
}
return arr`,
CompareExpr: `slices.Equal(AAA, BBB)`,
CompareExprImports: importers.List{`"slices"`},
},
"pq.ByteaArray": {
DependsOn: []string{"[]byte"},
Imports: importers.List{`"github.com/lib/pq"`},
RandomExpr: `arr := make(pq.ByteaArray, f.IntBetween(1, 5))
for i := range arr {
arr[i] = random___byte(f)
}
return arr`,
CompareExpr: `slices.EqualFunc(AAA, BBB, func(a, b []byte) bool {
return bytes.Equal(a, b)
})`,
CompareExprImports: importers.List{`"slices"`, `"bytes"`},
},
"pq.StringArray": {
DependsOn: []string{"string"},
Imports: importers.List{`"github.com/lib/pq"`},
RandomExpr: `arr := make(pq.StringArray, f.IntBetween(1, 5))
for i := range arr {
arr[i] = random_string(f)
}
return arr`,
CompareExpr: `slices.Equal(AAA, BBB)`,
CompareExprImports: importers.List{`"slices"`},
},
"pq.Float64Array": {
Imports: importers.List{`"github.com/lib/pq"`},
RandomExpr: `arr := make(pq.Float64Array, f.IntBetween(1, 5))
for i := range arr {
arr[i] = f.Float64(10, -1_000_000, 1_000_000)
}
return arr`,
CompareExpr: `slices.Equal(AAA, BBB)`,
CompareExprImports: importers.List{`"slices"`},
},
"pgeo.Box": {
Imports: importers.List{`"github.com/saulortega/pgeo"`},
RandomExpr: `return pgeo.NewRandBox()`,
},
"pgeo.Circle": {
Imports: importers.List{`"github.com/saulortega/pgeo"`},
RandomExpr: `return pgeo.NewRandCircle()`,
},
"pgeo.Line": {
Imports: importers.List{`"github.com/saulortega/pgeo"`},
RandomExpr: `return pgeo.NewRandLine()`,
},
"pgeo.Lseg": {
Imports: importers.List{`"github.com/saulortega/pgeo"`},
RandomExpr: `return pgeo.NewRandLseg()`,
},
"pgeo.Path": {
Imports: importers.List{`"github.com/saulortega/pgeo"`},
RandomExpr: `return pgeo.NewRandPath()`,
CompareExpr: `AAA.Closed == BBB.Closed && slices.Equal(AAA.Points, BBB.Points)`,
},
"pgeo.Point": {
Imports: importers.List{`"github.com/saulortega/pgeo"`},
RandomExpr: `return pgeo.NewRandPoint()`,
},
"pgeo.Polygon": {
Imports: importers.List{`"github.com/saulortega/pgeo"`},
RandomExpr: `return pgeo.NewRandPolygon()`,
CompareExpr: `slices.Equal(AAA, BBB)`,
CompareExprImports: importers.List{`"slices"`},
},
"decimal.Decimal": {
Imports: importers.List{`"github.com/shopspring/decimal"`},
RandomExpr: `return decimal.New(f.Int64Between(0, 1000), 0)`,
},
"pgtypes.LSN": {
Imports: importers.List{`"github.com/stephenafamo/bob/types/pgtypes"`},
RandomExpr: `return pgtypes.LSN(f.UInt64())`,
},
"pgtypes.TxIDSnapshot": {
Imports: importers.List{`"github.com/stephenafamo/bob/types/pgtypes"`},
RandomExpr: `active := make([]string, f.IntBetween(1, 5))
for i := range active {
active[i] = strconv.FormatUint(f.UInt64(), 10)
}
return pgtypes.TxIDSnapshot{
Min: strconv.FormatUint(f.UInt64(), 10),
Max: strconv.FormatUint(f.UInt64(), 10),
Active: active,
}`,
RandomExprImports: importers.List{`"strconv"`},
CompareExpr: `AAA.Min == BBB.Min && AAA.Max == BBB.Max && slices.Equal(AAA.Active, BBB.Active)`,
CompareExprImports: importers.List{`"slices"`},
},
"pgtypes.HStore": {
DependsOn: []string{"string"},
Imports: importers.List{`"github.com/stephenafamo/bob/types/pgtypes"`},
RandomExpr: `hs := make(pgtypes.HStore)
for i := 0; i < f.IntBetween(1, 5); i++ {
arr[random_string(f)] = null.FromCond(random_string(f), f.Bool())
}
return hs`,
},
"types.JSON[json.RawMessage]": {
Imports: importers.List{
`"encoding/json"`,
`"github.com/stephenafamo/bob/types"`,
},
RandomExpr: `s := &bytes.Buffer{}
s.WriteRune('{')
for i := 0; i < f.IntBetween(1, 5); i++ {
if i > 0 {
fmt.Fprint(s, ", ")
}
fmt.Fprintf(s, "%q:%q", f.Lorem().Word(), f.Lorem().Word())
}
s.WriteRune('}')
return types.NewJSON[json.RawMessage](s.Bytes())`,
RandomExprImports: importers.List{`"fmt"`, `"bytes"`},
CompareExpr: `bytes.Equal(AAA.Val, BBB.Val)`,
CompareExprImports: importers.List{`"bytes"`},
},
"xml": {
AliasOf: "string",
DependsOn: []string{"string"},
RandomExpr: `tag := f.Lorem().Word()
return fmt.Sprintf("<%s>%s</%s>", tag, f.Lorem().Word(), tag)`,
RandomExprImports: importers.List{`"fmt"`},
},
}
}
func GetFreePort() (int, error) {
a, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return 0, fmt.Errorf("resolve localhost:0: %w", err)
}
l, err := net.ListenTCP("tcp", a)
if err != nil {
return 0, fmt.Errorf("listen on localhost:0: %w", err)
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
func Migrate(ctx context.Context, db *sql.DB, dir fs.FS) error {
err := fs.WalkDir(dir, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
content, err := fs.ReadFile(dir, path)
if err != nil {
return fmt.Errorf("reading %s: %w", path, err)
}
fmt.Printf("migrating %s...\n", path)
if _, err = db.ExecContext(ctx, string(content)); err != nil {
return fmt.Errorf("migrating %s: %w", path, err)
}
return nil
})
if err != nil {
return err
}
fmt.Printf("migrations finished\n")
return nil
}