-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_init.go
52 lines (44 loc) · 1.2 KB
/
db_init.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
package db
import (
"strings"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
)
// TODO https://linear.app/znki/issue/ZNK-18/improve-mapping-from-protobuf-to-database-model
func CreateDBQuery(schemas []proto.Message) string {
if schemas == nil || len(schemas) == 0 {
return ""
}
var dbQuery strings.Builder
for _, message := range schemas {
tableName := strings.ToLower(string(proto.MessageName(message).Name()))
dbQuery.WriteString("CREATE TABLE IF NOT EXISTS " + tableName + " ( ")
fields := message.ProtoReflect().Descriptor().Fields()
for i := 0; i < fields.Len(); i++ {
typ := ConvertTyp(fields.Get(i))
dbQuery.WriteString(string(fields.Get(i).Name()) + " " + typ)
if i == 0 {
dbQuery.WriteString(" PRIMARY KEY")
}
if i != fields.Len()-1 {
dbQuery.WriteString(", ")
}
}
dbQuery.WriteString(");\n")
}
return dbQuery.String()
}
func ConvertTyp(field protoreflect.FieldDescriptor) string {
switch field.Kind() {
case protoreflect.Int32Kind:
return "INTEGER"
case protoreflect.StringKind:
return "TEXT"
case protoreflect.BoolKind:
return "BOOL"
case protoreflect.MessageKind:
return "TEXT"
default:
return "TEXT"
}
}