-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathchangeset.go
81 lines (69 loc) · 2.41 KB
/
changeset.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
package warppipe
import (
"strings"
"time"
"fmt"
)
// ChangesetKind is the type for changeset kinds
type ChangesetKind string
// ChangesetKind constants
const (
ChangesetKindInsert ChangesetKind = "insert"
ChangesetKindUpdate ChangesetKind = "update"
ChangesetKindDelete ChangesetKind = "delete"
)
// ParseChangesetKind parses a changeset kind from a string.
func ParseChangesetKind(kind string) ChangesetKind {
switch strings.ToLower(kind) {
case "insert":
return ChangesetKindInsert
case "update":
return ChangesetKindUpdate
case "delete":
return ChangesetKindDelete
default:
// TODO: should this error?
return ""
}
}
// Changeset represents a changeset for a record on a Postgres table.
type Changeset struct {
ID int64 `json:"id"`
Kind ChangesetKind `json:"kind"`
Schema string `json:"schema"`
Table string `json:"table"`
Timestamp time.Time `json:"timestamp"`
NewValues []*ChangesetColumn `json:"new_values"`
OldValues []*ChangesetColumn `json:"old_values"`
}
func (c *Changeset) getColumnValue(values []*ChangesetColumn, column string) (interface{}, bool) {
for _, v := range values {
if v.Column == column {
return v.Value, true
}
}
return nil, false
}
// String implements Stringer to create a useful string representation of a Changeset.
func (c *Changeset) String() string {
// While c.newValues is an ordered array, the original data source is a JSON
// object used as a hashmap, therefore the data is stored as a map in Go
// which means the field order in the array is randomized.
return fmt.Sprintf("{timestamp: %s, kind: %s, schema: %s, table: %s}", c.Timestamp, c.Kind, c.Schema, c.Table)
}
// GetNewColumnValue returns the current value for a column and a bool denoting
// whether a new value is present in the changeset.
func (c *Changeset) GetNewColumnValue(column string) (interface{}, bool) {
return c.getColumnValue(c.NewValues, column)
}
// GetPreviousColumnValue returns the previous value for a column and a bool denoting
// whether an old value is present in the changeset.
func (c *Changeset) GetPreviousColumnValue(column string) (interface{}, bool) {
return c.getColumnValue(c.OldValues, column)
}
// ChangesetColumn represents a type and value for a column in a changeset.
type ChangesetColumn struct {
Column string `json:"column"`
Value interface{} `json:"value"`
Type string `json:"type"`
}