-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathd2.go
67 lines (54 loc) · 1.22 KB
/
d2.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
package main
import (
"bufio"
"fmt"
"io"
"golang.org/x/exp/slices"
)
func d2(w io.Writer, tables Tables) error {
slices.SortFunc(tables, func(a, b Table) bool {
return a.Name < b.Name
})
bufW := bufio.NewWriter(w)
defer bufW.Flush()
for _, t := range tables {
bufW.WriteString(t.Name)
bufW.WriteString(": {")
bufW.WriteString("\n")
bufW.WriteString(" shape: sql_table")
bufW.WriteString("\n\n")
for _, c := range t.Columns {
bufW.WriteString(" ")
bufW.WriteString(c.Name)
bufW.WriteString(": ")
bufW.WriteString(c.Type)
if c.Default != nil {
fmt.Fprintf(bufW, " %v", c.Default)
}
if !c.NotNull {
bufW.WriteString(" (N)")
}
if c.PrimaryKey {
bufW.WriteString(" { constraint: primary_key }")
} else {
if i, _ := t.Refers(c.Name); i >= 0 {
bufW.WriteString(" { constraint: foreign_key }")
}
}
bufW.WriteString("\n")
}
bufW.WriteString("}")
bufW.WriteString("\n\n")
}
// Draw foreign keys
for _, t := range tables {
for _, r := range t.References {
tableIndex, _ := tables.Table(r.ToTable)
if tableIndex == -1 {
continue
}
fmt.Fprintf(bufW, "%s.%s -> %s.%s\n", t.Name, r.FromColumn, r.ToTable, r.ToColumn)
}
}
return nil
}