-
Notifications
You must be signed in to change notification settings - Fork 1
/
pgx.go
99 lines (77 loc) · 2.28 KB
/
pgx.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
package driver
import (
"context"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/pkg/errors"
"github.com/SKF/go-eventsource/v2/eventsource"
"github.com/SKF/go-utility/v2/uuid"
)
type PGX struct {
DB *pgxpool.Pool
}
func (pgx *PGX) Load(ctx context.Context, query string, args []interface{}) (records []eventsource.Record, err error) {
rows, err := pgx.DB.Query(ctx, query, args...)
if err != nil {
return records, errors.Wrap(err, "failed to load events using pgx")
}
for rows.Next() {
var (
record eventsource.Record
aggregateID uuid.UUID
userID uuid.UUID
)
// Scan aggregateID and userID to intermediate uuid, so they are transferred using binary representation
if err = rows.Scan(
&aggregateID, &record.SequenceID, &record.Timestamp,
&userID, &record.Type, &record.Data,
); err != nil {
err = errors.Wrap(err, "failed to scan sql row")
return
}
record.AggregateID = aggregateID.String()
record.UserID = userID.String()
records = append(records, record)
}
if err = rows.Err(); err != nil {
err = errors.Wrap(err, "errors returned from sql store")
return
}
return records, err
}
func (pgx *PGX) NewTransaction(ctx context.Context, query string, records ...eventsource.Record) (eventsource.StoreTransaction, error) {
tx, err := pgx.DB.Begin(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to start new transaction")
}
for _, record := range records {
_, err = tx.Exec(ctx, query, uuid.UUID(record.AggregateID), record.SequenceID, record.Timestamp, uuid.UUID(record.UserID), record.Type, record.Data)
if err != nil {
return nil, errors.Wrap(err, "failed to execute query")
}
}
return &pgxTransaction{
sqlTx: tx,
records: records,
}, nil
}
type pgxTransaction struct {
sqlTx pgx.Tx
records []eventsource.Record
}
// Commit ...
func (tx *pgxTransaction) Commit() (err error) {
if err := tx.sqlTx.Commit(context.Background()); err != nil {
return errors.Wrap(err, "failed to commit transaction")
}
return nil
}
func (tx *pgxTransaction) Rollback() error {
if err := tx.sqlTx.Rollback(context.Background()); err != nil {
return errors.Wrap(err, "failed to rollback transaction")
}
return nil
}
func (tx *pgxTransaction) GetRecords() []eventsource.Record {
return tx.records
}