-
Notifications
You must be signed in to change notification settings - Fork 0
/
Create.go
134 lines (91 loc) · 2.12 KB
/
Create.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package sqlite3orm
import (
"bytes"
"database/sql"
"errors"
"fmt"
_ "github.com/mattn/go-sqlite3"
"reflect"
)
type DBWrapper struct {
SqlDB *sql.DB
isDebug bool
}
func (w DBWrapper) CreateTable(instance interface{}) error {
var buffer bytes.Buffer
indexMap := make(map[string][]string)
v := reflect.ValueOf(instance)
t := v.Type()
if t.Kind() == reflect.Ptr {
t = v.Elem().Type()
}
if t.Kind() == reflect.Slice {
return errors.New("not expecting a slice")
}
buffer.WriteString(fmt.Sprintf("CREATE TABLE %s (", t.Name()))
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
sqlType, err := mapSqliteType(field.Type.Name())
if err != nil {
return err
}
if i > 0 {
buffer.WriteString(", ")
}
buffer.WriteString(field.Name)
buffer.WriteString(" ")
buffer.WriteString(sqlType)
index := field.Tag.Get("index")
if index != "" {
_, ok := indexMap[index]
if ok {
indexMap[index] = append(indexMap[index], field.Name)
} else {
indexMap[index] = []string{field.Name}
}
}
}
buffer.WriteString(")")
if w.isDebug {
fmt.Println(buffer.String())
}
_, err := w.SqlDB.Exec(buffer.String())
if err != nil {
return err
}
return createIndex(indexMap, t.Name(), w)
}
func mapSqliteType(instance interface{}) (string, error) {
switch t := instance.(type) {
case string, DBTime:
return "TEXT", nil
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, bool:
return "INTEGER", nil
case float32, float64:
return "REAL", nil
default:
return "", errors.New(fmt.Sprintf("unknown type: %T", t))
}
}
func createIndex(indexMap map[string][]string, typeName string, w DBWrapper) error {
var buffer bytes.Buffer
for index, fields := range indexMap {
buffer.WriteString(fmt.Sprintf("CREATE INDEX %s ON %s (", index, typeName))
for i, field := range fields {
if i > 0 {
buffer.WriteString(", ")
}
buffer.WriteString(field)
}
buffer.WriteString(")")
if w.isDebug {
fmt.Println(buffer.String())
}
_, err := w.SqlDB.Exec(buffer.String())
if err != nil {
return err
}
buffer.Reset()
}
return nil
}