-
Notifications
You must be signed in to change notification settings - Fork 269
/
schema_test_helper.go
299 lines (265 loc) · 9.4 KB
/
schema_test_helper.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
// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package entry
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
ticonfig "github.com/pingcap/tidb/pkg/config"
tiddl "github.com/pingcap/tidb/pkg/ddl"
"github.com/pingcap/tidb/pkg/domain"
"github.com/pingcap/tidb/pkg/kv"
timeta "github.com/pingcap/tidb/pkg/meta"
timodel "github.com/pingcap/tidb/pkg/parser/model"
"github.com/pingcap/tidb/pkg/session"
"github.com/pingcap/tidb/pkg/store/mockstore"
"github.com/pingcap/tidb/pkg/testkit"
"github.com/pingcap/tiflow/cdc/model"
"github.com/pingcap/tiflow/pkg/config"
"github.com/pingcap/tiflow/pkg/filter"
"github.com/pingcap/tiflow/pkg/integrity"
"github.com/pingcap/tiflow/pkg/spanz"
"github.com/pingcap/tiflow/pkg/util"
"github.com/stretchr/testify/require"
"github.com/tikv/client-go/v2/oracle"
)
// SchemaTestHelper is a test helper for schema which creates an internal tidb instance to generate DDL jobs with meta information
type SchemaTestHelper struct {
t testing.TB
tk *testkit.TestKit
storage kv.Storage
domain *domain.Domain
schemaStorage SchemaStorage
mounter Mounter
filter filter.Filter
}
// NewSchemaTestHelperWithReplicaConfig creates a SchemaTestHelper
// by using the given replica config.
func NewSchemaTestHelperWithReplicaConfig(
t testing.TB, replicaConfig *config.ReplicaConfig,
) *SchemaTestHelper {
store, err := mockstore.NewMockStore()
require.NoError(t, err)
ticonfig.UpdateGlobal(func(conf *ticonfig.Config) {
conf.AlterPrimaryKey = true
})
session.SetSchemaLease(0)
session.DisableStats4Test()
domain, err := session.BootstrapSession(store)
require.NoError(t, err)
domain.SetStatsUpdating(true)
tk := testkit.NewTestKit(t, store)
if replicaConfig.Integrity.IntegrityCheckLevel == integrity.CheckLevelCorrectness {
tk.MustExec("set global tidb_enable_row_level_checksum = 1")
tk.Session().GetSessionVars().EnableRowLevelChecksum = true
}
filter, err := filter.NewFilter(replicaConfig, "")
require.NoError(t, err)
ver, err := store.CurrentVersion(oracle.GlobalTxnScope)
require.NoError(t, err)
changefeedID := model.DefaultChangeFeedID("changefeed-testkit")
schemaStorage, err := NewSchemaStorage(
store, ver.Ver, replicaConfig.ForceReplicate,
changefeedID, util.RoleTester, filter)
require.NoError(t, err)
mounter := NewMounter(schemaStorage, changefeedID, time.Local,
filter, replicaConfig.Integrity)
return &SchemaTestHelper{
t: t,
tk: tk,
storage: store,
domain: domain,
filter: filter,
schemaStorage: schemaStorage,
mounter: mounter,
}
}
// NewSchemaTestHelper creates a SchemaTestHelper
func NewSchemaTestHelper(t testing.TB) *SchemaTestHelper {
return NewSchemaTestHelperWithReplicaConfig(t, config.GetDefaultReplicaConfig())
}
// DDL2Job executes the DDL stmt and returns the DDL job
func (s *SchemaTestHelper) DDL2Job(ddl string) *timodel.Job {
s.tk.MustExec(ddl)
jobs, err := tiddl.GetLastNHistoryDDLJobs(s.GetCurrentMeta(), 1)
require.Nil(s.t, err)
require.Len(s.t, jobs, 1)
// Set State from Synced to Done.
// Because jobs are put to history queue after TiDB alter its state from
// Done to Synced.
jobs[0].State = timodel.JobStateDone
res := jobs[0]
if res.Type != timodel.ActionRenameTables {
return res
}
// the RawArgs field in job fetched from tidb snapshot meta is incorrent,
// so we manually construct `job.RawArgs` to do the workaround.
// we assume the old schema name is same as the new schema name here.
// for example, "ALTER TABLE RENAME test.t1 TO test.t1, test.t2 to test.t22", schema name is "test"
schema := strings.Split(strings.Split(strings.Split(res.Query, ",")[1], " ")[1], ".")[0]
tableNum := len(res.BinlogInfo.MultipleTableInfos)
oldSchemaIDs := make([]int64, tableNum)
for i := 0; i < tableNum; i++ {
oldSchemaIDs[i] = res.SchemaID
}
oldTableIDs := make([]int64, tableNum)
for i := 0; i < tableNum; i++ {
oldTableIDs[i] = res.BinlogInfo.MultipleTableInfos[i].ID
}
newTableNames := make([]timodel.CIStr, tableNum)
for i := 0; i < tableNum; i++ {
newTableNames[i] = res.BinlogInfo.MultipleTableInfos[i].Name
}
oldSchemaNames := make([]timodel.CIStr, tableNum)
for i := 0; i < tableNum; i++ {
oldSchemaNames[i] = timodel.NewCIStr(schema)
}
newSchemaIDs := oldSchemaIDs
args := []interface{}{
oldSchemaIDs, newSchemaIDs,
newTableNames, oldTableIDs, oldSchemaNames,
}
rawArgs, err := json.Marshal(args)
require.NoError(s.t, err)
res.RawArgs = rawArgs
return res
}
// DDL2Jobs executes the DDL statement and return the corresponding DDL jobs.
// It is mainly used for "DROP TABLE" and "DROP VIEW" statement because
// multiple jobs will be generated after executing these two types of
// DDL statements.
func (s *SchemaTestHelper) DDL2Jobs(ddl string, jobCnt int) []*timodel.Job {
s.tk.MustExec(ddl)
jobs, err := tiddl.GetLastNHistoryDDLJobs(s.GetCurrentMeta(), jobCnt)
require.Nil(s.t, err)
require.Len(s.t, jobs, jobCnt)
// Set State from Synced to Done.
// Because jobs are put to history queue after TiDB alter its state from
// Done to Synced.
for i := range jobs {
jobs[i].State = timodel.JobStateDone
}
return jobs
}
// DML2Event execute the dml and return the corresponding row changed event.
// caution: it does not support `delete` since the key value cannot be found
// after the query executed.
func (s *SchemaTestHelper) DML2Event(dml string, schema, table string) *model.RowChangedEvent {
s.tk.MustExec(dml)
tableInfo, ok := s.schemaStorage.GetLastSnapshot().TableByName(schema, table)
require.True(s.t, ok)
key, value := s.getLastKeyValue(tableInfo.ID)
ts := s.schemaStorage.GetLastSnapshot().CurrentTs()
rawKV := &model.RawKVEntry{
OpType: model.OpTypePut,
Key: key,
Value: value,
OldValue: nil,
StartTs: ts - 1,
CRTs: ts + 1,
}
polymorphicEvent := model.NewPolymorphicEvent(rawKV)
err := s.mounter.DecodeEvent(context.Background(), polymorphicEvent)
require.NoError(s.t, err)
return polymorphicEvent.Row
}
func (s *SchemaTestHelper) getLastKeyValue(tableID int64) (key, value []byte) {
txn, err := s.storage.Begin()
require.NoError(s.t, err)
defer txn.Rollback() //nolint:errcheck
start, end := spanz.GetTableRange(tableID)
iter, err := txn.Iter(start, end)
require.NoError(s.t, err)
defer iter.Close()
for iter.Valid() {
key = iter.Key()
value = iter.Value()
err = iter.Next()
require.NoError(s.t, err)
}
return key, value
}
// DDL2Event executes the DDL and return the corresponding event.
func (s *SchemaTestHelper) DDL2Event(ddl string) *model.DDLEvent {
s.tk.MustExec(ddl)
jobs, err := tiddl.GetLastNHistoryDDLJobs(s.GetCurrentMeta(), 1)
require.NoError(s.t, err)
require.Len(s.t, jobs, 1)
// Set State from Synced to Done.
// Because jobs are put to history queue after TiDB alter its state from
// Done to Synced.
jobs[0].State = timodel.JobStateDone
res := jobs[0]
if res.Type == timodel.ActionRenameTables {
// the RawArgs field in job fetched from tidb snapshot meta is incorrent,
// so we manually construct `job.RawArgs` to do the workaround.
// we assume the old schema name is same as the new schema name here.
// for example, "ALTER TABLE RENAME test.t1 TO test.t1, test.t2 to test.t22", schema name is "test"
schema := strings.Split(strings.Split(strings.Split(res.Query, ",")[1], " ")[1], ".")[0]
tableNum := len(res.BinlogInfo.MultipleTableInfos)
oldSchemaIDs := make([]int64, tableNum)
for i := 0; i < tableNum; i++ {
oldSchemaIDs[i] = res.SchemaID
}
oldTableIDs := make([]int64, tableNum)
for i := 0; i < tableNum; i++ {
oldTableIDs[i] = res.BinlogInfo.MultipleTableInfos[i].ID
}
newTableNames := make([]timodel.CIStr, tableNum)
for i := 0; i < tableNum; i++ {
newTableNames[i] = res.BinlogInfo.MultipleTableInfos[i].Name
}
oldSchemaNames := make([]timodel.CIStr, tableNum)
for i := 0; i < tableNum; i++ {
oldSchemaNames[i] = timodel.NewCIStr(schema)
}
newSchemaIDs := oldSchemaIDs
args := []interface{}{
oldSchemaIDs, newSchemaIDs,
newTableNames, oldTableIDs, oldSchemaNames,
}
rawArgs, err := json.Marshal(args)
require.NoError(s.t, err)
res.RawArgs = rawArgs
}
err = s.schemaStorage.HandleDDLJob(res)
require.NoError(s.t, err)
ver, err := s.storage.CurrentVersion(oracle.GlobalTxnScope)
require.NoError(s.t, err)
s.schemaStorage.AdvanceResolvedTs(ver.Ver)
ctx := context.Background()
events, err := s.schemaStorage.BuildDDLEvents(ctx, res)
require.NoError(s.t, err)
return events[0]
}
// Storage returns the tikv storage
func (s *SchemaTestHelper) Storage() kv.Storage {
return s.storage
}
// Tk returns the TestKit
func (s *SchemaTestHelper) Tk() *testkit.TestKit {
return s.tk
}
// GetCurrentMeta return the current meta snapshot
func (s *SchemaTestHelper) GetCurrentMeta() *timeta.Meta {
ver, err := s.storage.CurrentVersion(oracle.GlobalTxnScope)
require.Nil(s.t, err)
return timeta.NewSnapshotMeta(s.storage.GetSnapshot(ver))
}
// Close closes the helper
func (s *SchemaTestHelper) Close() {
s.domain.Close()
s.storage.Close() //nolint:errcheck
}