-
Notifications
You must be signed in to change notification settings - Fork 3
/
schema.go
201 lines (174 loc) · 4.79 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
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package chstorage
import (
"context"
"crypto/sha256"
"fmt"
"strings"
"time"
"github.com/ClickHouse/ch-go"
"github.com/go-faster/errors"
"github.com/go-faster/sdk/zctx"
"go.uber.org/zap"
"github.com/go-faster/oteldb/internal/ddl"
)
// Tables define table names.
type Tables struct {
Spans string
Tags string
Points string
ExpHistograms string
Exemplars string
Labels string
Logs string
LogAttrs string
Migration string
TTL time.Duration
Cluster string
}
// Validate checks table names
func (t *Tables) Validate() error {
return t.Each(func(name *string) error {
if *name == "" {
return errors.New("table name must be non-empty")
}
return nil
})
}
// Each calls given callback for each table.
func (t *Tables) Each(cb func(name *string) error) error {
for _, table := range []struct {
field *string
fieldName string
}{
{&t.Spans, "Spans"},
{&t.Tags, "Tags"},
{&t.Points, "Points"},
{&t.ExpHistograms, "ExpHistograms"},
{&t.Exemplars, "Exemplars"},
{&t.Labels, "Labels"},
{&t.Logs, "Logs"},
{&t.LogAttrs, "LogAttrs"},
{&t.Migration, "Migration"},
} {
if err := cb(table.field); err != nil {
return errors.Wrapf(err, "table %s", table.fieldName)
}
}
return nil
}
// DefaultTables returns default tables.
func DefaultTables() Tables {
return Tables{
Spans: "traces_spans",
Tags: "traces_tags",
Points: "metrics_points",
ExpHistograms: "metrics_exp_histograms",
Exemplars: "metrics_exemplars",
Labels: "metrics_labels",
Logs: "logs",
LogAttrs: "logs_attrs",
Migration: "migration",
}
}
func (t Tables) getHashes(ctx context.Context, c ClickhouseClient) (map[string]string, error) {
col := newMigrationColumns()
if err := c.Do(ctx, ch.Query{
Logger: zctx.From(ctx).Named("ch"),
Body: fmt.Sprintf("SELECT table, ddl FROM %s FINAL", t.Migration),
Result: col.Result(),
}); err != nil {
return nil, errors.Wrap(err, "query")
}
return col.Mapping(), nil
}
func (t Tables) saveHashes(ctx context.Context, c ClickhouseClient, m map[string]string) error {
col := newMigrationColumns()
col.Save(m)
if err := c.Do(ctx, ch.Query{
Logger: zctx.From(ctx).Named("ch"),
Input: col.Input(),
Body: col.Input().Into(t.Migration),
}); err != nil {
return errors.Wrap(err, "query")
}
return nil
}
type generateOptions struct {
Name string
DDL string
TTLField string
}
func (t Tables) generateQuery(opts generateOptions) string {
var s strings.Builder
s.WriteString("CREATE TABLE IF NOT EXISTS ")
s.WriteString(ddl.Backtick(opts.Name))
if t.Cluster != "" {
s.WriteString(" ON CLUSTER ")
s.WriteString(ddl.Backtick(t.Cluster))
}
s.WriteString("\n")
s.WriteString(strings.TrimSpace(opts.DDL))
if t.TTL > 0 && opts.TTLField != "" {
s.WriteString(fmt.Sprintf("\nTTL toDateTime(%s) + toIntervalSecond(%d)",
ddl.Backtick(opts.TTLField), t.TTL/time.Second,
))
}
s.WriteString("\n")
return s.String()
}
// Create creates tables.
func (t Tables) Create(ctx context.Context, c ClickhouseClient) error {
if err := t.Validate(); err != nil {
return errors.Wrap(err, "validate")
}
if err := c.Do(ctx, ch.Query{
Logger: zctx.From(ctx).Named("ch"),
Body: t.generateQuery(generateOptions{Name: t.Migration, DDL: schemaMigration}),
}); err != nil {
return errors.Wrapf(err, "create %q", t.Migration)
}
hashes, err := t.getHashes(ctx, c)
if err != nil {
return errors.Wrap(err, "get hashes")
}
for _, s := range []generateOptions{
{Name: t.Spans, DDL: spansSchema, TTLField: "start"},
{Name: t.Tags, DDL: tagsSchema},
{Name: t.Points, DDL: pointsSchema, TTLField: "timestamp"},
{Name: t.ExpHistograms, DDL: expHistogramsSchema, TTLField: "timestamp"},
{Name: t.Exemplars, DDL: exemplarsSchema, TTLField: "timestamp"},
{Name: t.Labels, DDL: labelsSchema},
{Name: t.Logs, DDL: logsSchema, TTLField: "timestamp"},
{Name: t.LogAttrs, DDL: logAttrsSchema},
} {
query := t.generateQuery(s)
name := s.Name
target := fmt.Sprintf("%x", sha256.Sum256([]byte(query)))
if current, ok := hashes[s.Name]; ok && current != target {
// HACK: this will DROP all data in the table
// TODO: implement ALTER TABLE
zctx.From(ctx).Warn("DROPPING TABLE (schema changed!)",
zap.String("table", name),
zap.String("current", current),
zap.String("target", target),
)
if err := c.Do(ctx, ch.Query{
Logger: zctx.From(ctx).Named("ch"),
Body: fmt.Sprintf("DROP TABLE IF EXISTS %s", name),
}); err != nil {
return errors.Wrapf(err, "drop %q", name)
}
}
hashes[name] = target
if err := c.Do(ctx, ch.Query{
Logger: zctx.From(ctx).Named("ch"),
Body: query,
}); err != nil {
return errors.Wrapf(err, "create %q", name)
}
}
if err := t.saveHashes(ctx, c, hashes); err != nil {
return errors.Wrap(err, "save hashes")
}
return nil
}