-
Notifications
You must be signed in to change notification settings - Fork 0
/
participant.go
70 lines (61 loc) · 1.49 KB
/
participant.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
package gosql2pc
import (
"context"
"database/sql"
"fmt"
"github.com/google/uuid"
)
// Participant is a participant in a 2PC transaction
type Participant struct {
do func(ctx context.Context, tx *sql.Tx) error
db *sql.DB
txid string
prepared bool
committed bool
rollbacked bool
}
// NewParticipant creates a new participant
// The do function is called when the participant is prepared. It should contain all the
// database operations that should be performed in the transaction.
func NewParticipant(db *sql.DB, do func(ctx context.Context, tx *sql.Tx) error) Participant {
return Participant{
db: db,
do: do,
}
}
func (o *Participant) prepare(ctx context.Context) error {
tx, err := o.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if err := o.do(ctx, tx); err != nil {
return err
}
o.txid = getPreparedGid()
if _, err := tx.ExecContext(ctx, fmt.Sprintf("PREPARE TRANSACTION '%s'", o.txid)); err != nil {
return err
}
o.prepared = true
return nil
}
func (o *Participant) rollback() error {
if o.txid == "" || o.rollbacked || o.committed {
return nil
}
if _, err := o.db.Exec(fmt.Sprintf("ROLLBACK PREPARED '%s'", o.txid)); err != nil {
return err
}
o.rollbacked = true
return nil
}
func (o *Participant) commit() error {
if _, err := o.db.Exec(fmt.Sprintf("COMMIT PREPARED '%s'", o.txid)); err != nil {
return err
}
o.committed = true
return nil
}
func getPreparedGid() string {
return defaultPrefix + uuid.New().String()
}