-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
93 lines (75 loc) · 1.77 KB
/
table.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
package tsbuilder
import (
"bytes"
"fmt"
"strings"
)
var _ tdEngineSqlBuilder = (*createTableBuilder)(nil)
type createTableBuilder struct {
tableName string
sTableName string
tags map[string]any
}
func NewCreateTableBuilder() *createTableBuilder {
return &createTableBuilder{
tags: make(map[string]any),
}
}
func (s *createTableBuilder) TableName(tableName string) *createTableBuilder {
s.tableName = tableName
return s
}
func (s *createTableBuilder) STable(sTableName string) *createTableBuilder {
s.sTableName = sTableName
return s
}
func (s *createTableBuilder) Tags(tags map[string]any) *createTableBuilder {
if tags == nil {
tags = make(map[string]any)
}
s.tags = tags
return s
}
func (s *createTableBuilder) Build() (string, error) {
if err := s.validate(); err != nil {
return "", fmt.Errorf("validate error: %w", err)
}
b := bytes.NewBuffer([]byte{})
b.WriteString("CREATE TABLE IF NOT EXISTS ")
// add table name
b.WriteString(s.tableName + " ")
// add stable
if s.sTableName != "" {
b.WriteString("USING " + s.sTableName + " ")
}
// add tags
if len(s.tags) > 0 {
tagsKeys := make([]string, 0, len(s.tags))
tagsValues := make([]any, 0, len(s.tags))
for key, value := range s.tags {
tagsKeys = append(tagsKeys, key)
tagsValues = append(tagsValues, value)
}
b.WriteString("(" + strings.Join(tagsKeys, ", ") + ") ")
b.WriteString("TAGS (")
for index, value := range tagsValues {
v, err := castType(value)
if err != nil {
return "", err
}
b.WriteString(v)
if index != len(tagsValues)-1 {
b.WriteString(", ")
}
}
b.WriteString(")")
}
b.WriteString(";")
return b.String(), nil
}
func (s createTableBuilder) validate() error {
if s.tableName == "" {
return ErrEmptyTableName
}
return nil
}