-
Notifications
You must be signed in to change notification settings - Fork 22
/
store.go
82 lines (71 loc) · 2.18 KB
/
store.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
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
// Package timestamp implements a simple key-timestamp store.
package timestamp
// The code in this file is adapted from resolved_table.go
import (
"context"
"fmt"
"github.com/cockroachdb/cdc-sink/internal/types"
"github.com/cockroachdb/cdc-sink/internal/util/hlc"
"github.com/cockroachdb/cdc-sink/internal/util/ident"
"github.com/cockroachdb/cdc-sink/internal/util/retry"
"github.com/jackc/pgtype/pgxtype"
"github.com/jackc/pgx/v4"
"github.com/pkg/errors"
)
// store implements a simple key/value store for HLC timestamps.
type store struct {
sql struct {
swap string
}
}
var _ types.TimeKeeper = (*store)(nil)
// New constructs a store using the specified table for storage.
func New(
ctx context.Context, tx pgxtype.Querier, target ident.Table,
) (types.TimeKeeper, error) {
if err := retry.Execute(ctx, tx, fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %s (
key STRING NOT NULL PRIMARY KEY,
nanos INT8 NOT NULL,
logical INT8 NOT NULL
)
`, target)); err != nil {
return nil, errors.WithStack(err)
}
ret := &store{}
ret.sql.swap = fmt.Sprintf(swapTemplate, target)
return ret, nil
}
const swapTemplate = `
WITH u AS (UPSERT INTO %[1]s (nanos, logical, key) VALUES ($1, $2, $3) RETURNING 0)
SELECT nanos, logical FROM %[1]s WHERE key=$3`
// Put updates the value associated with the key, returning the
// previous value.
func (s *store) Put(
ctx context.Context, db pgxtype.Querier, key string, value hlc.Time,
) (hlc.Time, error) {
var nanos int64
var logical int
err := retry.Retry(ctx, func(ctx context.Context) error {
return db.QueryRow(
ctx,
s.sql.swap,
value.Nanos(),
value.Logical(),
key).Scan(&nanos, &logical)
})
// No rows means that we haven't seen this key before.
if errors.Is(err, pgx.ErrNoRows) {
return hlc.Zero(), nil
}
return hlc.New(nanos, logical), errors.Wrap(err, s.sql.swap)
}