-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbatching.go
73 lines (57 loc) · 1.56 KB
/
batching.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
package pgds
import (
"context"
"fmt"
ds "github.com/ipfs/go-datastore"
"github.com/jackc/pgx/v4"
)
type batch struct {
ds *Datastore
batch *pgx.Batch
maxBatchSize uint16
}
// Batch creates a set of deferred updates to the database.
func (d *Datastore) Batch() (ds.Batch, error) {
b := &batch{ds: d, batch: &pgx.Batch{}, maxBatchSize: 0}
b.batch.Queue("BEGIN")
return b, nil
}
// Set the max batch size (0 or default means unlimited - the batch is only cleared when calling Commit)
func (b *batch) SetMaxBatchSize(size uint16) {
b.maxBatchSize = size
}
func (b *batch) checkMaxBatchSize() error {
var err error
if b.maxBatchSize != 0 && b.batch.Len() >= int(b.maxBatchSize) {
err = b.CommitContext(context.Background())
}
if err != nil {
b.batch = &pgx.Batch{}
}
return err
}
func (b *batch) Put(key ds.Key, value []byte) error {
sql := fmt.Sprintf("INSERT INTO %s (key, data) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET data = $2", b.ds.table)
b.batch.Queue(sql, key.String(), value)
return b.checkMaxBatchSize()
}
func (b *batch) Delete(key ds.Key) error {
b.batch.Queue(fmt.Sprintf("DELETE FROM %s WHERE key = $1", b.ds.table), key.String())
return nil
}
func (b *batch) Commit() error {
return b.CommitContext(context.Background())
}
func (b *batch) CommitContext(ctx context.Context) error {
b.batch.Queue("COMMIT")
res := b.ds.pool.SendBatch(ctx, b.batch)
defer res.Close()
for i := 0; i < b.batch.Len(); i++ {
_, err := res.Exec()
if err != nil {
return err
}
}
return nil
}
var _ ds.Batching = (*Datastore)(nil)