-
Notifications
You must be signed in to change notification settings - Fork 163
/
mermaid.go
106 lines (95 loc) · 2.4 KB
/
mermaid.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
package mermaid
import (
"embed"
"io"
"os"
"text/template"
"github.com/k1LoW/tbls/config"
"github.com/k1LoW/tbls/output"
"github.com/k1LoW/tbls/schema"
"github.com/pkg/errors"
)
//go:embed templates/*
var tmpl embed.FS
// Mermaid struct
type Mermaid struct {
config *config.Config
tmpl embed.FS
}
// New return Mermaid
func New(c *config.Config) *Mermaid {
return &Mermaid{
config: c,
tmpl: tmpl,
}
}
func (m *Mermaid) schemaTemplate() (string, error) {
if len(m.config.Templates.Mermaid.Schema) > 0 {
tb, err := os.ReadFile(m.config.Templates.Mermaid.Schema)
if err != nil {
return "", errors.WithStack(err)
}
return string(tb), nil
} else {
tb, err := m.tmpl.ReadFile("templates/schema.mermaid.tmpl")
if err != nil {
return "", errors.WithStack(err)
}
return string(tb), nil
}
}
func (m *Mermaid) tableTemplate() (string, error) {
if len(m.config.Templates.Mermaid.Table) > 0 {
tb, err := os.ReadFile(m.config.Templates.Mermaid.Table)
if err != nil {
return "", errors.WithStack(err)
}
return string(tb), nil
} else {
tb, err := m.tmpl.ReadFile("templates/table.mermaid.tmpl")
if err != nil {
return "", errors.WithStack(err)
}
return string(tb), nil
}
}
// OutputSchema output dot format for full relation.
func (m *Mermaid) OutputSchema(wr io.Writer, s *schema.Schema) error {
ts, err := m.schemaTemplate()
if err != nil {
return errors.WithStack(err)
}
tmpl := template.Must(template.New(s.Name).Funcs(output.Funcs(&m.config.MergedDict)).Parse(ts))
err = tmpl.Execute(wr, map[string]interface{}{
"Schema": s,
"showComment": m.config.ER.Comment,
"showDef": !m.config.ER.HideDef,
})
if err != nil {
return errors.WithStack(err)
}
return nil
}
// OutputTable output dot format for table.
func (m *Mermaid) OutputTable(wr io.Writer, t *schema.Table) error {
tables, relations, err := t.CollectTablesAndRelations(*m.config.ER.Distance, true)
if err != nil {
return errors.WithStack(err)
}
ts, err := m.tableTemplate()
if err != nil {
return errors.WithStack(err)
}
tmpl := template.Must(template.New(t.Name).Funcs(output.Funcs(&m.config.MergedDict)).Parse(ts))
err = tmpl.Execute(wr, map[string]interface{}{
"Table": tables[0],
"Tables": tables[1:],
"Relations": relations,
"showComment": m.config.ER.Comment,
"showDef": !m.config.ER.HideDef,
})
if err != nil {
return errors.WithStack(err)
}
return nil
}