forked from uptrace/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.go
46 lines (37 loc) · 811 Bytes
/
encoder.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
package dbfixture
import (
"fmt"
"io"
"reflect"
"github.com/uptrace/bun"
"gopkg.in/yaml.v3"
)
type fixtureRows struct {
Model string `yaml:"model"`
Rows interface{} `yaml:"rows"`
}
type Encoder struct {
db *bun.DB
enc *yaml.Encoder
}
func NewEncoder(db *bun.DB, w io.Writer) *Encoder {
return &Encoder{
db: db,
enc: yaml.NewEncoder(w),
}
}
func (e *Encoder) Encode(multiRows ...interface{}) error {
fixtures := make([]fixtureRows, len(multiRows))
for i, rows := range multiRows {
v := reflect.ValueOf(rows)
if v.Kind() != reflect.Slice {
return fmt.Errorf("dbfixture: got %T, wanted a slice", rows)
}
table := e.db.Dialect().Tables().Get(v.Type().Elem())
fixtures[i] = fixtureRows{
Model: table.TypeName,
Rows: rows,
}
}
return e.enc.Encode(fixtures)
}