-
Notifications
You must be signed in to change notification settings - Fork 9
/
schema.go
106 lines (90 loc) · 2.3 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"fmt"
"io"
"os"
"sort"
"strings"
"github.com/Valentin-Kaiser/go-dbase/dbase"
)
func main() {
// Open debug log file so we see what's going on
f, err := os.OpenFile("debug.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println(err)
return
}
dbase.Debug(true, io.MultiWriter(os.Stdout, f))
db, err := dbase.OpenDatabase(&dbase.Config{
Filename: "../test_data/database/EXPENSES.DBC",
})
if err != nil {
panic(err)
}
defer db.Close()
// Print the database schema
schema := db.Schema()
tables := db.Tables()
length := len(tables)
fmt.Println("Generating schema...")
// Open schema output file
schemaFile, err := os.OpenFile("schema.gen.go", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
panic(err)
}
// Write file headline
_, err = schemaFile.WriteString("package main \n\n")
if err != nil {
panic(err)
}
keys := make([]string, 0)
for table := range schema {
keys = append(keys, table)
}
sort.Strings(keys)
timeImport := false
tablesStructs := make([]string, 0)
for i, name := range keys {
tableStructSchema := fmt.Sprintf("// Auto generated table struct: %v \n", name)
tableStructSchema += fmt.Sprintf("type %v struct {\n", strings.ToUpper(name))
for _, column := range schema[name] {
if column.DataType == byte(dbase.Date) || column.DataType == byte(dbase.DateTime) {
timeImport = true
}
typ, err := column.Reflect()
if err != nil {
panic(err)
}
tableStructSchema += fmt.Sprintf("\t%-12.12s %-12.12s `dbase:\"%v\"`\n", column.Name(), typ, column.Name())
}
tableStructSchema += "}\n\n"
tablesStructs = append(tablesStructs, tableStructSchema)
fmt.Printf("Generated %v/%v table schemas \n", i+1, length)
}
if timeImport {
_, err = schemaFile.WriteString("import \"time\"\n\n")
if err != nil {
panic(err)
}
}
for _, tableStruct := range tablesStructs {
_, err = schemaFile.WriteString(tableStruct)
if err != nil {
panic(err)
}
}
}
// ToByteString returns the number of bytes as a string with a unit
func ToByteString(b int) string {
const unit = 1000
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB",
float64(b)/float64(div), "kMGTPE"[exp])
}