-
Notifications
You must be signed in to change notification settings - Fork 162
/
dot.go
79 lines (69 loc) · 1.71 KB
/
dot.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
package dot
import (
"io"
"text/template"
"github.com/gobuffalo/packr"
"github.com/k1LoW/tbls/schema"
"github.com/pkg/errors"
)
// Dot struct
type Dot struct{}
// OutputSchema output dot format for full relation.
func (d *Dot) OutputSchema(wr io.Writer, s *schema.Schema) error {
box := packr.NewBox("./templates")
ts, _ := box.FindString("schema.dot.tmpl")
tmpl := template.Must(template.New(s.Name).Parse(ts))
err := tmpl.Execute(wr, map[string]interface{}{
"Schema": s,
})
if err != nil {
return errors.WithStack(err)
}
return nil
}
// OutputTable output dot format for table.
func (d *Dot) OutputTable(wr io.Writer, t *schema.Table) error {
encountered := make(map[string]bool)
tables := []*schema.Table{}
relations := []*schema.Relation{}
for _, c := range t.Columns {
for _, r := range c.ParentRelations {
if !encountered[r.ParentTable.Name] {
encountered[r.ParentTable.Name] = true
tables = append(tables, r.ParentTable)
}
if !contains(relations, r) {
relations = append(relations, r)
}
}
for _, r := range c.ChildRelations {
if !encountered[r.Table.Name] {
encountered[r.Table.Name] = true
tables = append(tables, r.Table)
}
if !contains(relations, r) {
relations = append(relations, r)
}
}
}
box := packr.NewBox("./templates")
ts, _ := box.FindString("table.dot.tmpl")
tmpl := template.Must(template.New(t.Name).Parse(ts))
err := tmpl.Execute(wr, map[string]interface{}{
"Table": t,
"Tables": tables,
"Relations": relations,
})
if err != nil {
return errors.WithStack(err)
}
return nil
}
func contains(rs []*schema.Relation, e *schema.Relation) bool {
for _, r := range rs {
if e == r {
return true
}
}
return false
}