forked from apache/incubator-seata-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgsql.go
486 lines (425 loc) · 14.4 KB
/
pgsql.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
package pgsql
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/go-xorm/xorm"
_ "github.com/lib/pq" // register pg
"xorm.io/builder"
"github.com/carlzhao/seata-golang/v2/pkg/apis"
"github.com/carlzhao/seata-golang/v2/pkg/tc/storage"
"github.com/carlzhao/seata-golang/v2/pkg/tc/storage/driver/factory"
"github.com/carlzhao/seata-golang/v2/pkg/util/log"
"github.com/carlzhao/seata-golang/v2/pkg/util/sql"
)
const (
InsertGlobalTransaction = `insert into %s (addressing, xid, transaction_id, transaction_name, timeout, begin_time,
status, active, gmt_create, gmt_modified) values($1, $2, $3, $4, $5, $6, $7, $8, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`
QueryGlobalTransactionByXid = `select addressing, xid, transaction_id, transaction_name, timeout, begin_time,
status, active, gmt_create, gmt_modified from %s where xid = $1`
UpdateGlobalTransaction = "update %s set status = $1, gmt_modified = CURRENT_TIMESTAMP where xid = $2"
InactiveGlobalTransaction = "update %s set active = 0, gmt_modified = CURRENT_TIMESTAMP where xid = $1"
DeleteGlobalTransaction = "delete from %s where xid = $1"
InsertBranchTransaction = `insert into %s (addressing, xid, branch_id, transaction_id, resource_id, lock_key, branch_type,
status, application_data, gmt_create, gmt_modified) values($1, $2, $3, $4, $5, $6, $7, $8, $9, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`
QueryBranchTransaction = `select addressing, xid, branch_id, transaction_id, resource_id, lock_key, branch_type, status,
application_data, gmt_create, gmt_modified from %s where %s order by gmt_create asc`
QueryBranchTransactionByXid = `select addressing, xid, branch_id, transaction_id, resource_id, lock_key, branch_type, status,
application_data, gmt_create, gmt_modified from %s where xid = $1 order by gmt_create asc`
UpdateBranchTransaction = "update %s set status = $1, gmt_modified = CURRENT_TIMESTAMP where xid = $2 and branch_id = $3"
DeleteBranchTransaction = "delete from %s where xid = $1 and branch_id = $2"
InsertRowLock = `insert into %s (xid, transaction_id, branch_id, resource_id, table_name, pk, row_key, gmt_create,
gmt_modified) values %s`
QueryRowKey = `select xid, transaction_id, branch_id, resource_id, table_name, pk, row_key, gmt_create, gmt_modified
from %s where %s order by gmt_create asc`
)
func init() {
factory.Register("pgsql", &pgsqlFactory{})
}
type DriverParameters struct {
DSN string
GlobalTable string
BranchTable string
LockTable string
QueryLimit int
MaxOpenConnections int
MaxIdleConnections int
MaxLifeTime time.Duration
}
// pgsqlFactory implements the factory.StorageDriverFactory interface
type pgsqlFactory struct{}
func (factory *pgsqlFactory) Create(parameters map[string]interface{}) (storage.Driver, error) {
return FromParameters(parameters)
}
type driver struct {
engine *xorm.Engine
globalTable string
branchTable string
lockTable string
queryLimit int
}
func FromParameters(parameters map[string]interface{}) (storage.Driver, error) {
dsn := parameters["dsn"]
if dsn == nil {
dsn = ""
}
globalTable := parameters["globaltable"]
if globalTable == nil {
dsn = "global_table"
}
branchTable := parameters["branchtable"]
if globalTable == nil {
dsn = "branch_table"
}
lockTable := parameters["locktable"]
if globalTable == nil {
dsn = "global_table"
}
queryLimit := 100
ql := parameters["querylimit"]
switch ql := ql.(type) {
case string:
var err error
queryLimit, err = strconv.Atoi(ql)
if err != nil {
log.Error("the querylimit parameter should be a integer")
}
case int:
queryLimit = ql
case nil:
// do nothing
default:
log.Error("the querylimit parameter should be a integer")
}
maxOpenConnections := 100
mc := parameters["maxopenconnections"]
switch mc := mc.(type) {
case string:
var err error
maxOpenConnections, err = strconv.Atoi(mc)
if err != nil {
log.Error("the maxopenconnections parameter should be a integer")
}
case int:
maxOpenConnections = mc
case nil:
// do nothing
default:
log.Error("the maxopenconnections parameter should be a integer")
}
maxIdleConnections := 20
mi := parameters["maxidleconnections"]
switch mi := mi.(type) {
case string:
var err error
maxOpenConnections, err = strconv.Atoi(mi)
if err != nil {
log.Error("the maxidleconnections parameter should be a integer")
}
case int:
maxIdleConnections = mi
case nil:
// do nothing
default:
log.Error("the maxidleconnections parameter should be a integer")
}
maxlifetime := 4 * time.Hour
ml := parameters["maxlifetime"]
switch ml := ml.(type) {
case string:
var err error
maxlifetime, err = time.ParseDuration(ml)
if err != nil {
log.Error("the maxlifetime parameter should be a duration")
}
case time.Duration:
maxlifetime = ml
case nil:
// do nothing
default:
log.Error("the maxlifetime parameter should be a duration")
}
driverParameters := DriverParameters{
DSN: fmt.Sprint(dsn),
GlobalTable: fmt.Sprint(globalTable),
BranchTable: fmt.Sprint(branchTable),
LockTable: fmt.Sprint(lockTable),
QueryLimit: queryLimit,
MaxOpenConnections: maxOpenConnections,
MaxIdleConnections: maxIdleConnections,
MaxLifeTime: maxlifetime,
}
return New(driverParameters)
}
// New constructs a new Driver
func New(params DriverParameters) (storage.Driver, error) {
if params.DSN == "" {
return nil, fmt.Errorf("the dsn parameter should not be empty")
}
engine, err := xorm.NewEngine("postgres", params.DSN)
if err != nil {
return nil, err
}
engine.SetMaxOpenConns(params.MaxOpenConnections)
engine.SetMaxIdleConns(params.MaxIdleConnections)
engine.SetConnMaxLifetime(params.MaxLifeTime)
return &driver{
engine: engine,
globalTable: params.GlobalTable,
branchTable: params.BranchTable,
lockTable: params.LockTable,
queryLimit: params.QueryLimit,
}, nil
}
// Add global session.
func (driver *driver) AddGlobalSession(session *apis.GlobalSession) error {
_, err := driver.engine.Exec(fmt.Sprintf(InsertGlobalTransaction, driver.globalTable),
session.Addressing, session.XID, session.TransactionID, session.TransactionName,
session.Timeout, session.BeginTime, session.Status, session.Active)
return err
}
// Find global session.
func (driver *driver) FindGlobalSession(xid string) *apis.GlobalSession {
var globalTransaction apis.GlobalSession
result, err := driver.engine.SQL(fmt.Sprintf(QueryGlobalTransactionByXid, driver.globalTable), xid).
Get(&globalTransaction)
if result {
return &globalTransaction
}
if err != nil {
log.Errorf(err.Error())
}
return nil
}
// Find global sessions list.
func (driver *driver) FindGlobalSessions(statuses []apis.GlobalSession_GlobalStatus) []*apis.GlobalSession {
var globalSessions []*apis.GlobalSession
err := driver.engine.Table(driver.globalTable).
Where(builder.In("status", statuses)).
OrderBy("gmt_modified").
Limit(driver.queryLimit).
Find(&globalSessions)
if err != nil {
log.Errorf(err.Error())
}
return globalSessions
}
// Find global sessions list with addressing identities
func (driver *driver) FindGlobalSessionsWithAddressingIdentities(statuses []apis.GlobalSession_GlobalStatus,
addressingIdentities []string) []*apis.GlobalSession {
var globalSessions []*apis.GlobalSession
err := driver.engine.Table(driver.globalTable).
Where(builder.
In("status", statuses).
And(builder.In("addressing", addressingIdentities))).
OrderBy("gmt_modified").
Limit(driver.queryLimit).
Find(&globalSessions)
if err != nil {
log.Errorf(err.Error())
}
return globalSessions
}
// All sessions collection.
func (driver *driver) AllSessions() []*apis.GlobalSession {
var globalSessions []*apis.GlobalSession
err := driver.engine.Table(driver.globalTable).
OrderBy("gmt_modified").
Find(&globalSessions)
if err != nil {
log.Errorf(err.Error())
}
return globalSessions
}
// Update global session status.
func (driver *driver) UpdateGlobalSessionStatus(session *apis.GlobalSession, status apis.GlobalSession_GlobalStatus) error {
_, err := driver.engine.Exec(fmt.Sprintf(UpdateGlobalTransaction, driver.globalTable), status, session.XID)
return err
}
// Inactive global session.
func (driver *driver) InactiveGlobalSession(session *apis.GlobalSession) error {
_, err := driver.engine.Exec(fmt.Sprintf(InactiveGlobalTransaction, driver.globalTable), session.XID)
return err
}
// Remove global session.
func (driver *driver) RemoveGlobalSession(session *apis.GlobalSession) error {
_, err := driver.engine.Exec(fmt.Sprintf(DeleteGlobalTransaction, driver.globalTable), session.XID)
return err
}
// Add branch session.
func (driver *driver) AddBranchSession(globalSession *apis.GlobalSession, session *apis.BranchSession) error {
_, err := driver.engine.Exec(fmt.Sprintf(InsertBranchTransaction, driver.branchTable),
session.Addressing, session.XID, session.BranchID, session.TransactionID, session.ResourceID, session.LockKey,
session.Type, session.Status, session.ApplicationData)
return err
}
// Find branch session.
func (driver *driver) FindBranchSessions(xid string) []*apis.BranchSession {
var branchTransactions []*apis.BranchSession
err := driver.engine.SQL(fmt.Sprintf(QueryBranchTransactionByXid, driver.branchTable), xid).Find(&branchTransactions)
if err != nil {
log.Errorf(err.Error())
}
return branchTransactions
}
// Find branch session.
func (driver *driver) FindBatchBranchSessions(xids []string) []*apis.BranchSession {
var (
branchTransactions []*apis.BranchSession
xidArgs []interface{}
)
whereCond := fmt.Sprintf("xid in %s", sql.PgsqlAppendInParam(len(xids)))
for _, xid := range xids {
xidArgs = append(xidArgs, xid)
}
err := driver.engine.SQL(fmt.Sprintf(QueryBranchTransaction, driver.branchTable, whereCond), xidArgs...).Find(&branchTransactions)
if err != nil {
log.Errorf(err.Error())
}
return branchTransactions
}
// Update branch session status.
func (driver *driver) UpdateBranchSessionStatus(session *apis.BranchSession, status apis.BranchSession_BranchStatus) error {
_, err := driver.engine.Exec(fmt.Sprintf(UpdateBranchTransaction, driver.branchTable),
status,
session.XID,
session.BranchID)
return err
}
// Remove branch session.
func (driver *driver) RemoveBranchSession(globalSession *apis.GlobalSession, session *apis.BranchSession) error {
_, err := driver.engine.Exec(fmt.Sprintf(DeleteBranchTransaction, driver.branchTable),
session.XID,
session.BranchID)
return err
}
// AcquireLock Acquire lock boolean.
func (driver *driver) AcquireLock(rowLocks []*apis.RowLock) bool {
locks, rowKeys := distinctByKey(rowLocks)
var (
existedRowLocks []*apis.RowLock
rowKeyArgs []interface{}
)
for _, rowKey := range rowKeys {
rowKeyArgs = append(rowKeyArgs, rowKey)
}
whereCond := fmt.Sprintf("row_key in %s", sql.PgsqlAppendInParam(len(rowKeys)))
err := driver.engine.SQL(fmt.Sprintf(QueryRowKey, driver.lockTable, whereCond), rowKeyArgs...).Find(&existedRowLocks)
if err != nil {
log.Errorf(err.Error())
}
currentXID := locks[0].XID
canLock := true
existedRowKeys := make([]string, 0)
unrepeatedLocks := make([]*apis.RowLock, 0)
for _, rowLock := range existedRowLocks {
if rowLock.XID != currentXID {
log.Infof("row lock [%s] on %s:%s is holding by xid {%s} branchID {%d}", rowLock.RowKey, driver.lockTable, rowLock.TableName,
rowLock.PK, rowLock.XID, rowLock.BranchID)
canLock = false
break
}
existedRowKeys = append(existedRowKeys, rowLock.RowKey)
}
if !canLock {
return false
}
if len(existedRowKeys) > 0 {
for _, lock := range locks {
if !contains(existedRowKeys, lock.RowKey) {
unrepeatedLocks = append(unrepeatedLocks, lock)
}
}
} else {
unrepeatedLocks = locks
}
if len(unrepeatedLocks) == 0 {
return true
}
var (
sb strings.Builder
args []interface{}
sqlOrArgs []interface{}
)
for i := 0; i < len(unrepeatedLocks); i++ {
sb.WriteString(fmt.Sprintf("($%d, $%d, $%d, $%d, $%d, $%d, $%d, now(), now()),", 7*i+1, 7*i+2, 7*i+3, 7*i+4, 7*i+5, 7*i+6, 7*i+7))
args = append(args, unrepeatedLocks[i].XID, unrepeatedLocks[i].TransactionID, unrepeatedLocks[i].BranchID,
unrepeatedLocks[i].ResourceID, unrepeatedLocks[i].TableName, unrepeatedLocks[i].PK, unrepeatedLocks[i].RowKey)
}
values := sb.String()
valueStr := values[:len(values)-1]
sqlOrArgs = append(sqlOrArgs, fmt.Sprintf(InsertRowLock, driver.lockTable, valueStr))
sqlOrArgs = append(sqlOrArgs, args...)
_, err = driver.engine.Exec(sqlOrArgs...)
if err != nil {
// In an extremely high concurrency scenario, the row lock has been written to the database,
// but the pgsql driver reports invalid connection exception, and then re-registers the branch,
// it will report the duplicate key exception.
log.Errorf("row locks batch acquire failed, %v, %v", unrepeatedLocks, err)
return false
}
return true
}
func distinctByKey(locks []*apis.RowLock) ([]*apis.RowLock, []string) {
result := make([]*apis.RowLock, 0)
rowKeys := make([]string, 0)
lockMap := make(map[string]byte)
for _, lockDO := range locks {
l := len(lockMap)
lockMap[lockDO.RowKey] = 0
if len(lockMap) != l {
result = append(result, lockDO)
rowKeys = append(rowKeys, lockDO.RowKey)
}
}
return result, rowKeys
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
// ReleaseLock Unlock boolean.
func (driver *driver) ReleaseLock(rowLocks []*apis.RowLock) bool {
if rowLocks != nil && len(rowLocks) == 0 {
return true
}
rowKeys := make([]string, 0)
for _, lock := range rowLocks {
rowKeys = append(rowKeys, lock.RowKey)
}
var lock = apis.RowLock{}
_, err := driver.engine.Table(driver.lockTable).
Where(builder.In("row_key", rowKeys).And(builder.Eq{"xid": rowLocks[0].XID})).
Delete(&lock)
if err != nil {
log.Errorf(err.Error())
return false
}
return true
}
// IsLockable Is lockable boolean.
func (driver *driver) IsLockable(xid string, resourceID string, lockKey string) bool {
locks := storage.CollectRowLocks(lockKey, resourceID, xid)
var existedRowLocks []*apis.RowLock
rowKeys := make([]interface{}, 0)
for _, lockDO := range locks {
rowKeys = append(rowKeys, lockDO.RowKey)
}
whereCond := fmt.Sprintf("row_key in %s", sql.PgsqlAppendInParam(len(rowKeys)))
err := driver.engine.SQL(fmt.Sprintf(QueryRowKey, driver.lockTable, whereCond), rowKeys...).Find(&existedRowLocks)
if err != nil {
log.Errorf(err.Error())
}
currentXID := locks[0].XID
for _, rowLock := range existedRowLocks {
if rowLock.XID != currentXID {
return false
}
}
return true
}