-
Notifications
You must be signed in to change notification settings - Fork 8
/
schema.go
89 lines (72 loc) · 1.92 KB
/
schema.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
package db
import (
"fmt"
"github.com/deckarep/golang-set"
"strings"
)
// Schema represents schema info
type Schema struct {
Tables []*Table
}
// NewSchema returns a new Schema instance
func NewSchema(tables []*Table) *Schema {
return &Schema{Tables: tables}
}
// ToErd returns ERD formatted schema
func (s *Schema) ToErd(showIndex bool) string {
var lines []string
tableNames := mapset.NewSet()
for _, table := range s.Tables {
lines = append(lines, table.ToErd(showIndex))
tableNames.Add(table.Name)
}
for _, table := range s.Tables {
for _, foreignKey := range table.ForeignKeys {
toTable := strings.ToLower(foreignKey.ToTable)
if tableNames.Contains(toTable) {
lines = append(lines, fmt.Sprintf("%s }-- %s", table.Name, toTable))
}
}
}
return strings.Join(lines, "\n\n")
}
// ToMermaid returns Mermaid formatted table
func (s *Schema) ToMermaid(showComment bool) string {
var lines []string
tableNames := mapset.NewSet()
lines = append(lines, "erDiagram")
for _, table := range s.Tables {
lines = append(lines, table.ToMermaid(showComment))
tableNames.Add(table.Name)
}
for _, table := range s.Tables {
for _, foreignKey := range table.ForeignKeys {
toTable := strings.ToLower(foreignKey.ToTable)
if tableNames.Contains(toTable) {
lines = append(lines, fmt.Sprintf("%s ||--o{ %s : owns", toTable, table.Name))
}
}
}
return strings.Join(lines, "\n\n")
}
// Subset returns subset of a schema
func (s *Schema) Subset(tableName string, distance int) *Schema {
explorer := NewSchemaExplorer(s)
tableNames := explorer.Explore(tableName, distance)
var tables []*Table
for _, tableName := range tableNames {
table := s.findTable(tableName)
if table != nil {
tables = append(tables, table)
}
}
return NewSchema(tables)
}
func (s *Schema) findTable(tableName string) *Table {
for _, table := range s.Tables {
if table.Name == tableName {
return table
}
}
return nil
}