-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdb_schema_gen_example_test.go
77 lines (63 loc) · 1.39 KB
/
db_schema_gen_example_test.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
package gen
import (
"context"
"fmt"
"os"
"reflect"
"time"
"github.com/kataras/pg"
)
type Features []Feature
type Feature struct {
IsFeatured bool `json:"is_featured"`
}
type Tag struct {
Name string `json:"name"`
Value any `json:"value"`
}
func ExampleGenerateSchemaFromDatabase() {
const (
rootDir = "./_testdata"
)
defer func() {
os.RemoveAll(rootDir)
time.Sleep(1 * time.Second)
}()
i := ImportOptions{
ConnString: "postgres://postgres:admin!123@localhost:5432/test_db?sslmode=disable",
ListTables: pg.ListTablesOptions{
Filter: pg.TableFilterFunc(func(table *pg.Table) bool {
columnFilter := func(column *pg.Column) bool {
columnName := column.Name
switch table.Name {
case "blog_posts":
switch columnName {
case "feature":
column.FieldType = reflect.TypeOf(Feature{})
case "other_features":
column.FieldType = reflect.TypeOf(Features{})
case "tags":
column.FieldType = reflect.TypeOf([]Tag{})
}
}
return true
}
table.FilterColumns(columnFilter)
return true
}),
},
}
e := ExportOptions{
RootDir: rootDir,
// Optionally:
// GetFileName: EachTableToItsOwnPackage,
GetFileName: EachTableGroupToItsOwnPackage(),
}
if err := GenerateSchemaFromDatabase(context.Background(), i, e); err != nil {
fmt.Println(err.Error())
return
}
fmt.Println("OK")
// Output:
// OK
}