-
Notifications
You must be signed in to change notification settings - Fork 18
/
mysql_undo_executor.go
224 lines (194 loc) · 5.98 KB
/
mysql_undo_executor.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
package mysql
import (
"database/sql/driver"
"encoding/json"
"fmt"
"strings"
"github.com/google/go-cmp/cmp"
"github.com/opentrx/seata-golang/v2/pkg/util/log"
"github.com/pkg/errors"
"github.com/opentrx/mysql/v2/schema"
)
const (
InsertSqlTemplate = "INSERT INTO %s (%s) VALUES (%s)"
DeleteSqlTemplate = "DELETE FROM %s WHERE `%s` = ?"
UpdateSqlTemplate = "UPDATE %s SET %s WHERE `%s` = ?"
SelectSqlTemplate = "SELECT %s FROM %s WHERE `%s` IN %s"
)
type BuildUndoSql func(undoLog sqlUndoLog) string
func DeleteBuildUndoSql(undoLog sqlUndoLog) string {
beforeImage := undoLog.BeforeImage
beforeImageRows := beforeImage.Rows
if beforeImageRows == nil || len(beforeImageRows) == 0 {
return ""
}
row := beforeImageRows[0]
fields := row.NonPrimaryKeys()
pkField := row.PrimaryKeys()[0]
// PK is at last one.
fields = append(fields, pkField)
var sbCols, sbVals strings.Builder
var size = len(fields)
for i, field := range fields {
fmt.Fprintf(&sbCols, "`%s`", field.Name)
fmt.Fprint(&sbVals, "?")
if i < size-1 {
fmt.Fprint(&sbCols, ", ")
fmt.Fprint(&sbVals, ", ")
}
}
insertColumns := sbCols.String()
insertValues := sbVals.String()
return fmt.Sprintf(InsertSqlTemplate, undoLog.TableName, insertColumns, insertValues)
}
func InsertBuildUndoSql(undoLog sqlUndoLog) string {
afterImage := undoLog.AfterImage
afterImageRows := afterImage.Rows
if afterImageRows == nil || len(afterImageRows) == 0 {
return ""
}
row := afterImageRows[0]
pkField := row.PrimaryKeys()[0]
return fmt.Sprintf(DeleteSqlTemplate, undoLog.TableName, pkField.Name)
}
func UpdateBuildUndoSql(undoLog sqlUndoLog) string {
beforeImage := undoLog.BeforeImage
beforeImageRows := beforeImage.Rows
if beforeImageRows == nil || len(beforeImageRows) == 0 {
return ""
}
row := beforeImageRows[0]
nonPkFields := row.NonPrimaryKeys()
pkField := row.PrimaryKeys()[0]
var sb strings.Builder
var size = len(nonPkFields)
for i, field := range nonPkFields {
fmt.Fprintf(&sb, "`%s` = ?", field.Name)
if i < size-1 {
fmt.Fprint(&sb, ", ")
}
}
updateColumns := sb.String()
return fmt.Sprintf(UpdateSqlTemplate, undoLog.TableName, updateColumns, pkField.Name)
}
type MysqlUndoExecutor struct {
sqlUndoLog sqlUndoLog
}
func NewMysqlUndoExecutor(undoLog sqlUndoLog) MysqlUndoExecutor {
return MysqlUndoExecutor{sqlUndoLog: undoLog}
}
func (executor MysqlUndoExecutor) Execute(conn *mysqlConn) error {
goOn, err := executor.dataValidationAndGoOn(conn)
if err != nil {
return err
}
if !goOn {
return nil
}
var undoSql string
var undoRows schema.TableRecords
switch executor.sqlUndoLog.SqlType {
case SQLType_INSERT:
undoSql = InsertBuildUndoSql(executor.sqlUndoLog)
undoRows = *executor.sqlUndoLog.AfterImage
break
case SQLType_DELETE:
undoSql = DeleteBuildUndoSql(executor.sqlUndoLog)
undoRows = *executor.sqlUndoLog.BeforeImage
break
case SQLType_UPDATE:
undoSql = UpdateBuildUndoSql(executor.sqlUndoLog)
undoRows = *executor.sqlUndoLog.BeforeImage
break
default:
panic(errors.Errorf("unsupport sql type:%s", executor.sqlUndoLog.SqlType.String()))
}
if undoSql == "" {
return nil
}
// PK is at last one.
// INSERT INTO a (x, y, z, pk) VALUES (?, ?, ?, ?)
// UPDATE a SET x=?, y=?, z=? WHERE pk = ?
// DELETE FROM a WHERE pk = ?
for i := len(undoRows.Rows) - 1; i >= 0; i-- {
row := undoRows.Rows[i]
var args = make([]driver.Value, 0)
var pkValue interface{}
for _, field := range row.Fields {
if field.KeyType == schema.PRIMARY_KEY {
pkValue = field.Value
} else {
if executor.sqlUndoLog.SqlType != SQLType_INSERT {
args = append(args, field.Value)
}
}
}
args = append(args, pkValue)
_, err = conn.execAlways(undoSql, args)
if err != nil {
return err
}
}
return nil
}
func (executor MysqlUndoExecutor) dataValidationAndGoOn(conn *mysqlConn) (bool, error) {
if executor.sqlUndoLog.BeforeImage != nil && executor.sqlUndoLog.AfterImage == nil {
return true, nil
}
beforeEqualsAfterResult := cmp.Equal(executor.sqlUndoLog.BeforeImage, executor.sqlUndoLog.AfterImage)
if beforeEqualsAfterResult {
return false, nil
}
currentRecords, err := executor.queryCurrentRecords(conn)
if err != nil {
return false, err
}
afterEqualsCurrentResult := cmp.Equal(executor.sqlUndoLog.AfterImage, currentRecords)
if !afterEqualsCurrentResult {
// If current data is not equivalent to the after data, then compare the current data with the before
// data, too. No need continue to undo if current data is equivalent to the before data snapshot
beforeEqualsCurrentResult := cmp.Equal(executor.sqlUndoLog.BeforeImage, currentRecords)
if beforeEqualsCurrentResult {
return false, nil
} else {
oldRows, _ := json.Marshal(executor.sqlUndoLog.AfterImage.Rows)
newRows, _ := json.Marshal(currentRecords.Rows)
log.Errorf("check dirty datas failed, old and new data are not equal, tableName:[%s], oldRows:[%s], newRows:[%s].",
executor.sqlUndoLog.TableName, string(oldRows), string(newRows))
return false, errors.New("Has dirty records when undo.")
}
}
return true, nil
}
func (executor MysqlUndoExecutor) queryCurrentRecords(conn *mysqlConn) (*schema.TableRecords, error) {
undoRecords := executor.sqlUndoLog.GetUndoRows()
tableMeta := undoRecords.TableMeta
pkName := tableMeta.GetPKName()
pkFields := undoRecords.PKFields()
if pkFields == nil || len(pkFields) == 0 {
return nil, nil
}
var pkValues = make([]driver.Value, 0)
for _, field := range pkFields {
pkValues = append(pkValues, field.Value)
}
var b strings.Builder
var i = 0
columnCount := len(tableMeta.Columns)
for _, columnName := range tableMeta.Columns {
fmt.Fprint(&b, CheckAndReplace(columnName))
i = i + 1
if i < columnCount {
fmt.Fprint(&b, ",")
} else {
fmt.Fprint(&b, " ")
}
}
inCondition := appendInParam(len(pkValues))
selectSql := fmt.Sprintf(SelectSqlTemplate, b.String(), tableMeta.TableName, pkName, inCondition)
rows, err := conn.prepareQuery(selectSql, pkValues)
if err != nil {
return nil, err
}
return buildRecords(tableMeta, rows), nil
}