-
Notifications
You must be signed in to change notification settings - Fork 7
/
sql.go
108 lines (94 loc) · 2.01 KB
/
sql.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
package edb
import (
"context"
"database/sql"
"fmt"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/clientv3/mirror"
)
type SQLDBSyncer struct {
Table string
NoOverwrite bool
Syncer mirror.Syncer
DB *sql.DB
}
func (ds *SQLDBSyncer) Validate() error {
// TODO: validate table schema
return nil
}
func (ds *SQLDBSyncer) Sync(ctx context.Context) error {
var (
stmt *sql.Stmt
dstmt *sql.Stmt
err error
)
if ds.NoOverwrite {
stmt, err = ds.DB.Prepare(fmt.Sprintf("INSERT INTO %s(key,event,value,revision) VALUES ($1,$2,$3,$4) ON CONFLICT(revision) DO NOTHING", ds.Table))
if err != nil {
return err
}
dstmt = stmt
} else {
stmt, err = ds.DB.Prepare(fmt.Sprintf("INSERT INTO %s(key,value) VALUES ($1,$2) ON CONFLICT (key) DO UPDATE SET value=$2", ds.Table))
if err != nil {
return err
}
dstmt, err = ds.DB.Prepare(fmt.Sprintf("DELETE FROM %s WHERE value=$1", ds.Table))
if err != nil {
return err
}
}
rc, errc := ds.Syncer.SyncBase(ctx)
var done bool
for {
if done {
break
}
select {
case r, ok := <-rc:
for _, kv := range r.Kvs {
if ds.NoOverwrite {
if _, err := stmt.Exec(kv.Key, clientv3.EventTypePut.String(), kv.Value, kv.ModRevision); err != nil {
return err
}
continue
}
if _, err := stmt.Exec(kv.Key, kv.Value); err != nil {
return err
}
}
if !ok {
done = true
}
case e := <-errc:
if e != nil {
return e
}
}
}
wch := ds.Syncer.SyncUpdates(ctx)
for wr := range wch {
if wr.Err() != nil {
return wr.Err()
}
for _, e := range wr.Events {
if ds.NoOverwrite {
if _, err := stmt.Exec(e.Kv.Key, e.Type.String(), e.Kv.Value, e.Kv.ModRevision); err != nil {
return err
}
continue
}
switch e.Type {
case clientv3.EventTypePut:
if _, err := stmt.Exec(e.Kv.Key, e.Kv.Value); err != nil {
return err
}
case clientv3.EventTypeDelete:
if _, err := dstmt.Exec(e.Kv.Key); err != nil {
return err
}
}
}
}
return ctx.Err()
}