@@ -42,13 +42,25 @@ func NewSequenceAdapter(db *sql.DB, buildParam func(int) string, options ...stri
42
42
BuildParam : buildParam ,
43
43
}
44
44
}
45
- func (s * SequenceAdapter ) Next (ctx context.Context , id string ) (int64 , error ) {
46
- query := fmt .Sprintf (`select %s from %s where %s = %s` , s .Sequence , s .Tables , s .Table , s .BuildParam (1 ))
47
- tx , err := s .DB .Begin ()
45
+ func (s * SequenceAdapter ) Next (ctx context.Context , seqName string ) (int64 , error ) {
46
+ seq , err := s .next (ctx , seqName )
48
47
if err != nil {
49
- return - 1 , err
48
+ return seq , err
49
+ }
50
+ for {
51
+ if seq == - 2 {
52
+ seq , err := s .next (ctx , seqName )
53
+ if err != nil {
54
+ return seq , err
55
+ }
56
+ } else {
57
+ return seq , nil
58
+ }
50
59
}
51
- rows , err := tx .QueryContext (ctx , query , id )
60
+ }
61
+ func (s * SequenceAdapter ) next (ctx context.Context , seqName string ) (int64 , error ) {
62
+ query := fmt .Sprintf (`select %s from %s where %s = %s` , s .Sequence , s .Tables , s .Table , s .BuildParam (1 ))
63
+ rows , err := s .DB .QueryContext (ctx , query , seqName )
52
64
if err != nil {
53
65
return - 1 , err
54
66
}
@@ -58,34 +70,29 @@ func (s *SequenceAdapter) Next(ctx context.Context, id string) (int64, error) {
58
70
if err := rows .Scan (& seq ); err != nil {
59
71
return - 1 , err
60
72
}
61
- updateSql := fmt .Sprintf (`update %s set %s = %s where %s = %s` , s .Tables , s .Sequence , s .BuildParam ( 1 ) , s .Table , s .BuildParam (2 ) )
62
- _ , err = tx . ExecContext (ctx , updateSql , seq + 1 , id )
73
+ updateSql := fmt .Sprintf (`update %s set %s = %s + 1 where %s = %s and %s = %d ` , s .Tables , s .Sequence , s .Sequence , s .Table , s .BuildParam (1 ), s . Sequence , seq )
74
+ res , err := s . DB . ExecContext (ctx , updateSql , seqName )
63
75
if err != nil {
64
- er := tx .Rollback ()
65
- if er != nil {
66
- return - 1 , er
67
- }
68
76
return - 1 , err
69
77
}
70
- err = tx . Commit ()
78
+ c , err := res . RowsAffected ()
71
79
if err != nil {
72
80
return - 1 , err
73
81
}
82
+ if c == 0 {
83
+ return - 2 , nil
84
+ }
74
85
return seq , nil
75
86
} else {
76
87
insertSql := fmt .Sprintf (`insert into %s (%s, %s) values (%s, 2)` , s .Tables , s .Table , s .Sequence , s .BuildParam (1 ))
77
- _ , err = tx . ExecContext (ctx , insertSql , id )
88
+ _ , err = s . DB . ExecContext (ctx , insertSql , seqName )
78
89
if err != nil {
79
- er := tx . Rollback ( )
80
- if er != nil {
81
- return - 1 , er
90
+ x := strings . ToLower ( err . Error () )
91
+ if strings . Index ( x , "unique constraint" ) >= 0 || strings . Index ( x , "Violation of PRIMARY KEY constraint" ) >= 0 {
92
+ return - 2 , nil
82
93
}
83
94
return - 1 , err
84
95
}
85
- err = tx .Commit ()
86
- if err != nil {
87
- return - 1 , err
88
- }
89
96
return 1 , nil
90
97
}
91
98
}
0 commit comments