/
postgres.go
103 lines (83 loc) · 2.03 KB
/
postgres.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
package testutil
import (
"fmt"
"testing"
"github.com/alextanhongpin/core/internal"
"github.com/alextanhongpin/core/test/testdump"
"github.com/google/go-cmp/cmp"
)
type SQL = testdump.SQL
func NewSQL(query string, args []any, result any) *SQL {
return &SQL{
Query: query,
Args: args,
Result: result,
}
}
type SQLOption interface {
isSQL()
}
func DumpPostgres(t *testing.T, dump *SQL, opts ...SQLOption) {
t.Helper()
var fileName string
var hooks []testdump.Hook[*SQL]
sqlOpt := new(testdump.PostgresOption)
for _, opt := range opts {
switch o := opt.(type) {
case FileName:
fileName = string(o)
case *sqlHookOption:
hooks = append(hooks, o.hook)
case *sqlCmpOption:
sqlOpt.Args = append(sqlOpt.Args, o.args...)
sqlOpt.Vars = append(sqlOpt.Vars, o.vars...)
sqlOpt.Result = append(sqlOpt.Result, o.result...)
default:
panic(fmt.Errorf("testutil: unhandled SQL option: %#v", opt))
}
}
p := Path{
Dir: "testdata",
FilePath: t.Name(),
FileName: fileName,
FileExt: ".sql",
}
if err := testdump.Postgres(testdump.NewFile(p.String()), dump, sqlOpt, hooks...); err != nil {
t.Fatal(err)
}
}
type sqlHookOption struct {
hook testdump.Hook[*SQL]
}
func (sqlHookOption) isSQL() {}
type sqlCmpOption struct {
args []cmp.Option
vars []cmp.Option
result []cmp.Option
}
func (sqlCmpOption) isSQL() {}
func IgnoreResultFields(fields ...string) *sqlCmpOption {
return &sqlCmpOption{
result: []cmp.Option{internal.IgnoreMapEntries(fields...)},
}
}
func IgnoreArgs(fields ...string) *sqlCmpOption {
return &sqlCmpOption{
args: []cmp.Option{internal.IgnoreMapEntries(fields...)},
}
}
func IgnoreVars(fields ...string) *sqlCmpOption {
return &sqlCmpOption{
vars: []cmp.Option{internal.IgnoreMapEntries(fields...)},
}
}
func InspectSQL(hook func(snapshot, received *SQL) error) *sqlHookOption {
return &sqlHookOption{
hook: testdump.CompareHook(hook),
}
}
func InterceptSQL(hook func(t *SQL) (*SQL, error)) *sqlHookOption {
return &sqlHookOption{
hook: testdump.MarshalHook(hook),
}
}