forked from alanshaw/ipfs-ds-postgres
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbatching.go
50 lines (40 loc) · 1.1 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
package pgds
import (
"context"
"fmt"
ds "github.com/ipfs/go-datastore"
"github.com/jackc/pgx/v4"
)
type batch struct {
ds *Datastore
batch *pgx.Batch
}
// Batch creates a set of deferred updates to the database.
func (d *Datastore) Batch(_ context.Context) (ds.Batch, error) {
return &batch{ds: d, batch: &pgx.Batch{}}, nil
}
func (b *batch) Put(ctx context.Context, key ds.Key, value []byte) error {
b.batch.Queue("BEGIN")
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)
b.batch.Queue("COMMIT")
return nil
}
func (b *batch) Delete(ctx context.Context, key ds.Key) error {
b.batch.Queue("BEGIN")
b.batch.Queue(fmt.Sprintf("DELETE FROM %s WHERE key = $1", b.ds.table), key.String())
b.batch.Queue("COMMIT")
return nil
}
func (b *batch) Commit(ctx context.Context) error {
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)