diff --git a/OWNERS b/OWNERS index 76864831d6..755182faed 100644 --- a/OWNERS +++ b/OWNERS @@ -3,7 +3,7 @@ approvers: - 3AceShowHand - asddongmen - CharlesCheung96 - - flowbehappy + - nongfushanquan - hicqu - hongyunyan - kennytm diff --git a/OWNERS_ALIASES b/OWNERS_ALIASES index dc4c537124..8d424557b7 100644 --- a/OWNERS_ALIASES +++ b/OWNERS_ALIASES @@ -3,6 +3,5 @@ aliases: - nongfushanquan - likidu - ginkgoch - # - lidezhu # When the first version is GA, we will enable the following members. # - yudongusa diff --git a/api/v2/changefeed.go b/api/v2/changefeed.go index 4175a7c82e..aa0a3b06b9 100644 --- a/api/v2/changefeed.go +++ b/api/v2/changefeed.go @@ -27,6 +27,7 @@ import ( "github.com/pingcap/kvproto/pkg/keyspacepb" "github.com/pingcap/log" "github.com/pingcap/ticdc/api/middleware" + "github.com/pingcap/ticdc/downstreamadapter/routing" "github.com/pingcap/ticdc/downstreamadapter/sink" "github.com/pingcap/ticdc/downstreamadapter/sink/columnselector" "github.com/pingcap/ticdc/downstreamadapter/sink/eventrouter" @@ -45,7 +46,7 @@ import ( "github.com/pingcap/ticdc/pkg/txnutil/gc" "github.com/pingcap/ticdc/pkg/util" "github.com/pingcap/ticdc/pkg/version" - tidbkv "github.com/pingcap/tidb/pkg/kv" + "github.com/pingcap/tidb/pkg/kv" "github.com/tikv/client-go/v2/oracle" pd "github.com/tikv/pd/client" "go.uber.org/zap" @@ -217,7 +218,7 @@ func (h *OpenAPIV2) CreateChangefeed(c *gin.Context) { cancel() }() - var kvStorage tidbkv.Storage + var kvStorage kv.Storage keyspaceManager := appcontext.GetService[keyspace.Manager](appcontext.KeyspaceManager) kvStorage, err = keyspaceManager.GetStorage(ctx, keyspaceName) if err != nil { @@ -245,7 +246,7 @@ func (h *OpenAPIV2) CreateChangefeed(c *gin.Context) { allTables []common.TableName ) protocol, _ := config.ParseSinkProtocolFromString(util.GetOrZero(replicaCfg.Sink.Protocol)) - ineligibleTables, eligibleTables, allTables, err = getVerifiedTables(ctx, replicaCfg, kvStorage, cfg.StartTs, scheme, topic, protocol) + ineligibleTables, eligibleTables, allTables, err = getVerifiedTables(ctx, changefeedID, replicaCfg, kvStorage, cfg.StartTs, scheme, topic, protocol) if err != nil { _ = c.Error(err) return @@ -454,7 +455,8 @@ func (h *OpenAPIV2) VerifyTable(c *gin.Context) { _ = c.Error(err) return } - ineligibleTables, eligibleTables, allTables, err := getVerifiedTables(ctx, replicaCfg, kvStorage, cfg.StartTs, scheme, topic, protocol) + changefeedID := common.NewChangeFeedIDWithName(cfg.ID, keyspaceName) + ineligibleTables, eligibleTables, allTables, err := getVerifiedTables(ctx, changefeedID, replicaCfg, kvStorage, cfg.StartTs, scheme, topic, protocol) if err != nil { _ = c.Error(err) return @@ -817,14 +819,14 @@ func (h *OpenAPIV2) ResumeChangefeed(c *gin.Context) { } protocol, _ := config.ParseSinkProtocolFromString(util.GetOrZero(cfInfo.Config.Sink.Protocol)) - var kvStorage tidbkv.Storage + var kvStorage kv.Storage keyspaceManager := appcontext.GetService[keyspace.Manager](appcontext.KeyspaceManager) kvStorage, err = keyspaceManager.GetStorage(ctx, keyspaceName) if err != nil { _ = c.Error(err) return } - ineligibleTables, eligibleTables, allTables, err = getVerifiedTables(ctx, cfInfo.Config, kvStorage, newCheckpointTs, scheme, topic, protocol) + ineligibleTables, eligibleTables, allTables, err = getVerifiedTables(ctx, cfInfo.ChangefeedID, cfInfo.Config, kvStorage, newCheckpointTs, scheme, topic, protocol) if err != nil { _ = c.Error(err) return @@ -981,7 +983,7 @@ func (h *OpenAPIV2) UpdateChangefeed(c *gin.Context) { } // use checkpointTs get snapshot from kv storage - ineligibleTables, eligibleTables, allTables, err = getVerifiedTables(ctx, oldCfInfo.Config, kvStorage, status.CheckpointTs, scheme, topic, protocol) + ineligibleTables, eligibleTables, allTables, err = getVerifiedTables(ctx, oldCfInfo.ChangefeedID, oldCfInfo.Config, kvStorage, status.CheckpointTs, scheme, topic, protocol) if err != nil { _ = c.Error(errors.ErrChangefeedUpdateRefused.GenWithStackByCause(err)) return @@ -1658,22 +1660,19 @@ func (h *OpenAPIV2) synced(c *gin.Context) { func getVerifiedTables( ctx context.Context, + changefeedID common.ChangeFeedID, replicaConfig *config.ReplicaConfig, - storage tidbkv.Storage, startTs uint64, + storage kv.Storage, startTs uint64, scheme string, topic string, protocol config.Protocol, ) ([]common.TableName, []common.TableName, []common.TableName, error) { f, err := filter.NewFilter(replicaConfig.Filter, "", util.GetOrZero(replicaConfig.CaseSensitive), util.GetOrZero(replicaConfig.ForceReplicate)) if err != nil { return nil, nil, nil, err } - tableInfos, ineligibleTables, eligibleTables, allTables, err := schemastore. - VerifyTables(f, storage, startTs) + tableInfos, ineligibleTables, eligibleTables, allTables, err := schemastore.VerifyTables(f, storage, startTs) if err != nil { return nil, nil, nil, err } - log.Info("verifyTables completed", - zap.Int("tableCount", len(tableInfos)), - zap.Uint64("startTs", startTs)) err = f.Verify(tableInfos) if err != nil { @@ -1684,6 +1683,10 @@ func getVerifiedTables( return nil, nil, nil, err } + if err := verifyRouteConflict(changefeedID, eligibleTables, ineligibleTables, replicaConfig); err != nil { + return nil, nil, nil, err + } + if ctx.Err() != nil { return nil, nil, nil, errors.Trace(ctx.Err()) } @@ -1699,7 +1702,7 @@ func verifyTablesForSink( tableInfos []*common.TableInfo, ) error { if config.IsStorageScheme(scheme) { - selectors, err := columnselector.New(replicaConfig.Sink) + selectors, err := columnselector.New(replicaConfig.Sink, util.GetOrZero(replicaConfig.CaseSensitive)) if err != nil { return err } @@ -1711,7 +1714,7 @@ func verifyTablesForSink( } isAvroLike := protocol == config.ProtocolAvro || protocol == config.ProtocolDebeziumAvro - eventRouter, err := eventrouter.NewEventRouter(replicaConfig.Sink, topic, config.IsPulsarScheme(scheme), isAvroLike) + eventRouter, err := eventrouter.NewEventRouter(replicaConfig.Sink, util.GetOrZero(replicaConfig.CaseSensitive), topic, config.IsPulsarScheme(scheme), isAvroLike) if err != nil { return err } @@ -1719,13 +1722,39 @@ func verifyTablesForSink( return err } - selectors, err := columnselector.New(replicaConfig.Sink) + selectors, err := columnselector.New(replicaConfig.Sink, util.GetOrZero(replicaConfig.CaseSensitive)) if err != nil { return err } return selectors.VerifyTables(tableInfos, eventRouter) } +func verifyRouteConflict( + changefeedID common.ChangeFeedID, + eligibleTables []common.TableName, + ineligibleTables []common.TableName, + replicaCfg *config.ReplicaConfig, +) error { + if replicaCfg == nil || replicaCfg.Sink == nil || len(replicaCfg.Sink.DispatchRules) == 0 { + return nil + } + if util.GetOrZero(replicaCfg.ForceReplicate) { + return routing.ValidateNoStaticRouteConflict( + changefeedID, + util.GetOrZero(replicaCfg.CaseSensitive), + replicaCfg.Sink.DispatchRules, + eligibleTables, + ineligibleTables, + ) + } + return routing.ValidateNoStaticRouteConflict( + changefeedID, + util.GetOrZero(replicaCfg.CaseSensitive), + replicaCfg.Sink.DispatchRules, + eligibleTables, + ) +} + func GetKeyspaceValueWithDefault(c *gin.Context) string { if kerneltype.IsClassic() { return common.DefaultKeyspaceName diff --git a/api/v2/changefeed_test.go b/api/v2/changefeed_test.go new file mode 100644 index 0000000000..63174b8a09 --- /dev/null +++ b/api/v2/changefeed_test.go @@ -0,0 +1,184 @@ +// Copyright 2026 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 v2 + +import ( + "testing" + + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/errors" + "github.com/pingcap/ticdc/pkg/util" + "github.com/pingcap/tidb/pkg/meta/model" + "github.com/pingcap/tidb/pkg/parser/ast" + "github.com/pingcap/tidb/pkg/parser/mysql" + "github.com/pingcap/tidb/pkg/types" + "github.com/stretchr/testify/require" +) + +func TestVerifyRouteConflict(t *testing.T) { + t.Parallel() + + changefeedID := common.NewChangeFeedIDWithName("test-changefeed", common.DefaultKeyspaceName) + replicaCfg := config.GetDefaultReplicaConfig() + replicaCfg.Sink.DispatchRules = []*config.DispatchRule{ + {Matcher: []string{"db1.*"}, TargetSchema: "archive", TargetTable: "{table}"}, + {Matcher: []string{"db2.*"}, TargetSchema: "archive", TargetTable: "{table}"}, + } + + eligibleTables := []common.TableName{{Schema: "db1", Table: "orders"}} + ineligibleTables := []common.TableName{{Schema: "db2", Table: "orders"}} + + replicaCfg.ForceReplicate = util.AddressOf(false) + replicaCfg.IgnoreIneligibleTable = util.AddressOf(true) + require.NoError(t, verifyRouteConflict(changefeedID, eligibleTables, ineligibleTables, replicaCfg)) + + replicaCfg.IgnoreIneligibleTable = util.AddressOf(false) + require.NoError(t, verifyRouteConflict(changefeedID, eligibleTables, ineligibleTables, replicaCfg)) + + err := verifyRouteConflict( + changefeedID, + []common.TableName{{Schema: "db1", Table: "orders"}, {Schema: "db2", Table: "orders"}}, + ineligibleTables, + replicaCfg, + ) + require.Error(t, err) + require.True(t, errors.ErrTableRouteConflict.Equal(err)) + + replicaCfg.ForceReplicate = util.AddressOf(true) + err = verifyRouteConflict(changefeedID, eligibleTables, ineligibleTables, replicaCfg) + require.Error(t, err) + require.True(t, errors.ErrTableRouteConflict.Equal(err)) + require.Contains(t, err.Error(), "target `archive`.`orders`") + require.Contains(t, err.Error(), "source `db1`.`orders`") + require.Contains(t, err.Error(), "source `db2`.`orders`") + + replicaCfg.ForceReplicate = util.AddressOf(false) + replicaCfg.Sink.DispatchRules = []*config.DispatchRule{ + {Matcher: []string{"db2.*"}, TargetSchema: "db1", TargetTable: "{table}"}, + } + err = verifyRouteConflict( + changefeedID, + []common.TableName{{Schema: "db1", Table: "orders"}, {Schema: "db2", Table: "orders"}}, + nil, + replicaCfg, + ) + require.Error(t, err) + require.True(t, errors.ErrTableRouteConflict.Equal(err)) + require.Contains(t, err.Error(), "target `db1`.`orders`") + require.Contains(t, err.Error(), "source `db1`.`orders`") + require.Contains(t, err.Error(), "source `db2`.`orders`") +} + +func TestVerifyRouteConflictCaseSensitive(t *testing.T) { + for _, tc := range []struct { + name string + caseSensitive *bool + }{ + {name: "unset"}, + {name: "insensitive", caseSensitive: util.AddressOf(false)}, + {name: "sensitive", caseSensitive: util.AddressOf(true)}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := config.GetDefaultReplicaConfig() + cfg.CaseSensitive = tc.caseSensitive + cfg.Sink.DispatchRules = []*config.DispatchRule{{Matcher: []string{"Sales.*"}, TargetSchema: "archive"}} + cfg = ToAPIReplicaConfig(cfg).ToInternalReplicaConfig() + runtimeCfg := (&config.ChangeFeedInfo{Config: cfg}).ToChangefeedConfig() + require.Equal(t, util.GetOrZero(tc.caseSensitive), runtimeCfg.CaseSensitive) + err := verifyRouteConflict(common.NewChangefeedID4Test("test", tc.name), + []common.TableName{{Schema: "sales", Table: "orders"}, {Schema: "archive", Table: "orders"}}, nil, cfg) + if util.GetOrZero(tc.caseSensitive) { + require.NoError(t, err) + } else { + require.True(t, errors.ErrTableRouteConflict.Equal(err), "%v", err) + } + }) + } +} + +func TestVerifyTablesForSinkCaseSensitive(t *testing.T) { + idType := types.NewFieldType(mysql.TypeLong) + idType.AddFlag(mysql.PriKeyFlag | mysql.NotNullFlag) + table := common.WrapTableInfo("sales", &model.TableInfo{ + ID: 1, Name: ast.NewCIStr("orders"), PKIsHandle: true, + Columns: []*model.ColumnInfo{{ID: 1, Name: ast.NewCIStr("id"), State: model.StatePublic, FieldType: *idType}}, + }) + for _, tc := range []struct { + name string + caseSensitive *bool + }{ + {name: "unset"}, + {name: "insensitive", caseSensitive: util.AddressOf(false)}, + {name: "sensitive", caseSensitive: util.AddressOf(true)}, + } { + t.Run(tc.name, func(t *testing.T) { + for _, scheme := range []string{config.FileScheme, config.KafkaScheme, config.PulsarScheme} { + t.Run(scheme, func(t *testing.T) { + cfg := config.GetDefaultReplicaConfig() + cfg.CaseSensitive = tc.caseSensitive + cfg.Sink.ColumnSelectors = []*config.ColumnSelector{{Matcher: []string{"Sales.*"}, Columns: []string{"*", "!id"}}} + cfg = ToAPIReplicaConfig(cfg).ToInternalReplicaConfig() + err := verifyTablesForSink(cfg, scheme, "default-topic", config.ProtocolCanalJSON, []*common.TableInfo{table}) + if util.GetOrZero(tc.caseSensitive) { + require.NoError(t, err) + } else { + require.True(t, errors.ErrColumnSelectorFailed.Equal(err), "%v", err) + } + if !config.IsMQScheme(scheme) { + return + } + cfg.Sink.ColumnSelectors = nil + cfg.Sink.DispatchRules = []*config.DispatchRule{{Matcher: []string{"Sales.*"}, PartitionRule: "index-value", IndexName: "missing_index"}} + err = verifyTablesForSink(cfg, scheme, "default-topic", config.ProtocolCanalJSON, []*common.TableInfo{table}) + if util.GetOrZero(tc.caseSensitive) { + require.NoError(t, err) + } else { + require.True(t, errors.ErrDispatcherFailed.Equal(err), "%v", err) + } + }) + } + }) + } +} + +func TestRouteMatcherValidation(t *testing.T) { + changefeedID := common.NewChangeFeedIDWithName("test", common.DefaultKeyspaceName) + for _, tc := range []struct { + name string + eligible []common.TableName + ineligible []common.TableName + }{ + {name: "empty"}, + {name: "eligible", eligible: []common.TableName{{Schema: "sales", Table: "orders"}}}, + {name: "ineligible", ineligible: []common.TableName{{Schema: "sales", Table: "orders"}}}, + } { + t.Run(tc.name, func(t *testing.T) { + for _, forceReplicate := range []bool{false, true} { + cfg := config.GetDefaultReplicaConfig() + cfg.ForceReplicate = util.AddressOf(forceReplicate) + cfg.Sink.DispatchRules = []*config.DispatchRule{{ + Matcher: []string{"["}, TargetSchema: "archive", + }} + err := verifyRouteConflict(changefeedID, tc.eligible, tc.ineligible, cfg) + code, ok := errors.RFCCode(err) + require.True(t, ok) + require.Equal(t, errors.ErrInvalidTableRoutingRule.RFCCode(), code) + + cfg.Sink.DispatchRules[0].Matcher = []string{"sales.*"} + require.NoError(t, verifyRouteConflict(changefeedID, tc.eligible, tc.ineligible, cfg)) + } + }) + } +} diff --git a/api/v2/model.go b/api/v2/model.go index d19c31d6f4..e1d87063ce 100644 --- a/api/v2/model.go +++ b/api/v2/model.go @@ -342,6 +342,8 @@ func (c *ReplicaConfig) toInternalReplicaConfigWithOriginConfig( IndexName: rule.IndexName, Columns: rule.Columns, TopicRule: rule.TopicRule, + TargetSchema: rule.TargetSchema, + TargetTable: rule.TargetTable, }) } var columnSelectors []*config.ColumnSelector @@ -702,6 +704,8 @@ func ToAPIReplicaConfig(c *config.ReplicaConfig) *ReplicaConfig { IndexName: rule.IndexName, Columns: rule.Columns, TopicRule: rule.TopicRule, + TargetSchema: rule.TargetSchema, + TargetTable: rule.TargetTable, }) } var columnSelectors []*ColumnSelector @@ -1194,6 +1198,21 @@ type DispatchRule struct { IndexName string `json:"index,omitempty"` Columns []string `json:"columns,omitempty"` TopicRule string `json:"topic,omitempty"` + + // TargetSchema sets the routed downstream schema name. + // Leave it empty to keep the source schema name. + // For example, if the source table is `sales`.`orders`, `target-schema = "sales_bak"` + // writes to `sales_bak`.`orders`. + // You can also use placeholders. For example, `target-schema = "{schema}_bak"` + // the target schema becomes `sales_bak`. + TargetSchema string `json:"target-schema,omitempty"` + // TargetTable sets the routed downstream table name. + // Leave it empty to keep the source table name. + // For example, if the source table is `sales`.`orders`, `target-table = "orders_bak"` + // writes to `sales`.`orders_bak`. + // You can also use placeholders. For example, `target-table = "{schema}_{table}"` + // becomes `sales_orders`. + TargetTable string `json:"target-table,omitempty"` } // ColumnSelector represents a column selector for a table. diff --git a/cmd/kafka-consumer/option.go b/cmd/kafka-consumer/option.go index 0113d0d3f3..8ded1ea222 100644 --- a/cmd/kafka-consumer/option.go +++ b/cmd/kafka-consumer/option.go @@ -41,8 +41,9 @@ type option struct { maxMessageBytes int maxBatchSize int - codecConfig *common.Config - sinkConfig *config.SinkConfig + codecConfig *common.Config + sinkConfig *config.SinkConfig + caseSensitive bool timezone string @@ -144,6 +145,7 @@ func (o *option) Adjust(upstreamURIStr string, configFile string) { replicaConfig.Sink.TiDBSourceID = 1 replicaConfig.Sink.Protocol = putil.AddressOf(protocol.String()) o.sinkConfig = replicaConfig.Sink + o.caseSensitive = putil.GetOrZero(replicaConfig.CaseSensitive) o.codecConfig = common.NewConfig(protocol) if err = o.codecConfig.Apply(upstreamURI, replicaConfig.Sink); err != nil { diff --git a/cmd/kafka-consumer/writer.go b/cmd/kafka-consumer/writer.go index 6ac5e0e1a4..3e67ae1aec 100644 --- a/cmd/kafka-consumer/writer.go +++ b/cmd/kafka-consumer/writer.go @@ -120,7 +120,7 @@ func newWriter(ctx context.Context, o *option) *writer { } isAvroLike := o.protocol == config.ProtocolAvro || o.protocol == config.ProtocolDebeziumAvro - eventRouter, err := eventrouter.NewEventRouter(o.sinkConfig, o.topic, false, isAvroLike) + eventRouter, err := eventrouter.NewEventRouter(o.sinkConfig, o.caseSensitive, o.topic, false, isAvroLike) if err != nil { log.Panic("initialize the event router failed", zap.Any("protocol", o.protocol), zap.Any("topic", o.topic), diff --git a/cmd/kafka-consumer/writer_test.go b/cmd/kafka-consumer/writer_test.go index b22c861d71..f0a2809e6d 100644 --- a/cmd/kafka-consumer/writer_test.go +++ b/cmd/kafka-consumer/writer_test.go @@ -297,7 +297,7 @@ func TestWriterWrite_sortsOutOfOrderDMLByWatermark(t *testing.T) { }).Times(2) replicaCfg := config.GetDefaultReplicaConfig() - eventRouter, err := eventrouter.NewEventRouter(replicaCfg.Sink, "test-topic", false, false) + eventRouter, err := eventrouter.NewEventRouter(replicaCfg.Sink, false, "test-topic", false, false) require.NoError(t, err) p := &partitionProgress{ @@ -351,7 +351,7 @@ func TestWriteMessageIgnoresFallbackDMLBelowGlobalWatermark(t *testing.T) { func TestAppendMessageKeepsFallbackDMLAboveGlobalWatermark(t *testing.T) { replicaCfg := config.GetDefaultReplicaConfig() - eventRouter, err := eventrouter.NewEventRouter(replicaCfg.Sink, "test-topic", false, false) + eventRouter, err := eventrouter.NewEventRouter(replicaCfg.Sink, false, "test-topic", false, false) require.NoError(t, err) progress := &partitionProgress{ @@ -383,7 +383,7 @@ func TestAppendRow2GroupKeepsDebeziumPartitionTableFallback(t *testing.T) { } { t.Run(protocol.String(), func(t *testing.T) { replicaCfg := config.GetDefaultReplicaConfig() - eventRouter, err := eventrouter.NewEventRouter(replicaCfg.Sink, "test-topic", false, false) + eventRouter, err := eventrouter.NewEventRouter(replicaCfg.Sink, false, "test-topic", false, false) require.NoError(t, err) w := &writer{ diff --git a/cmd/pulsar-consumer/writer.go b/cmd/pulsar-consumer/writer.go index 74abf91651..910e4847ed 100644 --- a/cmd/pulsar-consumer/writer.go +++ b/cmd/pulsar-consumer/writer.go @@ -112,7 +112,7 @@ func newWriter(ctx context.Context, o *option) *writer { w.progresses[i] = newPartitionProgress(int32(i), decoder) } - eventRouter, err := eventrouter.NewEventRouter(o.replicaConfig.Sink, o.topic, false, o.protocol == config.ProtocolAvro) + eventRouter, err := eventrouter.NewEventRouter(o.replicaConfig.Sink, putil.GetOrZero(o.replicaConfig.CaseSensitive), o.topic, false, o.protocol == config.ProtocolAvro) if err != nil { log.Panic("initialize the event router failed", zap.Any("protocol", o.protocol), zap.Any("topic", o.topic), diff --git a/cmd/storage-consumer/consumer.go b/cmd/storage-consumer/consumer.go index 42081fbc9d..98dbee6f76 100644 --- a/cmd/storage-consumer/consumer.go +++ b/cmd/storage-consumer/consumer.go @@ -124,7 +124,7 @@ func newConsumer(ctx context.Context) (*consumer, error) { if err != nil { return nil, err } - columnSelectors, err := columnselector.New(replicaConfig.Sink) + columnSelectors, err := columnselector.New(replicaConfig.Sink, putil.GetOrZero(replicaConfig.CaseSensitive)) if err != nil { return nil, err } @@ -141,8 +141,9 @@ func newConsumer(ctx context.Context) (*consumer, error) { stdCtx := ctx cfg := &config.ChangefeedConfig{ - SinkURI: downstreamURIStr, - SinkConfig: replicaConfig.Sink, + SinkURI: downstreamURIStr, + SinkConfig: replicaConfig.Sink, + CaseSensitive: putil.GetOrZero(replicaConfig.CaseSensitive), } sink, err := sink.New( stdCtx, diff --git a/coordinator/changefeed/backoff.go b/coordinator/changefeed/backoff.go index 42fed64c68..1a25bb69de 100644 --- a/coordinator/changefeed/backoff.go +++ b/coordinator/changefeed/backoff.go @@ -17,12 +17,12 @@ import ( "time" "github.com/cenkalti/backoff/v4" - "github.com/pingcap/errors" + perrors "github.com/pingcap/errors" "github.com/pingcap/log" "github.com/pingcap/ticdc/heartbeatpb" "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/config" - cerrors "github.com/pingcap/ticdc/pkg/errors" + "github.com/pingcap/ticdc/pkg/errors" "go.uber.org/atomic" "go.uber.org/zap" ) @@ -111,6 +111,29 @@ func (m *Backoff) resetErrRetry() { m.retrying.Store(false) } +func (m *Backoff) checkFailedStatus(status *heartbeatpb.MaintainerStatus) (bool, config.FeedState, *heartbeatpb.RunningError) { + if m.failed.Load() { + return false, config.StateFailed, nil + } + + if err := findFastFailError(status.Err); err != nil { + if m.checkpointTs < status.CheckpointTs { + m.checkpointTs = status.CheckpointTs + } + log.Error("changefeed maintainer report a fast fail error", + zap.Stringer("changefeed", m.id), + zap.Uint64("checkpointTs", m.checkpointTs), + zap.String("node", err.Node), + zap.String("code", err.Code), + zap.String("state", string(config.StateFailed)), + zap.Any("error", err)) + m.failed.Store(true) + return true, config.StateFailed, err + } + + return false, config.StateNormal, nil +} + // CheckStatus checks the current status of a changefeed and determines its state transition. // It takes a MaintainerStatus which contains the current checkpoint timestamp and any errors. // Returns: @@ -120,11 +143,12 @@ func (m *Backoff) resetErrRetry() { // // The method handles several cases: // 1. If the changefeed is marked as failed, returns Failed state -// 2. If checkpoint has advanced (making progress), resets any retry attempts and returns Normal state -// 3. If there are errors and checkpoint hasn't advanced, initiates the retry mechanism +// 2. If a fast-fail error is reported, returns Failed state +// 3. If checkpoint has advanced (making progress), resets any retry attempts and returns Normal state +// 4. If there are errors and checkpoint hasn't advanced, initiates the retry mechanism func (m *Backoff) CheckStatus(status *heartbeatpb.MaintainerStatus) (bool, config.FeedState, *heartbeatpb.RunningError) { - if m.failed.Load() { - return false, config.StateFailed, nil + if changed, state, err := m.checkFailedStatus(status); state == config.StateFailed { + return changed, state, err } if m.checkpointTs < status.CheckpointTs { @@ -182,16 +206,15 @@ func (m *Backoff) StartFinished() { // ShouldFailChangefeed return true if a running error contains a changefeed not retry error. func ShouldFailChangefeed(e *heartbeatpb.RunningError) bool { - return cerrors.ShouldFailChangefeed(errors.New(e.Message + e.Code)) + if e == nil { + return false + } + return errors.ShouldFailChangefeed(errors.New(e.Message + e.Code)) } func (m *Backoff) HandleError(errs []*heartbeatpb.RunningError) (bool, *heartbeatpb.RunningError) { - // if there are a fastFail error in errs, we can just fastFail the changefeed - for _, err := range errs { - if cerrors.IsChangefeedGCFastFailErrorCode(errors.RFCErrorCode(err.Code)) || - ShouldFailChangefeed(err) { - return true, err - } + if err := findFastFailError(errs); err != nil { + return true, err } lastError := errs[len(errs)-1] @@ -225,3 +248,16 @@ func (m *Backoff) HandleError(errs []*heartbeatpb.RunningError) (bool, *heartbea // patch the last error to changefeed info return false, lastError } + +func findFastFailError(errs []*heartbeatpb.RunningError) *heartbeatpb.RunningError { + for _, err := range errs { + if err == nil { + continue + } + if errors.IsChangefeedGCFastFailErrorCode(perrors.RFCErrorCode(err.Code)) || + ShouldFailChangefeed(err) { + return err + } + } + return nil +} diff --git a/coordinator/changefeed/backoff_test.go b/coordinator/changefeed/backoff_test.go index 02437b1052..3fc9a07d69 100644 --- a/coordinator/changefeed/backoff_test.go +++ b/coordinator/changefeed/backoff_test.go @@ -21,6 +21,7 @@ import ( "github.com/pingcap/ticdc/heartbeatpb" "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/errors" "github.com/stretchr/testify/require" ) @@ -130,6 +131,84 @@ func TestErrorReportedWhenRetrying(t *testing.T) { require.True(t, backoffInterval < backoff.backoffInterval) } +func TestTableRoutingErrorsFastFail(t *testing.T) { + tests := []struct { + name string + code string + message string + }{ + { + name: "invalid table routing rule", + code: string(errors.ErrInvalidTableRoutingRule.RFCCode()), + message: "invalid table routing rule", + }, + { + name: "table routing failed", + code: string(errors.ErrTableRoutingFailed.RFCCode()), + message: "table routing failed", + }, + { + name: "table route conflict", + code: string(errors.ErrTableRouteConflict.RFCCode()), + message: "table route conflict", + }, + } + + for _, tc := range tests { + tc := tc + t.Run(tc.name, func(t *testing.T) { + backoff := NewBackoff(common.NewChangeFeedIDWithName("test", common.DefaultKeyspaceName), time.Minute*30, 1) + require.True(t, backoff.ShouldRun()) + + changed, state, err := backoff.CheckStatus(&heartbeatpb.MaintainerStatus{ + CheckpointTs: 1, + Err: []*heartbeatpb.RunningError{ + { + Code: tc.code, + Message: tc.message, + }, + }, + }) + + require.True(t, changed) + require.Equal(t, config.StateFailed, state) + require.NotNil(t, err) + require.False(t, backoff.ShouldRun()) + require.False(t, backoff.retrying.Load()) + }) + } +} + +func TestFastFailErrorWinsOverCheckpointProgress(t *testing.T) { + backoff := NewBackoff(common.NewChangeFeedIDWithName("test", common.DefaultKeyspaceName), time.Minute*30, 1) + require.True(t, backoff.ShouldRun()) + + changed, state, err := backoff.CheckStatus(&heartbeatpb.MaintainerStatus{ + CheckpointTs: 2, + Err: []*heartbeatpb.RunningError{ + { + Code: string(errors.ErrTableRouteConflict.RFCCode()), + Message: "table route conflict", + }, + }, + }) + + require.True(t, changed) + require.Equal(t, config.StateFailed, state) + require.NotNil(t, err) + require.Equal(t, uint64(2), backoff.checkpointTs) + require.False(t, backoff.ShouldRun()) + require.False(t, backoff.retrying.Load()) + + changed, state, err = backoff.CheckStatus(&heartbeatpb.MaintainerStatus{ + CheckpointTs: 3, + }) + require.False(t, changed) + require.Equal(t, config.StateFailed, state) + require.Nil(t, err) + require.Equal(t, uint64(2), backoff.checkpointTs) +} + func TestFailedWhenRetry(t *testing.T) { backoff := NewBackoff(common.NewChangeFeedIDWithName("test", common.DefaultKeyspaceName), time.Second*30, 1) require.True(t, backoff.ShouldRun()) diff --git a/coordinator/changefeed/changefeed.go b/coordinator/changefeed/changefeed.go index 6d866873ca..da4a6c464d 100644 --- a/coordinator/changefeed/changefeed.go +++ b/coordinator/changefeed/changefeed.go @@ -151,30 +151,56 @@ func (c *Changefeed) ShouldRun() bool { // It returns false if the status is not changed // It returns the new state and error if the status is changed func (c *Changefeed) UpdateStatus(newStatus *heartbeatpb.MaintainerStatus) (bool, config.FeedState, *heartbeatpb.RunningError) { + if newStatus == nil { + return false, config.StateNormal, nil + } + old := c.status.Load() failpoint.Inject("CoordinatorDontUpdateChangefeedCheckpoint", func() { newStatus.CheckpointTs = old.CheckpointTs }) - if newStatus != nil && newStatus.CheckpointTs >= old.CheckpointTs { - c.status.Store(newStatus) - if old.BootstrapDone != newStatus.BootstrapDone { - log.Info("Received changefeed status with bootstrapDone", - zap.Stringer("changefeed", c.ID), - zap.Bool("bootstrapDone", newStatus.BootstrapDone)) - return true, config.StateNormal, nil + if newStatus.CheckpointTs < old.CheckpointTs { + if len(newStatus.Err) == 0 { + return false, config.StateNormal, nil } + statusWithMonotonicCheckpoint := *newStatus + statusWithMonotonicCheckpoint.CheckpointTs = old.CheckpointTs + newStatus = &statusWithMonotonicCheckpoint + } - info := c.GetInfo() - // the changefeed reaches the targetTs - if info.TargetTs != 0 && newStatus.CheckpointTs >= info.TargetTs { - return true, config.StateFinished, nil - } + // Bootstrap completion survives maintainer replacement until an explicit resume. + if old.BootstrapDone && !newStatus.BootstrapDone { + statusWithBootstrapDone := *newStatus + statusWithBootstrapDone.BootstrapDone = true + newStatus = &statusWithBootstrapDone + } + c.status.Store(newStatus) + bootstrapChanged := !old.BootstrapDone && newStatus.BootstrapDone + if bootstrapChanged { + // Record accepted bootstrap progress before returning without CheckStatus. + c.backoff.checkpointTs = newStatus.CheckpointTs + } + + changed, state, err := c.backoff.checkFailedStatus(newStatus) + if state == config.StateFailed { + return changed, state, err + } - return c.backoff.CheckStatus(newStatus) + if bootstrapChanged { + log.Info("Received changefeed status with bootstrapDone", + zap.Stringer("changefeed", c.ID), + zap.Bool("bootstrapDone", newStatus.BootstrapDone)) + return true, config.StateNormal, nil } - return false, config.StateNormal, nil + info := c.GetInfo() + // the changefeed reaches the targetTs + if info.TargetTs != 0 && newStatus.CheckpointTs >= info.TargetTs { + return true, config.StateFinished, nil + } + + return c.backoff.CheckStatus(newStatus) } func (c *Changefeed) GetLogCoordinatorResolvedTs() uint64 { diff --git a/coordinator/changefeed/changefeed_test.go b/coordinator/changefeed/changefeed_test.go index e8779f8cb9..febb21451e 100644 --- a/coordinator/changefeed/changefeed_test.go +++ b/coordinator/changefeed/changefeed_test.go @@ -14,11 +14,13 @@ package changefeed import ( + "fmt" "testing" "github.com/pingcap/ticdc/heartbeatpb" "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/errors" "github.com/pingcap/ticdc/pkg/messaging" "github.com/pingcap/ticdc/pkg/node" "github.com/stretchr/testify/require" @@ -90,6 +92,191 @@ func TestChangefeed_UpdateStatus(t *testing.T) { require.Equal(t, newStatus, cf.GetStatus()) } +func TestChangefeedUpdateStatusProcessesErrorsWhenCheckpointRegresses(t *testing.T) { + cfID := common.NewChangeFeedIDWithName("test", common.DefaultKeyspaceName) + info := &config.ChangeFeedInfo{ + SinkURI: "kafka://127.0.0.1:9092", + State: config.StateNormal, + Config: config.GetDefaultReplicaConfig(), + } + cf := NewChangefeed(cfID, info, 200, true) + + regressedStatus := &heartbeatpb.MaintainerStatus{CheckpointTs: 150} + updated, state, err := cf.UpdateStatus(regressedStatus) + require.False(t, updated) + require.Equal(t, config.StateNormal, state) + require.Nil(t, err) + require.Equal(t, uint64(200), cf.GetStatus().CheckpointTs) + + retryableErr := &heartbeatpb.RunningError{ + Node: "node-1", + Code: "CDC:ErrChangefeedRetryable", + Message: "retryable error", + } + regressedStatus = &heartbeatpb.MaintainerStatus{ + CheckpointTs: 150, + Err: []*heartbeatpb.RunningError{retryableErr}, + } + updated, state, err = cf.UpdateStatus(regressedStatus) + require.True(t, updated) + require.Equal(t, config.StateWarning, state) + require.Same(t, retryableErr, err) + require.Equal(t, uint64(150), regressedStatus.CheckpointTs) + status := cf.GetStatus() + require.Equal(t, uint64(200), status.CheckpointTs) + require.Len(t, status.Err, 1) + require.Same(t, retryableErr, status.Err[0]) + require.False(t, cf.ShouldRun()) + require.True(t, cf.backoff.retrying.Load()) + require.True(t, cf.backoff.isRestarting.Load()) +} + +func TestChangefeedUpdateStatusFastFailWithLowerCheckpoint(t *testing.T) { + cfID := common.NewChangeFeedIDWithName("test", common.DefaultKeyspaceName) + info := &config.ChangeFeedInfo{ + SinkURI: "kafka://127.0.0.1:9092", + State: config.StateNormal, + Config: config.GetDefaultReplicaConfig(), + } + cf := NewChangefeed(cfID, info, 100, true) + + fastFailErr := &heartbeatpb.RunningError{ + Node: "node-1", + Code: string(errors.ErrTableRouteConflict.RFCCode()), + Message: "table route conflict", + } + newStatus := &heartbeatpb.MaintainerStatus{ + CheckpointTs: 99, + BootstrapDone: true, + Err: []*heartbeatpb.RunningError{fastFailErr}, + } + updated, state, err := cf.UpdateStatus(newStatus) + + require.True(t, updated) + require.Equal(t, config.StateFailed, state) + require.Same(t, fastFailErr, err) + require.Equal(t, uint64(100), cf.GetStatus().CheckpointTs) + require.Equal(t, uint64(100), cf.backoff.checkpointTs) + require.Equal(t, uint64(99), newStatus.CheckpointTs) + require.Same(t, fastFailErr, cf.GetStatus().Err[0]) + require.False(t, cf.ShouldRun()) +} + +func TestBootstrapDoneFastFail(t *testing.T) { + cfID := common.NewChangeFeedIDWithName("test", common.DefaultKeyspaceName) + info := &config.ChangeFeedInfo{ + SinkURI: "kafka://127.0.0.1:9092", + State: config.StateNormal, + Config: config.GetDefaultReplicaConfig(), + } + cf := NewChangefeed(cfID, info, 100, true) + + fastFailErr := &heartbeatpb.RunningError{ + Node: "node-1", + Code: string(errors.ErrTableRouteConflict.RFCCode()), + Message: "table route conflict", + } + newStatus := &heartbeatpb.MaintainerStatus{ + CheckpointTs: 200, + BootstrapDone: true, + Err: []*heartbeatpb.RunningError{fastFailErr}, + } + updated, state, err := cf.UpdateStatus(newStatus) + + require.True(t, updated) + require.Equal(t, config.StateFailed, state) + require.Same(t, fastFailErr, err) + require.Equal(t, newStatus, cf.GetStatus()) + require.False(t, cf.ShouldRun()) +} + +func TestBootstrapDoneRetryableError(t *testing.T) { + cfID := common.NewChangeFeedIDWithName("test", common.DefaultKeyspaceName) + info := &config.ChangeFeedInfo{ + SinkURI: "kafka://127.0.0.1:9092", + State: config.StateNormal, + Config: config.GetDefaultReplicaConfig(), + } + cf := NewChangefeed(cfID, info, 100, true) + + retryableErr := &heartbeatpb.RunningError{ + Node: "node-1", + Code: "CDC:ErrChangefeedRetryable", + Message: "retryable error", + } + newStatus := &heartbeatpb.MaintainerStatus{ + CheckpointTs: 100, + BootstrapDone: true, + Err: []*heartbeatpb.RunningError{retryableErr}, + } + updated, state, err := cf.UpdateStatus(newStatus) + + require.True(t, updated) + require.Equal(t, config.StateNormal, state) + require.Nil(t, err) + require.Equal(t, newStatus, cf.GetStatus()) + require.True(t, cf.ShouldRun()) + require.False(t, cf.backoff.retrying.Load()) + require.False(t, cf.backoff.isRestarting.Load()) + require.True(t, cf.backoff.nextRetryTime.Load().IsZero()) + + nextStatus := &heartbeatpb.MaintainerStatus{ + CheckpointTs: 100, + BootstrapDone: true, + Err: []*heartbeatpb.RunningError{retryableErr}, + } + updated, state, err = cf.UpdateStatus(nextStatus) + + require.True(t, updated) + require.Equal(t, config.StateWarning, state) + require.Same(t, retryableErr, err) + require.Equal(t, nextStatus, cf.GetStatus()) + require.False(t, cf.ShouldRun()) + require.True(t, cf.backoff.retrying.Load()) + require.True(t, cf.backoff.isRestarting.Load()) +} + +func TestBootstrapDoneProgressDoesNotSkipRetry(t *testing.T) { + cfID := common.NewChangeFeedIDWithName("test", common.DefaultKeyspaceName) + info := &config.ChangeFeedInfo{ + SinkURI: "kafka://127.0.0.1:9092", + State: config.StateNormal, + Config: config.GetDefaultReplicaConfig(), + } + cf := NewChangefeed(cfID, info, 100, true) + + // A lower checkpoint heartbeat must not replace the accepted status. + updated, state, err := cf.UpdateStatus(&heartbeatpb.MaintainerStatus{CheckpointTs: 90}) + require.False(t, updated) + require.Equal(t, config.StateNormal, state) + require.Nil(t, err) + require.Equal(t, uint64(100), cf.GetStatus().CheckpointTs) + + bootstrapStatus := &heartbeatpb.MaintainerStatus{CheckpointTs: 200, BootstrapDone: true} + updated, state, err = cf.UpdateStatus(bootstrapStatus) + require.True(t, updated) + require.Equal(t, config.StateNormal, state) + require.Nil(t, err) + require.Same(t, bootstrapStatus, cf.GetStatus()) + require.False(t, cf.backoff.retrying.Load()) + require.True(t, cf.backoff.nextRetryTime.Load().IsZero()) + + // Bootstrap progress has already been accepted, so this error must trigger retry. + retryableErr := &heartbeatpb.RunningError{ + Node: "node-1", Code: "CDC:ErrChangefeedRetryable", Message: "retryable error", + } + updated, state, err = cf.UpdateStatus(&heartbeatpb.MaintainerStatus{ + CheckpointTs: 200, BootstrapDone: true, Err: []*heartbeatpb.RunningError{retryableErr}, + }) + require.True(t, updated) + require.Equal(t, config.StateWarning, state) + require.Same(t, retryableErr, err) + require.Equal(t, uint64(200), cf.backoff.checkpointTs) + require.True(t, cf.backoff.retrying.Load()) + require.True(t, cf.backoff.isRestarting.Load()) + require.False(t, cf.ShouldRun()) +} + func TestChangefeed_IsMQSink(t *testing.T) { cfID := common.NewChangeFeedIDWithName("test", common.DefaultKeyspaceName) info := &config.ChangeFeedInfo{ @@ -273,3 +460,32 @@ func TestChangefeed_GetKeyspaceID(t *testing.T) { } require.Equal(t, uint32(1), c4.GetKeyspaceID()) } + +func TestBootstrapDoneDoesNotRegress(t *testing.T) { + for _, targetTs := range []uint64{0, 200} { + t.Run(fmt.Sprintf("target %d", targetTs), func(t *testing.T) { + info := &config.ChangeFeedInfo{ + SinkURI: "mysql://localhost:3306", State: config.StateNormal, + Config: config.GetDefaultReplicaConfig(), TargetTs: targetTs, + } + cf := NewChangefeed(common.NewChangeFeedIDWithName("test", common.DefaultKeyspaceName), info, 200, true) + cf.UpdateStatus(&heartbeatpb.MaintainerStatus{CheckpointTs: 200, BootstrapDone: true}) + incoming := &heartbeatpb.MaintainerStatus{CheckpointTs: 200} + if targetTs == 0 { + incoming.Err = []*heartbeatpb.RunningError{{Code: "CDC:ErrChangefeedRetryable", Message: "retry"}} + } + changed, state, err := cf.UpdateStatus(incoming) + require.True(t, changed) + require.True(t, cf.GetStatus().BootstrapDone) + require.False(t, incoming.BootstrapDone) + if targetTs == 0 { + require.Equal(t, config.StateWarning, state) + require.Same(t, incoming.Err[0], err) + require.False(t, cf.ShouldRun()) + } else { + require.Equal(t, config.StateFinished, state) + require.Nil(t, err) + } + }) + } +} diff --git a/downstreamadapter/dispatcher/basic_dispatcher.go b/downstreamadapter/dispatcher/basic_dispatcher.go index e050297861..9200ad387b 100644 --- a/downstreamadapter/dispatcher/basic_dispatcher.go +++ b/downstreamadapter/dispatcher/basic_dispatcher.go @@ -21,6 +21,7 @@ import ( "github.com/pingcap/failpoint" "github.com/pingcap/log" + "github.com/pingcap/ticdc/downstreamadapter/routing" "github.com/pingcap/ticdc/downstreamadapter/sink" "github.com/pingcap/ticdc/eventpb" "github.com/pingcap/ticdc/heartbeatpb" @@ -43,6 +44,7 @@ type DispatcherService interface { GetBDRMode() bool GetChangefeedID() common.ChangeFeedID GetTableSpan() *heartbeatpb.TableSpan + GetRouter() routing.Router GetTimezone() string GetIntegrityConfig() *eventpb.IntegrityConfig GetFilterConfig() *eventpb.FilterConfig diff --git a/downstreamadapter/dispatcher/basic_dispatcher_active_active_test.go b/downstreamadapter/dispatcher/basic_dispatcher_active_active_test.go index a767b14beb..2f3ec09d46 100644 --- a/downstreamadapter/dispatcher/basic_dispatcher_active_active_test.go +++ b/downstreamadapter/dispatcher/basic_dispatcher_active_active_test.go @@ -15,6 +15,7 @@ package dispatcher import ( "testing" + "github.com/pingcap/ticdc/downstreamadapter/routing" "github.com/pingcap/ticdc/heartbeatpb" "github.com/pingcap/ticdc/pkg/common" commonEvent "github.com/pingcap/ticdc/pkg/common/event" @@ -135,6 +136,7 @@ func newTestBasicDispatcher(t *testing.T, sinkType common.SinkType, enableActive nil, nil, false, + routing.Router{}, statuses, blockStatuses, errCh, diff --git a/downstreamadapter/dispatcher/basic_dispatcher_info.go b/downstreamadapter/dispatcher/basic_dispatcher_info.go index 19a0980461..422f665cca 100644 --- a/downstreamadapter/dispatcher/basic_dispatcher_info.go +++ b/downstreamadapter/dispatcher/basic_dispatcher_info.go @@ -17,6 +17,7 @@ import ( "sync/atomic" "time" + "github.com/pingcap/ticdc/downstreamadapter/routing" "github.com/pingcap/ticdc/downstreamadapter/syncpoint" "github.com/pingcap/ticdc/eventpb" "github.com/pingcap/ticdc/heartbeatpb" @@ -54,6 +55,10 @@ type SharedInfo struct { // will break the splittability of this table. enableSplittableCheck bool + // router is used to route source schema/table names to target schema/table names. + // It is used to apply routing to TableInfo before storing it. + router routing.Router + // Shared resources // statusesChan is used to store the status of dispatchers when status changed // and push to heartbeatRequestQueue @@ -87,6 +92,7 @@ func NewSharedInfo( syncPointConfig *syncpoint.SyncPointConfig, txnAtomicity *config.AtomicityLevel, enableSplittableCheck bool, + router routing.Router, statusesChan chan TableSpanStatusWithSeq, blockStatusesChan chan *heartbeatpb.TableSpanBlockStatus, errCh chan error, @@ -101,6 +107,7 @@ func NewSharedInfo( filterConfig: filterConfig, syncPointConfig: syncPointConfig, enableSplittableCheck: enableSplittableCheck, + router: router, statusesChan: statusesChan, blockStatusesChan: blockStatusesChan, blockExecutor: newBlockEventExecutor(), @@ -176,6 +183,10 @@ func (d *BasicDispatcher) IsOutputRawChangeEvent() bool { return d.sharedInfo.outputRawChangeEvent } +func (d *BasicDispatcher) GetRouter() routing.Router { + return d.sharedInfo.GetRouter() +} + func (d *BasicDispatcher) GetFilterConfig() *eventpb.FilterConfig { return d.sharedInfo.filterConfig } @@ -266,6 +277,12 @@ func (s *SharedInfo) GetBlockEventExecutor() *blockEventExecutor { return s.blockExecutor } +// GetRouter returns the router for schema/table name routing. +// The zero value router is a no-op router. +func (s *SharedInfo) GetRouter() routing.Router { + return s.router +} + func (s *SharedInfo) Close() { if s.blockExecutor != nil { s.blockExecutor.Close() diff --git a/downstreamadapter/dispatcher/event_dispatcher_test.go b/downstreamadapter/dispatcher/event_dispatcher_test.go index 29b8ace3e2..ab9516afa6 100644 --- a/downstreamadapter/dispatcher/event_dispatcher_test.go +++ b/downstreamadapter/dispatcher/event_dispatcher_test.go @@ -21,6 +21,7 @@ import ( "time" "github.com/pingcap/failpoint" + "github.com/pingcap/ticdc/downstreamadapter/routing" "github.com/pingcap/ticdc/downstreamadapter/sink" "github.com/pingcap/ticdc/downstreamadapter/syncpoint" "github.com/pingcap/ticdc/heartbeatpb" @@ -82,6 +83,7 @@ func newDispatcherForTest(sink sink.Sink, tableSpan *heartbeatpb.TableSpan) *Eve }, // syncPointConfig &defaultAtomicity, false, // enableSplittableCheck + routing.Router{}, make(chan TableSpanStatusWithSeq, 128), make(chan *heartbeatpb.TableSpanBlockStatus, 128), make(chan error, 1), @@ -1003,6 +1005,7 @@ func TestDispatcherSplittableCheck(t *testing.T) { }, &defaultAtomicity, true, // enableSplittableCheck = true + routing.Router{}, make(chan TableSpanStatusWithSeq, 128), make(chan *heartbeatpb.TableSpanBlockStatus, 128), make(chan error, 1), @@ -1113,6 +1116,7 @@ func TestDispatcher_SkipDMLAsStartTs_FilterCorrectly(t *testing.T) { }, &defaultAtomicity, false, + routing.Router{}, make(chan TableSpanStatusWithSeq, 128), make(chan *heartbeatpb.TableSpanBlockStatus, 128), make(chan error, 1), @@ -1193,6 +1197,7 @@ func TestDispatcher_SkipDMLAsStartTs_Disabled(t *testing.T) { }, &defaultAtomicity, false, + routing.Router{}, make(chan TableSpanStatusWithSeq, 128), make(chan *heartbeatpb.TableSpanBlockStatus, 128), make(chan error, 1), diff --git a/downstreamadapter/dispatcher/redo_dispatcher_test.go b/downstreamadapter/dispatcher/redo_dispatcher_test.go index 68f97016b7..80832993ec 100644 --- a/downstreamadapter/dispatcher/redo_dispatcher_test.go +++ b/downstreamadapter/dispatcher/redo_dispatcher_test.go @@ -19,6 +19,7 @@ import ( "time" "github.com/pingcap/failpoint" + "github.com/pingcap/ticdc/downstreamadapter/routing" "github.com/pingcap/ticdc/downstreamadapter/sink" "github.com/pingcap/ticdc/heartbeatpb" "github.com/pingcap/ticdc/pkg/common" @@ -47,6 +48,7 @@ func newRedoDispatcherForTest(sink sink.Sink, tableSpan *heartbeatpb.TableSpan) nil, // redo dispatcher doesn't need syncPointConfig &defaultAtomicity, false, // enableSplittableCheck + routing.Router{}, make(chan TableSpanStatusWithSeq, 128), make(chan *heartbeatpb.TableSpanBlockStatus, 128), make(chan error, 1), diff --git a/downstreamadapter/dispatchermanager/dispatcher_manager.go b/downstreamadapter/dispatchermanager/dispatcher_manager.go index 5b0baebb58..5c712c741f 100644 --- a/downstreamadapter/dispatchermanager/dispatcher_manager.go +++ b/downstreamadapter/dispatchermanager/dispatcher_manager.go @@ -24,6 +24,7 @@ import ( "github.com/pingcap/log" "github.com/pingcap/ticdc/downstreamadapter/dispatcher" "github.com/pingcap/ticdc/downstreamadapter/eventcollector" + "github.com/pingcap/ticdc/downstreamadapter/routing" "github.com/pingcap/ticdc/downstreamadapter/sink" "github.com/pingcap/ticdc/downstreamadapter/sink/mysql" "github.com/pingcap/ticdc/downstreamadapter/sink/redo" @@ -224,6 +225,15 @@ func NewDispatcherManager( ) (manager *DispatcherManager, err error) { failpoint.Inject("NewDispatcherManagerDelay", nil) + router, err := routing.NewRouter( + changefeedID, + cfConfig.CaseSensitive, + cfConfig.SinkConfig.DispatchRules, + ) + if err != nil { + return nil, err + } + ctx, cancel := context.WithCancel(context.Background()) pdClock := appcontext.GetService[pdutil.Clock](appcontext.DefaultPDClock) @@ -325,6 +335,7 @@ func NewDispatcherManager( syncPointConfig, manager.config.SinkConfig.TxnAtomicity, manager.config.EnableSplittableCheck, + router, make(chan dispatcher.TableSpanStatusWithSeq, 8192), make(chan *heartbeatpb.TableSpanBlockStatus, 1024*1024), make(chan error, 1), diff --git a/downstreamadapter/dispatchermanager/dispatcher_manager_test.go b/downstreamadapter/dispatchermanager/dispatcher_manager_test.go index 0f6155c8b2..fb31a7b7b8 100644 --- a/downstreamadapter/dispatchermanager/dispatcher_manager_test.go +++ b/downstreamadapter/dispatchermanager/dispatcher_manager_test.go @@ -22,6 +22,7 @@ import ( "github.com/golang/mock/gomock" "github.com/pingcap/ticdc/downstreamadapter/dispatcher" "github.com/pingcap/ticdc/downstreamadapter/eventcollector" + "github.com/pingcap/ticdc/downstreamadapter/routing" "github.com/pingcap/ticdc/downstreamadapter/sink" "github.com/pingcap/ticdc/downstreamadapter/sink/mock" "github.com/pingcap/ticdc/downstreamadapter/sink/mysql" @@ -39,6 +40,7 @@ import ( mysqlcfg "github.com/pingcap/ticdc/pkg/sink/mysql" "github.com/pingcap/ticdc/pkg/util" "github.com/pingcap/ticdc/utils/threadpool" + "github.com/pingcap/tidb/pkg/meta/model" "github.com/stretchr/testify/require" ) @@ -64,6 +66,8 @@ func newDispatcherManagerTestSink(t *testing.T, sinkType common.SinkType) sink.S // createTestDispatcher creates a test dispatcher with given parameters func createTestDispatcher(t *testing.T, manager *DispatcherManager, id common.DispatcherID, tableID int64, startKey, endKey []byte) *dispatcher.EventDispatcher { + t.Helper() + span := &heartbeatpb.TableSpan{ TableID: tableID, StartKey: startKey, @@ -71,22 +75,7 @@ func createTestDispatcher(t *testing.T, manager *DispatcherManager, id common.Di } var redoTs atomic.Uint64 redoTs.Store(math.MaxUint64) - defaultAtomicity := config.DefaultAtomicityLevel() - sharedInfo := dispatcher.NewSharedInfo( - manager.changefeedID, - "system", - false, - false, - false, - nil, - nil, - nil, - &defaultAtomicity, - false, - make(chan dispatcher.TableSpanStatusWithSeq, 1), - make(chan *heartbeatpb.TableSpanBlockStatus, 1), - make(chan error, 1), - ) + require.NotNil(t, manager.sharedInfo) d := dispatcher.NewEventDispatcher( id, span, @@ -97,7 +86,7 @@ func createTestDispatcher(t *testing.T, manager *DispatcherManager, id common.Di false, // skipDMLAsStartTs 0, // currentPDTs manager.sink, - sharedInfo, + manager.sharedInfo, false, &redoTs, ) @@ -144,6 +133,7 @@ func createTestManager(t *testing.T) *DispatcherManager { nil, // syncPointConfig &defaultAtomicity, false, + routing.Router{}, make(chan dispatcher.TableSpanStatusWithSeq, 8192), make(chan *heartbeatpb.TableSpanBlockStatus, 1024*1024), make(chan error, 1), @@ -1089,3 +1079,70 @@ func TestAbortMergeRestoresSourceDispatchersRegistration(t *testing.T) { require.True(t, ec.HasDispatcher(dispatcher1.GetId())) require.True(t, ec.HasDispatcher(dispatcher2.GetId())) } + +func TestDispatcherManagerTableRoutingCaseSensitive(t *testing.T) { + appcontext.SetService(appcontext.DefaultPDClock, pdutil.NewClock4Test()) + collector := &HeartBeatCollector{ + heartBeatReqQueue: NewHeartbeatRequestQueue(), + blockStatusReqQueue: NewBlockStatusRequestQueue(), + heartBeatResponseDynamicStream: newHeartBeatResponseDynamicStream(dispatcher.GetDispatcherStatusDynamicStream()), + schedulerDispatcherRequestDynamicStream: newSchedulerDispatcherRequestDynamicStream(), + mergeDispatcherRequestDynamicStream: newMergeDispatcherRequestDynamicStream(), + } + appcontext.SetService(appcontext.HeartbeatCollector, collector) + defer collector.heartBeatResponseDynamicStream.Close() + defer collector.schedulerDispatcherRequestDynamicStream.Close() + defer collector.mergeDispatcherRequestDynamicStream.Close() + + for _, tc := range []struct { + name string + caseSensitive *bool + }{ + {name: "unset"}, + {name: "insensitive", caseSensitive: util.AddressOf(false)}, + {name: "sensitive", caseSensitive: util.AddressOf(true)}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := config.GetDefaultReplicaConfig() + cfg.CaseSensitive = tc.caseSensitive + cfg.Sink.DispatchRules = []*config.DispatchRule{ + {Matcher: []string{"Sales.*"}, TargetSchema: "archive"}, + {Matcher: []string{"Mixed.*"}, TargetSchema: "copy_{schema}", TargetTable: "{table}_copy"}, + } + info := &config.ChangeFeedInfo{Config: cfg, SinkURI: "blackhole://"} + manager, err := NewDispatcherManager(common.DefaultKeyspaceID, + common.NewChangefeedID4Test("test", tc.name), info.ToChangefeedConfig(), nil, nil, 1, node.NewID(), false) + require.NoError(t, err) + defer manager.close() + router := manager.sharedInfo.GetRouter() + for _, source := range []common.TableName{ + {Schema: "sales", Table: "orders"}, + {Schema: "archive", Table: "orders"}, + {Schema: "Mixed", Table: "OrDeRs"}, + {Schema: "mIxEd", Table: "OrDeRs"}, + } { + wantSchema, wantTable := source.Schema, source.Table + if source.Schema == "sales" && !util.GetOrZero(tc.caseSensitive) { + wantSchema = "archive" + } + if source.Schema == "Mixed" || source.Schema == "mIxEd" && !util.GetOrZero(tc.caseSensitive) { + wantSchema, wantTable = "copy_"+source.Schema, source.Table+"_copy" + } + tableInfo := &common.TableInfo{TableName: source} + routed, err := router.ApplyToTableInfo(tableInfo) + require.NoError(t, err) + require.Equal(t, wantSchema, routed.GetTargetSchemaName()) + require.Equal(t, wantTable, routed.GetTargetTableName()) + ddl, err := router.ApplyToDDLEvent(&event.DDLEvent{ + Type: byte(model.ActionCreateTable), SchemaName: source.Schema, TableName: source.Table, + Query: "CREATE TABLE `" + source.Schema + "`.`" + source.Table + "` (`id` INT)", TableInfo: tableInfo, + }) + require.NoError(t, err) + require.Contains(t, ddl.Query, "`"+wantSchema+"`.`"+wantTable+"`") + require.Equal(t, wantSchema, ddl.TableInfo.GetTargetSchemaName()) + require.Equal(t, wantTable, ddl.TableInfo.GetTargetTableName()) + require.Equal(t, source, tableInfo.TableName) + } + }) + } +} diff --git a/downstreamadapter/eventcollector/dispatcher_stat.go b/downstreamadapter/eventcollector/dispatcher_stat.go index 50025b36cc..400dab7f5d 100644 --- a/downstreamadapter/eventcollector/dispatcher_stat.go +++ b/downstreamadapter/eventcollector/dispatcher_stat.go @@ -14,6 +14,7 @@ package eventcollector import ( + "slices" "sync" "sync/atomic" @@ -26,6 +27,7 @@ import ( "github.com/pingcap/ticdc/pkg/messaging" "github.com/pingcap/ticdc/pkg/metrics" "github.com/pingcap/ticdc/pkg/node" + "github.com/pingcap/tidb/pkg/meta/model" "go.uber.org/zap" ) @@ -128,8 +130,8 @@ type dispatcherStat struct { gotSyncpointOnTS atomic.Bool // tableInfo is the latest table info of the dispatcher's corresponding table. tableInfo atomic.Value - // tableInfoVersion is the latest table info version of the dispatcher's corresponding table. - // It is updated by ddl event + // tableInfoVersion is the latest schema version delivered to this dispatcher. + // It may advance even when tableInfo is not replaced. tableInfoVersion atomic.Uint64 } @@ -421,10 +423,6 @@ func (d *dispatcherStat) handleBatchDataEvents(events []dispatcher.DispatcherEve batchDML := event.Event.(*commonEvent.BatchDMLEvent) batchDML.AssembleRows(tableInfo) for _, dml := range batchDML.DMLEvents { - // DMLs in the same batch share the same updateTs in their table info, - // but they may reference different table info objects, - // so each needs to be initialized separately. - dml.TableInfo.InitPrivateFields() dml.TableInfoVersion = tableInfoVersion dmlEvent := dispatcher.NewDispatcherEvent(event.From, dml) if d.filterAndUpdateEventByCommitTs(dmlEvent) { @@ -480,10 +478,19 @@ func (d *dispatcherStat) handleSingleDataEvents(events []dispatcher.DispatcherEv return false } ddl := events[0].Event.(*commonEvent.DDLEvent) - d.tableInfoVersion.Store(ddl.FinishedTs) - if ddl.TableInfo != nil { - d.tableInfo.Store(ddl.TableInfo) + ddl, err := d.target.GetRouter().ApplyToDDLEvent(ddl) + if err != nil { + log.Error("failed to apply routing to DDL event", + zap.Stringer("changefeedID", d.target.GetChangefeedID()), + zap.Stringer("dispatcher", d.getDispatcherID()), + zap.Error(err)) + if target, ok := d.target.(dispatcher.Dispatcher); ok { + target.HandleError(err) + } + return false } + events[0].Event = ddl + d.updateTableInfoByDDL(ddl) return d.target.HandleEvents(events, func() { d.wake() }) } else { if !d.filterAndUpdateEventByCommitTs(events[0]) { @@ -493,6 +500,53 @@ func (d *dispatcherStat) handleSingleDataEvents(events []dispatcher.DispatcherEv } } +// updateTableInfoByDDL advances the table schema version and, when the DDL +// event carries a TableInfo matching the dispatcher's table, refreshes the +// cached TableInfo used for DML row assembly. +// +// Must be called from the per-dispatcher event loop (handleSingleDataEvents), +// which guarantees serial access to dispatcherStat fields for a given table. +func (d *dispatcherStat) updateTableInfoByDDL(ddl *commonEvent.DDLEvent) { + tableSpan := d.target.GetTableSpan() + if tableSpan == nil || tableSpan.TableID == common.DDLSpanTableID { + return + } + + // EXCHANGE PARTITION can change the schema version of a physical table dispatcher + // while ddl.TableInfo carries another logical table. The storage sink uses + // tableInfoVersion to decide whether a DML belongs to an old schema, so advance + // it for every DDL delivered to this dispatcher. + // TODO: Revisit whether the storage sink should discard DML solely by comparing + // tableInfoVersion with existing schema files. + d.tableInfoVersion.Store(ddl.FinishedTs) + + if ddl.TableInfo == nil { + return + } + + // A table dispatcher can receive DDLs unrelated to its own table for barrier + // coordination, for example CREATE VIEW is tracked in every table's DDL history. + // The cached table info is used to assemble subsequent DML rows. For partition + // tables, the dispatcher span ID is a physical partition ID while TableInfo + // carries the logical table ID, so compare with the cached table info first. + expectedTableID := tableSpan.TableID + current := d.tableInfo.Load() + if current != nil { + expectedTableID = current.(*common.TableInfo).TableName.TableID + } + if ddl.TableInfo.TableName.TableID != expectedTableID { + // EXCHANGE changes the logical owner of each participating physical span. + // Other DDLs, including unrelated broadcasts, must retain the ID guard. + if ddl.GetDDLType() != model.ActionExchangeTablePartition || + ddl.BlockedTables == nil || ddl.BlockedTables.InfluenceType != commonEvent.InfluenceTypeNormal || + !slices.Contains(ddl.BlockedTables.TableIDs, tableSpan.TableID) { + return + } + } + + d.tableInfo.Store(ddl.TableInfo) +} + func (d *dispatcherStat) handleDataEvents(events ...dispatcher.DispatcherEvent) bool { switch events[0].GetType() { case commonEvent.TypeDMLEvent, @@ -637,6 +691,17 @@ func (d *dispatcherStat) handleHandshakeEvent(event dispatcher.DispatcherEvent) } tableInfo := handshakeEvent.TableInfo if tableInfo != nil { + tableInfo, err := d.target.GetRouter().ApplyToTableInfo(tableInfo) + if err != nil { + log.Error("failed to apply routing to handshake table info", + zap.Stringer("changefeedID", d.target.GetChangefeedID()), + zap.Stringer("dispatcher", d.getDispatcherID()), + zap.Error(err)) + if target, ok := d.target.(dispatcher.Dispatcher); ok { + target.HandleError(err) + } + return + } d.tableInfo.Store(tableInfo) } d.lastEventSeq.Store(handshakeEvent.Seq) diff --git a/downstreamadapter/eventcollector/dispatcher_stat_test.go b/downstreamadapter/eventcollector/dispatcher_stat_test.go index 203fea8874..a4b3b76689 100644 --- a/downstreamadapter/eventcollector/dispatcher_stat_test.go +++ b/downstreamadapter/eventcollector/dispatcher_stat_test.go @@ -15,10 +15,12 @@ package eventcollector import ( "context" + "fmt" "testing" "time" "github.com/pingcap/ticdc/downstreamadapter/dispatcher" + "github.com/pingcap/ticdc/downstreamadapter/routing" "github.com/pingcap/ticdc/eventpb" "github.com/pingcap/ticdc/heartbeatpb" "github.com/pingcap/ticdc/pkg/common" @@ -27,6 +29,9 @@ import ( "github.com/pingcap/ticdc/pkg/config" "github.com/pingcap/ticdc/pkg/messaging" "github.com/pingcap/ticdc/pkg/node" + "github.com/pingcap/tidb/pkg/domain" + "github.com/pingcap/tidb/pkg/meta/model" + "github.com/pingcap/tidb/pkg/parser/ast" "github.com/pingcap/tidb/pkg/util/chunk" "github.com/stretchr/testify/require" "github.com/tikv/client-go/v2/oracle" @@ -41,10 +46,13 @@ type mockDispatcher struct { id common.DispatcherID changefeedID common.ChangeFeedID handleEvents func(events []dispatcher.DispatcherEvent, wakeCallback func()) (block bool) + handleError func(err error) events []dispatcher.DispatcherEvent checkPointTs uint64 + tableSpan *heartbeatpb.TableSpan skipSyncpointAtStartTs bool + router routing.Router } func newMockDispatcher(id common.DispatcherID, startTs uint64) *mockDispatcher { @@ -73,6 +81,9 @@ func (m *mockDispatcher) GetChangefeedID() common.ChangeFeedID { } func (m *mockDispatcher) GetTableSpan() *heartbeatpb.TableSpan { + if m.tableSpan != nil { + return m.tableSpan + } return &heartbeatpb.TableSpan{ TableID: 1, } @@ -131,6 +142,16 @@ func (m *mockDispatcher) IsOutputRawChangeEvent() bool { return false } +func (m *mockDispatcher) GetRouter() routing.Router { + return m.router +} + +func (m *mockDispatcher) HandleError(err error) { + if m.handleError != nil { + m.handleError(err) + } +} + // mockEvent implements the Event interface for testing type mockEvent struct { eventType int @@ -1340,3 +1361,170 @@ func TestRegisterTo(t *testing.T) { } }) } + +func TestHandleDDLEventTableInfoUpdate(t *testing.T) { + helper := commonEvent.NewEventTestHelper(t) + defer helper.Close() + helper.Tk().MustExec("use test") + + tableDDL := helper.DDL2Event("CREATE TABLE `products` (`id` INT PRIMARY KEY)") + viewDDL := helper.DDL2Event("CREATE VIEW `transient_view` AS SELECT 1 AS `id`") + + localServerID := node.ID("local") + remoteServerID := node.ID("remote") + + mockDisp := newMockDispatcher(common.NewDispatcherID(), 0) + mockDisp.tableSpan = &heartbeatpb.TableSpan{TableID: tableDDL.TableInfo.TableName.TableID} + mockDisp.handleEvents = func(events []dispatcher.DispatcherEvent, wakeCallback func()) bool { + return false + } + + stat := newDispatcherStat(mockDisp, newTestEventCollector(localServerID), nil) + stat.connState.setEventServiceID(remoteServerID) + stat.epoch.Store(10) + stat.lastEventSeq.Store(1) + stat.lastEventCommitTs.Store(50) + + tableDDL.Epoch = 10 + tableDDL.Seq = 2 + stat.handleDataEvents(dispatcher.DispatcherEvent{From: &remoteServerID, Event: tableDDL}) + + storedTableInfo := stat.tableInfo.Load().(*common.TableInfo) + require.NotNil(t, storedTableInfo) + require.Same(t, tableDDL.TableInfo, storedTableInfo) + require.Equal(t, "test", storedTableInfo.TableName.Schema) + require.Equal(t, "products", storedTableInfo.TableName.Table) + require.Equal(t, tableDDL.TableInfo.TableName.TableID, storedTableInfo.TableName.TableID) + require.Equal(t, tableDDL.FinishedTs, stat.tableInfoVersion.Load()) + require.Len(t, mockDisp.events, 1) + require.Same(t, tableDDL, mockDisp.events[0].Event) + + viewDDL.Epoch = 10 + viewDDL.Seq = 3 + stat.handleDataEvents(dispatcher.DispatcherEvent{From: &remoteServerID, Event: viewDDL}) + + storedTableInfo = stat.tableInfo.Load().(*common.TableInfo) + require.Same(t, tableDDL.TableInfo, storedTableInfo) + require.Equal(t, viewDDL.FinishedTs, stat.tableInfoVersion.Load()) + require.Len(t, mockDisp.events, 2) + require.Same(t, viewDDL, mockDisp.events[1].Event) +} + +func TestExchangeDMLRouting(t *testing.T) { + helper := commonEvent.NewEventTestHelper(t) + defer helper.Close() + helper.DDL2Job("CREATE DATABASE normal_db") + helper.DDL2Job("CREATE DATABASE partition_db") + normal := helper.DDL2Job("CREATE TABLE normal_db.nt (id INT PRIMARY KEY)") + partition := helper.DDL2Job("CREATE TABLE partition_db.pt (id INT PRIMARY KEY) PARTITION BY RANGE(id) (PARTITION p0 VALUES LESS THAN (100), PARTITION p1 VALUES LESS THAN MAXVALUE)") + oldNormal := common.WrapTableInfo("normal_db", normal.BinlogInfo.TableInfo) + oldPartition := common.WrapTableInfo("partition_db", partition.BinlogInfo.TableInfo) + partitionID := partition.BinlogInfo.TableInfo.Partition.Definitions[0].ID + job := helper.DDL2Job("ALTER TABLE partition_db.pt EXCHANGE PARTITION p0 WITH TABLE normal_db.nt") + for _, tc := range []struct { + schema, table string + physical int64 + old *common.TableInfo + row int64 + }{ + {"partition_db", "pt", normal.TableID, oldNormal, 7}, + {"normal_db", "nt", partitionID, oldPartition, 8}, + } { + table, err := domain.GetDomain(helper.Tk().Session()).InfoSchema().TableByName(t.Context(), ast.NewCIStr(tc.schema), ast.NewCIStr(tc.table)) + require.NoError(t, err) + helper.ApplyJob(&model.Job{SchemaName: tc.schema, BinlogInfo: &model.HistoryInfo{TableInfo: table.Meta()}}) + next := common.WrapTableInfo(tc.schema, table.Meta()) + var dml *commonEvent.DMLEvent + if tc.table == "pt" { + dml = helper.DML2Event4PartitionTable(tc.schema, tc.table, "p0", "INSERT INTO partition_db.pt VALUES (7)") + } else { + dml = helper.DML2Event(tc.schema, tc.table, "INSERT INTO normal_db.nt VALUES (8)") + } + require.Equal(t, tc.physical, dml.PhysicalTableID) + batch := &commonEvent.BatchDMLEvent{Version: commonEvent.BatchDMLEventVersion1, DMLEvents: []*commonEvent.DMLEvent{dml}, Rows: dml.Rows, TableInfo: dml.TableInfo} + data, err := batch.Marshal() + require.NoError(t, err) + for _, route := range []bool{false, true} { + for _, local := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/route=%t/local=%t", tc.table, route, local), func(t *testing.T) { + mock := newMockDispatcher(common.NewDispatcherID(), 0) + mock.tableSpan = &heartbeatpb.TableSpan{TableID: tc.physical} + mock.handleEvents = func([]dispatcher.DispatcherEvent, func()) bool { return true } + if route { + mock.router, err = routing.NewRouter(mock.changefeedID, false, []*config.DispatchRule{ + {Matcher: []string{"normal_db.*"}, TargetSchema: "normal_target"}, + {Matcher: []string{"partition_db.*"}, TargetSchema: "partition_target"}, + }) + require.NoError(t, err) + } + stat := newDispatcherStat(mock, newTestEventCollector(node.ID("local")), nil) + stat.epoch.Store(1) + from := createNodeID("service1") + handshake := commonEvent.NewHandshakeEvent(mock.id, 0, 1, tc.old) + stat.handleHandshakeEvent(dispatcher.NewDispatcherEvent(from, &handshake)) + ddl := &commonEvent.DDLEvent{ + Version: commonEvent.DDLEventVersion1, Type: byte(model.ActionExchangeTablePartition), TableInfo: next, FinishedTs: job.BinlogInfo.FinishedTS, + Query: job.Query, SchemaName: "normal_db", TableName: "nt", ExtraSchemaName: "partition_db", ExtraTableName: "pt", + DispatcherID: mock.id, Epoch: 1, Seq: 2, + BlockedTables: &commonEvent.InfluencedTables{InfluenceType: commonEvent.InfluenceTypeNormal, TableIDs: []int64{normal.TableID, partitionID, common.DDLSpanTableID}}, + } + // A remote DDL carries the same table identity as a local DDL. + if !local { + encoded, err := ddl.Marshal() + require.NoError(t, err) + ddl = &commonEvent.DDLEvent{} + require.NoError(t, ddl.Unmarshal(encoded)) + } + require.True(t, stat.handleSingleDataEvents([]dispatcher.DispatcherEvent{dispatcher.NewDispatcherEvent(from, ddl)})) + incoming := &commonEvent.BatchDMLEvent{} + require.NoError(t, incoming.Unmarshal(data)) + if local { + incoming.AssembleRows(next) + } + incoming.DMLEvents[0].Seq = 3 + incoming.DMLEvents[0].Epoch = 1 + incoming.DMLEvents[0].CommitTs = ddl.FinishedTs + 1 + incoming.DMLEvents[0].DispatcherID = mock.id + require.True(t, stat.handleBatchDataEvents([]dispatcher.DispatcherEvent{dispatcher.NewDispatcherEvent(from, incoming)})) + received := mock.events[len(mock.events)-1].Event.(*commonEvent.DMLEvent) + expected, err := mock.router.ApplyToTableInfo(next) + require.NoError(t, err) + require.Equal(t, expected.GetSchemaName(), received.TableInfo.GetSchemaName()) + require.Equal(t, expected.GetTableName(), received.TableInfo.GetTableName()) + require.Equal(t, expected.GetTargetSchemaName(), received.TableInfo.GetTargetSchemaName()) + require.Equal(t, expected.GetTargetTableName(), received.TableInfo.GetTargetTableName()) + require.Equal(t, expected.TableName.TableID, received.TableInfo.TableName.TableID) + require.Equal(t, tc.row, received.Rows.GetRow(0).GetInt64(0)) + require.Equal(t, ddl.FinishedTs, stat.tableInfoVersion.Load()) + stat.epoch.Store(2) + recovered := commonEvent.NewHandshakeEvent(mock.id, ddl.FinishedTs, 2, next) + stat.handleHandshakeEvent(dispatcher.NewDispatcherEvent(from, &recovered)) + require.Equal(t, expected.TableName, stat.tableInfo.Load().(*common.TableInfo).TableName) + }) + } + } + } +} + +func TestExchangeCacheGuard(t *testing.T) { + old := &common.TableInfo{TableName: common.TableName{TableID: 100}} + next := &common.TableInfo{TableName: common.TableName{TableID: 200}} + for _, tc := range []struct { + name string + blocked *commonEvent.InfluencedTables + }{ + {"missing", nil}, + {"database", &commonEvent.InfluencedTables{InfluenceType: commonEvent.InfluenceTypeDB, SchemaID: 1}}, + {"other span", &commonEvent.InfluencedTables{InfluenceType: commonEvent.InfluenceTypeNormal, TableIDs: []int64{201, 202}}}, + } { + t.Run(tc.name, func(t *testing.T) { + mock := newMockDispatcher(common.NewDispatcherID(), 0) + mock.tableSpan = &heartbeatpb.TableSpan{TableID: 101} + stat := newDispatcherStat(mock, newTestEventCollector(node.ID("local")), nil) + stat.tableInfo.Store(old) + stat.updateTableInfoByDDL(&commonEvent.DDLEvent{Type: byte(model.ActionExchangeTablePartition), TableInfo: next, BlockedTables: tc.blocked, FinishedTs: 10}) + require.Same(t, old, stat.tableInfo.Load()) + require.Equal(t, uint64(10), stat.tableInfoVersion.Load()) + }) + } +} diff --git a/downstreamadapter/eventcollector/event_collector_test.go b/downstreamadapter/eventcollector/event_collector_test.go index 8256236b53..e2fc5f62fd 100644 --- a/downstreamadapter/eventcollector/event_collector_test.go +++ b/downstreamadapter/eventcollector/event_collector_test.go @@ -20,6 +20,7 @@ import ( "time" "github.com/pingcap/ticdc/downstreamadapter/dispatcher" + "github.com/pingcap/ticdc/downstreamadapter/routing" "github.com/pingcap/ticdc/eventpb" "github.com/pingcap/ticdc/heartbeatpb" "github.com/pingcap/ticdc/pkg/common" @@ -116,6 +117,10 @@ func (m *mockEventDispatcher) IsOutputRawChangeEvent() bool { return false } +func (m *mockEventDispatcher) GetRouter() routing.Router { + return routing.Router{} +} + func newMessage(id node.ID, msg messaging.IOTypeT) *messaging.TargetMessage { targetMessage := messaging.NewSingleTargetMessage(id, messaging.EventCollectorTopic, msg) targetMessage.From = id diff --git a/downstreamadapter/routing/ddl_query_rewriter.go b/downstreamadapter/routing/ddl_query_rewriter.go new file mode 100644 index 0000000000..d326c74ff9 --- /dev/null +++ b/downstreamadapter/routing/ddl_query_rewriter.go @@ -0,0 +1,502 @@ +// Copyright 2026 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 routing + +import ( + "bytes" + "slices" + "strings" + + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/errors" + "github.com/pingcap/tidb/pkg/parser" + "github.com/pingcap/tidb/pkg/parser/ast" + "github.com/pingcap/tidb/pkg/parser/format" +) + +// rewriteParserBackedDDLQuery rewrites a parser-supported DDL query by applying routing rules. +func (r Router) rewriteParserBackedDDLQuery(ddl *commonEvent.DDLEvent) (string, error) { + if len(r.rules) == 0 { + return ddl.Query, nil + } + + queries, err := splitMultiStmtDDLQuery(ddl.Query) + if err != nil { + return "", errors.WrapError(errors.ErrTableRoutingFailed, err) + } + + var ( + builder strings.Builder + routed bool + ) + for i := range queries { + query := queries[i] + newQuery, err := r.rewriteSingleDDLQuery(query, ddl.GetSchemaName()) + if err != nil { + return "", err + } + if newQuery != query { + routed = true + query = newQuery + } + builder.WriteString(query) + if len(queries) > 1 && !strings.HasSuffix(query, ";") { + builder.WriteByte(';') + } + } + if !routed { + return ddl.Query, nil + } + + return builder.String(), nil +} + +func splitMultiStmtDDLQuery(query string) ([]string, error) { + if !strings.Contains(query, ";") { + return []string{query}, nil + } + + // SplitQueries is parser-backed. Use its statement count to distinguish a + // real multi-statement query from semicolons inside strings or comments. + queries, err := commonEvent.SplitQueries(query) + if err != nil { + return nil, err + } + if len(queries) <= 1 { + return []string{query}, nil + } + return queries, nil +} + +// rewriteSingleDDLQuery routes a single DDL statement. +// If the schema is not qualified, fill it with the default schema. +// Cross schema scenario must be qualified before enter the router. +// Example: +// +// defaultSchema = "source_db" +// query = "ALTER TABLE t ADD COLUMN c INT" +// fillDefaultSchema → [{source_db, t}] +// route({source_db, t}) with rule source_db.* → target_db.{table}_r +// → "ALTER TABLE `target_db`.`t_r` ADD COLUMN `c` INT" +func (r Router) rewriteSingleDDLQuery(query string, defaultSchema string) (string, error) { + p := parser.New() + stmt, err := p.ParseOneStmt(query, "", "") + if err != nil { + return "", errors.WrapError(errors.ErrTableRoutingFailed, err) + } + + sourceTables := extractTableNames(stmt) + if len(sourceTables) == 0 { + return query, nil + } + fillDefaultSchema(sourceTables, defaultSchema) + + var ( + routed bool + targetTables = make([]commonEvent.SchemaTableName, 0, len(sourceTables)) + ) + for _, srcTable := range sourceTables { + binding, err := r.route(srcTable.SchemaName, srcTable.TableName) + if err != nil { + return "", err + } + if binding.routed() { + routed = true + } + targetTables = append(targetTables, commonEvent.SchemaTableName{ + SchemaName: binding.Target.Schema, + TableName: binding.Target.Table, + }) + } + + if !routed { + return query, nil + } + + newQuery, err := rewriteDDLStmtTables(stmt, sourceTables, targetTables) + if err != nil { + return "", err + } + return newQuery, nil +} + +func fillDefaultSchema(tables []commonEvent.SchemaTableName, defaultSchema string) { + if defaultSchema == "" { + return + } + + for i := range tables { + if tables[i].SchemaName == "" && tables[i].TableName != "" { + tables[i].SchemaName = defaultSchema + } + } +} + +// cteScopes tracks CTE visibility in AST visit order. Non-recursive CTEs +// become visible after their definition; recursive CTEs can reference themselves. +// Both extraction and rewriting must skip the same CTE references. +type cteScopes struct { + scopes []map[string]struct{} +} + +func (c *cteScopes) enter(in ast.Node) { + switch n := in.(type) { + case *ast.SelectStmt, *ast.SetOprStmt, *ast.SetOprSelectList: + c.scopes = append(c.scopes, nil) + case *ast.CommonTableExpression: + if n.IsRecursive { + c.add(n.Name.L) + } + } +} + +func (c *cteScopes) leave(in ast.Node) { + switch n := in.(type) { + case *ast.SelectStmt, *ast.SetOprStmt, *ast.SetOprSelectList: + c.scopes = c.scopes[:len(c.scopes)-1] + case *ast.CommonTableExpression: + c.add(n.Name.L) + } +} + +func (c *cteScopes) add(name string) { + i := len(c.scopes) - 1 + if c.scopes[i] == nil { + c.scopes[i] = make(map[string]struct{}) + } + c.scopes[i][name] = struct{}{} +} + +func (c *cteScopes) contains(table *ast.TableName) bool { + if table.Schema.O != "" { + return false + } + for _, scope := range slices.Backward(c.scopes) { + if _, ok := scope[table.Name.L]; ok { + return true + } + } + return false +} + +// tableNameExtractor extracts table names from DDL AST nodes. +// ref: https://github.com/pingcap/tidb/blob/09feccb529be2830944e11f5fed474020f50370f/server/sql_info_fetcher.go#L46 +type tableNameExtractor struct { + ctes cteScopes + names []commonEvent.SchemaTableName +} + +func (tne *tableNameExtractor) Enter(in ast.Node) (ast.Node, bool) { + tne.ctes.enter(in) + if t, ok := in.(*ast.TableName); ok { + if tne.ctes.contains(t) { + return in, true + } + tne.names = append(tne.names, commonEvent.SchemaTableName{SchemaName: t.Schema.O, TableName: t.Name.O}) + return in, true + } + return in, false +} + +func (tne *tableNameExtractor) Leave(in ast.Node) (ast.Node, bool) { + tne.ctes.leave(in) + return in, true +} + +// extractTableNames returns the tables in a DDL statement in AST visit order. +// The first element is always the topmost table (the DDL target). +// +// Examples (sourceTables returned): +// +// CREATE TABLE `db`.`t1` LIKE `db`.`t2` +// → [{db, t1}, {db, t2}] +// RENAME TABLE `db`.`a` TO `db`.`b`, `db`.`c` TO `db`.`d` +// → [{db, a}, {db, b}, {db, c}, {db, d}] +// ALTER TABLE `db`.`t` ADD COLUMN `c` INT +// → [{db, t}] +func extractTableNames(stmt ast.StmtNode) []commonEvent.SchemaTableName { + // Special cases: schema related SQLs don't have tableName + switch v := stmt.(type) { + case *ast.AlterDatabaseStmt: + return []commonEvent.SchemaTableName{{SchemaName: v.Name.O, TableName: ""}} + case *ast.CreateDatabaseStmt: + return []commonEvent.SchemaTableName{{SchemaName: v.Name.O, TableName: ""}} + case *ast.DropDatabaseStmt: + return []commonEvent.SchemaTableName{{SchemaName: v.Name.O, TableName: ""}} + } + + e := &tableNameExtractor{ + names: make([]commonEvent.SchemaTableName, 0), + } + stmt.Accept(e) + + return e.names +} + +// tableRenameVisitor rewrites table names in a DDL AST. +// +// TableName nodes are rewritten positionally in the same traversal order as +// extractTableNames. For CREATE VIEW, TiDB represents `db`.`table`.`column` as +// a ColumnName node, so the visitor also rewrites the schema/table qualifier +// when it is explicitly schema-qualified. Table-qualified columns and wildcards +// follow unaliased physical tables in their SELECT; CTE and alias references +// retain their names. +// +// Example for a CREATE VIEW with routing rule source_db.* → target_db.{table}_r: +// +// Source AST: +// CREATE VIEW `source_db`.`v` AS +// SELECT `source_db`.`t`.`id` FROM `source_db`.`t` +// +// Positional: {source_db, v} → {target_db, v_r} +// {source_db, t} → {target_db, t_r} +// +// Schema-qualified column reference: `source_db`.`t`.`id` +// qualified lookup: {source_db, t} → {target_db, t_r} +// → `target_db`.`t_r`.`id` +// +// Rewritten AST: +// CREATE VIEW `target_db`.`v_r` AS +// SELECT `target_db`.`t_r`.`id` FROM `target_db`.`t_r` +type tableRenameVisitor struct { + ctes cteScopes + sourceNames []commonEvent.SchemaTableName + // Each SELECT owns its unqualified column and wildcard references. + selectScopes []selectScope + // targetNames contains routed names aligned with tableNameExtractor output. + targetNames []commonEvent.SchemaTableName + // targetByQualifiedSource maps qualified source table names to routed names. + targetByQualifiedSource map[commonEvent.SchemaTableName]commonEvent.SchemaTableName + // i is the next targetNames index to consume. + i int + // hasErr records targetNames exhaustion because ast.Visitor cannot return an error. + hasErr bool +} + +type selectScope struct { + columns []*ast.ColumnName + tables map[string]commonEvent.SchemaTableName + fields *ast.FieldList + targets map[*ast.WildCardField]commonEvent.SchemaTableName +} + +func (v *tableRenameVisitor) Enter(in ast.Node) (ast.Node, bool) { + if v.hasErr { + return in, true + } + v.ctes.enter(in) + switch n := in.(type) { + case *ast.SelectStmt: + v.selectScopes = append(v.selectScopes, selectScope{ + fields: n.Fields, + tables: make(map[string]commonEvent.SchemaTableName), + targets: make(map[*ast.WildCardField]commonEvent.SchemaTableName), + }) + case *ast.TableSource: + v.collectTable(n) + } + if t, ok := in.(*ast.TableName); ok { + if v.ctes.contains(t) { + return in, true + } + if v.i >= len(v.targetNames) { + v.hasErr = true + return in, true + } + t.Schema = ast.NewCIStr(v.targetNames[v.i].SchemaName) + t.Name = ast.NewCIStr(v.targetNames[v.i].TableName) + v.i++ + return in, true + } + if c, ok := in.(*ast.ColumnName); ok { + if c.Schema.O == "" && c.Table.O != "" && len(v.selectScopes) > 0 { + scope := &v.selectScopes[len(v.selectScopes)-1] + scope.columns = append(scope.columns, c) + } + v.rewriteColumnName(c) + return in, true + } + return in, false +} + +func (v *tableRenameVisitor) Leave(in ast.Node) (ast.Node, bool) { + if v.hasErr { + return in, false + } + v.ctes.leave(in) + if _, ok := in.(*ast.SelectStmt); ok { + scope := v.selectScopes[len(v.selectScopes)-1] + for _, column := range scope.columns { + if target, ok := scope.tables[column.Table.L]; ok { + column.Schema = ast.NewCIStr(target.SchemaName) + column.Table = ast.NewCIStr(target.TableName) + } + } + for field, target := range scope.targets { + field.Schema = ast.NewCIStr(target.SchemaName) + field.Table = ast.NewCIStr(target.TableName) + } + v.selectScopes = v.selectScopes[:len(v.selectScopes)-1] + } + return in, true +} + +func (v *tableRenameVisitor) collectTable(table *ast.TableSource) { + if table.AsName.O != "" || len(v.selectScopes) == 0 { + return + } + sourceTable, ok := table.Source.(*ast.TableName) + if !ok || v.ctes.contains(sourceTable) { + return + } + if v.i >= len(v.sourceNames) || v.i >= len(v.targetNames) { + return + } + // The TableName immediately following this TableSource uses index i. + source, target := v.sourceNames[v.i], v.targetNames[v.i] + scope := v.selectScopes[len(v.selectScopes)-1] + // Stored view queries can omit a column's schema even when FROM is qualified. + // Only unaliased physical tables in this SELECT can bind these references. + scope.tables[strings.ToLower(source.TableName)] = target + if scope.fields == nil { + return + } + for _, field := range scope.fields.Fields { + wildcard := field.WildCard + if wildcard == nil || wildcard.Table.O == "" || !strings.EqualFold(wildcard.Table.O, source.TableName) { + continue + } + if wildcard.Schema.O != "" && !strings.EqualFold(wildcard.Schema.O, source.SchemaName) { + continue + } + // Apply after visiting FROM so routed names cannot match another source. + scope.targets[wildcard] = target + } +} + +// rewriteColumnName rewrites only schema-qualified column references +// (e.g. `db`.`t`.`col`) to match routed table names. +func (v *tableRenameVisitor) rewriteColumnName(c *ast.ColumnName) { + if c == nil || c.Schema.O == "" || c.Table.O == "" { + return + } + + target, ok := v.targetByQualifiedSource[normalizedSchemaTableName(c.Schema.O, c.Table.O)] + if !ok { + return + } + c.Schema = ast.NewCIStr(target.SchemaName) + c.Table = ast.NewCIStr(target.TableName) +} + +// newTableRenameVisitor builds the lookup map used for schema-qualified column +// references. It pairs each source table with its routed target. +func newTableRenameVisitor( + sourceTables []commonEvent.SchemaTableName, + targetTables []commonEvent.SchemaTableName, +) *tableRenameVisitor { + visitor := &tableRenameVisitor{ + sourceNames: sourceTables, + targetNames: targetTables, + targetByQualifiedSource: make(map[commonEvent.SchemaTableName]commonEvent.SchemaTableName, len(sourceTables)), + } + + for i, source := range sourceTables { + if i >= len(targetTables) || source.TableName == "" { + continue + } + target := targetTables[i] + if source.SchemaName != "" { + visitor.targetByQualifiedSource[normalizedSchemaTableName(source.SchemaName, source.TableName)] = target + } + } + return visitor +} + +func normalizedSchemaTableName(schema, table string) commonEvent.SchemaTableName { + return commonEvent.SchemaTableName{ + SchemaName: strings.ToLower(schema), + TableName: strings.ToLower(table), + } +} + +// rewriteDDLStmtTables rewrites table names in a DDL AST. +// sourceTables and targetTables must have matching lengths and follow the +// traversal order produced by extractTableNames. TableName nodes are rewritten +// positionally. For CREATE VIEW, schema-qualified column references are also +// updated so `db`.`table`.`column` keeps pointing at the routed table. +// Table-qualified wildcards follow their unaliased table within each SELECT. +// +// Returned DDL uses StringSingleQuotes, KeyWordUppercase and NameBackQuotes. +func rewriteDDLStmtTables( + stmt ast.StmtNode, + sourceTables []commonEvent.SchemaTableName, + targetTables []commonEvent.SchemaTableName, +) (string, error) { + if _, ok := stmt.(ast.DDLNode); !ok { + return "", errors.ErrTableRoutingFailed.GenWithStack( + "rewrite ddl query got non ddl statement: %T", stmt) + } + + switch v := stmt.(type) { + case *ast.AlterDatabaseStmt: + if len(targetTables) != 1 { + return "", errors.ErrTableRoutingFailed.GenWithStack( + "rewrite ddl query got unexpected target table count: expected 1, got %d", len(targetTables)) + } + v.Name = ast.NewCIStr(targetTables[0].SchemaName) + case *ast.CreateDatabaseStmt: + if len(targetTables) != 1 { + return "", errors.ErrTableRoutingFailed.GenWithStack( + "rewrite ddl query got unexpected target table count: expected 1, got %d", len(targetTables)) + } + v.Name = ast.NewCIStr(targetTables[0].SchemaName) + case *ast.DropDatabaseStmt: + if len(targetTables) != 1 { + return "", errors.ErrTableRoutingFailed.GenWithStack( + "rewrite ddl query got unexpected target table count: expected 1, got %d", len(targetTables)) + } + v.Name = ast.NewCIStr(targetTables[0].SchemaName) + default: + visitor := newTableRenameVisitor(sourceTables, targetTables) + stmt.Accept(visitor) + if visitor.hasErr { + return "", errors.ErrTableRoutingFailed.GenWithStack( + "rewrite ddl query got too few target tables: count=%d", len(targetTables)) + } + // Check if all target tables were consumed - extra targets indicate a configuration mismatch + if visitor.i < len(targetTables) { + return "", errors.ErrTableRoutingFailed.GenWithStack( + "rewrite ddl query got too many target tables: count=%d, used=%d", len(targetTables), visitor.i) + } + } + + bf := &bytes.Buffer{} + err := stmt.Restore(&format.RestoreCtx{ + // TiDB stores the original SQL in sessionctx.QueryString and copies it into + // DDL job.Query: + // https://github.com/pingcap/tidb/blob/8f2630e53d5d/pkg/session/session.go#L2905 + // https://github.com/pingcap/tidb/blob/8f2630e53d5d/pkg/ddl/executor.go#L6952-L6957 + // After routing mutates the AST, CDC must serialize it again. Keep the + // parser's standard restore style, TiDB special comments, and default + // charset handling consistent with CDC's DDL query normalization. + Flags: format.DefaultRestoreFlags | format.RestoreTiDBSpecialComment | format.RestoreStringWithoutDefaultCharset, + In: bf, + }) + if err != nil { + return "", errors.WrapError(errors.ErrTableRoutingFailed, err) + } + + return bf.String(), nil +} diff --git a/downstreamadapter/routing/ddl_query_rewriter_test.go b/downstreamadapter/routing/ddl_query_rewriter_test.go new file mode 100644 index 0000000000..d70eca0819 --- /dev/null +++ b/downstreamadapter/routing/ddl_query_rewriter_test.go @@ -0,0 +1,534 @@ +// Copyright 2026 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 routing + +import ( + "testing" + + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/errors" + "github.com/pingcap/tidb/pkg/parser" + "github.com/stretchr/testify/require" +) + +type testCase struct { + sql string + expectedTableNames []commonEvent.SchemaTableName + targetTableNames []commonEvent.SchemaTableName + targetSQL string +} + +// TestResolveDDL tests FetchDDLTables and RenameDDLTable +func TestResolveDDL(t *testing.T) { + t.Parallel() + testCases := []testCase{ + // Test case with foreign key - foreign key references should be renamed together + { + "create table `t1` (`id` int, `student_id` int, primary key (`id`), foreign key (`student_id`) references `t2`(`id`))", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}, {SchemaName: "", TableName: "t2"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "t1"}, {SchemaName: "xtest", TableName: "t2"}}, + "CREATE TABLE `xtest`.`t1` (`id` INT,`student_id` INT,PRIMARY KEY(`id`),CONSTRAINT FOREIGN KEY (`student_id`) REFERENCES `xtest`.`t2`(`id`))", + }, + // CREATE SCHEMA/DATABASE + { + "create schema `s1`", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: ""}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: ""}}, + "CREATE DATABASE `xs1`", + }, + { + "create schema if not exists `s1`", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: ""}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: ""}}, + "CREATE DATABASE IF NOT EXISTS `xs1`", + }, + // DROP SCHEMA/DATABASE + { + "drop schema `s1`", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: ""}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: ""}}, + "DROP DATABASE `xs1`", + }, + { + "drop schema if exists `s1`", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: ""}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: ""}}, + "DROP DATABASE IF EXISTS `xs1`", + }, + // ALTER DATABASE without explicit name - cannot rename since AST doesn't store database name + { + "alter database collate utf8mb4_general_ci", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: ""}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: ""}}, + // Note: When no database name is in original SQL, RenameDDLTable cannot add it + // because the AST parser tracks whether name was present + "ALTER DATABASE COLLATE = utf8mb4_general_ci", + }, + // DROP TABLE - single table + { + "drop table `Ss1`.`tT1`", + []commonEvent.SchemaTableName{{SchemaName: "Ss1", TableName: "tT1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xSs1", TableName: "xtT1"}}, + "DROP TABLE `xSs1`.`xtT1`", + }, + // DROP TABLE - multiple tables (requires SplitDDL to split, so we test without splitting) + { + "drop table `s1`.`t1`, `s2`.`t2`", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: "t1"}, {SchemaName: "s2", TableName: "t2"}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: "xt1"}, {SchemaName: "xs2", TableName: "xt2"}}, + "DROP TABLE `xs1`.`xt1`, `xs2`.`xt2`", + }, + { + "drop table `s1`.`t1`, `s2`.`t2`, `xx`", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: "t1"}, {SchemaName: "s2", TableName: "t2"}, {SchemaName: "", TableName: "xx"}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: "xt1"}, {SchemaName: "xs2", TableName: "xt2"}, {SchemaName: "xtest", TableName: "xxx"}}, + "DROP TABLE `xs1`.`xt1`, `xs2`.`xt2`, `xtest`.`xxx`", + }, + // CREATE TABLE + { + "create table `s1`.`t1` (id int)", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: "xt1"}}, + "CREATE TABLE `xs1`.`xt1` (`id` INT)", + }, + { + "create table `t1` (id int)", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "CREATE TABLE `xtest`.`xt1` (`id` INT)", + }, + { + "create table `s1` (c int default '0')", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "s1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xs1"}}, + "CREATE TABLE `xtest`.`xs1` (`c` INT DEFAULT '0')", + }, + // CREATE TABLE LIKE + { + "create table `t1` like `t2`", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}, {SchemaName: "", TableName: "t2"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}, {SchemaName: "xtest", TableName: "xt2"}}, + "CREATE TABLE `xtest`.`xt1` LIKE `xtest`.`xt2`", + }, + { + "create table `s1`.`t1` like `t2`", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: "t1"}, {SchemaName: "", TableName: "t2"}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: "xt1"}, {SchemaName: "xtest", TableName: "xt2"}}, + "CREATE TABLE `xs1`.`xt1` LIKE `xtest`.`xt2`", + }, + { + "create table `t1` like `xx`.`t2`", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}, {SchemaName: "xx", TableName: "t2"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}, {SchemaName: "xxx", TableName: "xt2"}}, + "CREATE TABLE `xtest`.`xt1` LIKE `xxx`.`xt2`", + }, + // TRUNCATE TABLE + { + "truncate table `t1`", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "TRUNCATE TABLE `xtest`.`xt1`", + }, + { + "truncate table `s1`.`t1`", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: "xt1"}}, + "TRUNCATE TABLE `xs1`.`xt1`", + }, + // RENAME TABLE - single + { + "rename table `s1`.`t1` to `s2`.`t2`", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: "t1"}, {SchemaName: "s2", TableName: "t2"}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: "xt1"}, {SchemaName: "xs2", TableName: "xt2"}}, + "RENAME TABLE `xs1`.`xt1` TO `xs2`.`xt2`", + }, + // RENAME TABLE - multiple (no splitting) + { + "rename table `t1` to `t2`, `s1`.`t1` to `t2`", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}, {SchemaName: "", TableName: "t2"}, {SchemaName: "s1", TableName: "t1"}, {SchemaName: "", TableName: "t2"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}, {SchemaName: "xtest", TableName: "xt2"}, {SchemaName: "xs1", TableName: "xt1"}, {SchemaName: "xtest", TableName: "xt2"}}, + "RENAME TABLE `xtest`.`xt1` TO `xtest`.`xt2`, `xs1`.`xt1` TO `xtest`.`xt2`", + }, + // DROP INDEX + { + "drop index i1 on `s1`.`t1`", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: "xt1"}}, + "DROP INDEX `i1` ON `xs1`.`xt1`", + }, + { + "drop index i1 on `t1`", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "DROP INDEX `i1` ON `xtest`.`xt1`", + }, + // CREATE INDEX + { + "create index i1 on `t1`(`c1`)", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "CREATE INDEX `i1` ON `xtest`.`xt1` (`c1`)", + }, + { + "create index i1 on `s1`.`t1`(`c1`)", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: "xt1"}}, + "CREATE INDEX `i1` ON `xs1`.`xt1` (`c1`)", + }, + // ALTER TABLE - multiple specs (no splitting, test as single statement) + { + "alter table `t1` add column c1 int, drop column c2", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` ADD COLUMN `c1` INT, DROP COLUMN `c2`", + }, + { + "alter table `s1`.`t1` add column c1 int, rename to `t2`, drop column c2", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: "t1"}, {SchemaName: "", TableName: "t2"}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: "xt1"}, {SchemaName: "xtest", TableName: "xt2"}}, + "ALTER TABLE `xs1`.`xt1` ADD COLUMN `c1` INT, RENAME AS `xtest`.`xt2`, DROP COLUMN `c2`", + }, + { + "alter table `s1`.`t1` add column c1 int, rename to `xx`.`t2`, drop column c2", + []commonEvent.SchemaTableName{{SchemaName: "s1", TableName: "t1"}, {SchemaName: "xx", TableName: "t2"}}, + []commonEvent.SchemaTableName{{SchemaName: "xs1", TableName: "xt1"}, {SchemaName: "xxx", TableName: "xt2"}}, + "ALTER TABLE `xs1`.`xt1` ADD COLUMN `c1` INT, RENAME AS `xxx`.`xt2`, DROP COLUMN `c2`", + }, + // ALTER TABLE with IF NOT EXISTS / IF EXISTS + // Note: TiDB parser converts these to TiDB-specific comment syntax (/*T! ... */) + { + "alter table `t1` add column if not exists c1 int", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` ADD COLUMN /*T! IF NOT EXISTS */`c1` INT", + }, + { + "alter table `t1` add index if not exists (a) using btree comment 'a'", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` ADD INDEX/*T! IF NOT EXISTS */(`a`) USING BTREE COMMENT 'a'", + }, + { + "alter table `t1` add constraint fk_t2_id foreign key if not exists (t2_id) references t2(id)", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}, {SchemaName: "", TableName: "t2"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}, {SchemaName: "xtest", TableName: "xt2"}}, + "ALTER TABLE `xtest`.`xt1` ADD CONSTRAINT `fk_t2_id` FOREIGN KEY /*T! IF NOT EXISTS */(`t2_id`) REFERENCES `xtest`.`xt2`(`id`)", + }, + { + "create index if not exists i1 on `t1`(`c1`)", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "CREATE INDEX /*T! IF NOT EXISTS */`i1` ON `xtest`.`xt1` (`c1`)", + }, + { + "alter table `t1` add partition if not exists ( partition p2 values less than maxvalue)", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` ADD PARTITION/*T! IF NOT EXISTS */ (PARTITION `p2` VALUES LESS THAN (MAXVALUE))", + }, + { + "alter table `t1` drop column if exists c2", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` DROP COLUMN /*T! IF EXISTS */`c2`", + }, + { + "alter table `t1` change column if exists a b varchar(255)", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` CHANGE COLUMN /*T! IF EXISTS */`a` `b` VARCHAR(255)", + }, + { + "alter table `t1` modify column if exists a varchar(255)", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` MODIFY COLUMN /*T! IF EXISTS */`a` VARCHAR(255)", + }, + { + "alter table `t1` drop index if exists i1", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` DROP INDEX /*T! IF EXISTS */`i1`", + }, + { + "alter table `t1` drop foreign key fk_t2_id", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` DROP FOREIGN KEY `fk_t2_id`", + }, + { + "alter table `t1` drop partition if exists p2", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` DROP PARTITION /*T! IF EXISTS */`p2`", + }, + // ALTER TABLE PARTITION BY + { + "alter table `t1` partition by hash(a)", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` PARTITION BY HASH (`a`) PARTITIONS 1", + }, + { + "alter table `t1` partition by key(a)", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` PARTITION BY KEY (`a`) PARTITIONS 1", + }, + { + "alter table `t1` partition by range(a) (partition x values less than (75))", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` PARTITION BY RANGE (`a`) (PARTITION `x` VALUES LESS THAN (75))", + }, + { + "alter table `t1` partition by list columns (a, b) (partition x values in ((10, 20)))", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` PARTITION BY LIST COLUMNS (`a`,`b`) (PARTITION `x` VALUES IN ((10, 20)))", + }, + { + "alter table `t1` partition by list (a) (partition x default)", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` PARTITION BY LIST (`a`) (PARTITION `x` DEFAULT)", + }, + { + "alter table `t1` partition by system_time (partition x history, partition y current)", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "xt1"}}, + "ALTER TABLE `xtest`.`xt1` PARTITION BY SYSTEM_TIME (PARTITION `x` HISTORY,PARTITION `y` CURRENT)", + }, + // ALTER DATABASE with explicit name + { + "alter database `test` charset utf8mb4", + []commonEvent.SchemaTableName{{SchemaName: "test", TableName: ""}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: ""}}, + "ALTER DATABASE `xtest` CHARACTER SET = utf8mb4", + }, + // ALTER TABLE ADD COLUMN with multiple columns (no splitting) + { + "alter table `t1` add column (c1 int, c2 int)", + []commonEvent.SchemaTableName{{SchemaName: "", TableName: "t1"}}, + []commonEvent.SchemaTableName{{SchemaName: "xtest", TableName: "t1"}}, + "ALTER TABLE `xtest`.`t1` ADD COLUMN (`c1` INT, `c2` INT)", + }, + } + p := parser.New() + + for _, ca := range testCases { + stmts, _, err := p.Parse(ca.sql, "", "") + require.NoError(t, err) + require.Len(t, stmts, 1) + + // Test extractTableNames + tableNames := extractTableNames(stmts[0]) + require.Equal(t, ca.expectedTableNames, tableNames, "extractTableNames failed for: %s", ca.sql) + + // Re-parse for rewriteDDLStmtTables since it modifies AST in place + stmts, _, err = p.Parse(ca.sql, "", "") + require.NoError(t, err) + + // Test rewriteDDLStmtTables + targetSQL, err := rewriteDDLStmtTables(stmts[0], ca.expectedTableNames, ca.targetTableNames) + require.NoError(t, err, "rewriteDDLStmtTables failed for: %s", ca.sql) + require.Equal(t, ca.targetSQL, targetSQL, "rewriteDDLStmtTables failed for: %s", ca.sql) + } +} + +func TestFetchDDLTablesError(t *testing.T) { + t.Parallel() + + p := parser.New() + // SELECT is not a DDL statement - extractTableNames returns empty names + stmts, _, err := p.Parse("SELECT 1", "", "") + require.NoError(t, err) + require.Len(t, stmts, 1) + + names := extractTableNames(stmts[0]) + require.Empty(t, names) +} + +func TestRewriteDDLStmtTablesError(t *testing.T) { + t.Parallel() + + p := parser.New() + + t.Run("non ddl statement", func(t *testing.T) { + stmts, _, err := p.Parse("SELECT 1", "", "") + require.NoError(t, err) + _, err = rewriteDDLStmtTables(stmts[0], extractTableNames(stmts[0]), []commonEvent.SchemaTableName{}) + require.True(t, errors.ErrTableRoutingFailed.Equal(err)) + }) + + t.Run("unexpected target table count for alter database", func(t *testing.T) { + stmts, _, err := p.Parse("ALTER DATABASE `test` CHARACTER SET utf8mb4", "", "") + require.NoError(t, err) + _, err = rewriteDDLStmtTables(stmts[0], extractTableNames(stmts[0]), []commonEvent.SchemaTableName{{}, {}}) + require.True(t, errors.ErrTableRoutingFailed.Equal(err)) + }) + + t.Run("too few target tables", func(t *testing.T) { + stmts, _, err := p.Parse("RENAME TABLE `db1`.`t1` TO `db2`.`t2`", "", "") + require.NoError(t, err) + _, err = rewriteDDLStmtTables(stmts[0], extractTableNames(stmts[0]), []commonEvent.SchemaTableName{{SchemaName: "db1", TableName: "t1"}}) + require.True(t, errors.ErrTableRoutingFailed.Equal(err)) + }) + + t.Run("too many target tables", func(t *testing.T) { + stmts, _, err := p.Parse("CREATE TABLE `t1` (id INT)", "", "") + require.NoError(t, err) + _, err = rewriteDDLStmtTables(stmts[0], extractTableNames(stmts[0]), []commonEvent.SchemaTableName{{}, {}, {}}) + require.True(t, errors.ErrTableRoutingFailed.Equal(err)) + }) +} + +func TestRewriteParserBackedDDLQueryWithSemicolonsInLiteralsAndComments(t *testing.T) { + t.Parallel() + + router := newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + TargetTable: "{table}_routed", + }}) + + tests := []struct { + name string + query string + requiredFragments []string + forbiddenFragment string + }{ + { + name: "semicolon inside default string", + query: "CREATE TABLE `source_db`.`semi_table` (`c` VARCHAR(100) DEFAULT 'a;b;c');", + requiredFragments: []string{ + "`target_db`.`semi_table_routed`", + "DEFAULT 'a;b;c'", + }, + forbiddenFragment: "`source_db`.`semi_table`", + }, + { + name: "semicolon inside block comment", + query: "/* comment; not a statement */ CREATE TABLE `source_db`.`comment_table` (`c` INT);", + requiredFragments: []string{ + "`target_db`.`comment_table_routed`", + }, + forbiddenFragment: "`source_db`.`comment_table`", + }, + { + name: "multi statement with semicolons inside default string and comment", + query: "CREATE TABLE `source_db`.`t1` (`c` VARCHAR(100) DEFAULT 'a;b'); " + + "/* comment; not a statement */ CREATE TABLE `source_db`.`t2` (`c` INT);", + requiredFragments: []string{ + "`target_db`.`t1_routed`", + "DEFAULT 'a;b'", + "`target_db`.`t2_routed`", + }, + forbiddenFragment: "`source_db`", + }, + } + + for _, tc := range tests { + tc := tc + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + newQuery, err := router.rewriteParserBackedDDLQuery(&commonEvent.DDLEvent{Query: tc.query}) + require.NoError(t, err) + for _, fragment := range tc.requiredFragments { + require.Contains(t, newQuery, fragment) + } + require.NotContains(t, newQuery, tc.forbiddenFragment) + }) + } +} + +func TestRewriteParserBackedDDLQueryUsesEventSchemaForUnqualifiedReferences(t *testing.T) { + t.Parallel() + + router := newTestRouter(t, false, []*config.DispatchRule{ + { + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + TargetTable: TablePlaceholder, + }, + { + Matcher: []string{"source_extra_db.*"}, + TargetSchema: "target_extra_db", + TargetTable: TablePlaceholder, + }, + }) + + tests := []struct { + name string + query string + expected string + }{ + { + name: "create table like", + query: "CREATE TABLE `source_db`.`external_users` LIKE `users`", + expected: "CREATE TABLE `target_db`.`external_users` LIKE `target_db`.`users`", + }, + { + name: "create table as select", + query: "CREATE TABLE `source_db`.`external_users` AS SELECT * FROM `users`", + expected: "CREATE TABLE `target_db`.`external_users` AS SELECT * FROM `target_db`.`users`", + }, + { + name: "create view as select", + query: "CREATE VIEW `source_db`.`external_users` AS SELECT * FROM `users`", + expected: "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`external_users` AS SELECT * FROM `target_db`.`users`", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + newQuery, err := router.rewriteParserBackedDDLQuery(&commonEvent.DDLEvent{ + SchemaName: "source_db", + TableName: "external_users", + Query: tc.query, + }) + require.NoError(t, err) + require.Equal(t, tc.expected, newQuery) + }) + } +} + +func TestRewriteParserBackedDDLQueryUsesQuerySchemaForCreateTableLike(t *testing.T) { + t.Parallel() + + router := newTestRouter(t, false, []*config.DispatchRule{ + { + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + TargetTable: TablePlaceholder, + }, + { + Matcher: []string{"source_extra_db.*"}, + TargetSchema: "target_extra_db", + TargetTable: TablePlaceholder, + }, + }) + + newQuery, err := router.rewriteParserBackedDDLQuery(&commonEvent.DDLEvent{ + SchemaName: "source_extra_db", + TableName: "external_users", + Query: "CREATE TABLE `source_extra_db`.`external_users` LIKE `source_db`.`users`", + }) + require.NoError(t, err) + require.Equal(t, "CREATE TABLE `target_extra_db`.`external_users` LIKE `target_db`.`users`", newQuery) +} diff --git a/downstreamadapter/routing/registry.go b/downstreamadapter/routing/registry.go new file mode 100644 index 0000000000..3794b56711 --- /dev/null +++ b/downstreamadapter/routing/registry.go @@ -0,0 +1,64 @@ +// Copyright 2026 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 routing + +import ( + "github.com/pingcap/log" + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/errors" + "go.uber.org/zap" +) + +type targetKey = tableKey + +// TargetTableRegistry tracks which upstream source table name owns each downstream +// target table name. Different source names mapping to the same target is a conflict; +// registering the same source-target mapping repeatedly is idempotent. +type TargetTableRegistry struct { + changefeedID common.ChangeFeedID + memo map[targetKey]routeBinding +} + +// NewTargetTableRegistry creates an empty registry. +func NewTargetTableRegistry(changefeedID common.ChangeFeedID) *TargetTableRegistry { + return &TargetTableRegistry{ + changefeedID: changefeedID, + memo: make(map[targetKey]routeBinding), + } +} + +// Add validates and records a source-to-target table name mapping. +func (r *TargetTableRegistry) Add(binding routeBinding) error { + existing, ok := r.memo[binding.Target] + if !ok { + r.memo[binding.Target] = binding + return nil + } + if existing.Source.Equal(binding.Source) { + return nil + } + log.Warn("table route conflict detected", + zap.String("keyspace", r.changefeedID.Keyspace()), + zap.String("changefeed", r.changefeedID.Name()), + zap.String("targetSchema", binding.Target.Schema), + zap.String("targetTable", binding.Target.Table), + zap.String("existingSourceSchema", existing.Source.Schema), + zap.String("existingSourceTable", existing.Source.Table), + zap.String("incomingSourceSchema", binding.Source.Schema), + zap.String("incomingSourceTable", binding.Source.Table)) + return errors.ErrTableRouteConflict.FastGenByArgs( + binding.Target.Schema, binding.Target.Table, + existing.Source.Schema, existing.Source.Table, + binding.Source.Schema, binding.Source.Table) +} diff --git a/downstreamadapter/routing/registry_test.go b/downstreamadapter/routing/registry_test.go new file mode 100644 index 0000000000..c87c3dee80 --- /dev/null +++ b/downstreamadapter/routing/registry_test.go @@ -0,0 +1,104 @@ +// Copyright 2026 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 routing + +import ( + "testing" + + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/errors" + "github.com/stretchr/testify/require" +) + +func TestTargetTableRegistryAdd(t *testing.T) { + t.Parallel() + + changefeedID := common.NewChangeFeedIDWithName("test-changefeed", common.DefaultKeyspaceName) + t.Run("non-conflicting bindings", func(t *testing.T) { + t.Parallel() + r := NewTargetTableRegistry(changefeedID) + require.NotNil(t, r) + + require.NoError(t, r.Add(newRouteBinding("db1", "t1", "db1", "t1"))) + require.NoError(t, r.Add(newRouteBinding("db1", "t2", "archive", "t2"))) + }) + + t.Run("conflicting bindings fail", func(t *testing.T) { + t.Parallel() + r := NewTargetTableRegistry(changefeedID) + + require.NoError(t, r.Add(newRouteBinding("db1", "t1", "archive", "orders"))) + err := r.Add(newRouteBinding("db2", "t1", "archive", "orders")) + require.Error(t, err) + require.True(t, errors.ErrTableRouteConflict.Equal(err)) + require.Contains(t, err.Error(), "target `archive`.`orders`") + require.Contains(t, err.Error(), "source `db1`.`t1`") + require.Contains(t, err.Error(), "source `db2`.`t1`") + }) + + t.Run("same source mapping is idempotent", func(t *testing.T) { + t.Parallel() + r := NewTargetTableRegistry(changefeedID) + + require.NoError(t, r.Add(newRouteBinding("db1", "t1", "db1", "t1"))) + require.NoError(t, r.Add(newRouteBinding("db1", "t1", "db1", "t1"))) + }) +} + +func TestValidateNoStaticRouteConflict(t *testing.T) { + t.Parallel() + + changefeedID := common.NewChangeFeedIDWithName("test-changefeed", common.DefaultKeyspaceName) + rules := []*config.DispatchRule{ + {Matcher: []string{"db1.*"}, TargetSchema: "archive", TargetTable: "{table}"}, + {Matcher: []string{"db2.*"}, TargetSchema: "archive", TargetTable: "{table}"}, + } + + err := ValidateNoStaticRouteConflict( + changefeedID, + false, + rules, + []common.TableName{{Schema: "db1", Table: "orders"}}, + []common.TableName{{Schema: "db2", Table: "orders"}}, + ) + require.Error(t, err) + require.True(t, errors.ErrTableRouteConflict.Equal(err)) + require.Contains(t, err.Error(), "target `archive`.`orders`") + require.Contains(t, err.Error(), "source `db1`.`orders`") + require.Contains(t, err.Error(), "source `db2`.`orders`") + + err = ValidateNoStaticRouteConflict(changefeedID, false, rules, []common.TableName{ + {Schema: "db1", Table: "orders"}, + {Schema: "db2", Table: "customers"}, + }) + require.NoError(t, err) + + err = ValidateNoStaticRouteConflict( + changefeedID, + false, + []*config.DispatchRule{ + {Matcher: []string{"db2.*"}, TargetSchema: "db1", TargetTable: "{table}"}, + }, + []common.TableName{ + {Schema: "db1", Table: "orders"}, + {Schema: "db2", Table: "orders"}, + }, + ) + require.Error(t, err) + require.True(t, errors.ErrTableRouteConflict.Equal(err)) + require.Contains(t, err.Error(), "target `db1`.`orders`") + require.Contains(t, err.Error(), "source `db1`.`orders`") + require.Contains(t, err.Error(), "source `db2`.`orders`") +} diff --git a/downstreamadapter/routing/router.go b/downstreamadapter/routing/router.go new file mode 100644 index 0000000000..d49d885bf2 --- /dev/null +++ b/downstreamadapter/routing/router.go @@ -0,0 +1,397 @@ +// Copyright 2026 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 routing + +import ( + "strings" + + "github.com/pingcap/log" + "github.com/pingcap/ticdc/pkg/common" + commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/errors" + cdcfilter "github.com/pingcap/ticdc/pkg/filter" + "github.com/pingcap/tidb/pkg/meta/model" + tfilter "github.com/pingcap/tidb/pkg/util/table-filter" + "go.uber.org/zap" +) + +// Routing expression placeholders that can be used in TargetSchema and TargetTable. +const ( + // SchemaPlaceholder is replaced with the source schema name in routing expressions. + SchemaPlaceholder = "{schema}" + // TablePlaceholder is replaced with the source table name in routing expressions. + TablePlaceholder = "{table}" +) + +type tableKey struct { + Schema string + Table string +} + +func (k tableKey) Equal(other tableKey) bool { + return k.Schema == other.Schema && k.Table == other.Table +} + +// routeBinding records one source-to-target route mapping. +type routeBinding struct { + Source tableKey + Target tableKey +} + +func newRouteBinding(schema, table, targetSchema, targetTable string) routeBinding { + return routeBinding{ + Source: tableKey{ + Schema: schema, + Table: table, + }, + Target: tableKey{ + Schema: targetSchema, + Table: targetTable, + }, + } +} + +func (b routeBinding) routed() bool { + return !b.Source.Equal(b.Target) +} + +// rule represents a single routing rule. +type rule struct { + filter tfilter.Filter + targetSchemaExpr string + targetTableExpr string +} + +// Router is used to support the table route functionality, +// which map the origin schema/table names to target schema/table names based on the given rules. +type Router struct { + changefeedID common.ChangeFeedID + rules []rule +} + +func (r Router) enabled() bool { + return len(r.rules) != 0 +} + +// NewRouter creates a new Router from dispatch rules. +// When multiple rules match the same table, the first matching rule wins. +func NewRouter( + changefeedID common.ChangeFeedID, caseSensitive bool, rules []*config.DispatchRule, +) (Router, error) { + routingRules := make([]rule, 0, len(rules)) + for _, r := range rules { + if r == nil || (r.TargetSchema == "" && r.TargetTable == "") { + continue + } + + f, err := tfilter.Parse(r.Matcher) + if err != nil { + log.Warn("router failed to initialize", + zap.String("keyspace", changefeedID.Keyspace()), + zap.String("changefeed", changefeedID.Name()), + zap.Strings("matcher", r.Matcher), + zap.Error(err)) + return Router{}, errors.WrapError(errors.ErrInvalidTableRoutingRule, err) + } + if !caseSensitive { + f = tfilter.CaseInsensitive(f) + } + + routingRules = append(routingRules, rule{ + filter: f, + targetSchemaExpr: r.TargetSchema, + targetTableExpr: r.TargetTable, + }) + } + + return Router{ + changefeedID: changefeedID, + rules: routingRules, + }, nil +} + +// ApplyToTableInfo returns the original TableInfo unless routing changes the target name. +// When routing changes the target, it clones the TableInfo so the caller can safely reuse +// routed metadata without mutating the shared source TableInfo. +func (r Router) ApplyToTableInfo(tableInfo *common.TableInfo) (*common.TableInfo, error) { + if len(r.rules) == 0 || tableInfo == nil { + return tableInfo, nil + } + + binding, err := r.route(tableInfo.GetSchemaName(), tableInfo.GetTableName()) + if err != nil { + return nil, err + } + if !binding.routed() { + return tableInfo, nil + } + return tableInfo.CloneWithRouting(binding.Target.Schema, binding.Target.Table), nil +} + +// ApplyToDDLEvent returns the original DDL event unless routing changes the DDL query; +// when query changes, it also routes related metadata. +func (r Router) ApplyToDDLEvent(ddl *commonEvent.DDLEvent) (*commonEvent.DDLEvent, error) { + if len(r.rules) == 0 || ddl == nil { + return ddl, nil + } + + switch model.ActionType(ddl.Type) { + case cdcfilter.ActionAddFullTextIndex, cdcfilter.ActionCreateHybridIndex: + return nil, errors.ErrTableRoutingFailed.GenWithStack( + "table routing does not support ddl type %d, query: %s", ddl.Type, ddl.Query) + } + + // Do not decide whether a DDL needs routing only from DDLEvent.SchemaName/TableName. + // Some DDL queries contain extra table references that are not the event's primary table. + // For example: + // + // CREATE VIEW `other_db`.`v1` AS SELECT * FROM `source_db`.`orders` + // + // The event primary table is `other_db`.`v1`, but table route may need to rewrite + // the referenced table `source_db`.`orders`. + // + // Another example is: + // + // ALTER TABLE `other_db`.`child` ADD CONSTRAINT `fk_order` + // FOREIGN KEY (`order_id`) REFERENCES `source_db`.`orders`(`id`) + // + // The event primary table is `other_db`.`child`, but the FOREIGN KEY reference can + // still match table route rules. So when table route is enabled, inspect the query + // through TiDB parser and let the AST visitor find all table names. + newQuery, err := r.rewriteParserBackedDDLQuery(ddl) + if err != nil { + return nil, err + } + + // In CDC DDL events, routed DDL metadata should correspond to names in Query. + // If Query is unchanged, no routed DDL event is needed. + if newQuery == ddl.Query { + return ddl, nil + } + + binding, err := r.route(ddl.GetSchemaName(), ddl.GetTableName()) + if err != nil { + return nil, err + } + + extraBinding, err := r.route(ddl.GetExtraSchemaName(), ddl.GetExtraTableName()) + if err != nil { + return nil, err + } + + tableInfo, err := r.ApplyToTableInfo(ddl.TableInfo) + if err != nil { + return nil, err + } + multipleTableInfos, err := r.applyToMultipleTableInfos(ddl.MultipleTableInfos) + if err != nil { + return nil, err + } + blockedTableNames, err := r.applyToBlockedTableNames(ddl.BlockedTableNames) + if err != nil { + return nil, err + } + + if multipleTableInfos == nil { + multipleTableInfos = append([]*common.TableInfo(nil), ddl.MultipleTableInfos...) + } + if blockedTableNames == nil { + blockedTableNames = append([]commonEvent.SchemaTableName(nil), ddl.BlockedTableNames...) + } + + log.Info("ddl query rewritten with routing", + zap.String("keyspace", r.changefeedID.Keyspace()), + zap.String("changefeed", r.changefeedID.Name()), + zap.String("originalQuery", ddl.Query), + zap.String("newQuery", newQuery)) + + return commonEvent.NewRoutedDDLEvent( + ddl, + newQuery, + binding.Target.Schema, + binding.Target.Table, + extraBinding.Target.Schema, + extraBinding.Target.Table, + tableInfo, + multipleTableInfos, + blockedTableNames, + ), nil +} + +// route returns the source-to-target table name binding. +func (r Router) route(originSchema, originTable string) (binding routeBinding, err error) { + // In CDC runtime, table names should always carry schema. + // Empty schema means this name pair is absent, so keep it unchanged. + // This also prevents wildcard rules like *.* from matching it. + if originSchema == "" { + return newRouteBinding(originSchema, originTable, originSchema, originTable), nil + } + + rule, err := r.matchRule(originSchema, originTable) + if err != nil { + return routeBinding{}, err + } + if rule == nil { + return newRouteBinding(originSchema, originTable, originSchema, originTable), nil + } + + targetSchema := substituteExpression(rule.targetSchemaExpr, originSchema, originTable, originSchema) + if targetSchema == "" { + return routeBinding{}, errors.ErrTableRoutingFailed.GenWithStack( + "target schema is empty for source %s.%s with expression %q", + originSchema, originTable, rule.targetSchemaExpr) + } + if originTable == "" { + return newRouteBinding(originSchema, originTable, targetSchema, originTable), nil + } + + targetTable := substituteExpression(rule.targetTableExpr, originSchema, originTable, originTable) + return newRouteBinding(originSchema, originTable, targetSchema, targetTable), nil +} + +// matchRule finds the first rule that matches the given schema/table. +func (r Router) matchRule(schema, table string) (*rule, error) { + if table == "" { + var ( + matched *rule + targetSchema string + ) + for i := range r.rules { + if !r.rules[i].filter.MatchSchema(schema) { + continue + } + + currentTargetSchema := substituteExpression(r.rules[i].targetSchemaExpr, schema, "", schema) + if matched == nil { + matched = &r.rules[i] + targetSchema = currentTargetSchema + continue + } + if currentTargetSchema != targetSchema { + return nil, errors.ErrTableRoutingFailed.GenWithStack( + "ambiguous schema routing for schema %s: target schema %s conflicts with %s", + schema, currentTargetSchema, targetSchema) + } + } + return matched, nil + } + + for i := range r.rules { + if r.rules[i].filter.MatchTable(schema, table) { + return &r.rules[i], nil + } + } + return nil, nil +} + +// applyToMultipleTableInfos returns nil when no entry changes. +// On the first routed entry, it clones the original slice once and only rewrites changed items, +// so unchanged entries keep their original references and the source event slice is left untouched. +func (r Router) applyToMultipleTableInfos(tableInfos []*common.TableInfo) ([]*common.TableInfo, error) { + if len(tableInfos) == 0 { + return nil, nil + } + + var result []*common.TableInfo + for i, tableInfo := range tableInfos { + routedTableInfo, err := r.ApplyToTableInfo(tableInfo) + if err != nil { + return nil, err + } + if routedTableInfo == tableInfo { + continue + } + if result == nil { + result = append([]*common.TableInfo(nil), tableInfos...) + } + result[i] = routedTableInfo + } + return result, nil +} + +// applyToBlockedTableNames returns nil when no entry changes. +// On the first routed entry, it clones the original slice once and only rewrites changed items, +// so unchanged entries keep their original values and the source event slice is left untouched. +func (r Router) applyToBlockedTableNames(tableNames []commonEvent.SchemaTableName) ([]commonEvent.SchemaTableName, error) { + if len(tableNames) == 0 { + return nil, nil + } + + var result []commonEvent.SchemaTableName + for i, tableName := range tableNames { + binding, err := r.route(tableName.SchemaName, tableName.TableName) + if err != nil { + return nil, err + } + if !binding.routed() { + continue + } + if result == nil { + result = append([]commonEvent.SchemaTableName(nil), tableNames...) + } + result[i] = commonEvent.SchemaTableName{ + SchemaName: binding.Target.Schema, + TableName: binding.Target.Table, + } + } + return result, nil +} + +// substituteExpression replaces {schema} and {table} placeholders with actual values. +// Placeholder-like text in source names is preserved literally. +// If expr is empty, returns defaultValue (typically sourceSchema for schema expressions, +// sourceTable for table expressions). +func substituteExpression(expr, sourceSchema, sourceTable, defaultValue string) string { + if expr == "" { + return defaultValue + } + + return strings.NewReplacer( + SchemaPlaceholder, sourceSchema, + TablePlaceholder, sourceTable, + ).Replace(expr) +} + +// ValidateNoStaticRouteConflict checks whether the given table names would produce +// any route conflicts under the provided dispatch rules. It returns ErrTableRouteConflict +// on the first conflict found, or nil when there is no conflict. +func ValidateNoStaticRouteConflict( + changefeedID common.ChangeFeedID, + caseSensitive bool, + rules []*config.DispatchRule, + tableNameGroups ...[]common.TableName, +) error { + router, err := NewRouter(changefeedID, caseSensitive, rules) + if err != nil { + return err + } + if !router.enabled() { + return nil + } + + registry := NewTargetTableRegistry(changefeedID) + for _, tableNames := range tableNameGroups { + for _, tableName := range tableNames { + binding, err := router.route(tableName.Schema, tableName.Table) + if err != nil { + return err + } + if err := registry.Add(binding); err != nil { + return err + } + } + } + return nil +} diff --git a/downstreamadapter/routing/router_apply_test.go b/downstreamadapter/routing/router_apply_test.go new file mode 100644 index 0000000000..ed7b7f309d --- /dev/null +++ b/downstreamadapter/routing/router_apply_test.go @@ -0,0 +1,1052 @@ +// Copyright 2026 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 routing + +import ( + "testing" + + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/errors" + cdcfilter "github.com/pingcap/ticdc/pkg/filter" + "github.com/pingcap/tidb/pkg/meta/model" + "github.com/pingcap/tidb/pkg/testkit" + "github.com/stretchr/testify/require" +) + +func newTestChangefeedID() common.ChangeFeedID { + return common.NewChangefeedID4Test(common.DefaultKeyspaceName, "test-changefeed") +} + +func TestApplyToTableInfo(t *testing.T) { + t.Parallel() + + tableInfo := &common.TableInfo{ + TableName: common.TableName{ + Schema: "source_db", + Table: "source_table", + TableID: 1, + }, + } + + var zeroRouter Router + routed, err := zeroRouter.ApplyToTableInfo(tableInfo) + require.NoError(t, err) + require.Same(t, tableInfo, routed) + + noOpRouter, err := NewRouter(newTestChangefeedID(), false, []*config.DispatchRule{ + { + Matcher: []string{"other_db.*"}, + TargetSchema: "target_db", + TargetTable: TablePlaceholder, + }, + }) + require.NoError(t, err) + routed, err = noOpRouter.ApplyToTableInfo(tableInfo) + require.NoError(t, err) + require.Same(t, tableInfo, routed) + + router, err := NewRouter(newTestChangefeedID(), false, []*config.DispatchRule{ + { + Matcher: []string{"source_db.source_table"}, + TargetSchema: "target_db", + TargetTable: "target_table", + }, + }) + require.NoError(t, err) + + routed, err = router.ApplyToTableInfo(tableInfo) + require.NoError(t, err) + require.NotSame(t, tableInfo, routed) + require.Equal(t, "source_db", routed.GetSchemaName()) + require.Equal(t, "source_table", routed.GetTableName()) + require.Equal(t, "target_db", routed.GetTargetSchemaName()) + require.Equal(t, "target_table", routed.GetTargetTableName()) + require.Equal(t, "source_db", routed.TableName.Schema) + require.Equal(t, "source_table", routed.TableName.Table) + require.Equal(t, "target_db", routed.TableName.TargetSchema) + require.Equal(t, "target_table", routed.TableName.TargetTable) + + require.Empty(t, tableInfo.TableName.TargetSchema) + require.Empty(t, tableInfo.TableName.TargetTable) +} + +func TestApplyToTableInfoReturnsAmbiguousSchemaRoutingError(t *testing.T) { + t.Parallel() + + router := newTestRouter(t, false, []*config.DispatchRule{ + { + Matcher: []string{"source_db.orders"}, + TargetSchema: "orders_db", + TargetTable: TablePlaceholder, + }, + { + Matcher: []string{"source_db.users"}, + TargetSchema: "users_db", + TargetTable: TablePlaceholder, + }, + }) + tableInfo := &common.TableInfo{ + TableName: common.TableName{ + Schema: "source_db", + }, + } + + _, err := router.ApplyToTableInfo(tableInfo) + require.Error(t, err) + require.True(t, errors.ErrTableRoutingFailed.Equal(err)) + require.Contains(t, err.Error(), "ambiguous schema routing") +} + +func TestApplyToDDLEvent(t *testing.T) { + helper := event.NewEventTestHelper(t) + defer helper.Close() + + sourceDBDDL := helper.DDL2Event("CREATE DATABASE `source_db`") + oldDBDDL := helper.DDL2Event("CREATE DATABASE `old_db`") + newDBDDL := helper.DDL2Event("CREATE DATABASE `new_db`") + multiDBDDL := helper.DDL2Event("CREATE DATABASE `multi_db`") + sourceTableDDL := helper.DDL2Event("CREATE TABLE `source_db`.`source_table` (`id` INT PRIMARY KEY)") + singleTableDDL := helper.DDL2Event("ALTER TABLE `source_db`.`source_table` ADD INDEX `idx_id`(`id`)") + helper.DDL2Event("CREATE DATABASE `other_db`") + queryOnlyRouteDDL := helper.DDL2Event("CREATE VIEW `other_db`.`source_view` AS SELECT * FROM `source_db`.`source_table`") + queryOnlyRouteDDL.BlockedTableNames = []event.SchemaTableName{{SchemaName: "other_db", TableName: "source_view"}} + queryOnlyRouteDDL.MultipleTableInfos = []*common.TableInfo{{ + TableName: common.TableName{Schema: "other_db", Table: "source_view"}, + }} + multiT1DDL := helper.DDL2Event("CREATE TABLE `multi_db`.`t1` (`id` INT PRIMARY KEY)") + multiT2DDL := helper.DDL2Event("CREATE TABLE `multi_db`.`t2` (`id` INT PRIMARY KEY)") + renameTablesDDL := helper.DDL2Event("RENAME TABLE `multi_db`.`t1` TO `multi_db`.`t1_new`, `multi_db`.`t2` TO `multi_db`.`t2_new`") + oldOrdersDDL := helper.DDL2Event("CREATE TABLE `old_db`.`orders` (`id` INT PRIMARY KEY)") + renameDDL := helper.DDL2Event("RENAME TABLE `old_db`.`orders` TO `new_db`.`orders_archive`") + helper.DDL2Event("CREATE DATABASE `db{table}`") + literalSchemaDDL := helper.DDL2Event("CREATE TABLE `db{table}`.`orders` (`id` INT PRIMARY KEY)") + literalTableDDL := helper.DDL2Event("CREATE TABLE `source_db`.`table{table}` (`id` INT PRIMARY KEY)") + literalNameRouter := newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"*.*"}, + TargetSchema: "{schema}_archive", + TargetTable: "{schema}_{table}", + }}) + + var zeroRouter Router + noMatchedRouter := newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"other_db.*"}, + TargetSchema: "target_db", + TargetTable: "target_table", + }}) + sourceRouter := newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_db.source_table"}, + TargetSchema: "target_db", + TargetTable: "target_table", + }}) + sourceSchemaRouter := newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + TargetTable: "target_table", + }}) + renameRouter := newTestRouter(t, false, []*config.DispatchRule{ + { + Matcher: []string{"old_db.*"}, + TargetSchema: "old_target_db", + TargetTable: "{table}_old", + }, + { + Matcher: []string{"new_db.*"}, + TargetSchema: "new_target_db", + TargetTable: "{table}_new", + }, + }) + multiRouter := newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"multi_db.*"}, + TargetSchema: "target_multi_db", + TargetTable: "{table}_routed", + }}) + + tests := []struct { + name string + router Router + ddl *event.DDLEvent + expectSame bool + check func(t *testing.T, original, routed *event.DDLEvent) + }{ + { + name: "zero router keeps original", + router: zeroRouter, + ddl: singleTableDDL, + expectSame: true, + }, + { + name: "placeholder in source schema stays literal", + router: literalNameRouter, + ddl: literalSchemaDDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Contains(t, routed.Query, "`db{table}_archive`.`db{table}_orders`") + require.Equal(t, "db{table}_archive", routed.TableInfo.GetTargetSchemaName()) + require.Equal(t, "db{table}_orders", routed.TableInfo.GetTargetTableName()) + }, + }, + { + name: "placeholder in source table stays literal", + router: literalNameRouter, + ddl: literalTableDDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Contains(t, routed.Query, "`source_db_archive`.`source_db_table{table}`") + require.Equal(t, "source_db_archive", routed.TableInfo.GetTargetSchemaName()) + require.Equal(t, "source_db_table{table}", routed.TableInfo.GetTargetTableName()) + }, + }, + { + name: "no matched rule keeps original", + router: noMatchedRouter, + ddl: singleTableDDL, + expectSame: true, + }, + { + name: "source database ddl", + router: sourceSchemaRouter, + ddl: sourceDBDDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Contains(t, routed.Query, "`target_db`") + require.NotContains(t, routed.Query, "`source_db`") + require.Equal(t, "source_db", routed.SchemaName) + require.Equal(t, "target_db", routed.GetTargetSchemaName()) + require.Equal(t, "source_db", original.SchemaName) + }, + }, + { + name: "old database ddl", + router: renameRouter, + ddl: oldDBDDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Contains(t, routed.Query, "`old_target_db`") + require.Equal(t, "old_db", routed.SchemaName) + require.Equal(t, "old_target_db", routed.GetTargetSchemaName()) + }, + }, + { + name: "new database ddl", + router: renameRouter, + ddl: newDBDDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Contains(t, routed.Query, "`new_target_db`") + require.Equal(t, "new_db", routed.SchemaName) + require.Equal(t, "new_target_db", routed.GetTargetSchemaName()) + }, + }, + { + name: "multi database ddl", + router: multiRouter, + ddl: multiDBDDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Contains(t, routed.Query, "`target_multi_db`") + require.Equal(t, "multi_db", routed.SchemaName) + require.Equal(t, "target_multi_db", routed.GetTargetSchemaName()) + }, + }, + { + name: "create source table ddl", + router: sourceRouter, + ddl: sourceTableDDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Contains(t, routed.Query, "`target_db`.`target_table`") + require.NotSame(t, original.TableInfo, routed.TableInfo) + require.Equal(t, "target_db", routed.TableInfo.GetTargetSchemaName()) + require.Equal(t, "target_table", routed.TableInfo.GetTargetTableName()) + }, + }, + { + name: "single table ddl", + router: sourceRouter, + ddl: singleTableDDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Contains(t, routed.Query, "`target_db`.`target_table`") + require.Equal(t, "source_db", routed.GetSchemaName()) + require.Equal(t, "source_db", routed.SchemaName) + require.Equal(t, "source_table", routed.TableName) + require.Equal(t, "target_db", routed.GetTargetSchemaName()) + require.Equal(t, "target_table", routed.GetTargetTableName()) + require.NotSame(t, original.TableInfo, routed.TableInfo) + require.Equal(t, "source_db", routed.TableInfo.GetSchemaName()) + require.Equal(t, "source_table", routed.TableInfo.GetTableName()) + require.Equal(t, "target_db", routed.TableInfo.GetTargetSchemaName()) + require.Equal(t, "target_table", routed.TableInfo.GetTargetTableName()) + require.Equal(t, "target_db", routed.TableInfo.TableName.TargetSchema) + require.Equal(t, "target_table", routed.TableInfo.TableName.TargetTable) + require.Equal(t, event.SchemaTableName{ + SchemaName: "target_db", + TableName: "target_table", + }, routed.BlockedTableNames[0]) + + require.Contains(t, original.Query, "`source_db`.`source_table`") + require.Equal(t, "source_db", original.GetSchemaName()) + require.Empty(t, original.TableInfo.TableName.TargetSchema) + require.Empty(t, original.TableInfo.TableName.TargetTable) + }, + }, + { + name: "old table create ddl", + router: renameRouter, + ddl: oldOrdersDDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Contains(t, routed.Query, "`old_target_db`.`orders_old`") + require.NotSame(t, original.TableInfo, routed.TableInfo) + require.Equal(t, "old_target_db", routed.TableInfo.GetTargetSchemaName()) + require.Equal(t, "orders_old", routed.TableInfo.GetTargetTableName()) + }, + }, + { + name: "rename ddl", + router: renameRouter, + ddl: renameDDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Equal(t, "new_db", routed.SchemaName) + require.Equal(t, "orders_archive", routed.TableName) + require.Equal(t, "old_db", routed.ExtraSchemaName) + require.Equal(t, "orders", routed.ExtraTableName) + require.Equal(t, "new_target_db", routed.GetTargetSchemaName()) + require.Equal(t, "orders_archive_new", routed.GetTargetTableName()) + require.Equal(t, "old_target_db", routed.GetTargetExtraSchemaName()) + require.Equal(t, "orders_old", routed.GetTargetExtraTableName()) + require.Equal(t, event.SchemaTableName{ + SchemaName: "new_db", + TableName: "orders_archive", + }, routed.TableNameChange.AddName[0]) + require.Equal(t, event.SchemaTableName{ + SchemaName: "old_db", + TableName: "orders", + }, routed.TableNameChange.DropName[0]) + require.Contains(t, routed.Query, "`old_target_db`.`orders_old`") + require.Contains(t, routed.Query, "`new_target_db`.`orders_archive_new`") + require.Equal(t, "new_db", original.SchemaName) + require.Equal(t, "orders_archive", original.TableName) + require.Equal(t, "old_db", original.ExtraSchemaName) + require.Equal(t, "orders", original.ExtraTableName) + }, + }, + { + name: "multi table t1 create ddl", + router: multiRouter, + ddl: multiT1DDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Contains(t, routed.Query, "`target_multi_db`.`t1_routed`") + require.NotSame(t, original.TableInfo, routed.TableInfo) + require.Equal(t, "target_multi_db", routed.TableInfo.GetTargetSchemaName()) + require.Equal(t, "t1_routed", routed.TableInfo.GetTargetTableName()) + }, + }, + { + name: "multi table t2 create ddl", + router: multiRouter, + ddl: multiT2DDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Contains(t, routed.Query, "`target_multi_db`.`t2_routed`") + require.NotSame(t, original.TableInfo, routed.TableInfo) + require.Equal(t, "target_multi_db", routed.TableInfo.GetTargetSchemaName()) + require.Equal(t, "t2_routed", routed.TableInfo.GetTargetTableName()) + }, + }, + { + name: "rename tables routes multiple table infos", + router: multiRouter, + ddl: renameTablesDDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Len(t, routed.MultipleTableInfos, 2) + require.Contains(t, routed.Query, "`target_multi_db`.`t1_routed`") + require.Contains(t, routed.Query, "`target_multi_db`.`t1_new_routed`") + require.Contains(t, routed.Query, "`target_multi_db`.`t2_routed`") + require.Contains(t, routed.Query, "`target_multi_db`.`t2_new_routed`") + require.NotSame(t, original.MultipleTableInfos[0], routed.MultipleTableInfos[0]) + require.NotSame(t, original.MultipleTableInfos[1], routed.MultipleTableInfos[1]) + require.Equal(t, "multi_db", routed.MultipleTableInfos[0].GetSchemaName()) + require.Equal(t, "t1_new", routed.MultipleTableInfos[0].GetTableName()) + require.Equal(t, "target_multi_db", routed.MultipleTableInfos[0].GetTargetSchemaName()) + require.Equal(t, "t1_new_routed", routed.MultipleTableInfos[0].GetTargetTableName()) + require.Equal(t, "multi_db", routed.MultipleTableInfos[1].GetSchemaName()) + require.Equal(t, "t2_new", routed.MultipleTableInfos[1].GetTableName()) + require.Equal(t, "target_multi_db", routed.MultipleTableInfos[1].GetTargetSchemaName()) + require.Equal(t, "t2_new_routed", routed.MultipleTableInfos[1].GetTargetTableName()) + require.Empty(t, original.MultipleTableInfos[0].TableName.TargetSchema) + require.Empty(t, original.MultipleTableInfos[0].TableName.TargetTable) + }, + }, + { + name: "single table ddl routes blocked table names", + router: sourceRouter, + ddl: singleTableDDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.True(t, &original.BlockedTableNames[0] != &routed.BlockedTableNames[0]) + require.Equal(t, event.SchemaTableName{ + SchemaName: "target_db", + TableName: "target_table", + }, routed.BlockedTableNames[0]) + require.Equal(t, event.SchemaTableName{ + SchemaName: "source_db", + TableName: "source_table", + }, original.BlockedTableNames[0]) + }, + }, + { + name: "query-only routing clones unchanged metadata slices", + router: sourceSchemaRouter, + ddl: queryOnlyRouteDDL, + check: func(t *testing.T, original, routed *event.DDLEvent) { + require.Contains(t, routed.Query, "`target_db`.`target_table`") + require.Equal(t, original.BlockedTableNames, routed.BlockedTableNames) + require.True(t, &original.BlockedTableNames[0] != &routed.BlockedTableNames[0]) + require.Equal(t, original.MultipleTableInfos, routed.MultipleTableInfos) + require.Same(t, original.MultipleTableInfos[0], routed.MultipleTableInfos[0]) + require.True(t, &original.MultipleTableInfos[0] != &routed.MultipleTableInfos[0]) + }, + }, + } + + for _, tc := range tests { + tc := tc + t.Run(tc.name, func(t *testing.T) { + routed, err := tc.router.ApplyToDDLEvent(tc.ddl) + require.NoError(t, err) + if tc.expectSame { + require.Same(t, tc.ddl, routed) + return + } + require.NotSame(t, tc.ddl, routed) + tc.check(t, tc.ddl, routed) + }) + } +} + +func TestApplyToDDLEventRejectsAmbiguousSchemaRouting(t *testing.T) { + router := newTestRouter(t, false, []*config.DispatchRule{ + { + Matcher: []string{"source_db.orders"}, + TargetSchema: "orders_db", + TargetTable: TablePlaceholder, + }, + { + Matcher: []string{"source_db.users"}, + TargetSchema: "users_db", + TargetTable: TablePlaceholder, + }, + }) + + helper := event.NewEventTestHelper(t) + defer helper.Close() + + ddl := helper.DDL2Event("CREATE DATABASE `source_db`") + + _, err := router.ApplyToDDLEvent(ddl) + require.Error(t, err) + require.True(t, errors.ErrTableRoutingFailed.Equal(err)) + require.Contains(t, err.Error(), "ambiguous schema routing") +} + +func TestRewriteDDLQueryWithRouting(t *testing.T) { + helper := event.NewEventTestHelper(t) + defer helper.Close() + + sourceDBDDL := helper.DDL2Event("CREATE DATABASE `source_db`") + otherDBDDL := helper.DDL2Event("CREATE DATABASE `other_db`") + db1DDL := helper.DDL2Event("CREATE DATABASE `db1`") + db2DDL := helper.DDL2Event("CREATE DATABASE `db2`") + noRouterDDL := helper.DDL2Event("CREATE TABLE `source_db`.`test_table` (`id` INT PRIMARY KEY)") + noMatchedDDL := helper.DDL2Event("CREATE TABLE `other_db`.`test_table` (`id` INT PRIMARY KEY)") + matchedTableDDL := helper.DDL2Event("ALTER TABLE `source_db`.`test_table` ADD COLUMN `c` INT") + databaseDDL := helper.DDL2Event("ALTER DATABASE `source_db` CHARACTER SET utf8mb4") + db1TableDDL := helper.DDL2Event("CREATE TABLE `db1`.`t1` (`id` INT PRIMARY KEY)") + renameDDL := helper.DDL2Event("RENAME TABLE `db1`.`t1` TO `db2`.`t2`") + + tests := []struct { + name string + router Router + ddl *event.DDLEvent + expectedChanged bool + expectedQuery string + requiredFragments []string + forbiddenFragment string + }{ + { + name: "source database ddl rewrites schema", + router: newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + }}), + ddl: sourceDBDDL, + expectedChanged: true, + requiredFragments: []string{"`target_db`"}, + forbiddenFragment: "`source_db`", + }, + { + name: "other database ddl keeps original query", + router: newTestRouter(t, false, []*config.DispatchRule{{Matcher: []string{"source_db.*"}, TargetSchema: "target_db"}}), + ddl: otherDBDDL, + expectedChanged: false, + expectedQuery: otherDBDDL.Query, + }, + { + name: "db1 database ddl rewrites schema", + router: newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"db1.*"}, + TargetSchema: "target1", + }}), + ddl: db1DDL, + expectedChanged: true, + requiredFragments: []string{"`target1`"}, + forbiddenFragment: "`db1`", + }, + { + name: "db2 database ddl rewrites schema", + router: newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"db2.*"}, + TargetSchema: "target2", + }}), + ddl: db2DDL, + expectedChanged: true, + requiredFragments: []string{"`target2`"}, + forbiddenFragment: "`db2`", + }, + { + name: "no router keeps original query", + ddl: noRouterDDL, + expectedChanged: false, + expectedQuery: noRouterDDL.Query, + }, + { + name: "no matched rule keeps original query", + router: newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + TargetTable: TablePlaceholder, + }}), + ddl: noMatchedDDL, + expectedChanged: false, + expectedQuery: noMatchedDDL.Query, + }, + { + name: "matched table ddl rewrites target table", + router: newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + TargetTable: "{table}_routed", + }}), + ddl: matchedTableDDL, + expectedChanged: true, + requiredFragments: []string{"`target_db`.`test_table_routed`"}, + forbiddenFragment: "`source_db`.`test_table`", + }, + { + name: "db1 table create ddl rewrites table", + router: newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"db1.*"}, + TargetSchema: "target1", + TargetTable: TablePlaceholder, + }}), + ddl: db1TableDDL, + expectedChanged: true, + requiredFragments: []string{"`target1`.`t1`"}, + forbiddenFragment: "`db1`.`t1`", + }, + { + name: "rename ddl rewrites both tables", + router: newTestRouter(t, false, []*config.DispatchRule{ + { + Matcher: []string{"db1.*"}, + TargetSchema: "target1", + TargetTable: TablePlaceholder, + }, + { + Matcher: []string{"db2.*"}, + TargetSchema: "target2", + TargetTable: TablePlaceholder, + }, + }), + ddl: renameDDL, + expectedChanged: true, + requiredFragments: []string{"`target1`.`t1`", "`target2`.`t2`"}, + }, + { + name: "database ddl rewrites schema", + router: newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + }}), + ddl: databaseDDL, + expectedChanged: true, + requiredFragments: []string{"`target_db`"}, + forbiddenFragment: "`source_db`", + }, + } + + for _, tc := range tests { + tc := tc + t.Run(tc.name, func(t *testing.T) { + newQuery, err := tc.router.rewriteParserBackedDDLQuery(tc.ddl) + require.NoError(t, err) + require.Equal(t, tc.expectedChanged, newQuery != tc.ddl.Query) + if tc.expectedQuery != "" { + require.Equal(t, tc.expectedQuery, newQuery) + } + for _, fragment := range tc.requiredFragments { + require.Contains(t, newQuery, fragment) + } + if tc.forbiddenFragment != "" { + require.NotContains(t, newQuery, tc.forbiddenFragment) + } + }) + } +} + +func TestApplyToDDLEventReturnsOriginalWhenQueryDoesNotRoute(t *testing.T) { + router := newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + TargetTable: TablePlaceholder, + }}) + + helper := event.NewEventTestHelper(t) + defer helper.Close() + + otherDBDDL := helper.DDL2Event("CREATE DATABASE `other_db`") + otherTableDDL := helper.DDL2Event("CREATE TABLE `other_db`.`t1` (`id` INT PRIMARY KEY)") + ddl := helper.DDL2Event("ALTER TABLE `other_db`.`t1` ADD COLUMN `c1` INT") + + routed, err := router.ApplyToDDLEvent(otherDBDDL) + require.NoError(t, err) + require.Same(t, otherDBDDL, routed) + + routed, err = router.ApplyToDDLEvent(otherTableDDL) + require.NoError(t, err) + require.Same(t, otherTableDDL, routed) + + routed, err = router.ApplyToDDLEvent(ddl) + require.NoError(t, err) + require.Same(t, ddl, routed) +} + +func TestApplyToDDLEventRewritesQueryOnlyTableReferences(t *testing.T) { + router := newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + TargetTable: "{table}_routed", + }}) + + helper := event.NewEventTestHelper(t) + defer helper.Close() + + sourceDBDDL := helper.DDL2Event("CREATE DATABASE `source_db`") + otherDBDDL := helper.DDL2Event("CREATE DATABASE `other_db`") + sourceOrdersDDL := helper.DDL2Event("CREATE TABLE `source_db`.`orders` (`id` INT PRIMARY KEY)") + otherChildDDL := helper.DDL2Event("CREATE TABLE `other_db`.`child` (`id` INT PRIMARY KEY, `order_id` INT)") + ddl := helper.DDL2Event("CREATE VIEW `other_db`.`v1` AS SELECT * FROM `source_db`.`orders`") + qualifiedColumnDDL := helper.DDL2Event("CREATE VIEW `other_db`.`v2` AS SELECT `source_db`.`orders`.`id` FROM `source_db`.`orders`") + aliasedColumnDDL := helper.DDL2Event("CREATE VIEW `other_db`.`v3` AS SELECT `orders`.`id` FROM `source_db`.`orders` AS `orders`") + fkDDL := helper.DDL2Event("ALTER TABLE `other_db`.`child` ADD CONSTRAINT `fk_order` FOREIGN KEY (`order_id`) REFERENCES `source_db`.`orders`(`id`)") + + routed, err := router.ApplyToDDLEvent(sourceDBDDL) + require.NoError(t, err) + require.Contains(t, routed.Query, "`target_db`") + + routed, err = router.ApplyToDDLEvent(otherDBDDL) + require.NoError(t, err) + require.Same(t, otherDBDDL, routed) + + routed, err = router.ApplyToDDLEvent(sourceOrdersDDL) + require.NoError(t, err) + require.Contains(t, routed.Query, "`target_db`.`orders_routed`") + + routed, err = router.ApplyToDDLEvent(otherChildDDL) + require.NoError(t, err) + require.Same(t, otherChildDDL, routed) + + routed, err = router.ApplyToDDLEvent(ddl) + require.NoError(t, err) + require.NotSame(t, ddl, routed) + require.Contains(t, routed.Query, "`other_db`.`v1`") + require.Contains(t, routed.Query, "`target_db`.`orders_routed`") + require.NotContains(t, routed.Query, "`source_db`.`orders`") + require.Equal(t, "other_db", routed.GetTargetSchemaName()) + require.Equal(t, "v1", routed.GetTargetTableName()) + + routed, err = router.ApplyToDDLEvent(qualifiedColumnDDL) + require.NoError(t, err) + require.NotSame(t, qualifiedColumnDDL, routed) + require.Equal(t, + "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `other_db`.`v2` AS SELECT `target_db`.`orders_routed`.`id` AS `id` FROM `target_db`.`orders_routed`", + routed.Query) + require.Equal(t, "other_db", routed.GetTargetSchemaName()) + require.Equal(t, "v2", routed.GetTargetTableName()) + + routed, err = router.ApplyToDDLEvent(aliasedColumnDDL) + require.NoError(t, err) + require.NotSame(t, aliasedColumnDDL, routed) + require.Equal(t, + "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `other_db`.`v3` AS SELECT `orders`.`id` AS `id` FROM `target_db`.`orders_routed` AS `orders`", + routed.Query) + require.Equal(t, "other_db", routed.GetTargetSchemaName()) + require.Equal(t, "v3", routed.GetTargetTableName()) + + routed, err = router.ApplyToDDLEvent(fkDDL) + require.NoError(t, err) + require.NotSame(t, fkDDL, routed) + require.Contains(t, routed.Query, "REFERENCES `target_db`.`orders_routed`") + require.NotContains(t, routed.Query, "REFERENCES `source_db`.`orders`") + require.Equal(t, "other_db", routed.GetTargetSchemaName()) + require.Equal(t, "child", routed.GetTargetTableName()) +} + +func TestApplyToDDLEventRewritesCrossDatabaseDDLReferences(t *testing.T) { + router := newTestRouter(t, false, []*config.DispatchRule{ + { + Matcher: []string{"cross_src.*"}, + TargetSchema: "routed_src", + TargetTable: "{table}_r", + }, + { + Matcher: []string{"cross_dst.*"}, + TargetSchema: "routed_dst", + TargetTable: "{table}_r", + }, + }) + + helper := event.NewEventTestHelper(t) + defer helper.Close() + + routed, err := router.ApplyToDDLEvent(helper.DDL2Event("CREATE DATABASE `cross_src`")) + require.NoError(t, err) + require.Contains(t, routed.Query, "`routed_src`") + + routed, err = router.ApplyToDDLEvent(helper.DDL2Event("CREATE DATABASE `cross_dst`")) + require.NoError(t, err) + require.Contains(t, routed.Query, "`routed_dst`") + + routed, err = router.ApplyToDDLEvent(helper.DDL2Event("CREATE TABLE `cross_src`.`src` (`id` INT PRIMARY KEY)")) + require.NoError(t, err) + require.Contains(t, routed.Query, "`routed_src`.`src_r`") + + routed, err = router.ApplyToDDLEvent(helper.DDL2Event("CREATE TABLE `cross_dst`.`dst` LIKE `cross_src`.`src`")) + require.NoError(t, err) + require.Contains(t, routed.Query, "CREATE TABLE `routed_dst`.`dst_r` LIKE `routed_src`.`src_r`") + require.NotContains(t, routed.Query, "`cross_dst`.`dst`") + require.NotContains(t, routed.Query, "`cross_src`.`src`") + require.Equal(t, "routed_dst", routed.GetTargetSchemaName()) + require.Equal(t, "dst_r", routed.GetTargetTableName()) + require.Equal(t, []event.SchemaTableName{{SchemaName: "routed_src", TableName: "src_r"}}, routed.BlockedTableNames) + + routed, err = router.ApplyToDDLEvent(helper.DDL2Event("ALTER TABLE `cross_dst`.`dst` RENAME TO `cross_src`.`dst_moved`")) + require.NoError(t, err) + require.Contains(t, routed.Query, "`routed_dst`.`dst_r`") + require.Contains(t, routed.Query, "`routed_src`.`dst_moved_r`") + require.NotContains(t, routed.Query, "`cross_dst`.`dst`") + require.NotContains(t, routed.Query, "`cross_src`.`dst_moved`") + require.Equal(t, "routed_src", routed.GetTargetSchemaName()) + require.Equal(t, "dst_moved_r", routed.GetTargetTableName()) + require.Equal(t, "routed_dst", routed.GetTargetExtraSchemaName()) + require.Equal(t, "dst_r", routed.GetTargetExtraTableName()) + + routed, err = router.ApplyToDDLEvent(helper.DDL2Event("CREATE TABLE `cross_dst`.`drop_me` (`id` INT PRIMARY KEY)")) + require.NoError(t, err) + require.Contains(t, routed.Query, "`routed_dst`.`drop_me_r`") + + routed, err = router.ApplyToDDLEvent(helper.DDL2Event("DROP TABLE `cross_src`.`dst_moved`, `cross_dst`.`drop_me`")) + require.NoError(t, err) + require.Contains(t, routed.Query, "`routed_src`.`dst_moved_r`") + require.Contains(t, routed.Query, "`routed_dst`.`drop_me_r`") + require.NotContains(t, routed.Query, "`cross_src`.`dst_moved`") + require.NotContains(t, routed.Query, "`cross_dst`.`drop_me`") + + routed, err = router.ApplyToDDLEvent(helper.DDL2Event("CREATE TABLE `cross_src`.`rename_a` (`id` INT PRIMARY KEY)")) + require.NoError(t, err) + require.Contains(t, routed.Query, "`routed_src`.`rename_a_r`") + + routed, err = router.ApplyToDDLEvent(helper.DDL2Event("CREATE TABLE `cross_dst`.`rename_b` (`id` INT PRIMARY KEY)")) + require.NoError(t, err) + require.Contains(t, routed.Query, "`routed_dst`.`rename_b_r`") + + routed, err = router.ApplyToDDLEvent(helper.DDL2Event("RENAME TABLE `cross_src`.`rename_a` TO `cross_dst`.`rename_a_new`, `cross_dst`.`rename_b` TO `cross_src`.`rename_b_new`")) + require.NoError(t, err) + require.Contains(t, routed.Query, "`routed_src`.`rename_a_r`") + require.Contains(t, routed.Query, "`routed_dst`.`rename_a_new_r`") + require.Contains(t, routed.Query, "`routed_dst`.`rename_b_r`") + require.Contains(t, routed.Query, "`routed_src`.`rename_b_new_r`") + require.NotContains(t, routed.Query, "`cross_src`.`rename_a`") + require.NotContains(t, routed.Query, "`cross_dst`.`rename_a_new`") + require.NotContains(t, routed.Query, "`cross_dst`.`rename_b`") + require.NotContains(t, routed.Query, "`cross_src`.`rename_b_new`") + require.Len(t, routed.MultipleTableInfos, 2) + require.Equal(t, "routed_dst", routed.MultipleTableInfos[0].GetTargetSchemaName()) + require.Equal(t, "rename_a_new_r", routed.MultipleTableInfos[0].GetTargetTableName()) + require.Equal(t, "routed_src", routed.MultipleTableInfos[1].GetTargetSchemaName()) + require.Equal(t, "rename_b_new_r", routed.MultipleTableInfos[1].GetTargetTableName()) + require.Equal(t, []event.SchemaTableName{ + {SchemaName: "routed_src", TableName: "rename_a_r"}, + {SchemaName: "routed_dst", TableName: "rename_b_r"}, + }, routed.BlockedTableNames) +} + +func TestApplyToDDLEventRewritesCreateTableLikeWithSessionDefaultSchema(t *testing.T) { + router := newTestRouter(t, false, []*config.DispatchRule{ + { + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + TargetTable: TablePlaceholder, + }, + { + Matcher: []string{"source_extra_db.*"}, + TargetSchema: "target_extra_db", + TargetTable: TablePlaceholder, + }, + }) + + helper := event.NewEventTestHelper(t) + defer helper.Close() + + require.Contains(t, mustRouteDDL(t, router, helper.DDL2Event("CREATE DATABASE `source_db`")).Query, "`target_db`") + require.Contains(t, mustRouteDDL(t, router, helper.DDL2Event("CREATE DATABASE `source_extra_db`")).Query, "`target_extra_db`") + require.Contains(t, + mustRouteDDL(t, router, helper.DDL2Event("CREATE TABLE `source_db`.`users` (`id` INT PRIMARY KEY)")).Query, + "`target_db`.`users`") + + helper.Tk().MustExec("USE `source_db`") + ddl := helper.DDL2Event("CREATE TABLE `source_extra_db`.`external_users` LIKE `users`") + require.Equal(t, "CREATE TABLE `source_extra_db`.`external_users` LIKE `source_db`.`users`", ddl.Query) + require.Equal(t, []event.SchemaTableName{{SchemaName: "source_db", TableName: "users"}}, ddl.BlockedTableNames) + + routed := mustRouteDDL(t, router, ddl) + require.Equal(t, "CREATE TABLE `target_extra_db`.`external_users` LIKE `target_db`.`users`", routed.Query) + require.Equal(t, []event.SchemaTableName{{SchemaName: "target_db", TableName: "users"}}, routed.BlockedTableNames) +} + +func mustRouteDDL(t *testing.T, router Router, ddl *event.DDLEvent) *event.DDLEvent { + t.Helper() + + routed, err := router.ApplyToDDLEvent(ddl) + require.NoError(t, err) + return routed +} + +func newTestRouter(t *testing.T, caseSensitive bool, rules []*config.DispatchRule) Router { + t.Helper() + + router, err := NewRouter(newTestChangefeedID(), caseSensitive, rules) + require.NoError(t, err) + return router +} + +func TestRewriteParserBackedDDLQueryError(t *testing.T) { + t.Parallel() + + router := newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + TargetTable: TablePlaceholder, + }}) + + _, err := router.rewriteSingleDDLQuery("INVALID SQL !!!", "") + code, ok := errors.RFCCode(err) + require.True(t, ok) + require.Equal(t, errors.ErrTableRoutingFailed.RFCCode(), code) +} + +func TestApplyToDDLEventRejectsParserUnsupportedIndexDDL(t *testing.T) { + t.Parallel() + + router := newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + TargetTable: "{table}_r", + }}) + + cases := []struct { + name string + action byte + tableName string + }{ + { + name: "add fulltext index", + action: byte(cdcfilter.ActionAddFullTextIndex), + tableName: "t1", + }, + { + name: "create hybrid index", + action: byte(cdcfilter.ActionCreateHybridIndex), + tableName: "t2", + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + // These CDC-local action types are derived from parser-unsupported DDLs, + // so EventTestHelper cannot synthesize them through TiDB parser execution. + ddl := &event.DDLEvent{ + Type: tc.action, + SchemaName: "source_db", + TableName: tc.tableName, + } + _, err := router.ApplyToDDLEvent(ddl) + require.True(t, errors.ErrTableRoutingFailed.Equal(err)) + require.Contains(t, err.Error(), "table routing does not support ddl type") + }) + } +} + +func TestApplyToDDLEventPreservesIndexIDs(t *testing.T) { + router := newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_db.*"}, TargetSchema: "target_db", + }}) + original := &event.DDLEvent{ + Type: byte(model.ActionAddIndex), + SchemaName: "source_db", TableName: "t", + Query: "ALTER TABLE `source_db`.`t` ADD INDEX `idx` (`id`)", + IndexIDs: []int64{42}, + } + routed, err := router.ApplyToDDLEvent(original) + require.NoError(t, err) + require.Contains(t, routed.Query, "`target_db`.`t`") + require.Equal(t, original.IndexIDs, routed.IndexIDs) + routed.IndexIDs[0] = 43 + require.Equal(t, []int64{42}, original.IndexIDs) +} + +func TestSchemaDDLRejectsEmptyTarget(t *testing.T) { + router, err := NewRouter(newTestChangefeedID(), false, []*config.DispatchRule{ + {Matcher: []string{"source_db.*"}, TargetSchema: "{table}"}, + }) + require.NoError(t, err) + for _, tc := range []struct { + query string + action model.ActionType + }{ + {"CREATE DATABASE source_db", model.ActionCreateSchema}, + {"ALTER DATABASE source_db CHARACTER SET utf8mb4", model.ActionModifySchemaCharsetAndCollate}, + {"DROP DATABASE source_db", model.ActionDropSchema}, + } { + t.Run(tc.query, func(t *testing.T) { + ddl := &event.DDLEvent{Query: tc.query, Type: byte(tc.action), SchemaName: "source_db"} + _, err := router.ApplyToDDLEvent(ddl) + require.Error(t, err) + require.True(t, errors.ErrTableRoutingFailed.Equal(err)) + require.Contains(t, err.Error(), "target schema is empty") + require.Equal(t, tc.query, ddl.Query) + }) + } + binding, err := router.route("source_db", "orders") + require.NoError(t, err) + require.Equal(t, "orders", binding.Target.Schema) +} + +func TestRouteCorrelatedViewColumns(t *testing.T) { + stored := "SELECT orders.id FROM source_db.orders WHERE EXISTS (SELECT 1 FROM source_db.lines WHERE lines.order_id = orders.id)" + query, err := event.NormalizeCreateViewQueryWithStoredSelect("CREATE VIEW source_db.v AS "+stored, stored, "source_db") + require.NoError(t, err) + router, err := NewRouter(newTestChangefeedID(), false, []*config.DispatchRule{ + {Matcher: []string{"source_db.*"}, TargetSchema: "target_db", TargetTable: "{table}_r"}, + }) + require.NoError(t, err) + routed, err := router.ApplyToDDLEvent(&event.DDLEvent{ + Query: query, Type: byte(model.ActionCreateView), SchemaName: "source_db", TableName: "v", + }) + require.NoError(t, err) + require.Contains(t, routed.Query, "`target_db`.`lines_r`.`order_id`=`target_db`.`orders_r`.`id`") +} + +func TestViewWildcardRouting(t *testing.T) { + helper := event.NewEventTestHelper(t) + defer helper.Close() + helper.Tk().MustExec("USE test") + helper.DDL2Event("CREATE TABLE t (id INT PRIMARY KEY)") + helper.Tk().MustExec("INSERT INTO t VALUES (7)") + helper.Tk().MustExec("CREATE DATABASE dst") + for _, table := range []string{"dst.t_r", "dst.t", "test.t_r"} { + helper.Tk().MustExec("CREATE TABLE " + table + " (id INT PRIMARY KEY)") + helper.Tk().MustExec("INSERT INTO " + table + " VALUES (7)") + } + for _, tc := range []struct{ name, query string }{ + {"v_table", "SELECT t.* FROM t"}, + {"v_schema", "SELECT test.t.* FROM test.t"}, + {"v_star", "SELECT * FROM t"}, + {"v_alias", "SELECT x.* FROM t AS x"}, + {"v_same_alias", "SELECT t.* FROM t AS t"}, + {"v_join", "SELECT t.* FROM t JOIN t AS x ON t.id = x.id"}, + {"v_nested", "SELECT x.* FROM (SELECT t.* FROM t) AS x"}, + {"v_scopes", "SELECT t.* FROM t WHERE EXISTS (SELECT t.* FROM t AS t)"}, + } { + t.Run(tc.name, func(t *testing.T) { + helper.Tk().MustExec("USE test") + ddl := helper.DDL2Event("CREATE VIEW " + tc.name + " AS " + tc.query) + helper.Tk().MustQuery("SELECT * FROM " + tc.name).Check(testkit.Rows("7")) + helper.Tk().MustExec("DROP VIEW " + tc.name) + for _, rule := range []*config.DispatchRule{ + {Matcher: []string{"test.*"}, TargetSchema: "dst", TargetTable: "{table}_r"}, + {Matcher: []string{"test.*"}, TargetSchema: "dst"}, + {Matcher: []string{"test.*"}, TargetTable: "{table}_r"}, + {Matcher: []string{"other.*"}, TargetSchema: "dst"}, + } { + router := newTestRouter(t, false, []*config.DispatchRule{rule}) + routed, err := router.ApplyToDDLEvent(ddl) + require.NoError(t, err) + helper.Tk().MustExec("USE " + common.QuoteName(routed.GetTargetSchemaName())) + helper.Tk().MustExec(routed.Query) + view := common.QuoteSchema(routed.GetTargetSchemaName(), routed.GetTargetTableName()) + helper.Tk().MustQuery("SELECT * FROM " + view).Check(testkit.Rows("7")) + helper.Tk().MustExec("DROP VIEW " + view) + } + }) + } +} + +func TestViewCTERouting(t *testing.T) { + helper := event.NewEventTestHelper(t) + defer helper.Close() + helper.Tk().MustExec("USE test") + helper.DDL2Event("CREATE TABLE t (id INT PRIMARY KEY)") + helper.Tk().MustExec("INSERT INTO t VALUES (7)") + helper.DDL2Event("CREATE TABLE orders (id INT PRIMARY KEY)") + helper.Tk().MustExec("INSERT INTO orders VALUES (99)") + helper.Tk().MustExec("CREATE DATABASE dst") + for _, table := range []string{"t", "orders"} { + helper.Tk().MustExec("CREATE TABLE dst." + table + "_r LIKE test." + table) + helper.Tk().MustExec("INSERT INTO dst." + table + "_r SELECT * FROM test." + table) + } + router := newTestRouter(t, false, []*config.DispatchRule{{Matcher: []string{"test.*"}, TargetSchema: "dst", TargetTable: "{table}_r"}}) + for _, tc := range []struct{ name, query string }{ + {"plain", "WITH c AS (SELECT id FROM t) SELECT id FROM c"}, + {"shadow", "WITH orders AS (SELECT id FROM t) SELECT id FROM orders"}, + {"column", "WITH orders AS (SELECT id FROM t) SELECT orders.id FROM orders"}, + {"wildcard", "WITH orders AS (SELECT id FROM t) SELECT orders.* FROM orders"}, + {"definition", "WITH t AS (SELECT id FROM t) SELECT id FROM t"}, + {"qualified", "WITH t AS (SELECT 99 AS id) SELECT test.t.* FROM test.t"}, + {"forward", "WITH a AS (SELECT id FROM t), t AS (SELECT 99 AS id) SELECT id FROM a"}, + {"multiple", "WITH a AS (SELECT id FROM t), b AS (SELECT id FROM a) SELECT id FROM b"}, + {"nested", "WITH c AS (SELECT id FROM t) SELECT id FROM (WITH c AS (SELECT id FROM c) SELECT id FROM c) AS x"}, + {"scope", "SELECT t.* FROM t WHERE EXISTS (WITH t AS (SELECT 99 AS id) SELECT id FROM t)"}, + {"union", "WITH c AS (SELECT id FROM t) SELECT id FROM c UNION SELECT id FROM c"}, + {"recursive", "WITH RECURSIVE c(id) AS (SELECT id - 1 FROM t UNION ALL SELECT id + 1 FROM c WHERE id < 7) SELECT id FROM c WHERE id = 7"}, + } { + t.Run(tc.name, func(t *testing.T) { + helper.Tk().MustExec("USE test") + ddl := helper.DDL2Event("CREATE VIEW v AS " + tc.query) + helper.Tk().MustQuery("SELECT * FROM v").Check(testkit.Rows("7")) + routed, err := router.ApplyToDDLEvent(ddl) + require.NoError(t, err) + helper.Tk().MustExec("USE dst") + helper.Tk().MustExec(routed.Query) + helper.Tk().MustQuery("SELECT * FROM v_r").Check(testkit.Rows("7")) + helper.Tk().MustExec("DROP VIEW v_r") + helper.Tk().MustExec("DROP VIEW test.v") + }) + } +} diff --git a/downstreamadapter/routing/router_supported_ddl_test.go b/downstreamadapter/routing/router_supported_ddl_test.go new file mode 100644 index 0000000000..91ff8a86b1 --- /dev/null +++ b/downstreamadapter/routing/router_supported_ddl_test.go @@ -0,0 +1,1095 @@ +// Copyright 2026 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 routing + +import ( + "testing" + + "github.com/pingcap/ticdc/pkg/common" + "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/config" + ddlutil "github.com/pingcap/tidb/pkg/ddl/util" + timodel "github.com/pingcap/tidb/pkg/meta/model" + "github.com/pingcap/tidb/pkg/parser/ast" + "github.com/stretchr/testify/require" +) + +type supportedDDLRewriteCase struct { + name string + action timodel.ActionType + ddl *event.DDLEvent + requiredFragments []string + forbiddenFragments []string +} + +func TestRewriteDDLQueryWithRoutingSupportsParserBackedDDLTypes(t *testing.T) { + originGC := ddlutil.IsEmulatorGCEnable() + ddlutil.EmulatorGCDisable() + defer func() { + if originGC { + ddlutil.EmulatorGCEnable() + } + }() + + router := newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_*.*"}, + TargetSchema: "target_db", + TargetTable: "{table}_r", + }}) + + helper := event.NewEventTestHelper(t) + defer helper.Close() + cases := make([]supportedDDLRewriteCase, 0, 117) + + cases = append(cases, supportedDDLRewriteCase{ + name: "create schema", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_create_schema`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_create_schema`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_drop_schema", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_drop_schema`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_drop_schema`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "drop schema", + action: timodel.ActionDropSchema, + ddl: helper.DDL2Event("DROP DATABASE `source_drop_schema`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_drop_schema`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_modify_schema", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_modify_schema`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_modify_schema`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "modify schema charset", + action: timodel.ActionModifySchemaCharsetAndCollate, + ddl: helper.DDL2Event("ALTER DATABASE `source_modify_schema` COLLATE utf8mb4_general_ci"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_modify_schema`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_create_table", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_create_table`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_create_table`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "create table", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_create_table`.`t_create` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t_create_r`"}, + forbiddenFragments: []string{"`source_create_table`.`t_create`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_create_tables", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_create_tables`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_create_tables`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "create tables", + action: timodel.ActionCreateTables, + ddl: helper.BatchCreateTableDDLs2Event("source_create_tables", "CREATE TABLE `source_create_tables`.`t_create_1` (`id` INT PRIMARY KEY)", "CREATE TABLE `source_create_tables`.`t_create_2` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"CREATE TABLE `target_db`.`t_create_1_r`", "CREATE TABLE `target_db`.`t_create_2_r`"}, + forbiddenFragments: []string{"`source_create_tables`.`t_create_1`", "`source_create_tables`.`t_create_2`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_drop_table", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_drop_table`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_drop_table`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_drop_table.t_drop", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_drop_table`.`t_drop` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t_drop_r`"}, + forbiddenFragments: []string{"`source_drop_table`.`t_drop`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "drop table", + action: timodel.ActionDropTable, + ddl: helper.DDL2Event("DROP TABLE `source_drop_table`.`t_drop`"), + requiredFragments: []string{"`target_db`.`t_drop_r`"}, + forbiddenFragments: []string{"`source_drop_table`.`t_drop`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_truncate_table", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_truncate_table`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_truncate_table`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_truncate_table.t_truncate", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_truncate_table`.`t_truncate` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t_truncate_r`"}, + forbiddenFragments: []string{"`source_truncate_table`.`t_truncate`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "truncate table", + action: timodel.ActionTruncateTable, + ddl: helper.DDL2Event("TRUNCATE TABLE `source_truncate_table`.`t_truncate`"), + requiredFragments: []string{"`target_db`.`t_truncate_r`"}, + forbiddenFragments: []string{"`source_truncate_table`.`t_truncate`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_rename_table", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_rename_table`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_rename_table`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_rename_table.t_old", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_rename_table`.`t_old` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t_old_r`"}, + forbiddenFragments: []string{"`source_rename_table`.`t_old`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "rename table", + action: timodel.ActionRenameTable, + ddl: helper.DDL2Event("RENAME TABLE `source_rename_table`.`t_old` TO `source_rename_table`.`t_new`"), + requiredFragments: []string{"`target_db`.`t_old_r`", "`target_db`.`t_new_r`"}, + forbiddenFragments: []string{"`source_rename_table`.`t_old`", "`source_rename_table`.`t_new`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_rename_tables", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_rename_tables`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_rename_tables`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_rename_tables.t1_old", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_rename_tables`.`t1_old` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t1_old_r`"}, + forbiddenFragments: []string{"`source_rename_tables`.`t1_old`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_rename_tables.t2_old", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_rename_tables`.`t2_old` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t2_old_r`"}, + forbiddenFragments: []string{"`source_rename_tables`.`t2_old`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "rename tables", + action: timodel.ActionRenameTables, + ddl: helper.DDL2Event("RENAME TABLE `source_rename_tables`.`t1_old` TO `source_rename_tables`.`t1_new`, `source_rename_tables`.`t2_old` TO `source_rename_tables`.`t2_new`"), + requiredFragments: []string{"`target_db`.`t1_old_r`", "`target_db`.`t1_new_r`", "`target_db`.`t2_old_r`", "`target_db`.`t2_new_r`"}, + forbiddenFragments: []string{"`source_rename_tables`.`t1_old`", "`source_rename_tables`.`t1_new`", "`source_rename_tables`.`t2_old`", "`source_rename_tables`.`t2_new`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_recover_table", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_recover_table`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_recover_table`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_recover_table.t_recover", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_recover_table`.`t_recover` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t_recover_r`"}, + forbiddenFragments: []string{"`source_recover_table`.`t_recover`"}, + }) + + helper.Tk().MockGCSavePoint() + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup drop table source_recover_table.t_recover", + action: timodel.ActionDropTable, + ddl: helper.DDL2Event("DROP TABLE `source_recover_table`.`t_recover`"), + requiredFragments: []string{"`target_db`.`t_recover_r`"}, + forbiddenFragments: []string{"`source_recover_table`.`t_recover`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "recover table", + action: timodel.ActionRecoverTable, + ddl: helper.DDL2Event("FLASHBACK TABLE `source_recover_table`.`t_recover`"), + requiredFragments: []string{"`target_db`.`t_recover_r`"}, + forbiddenFragments: []string{"`source_recover_table`.`t_recover`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_modify_table_comment", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_modify_table_comment`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_modify_table_comment`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_modify_table_comment.t_comment", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_modify_table_comment`.`t_comment` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t_comment_r`"}, + forbiddenFragments: []string{"`source_modify_table_comment`.`t_comment`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "modify table comment", + action: timodel.ActionModifyTableComment, + ddl: helper.DDL2Event("ALTER TABLE `source_modify_table_comment`.`t_comment` COMMENT = 'hello'"), + requiredFragments: []string{"`target_db`.`t_comment_r`"}, + forbiddenFragments: []string{"`source_modify_table_comment`.`t_comment`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_modify_table_charset", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_modify_table_charset`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_modify_table_charset`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_modify_table_charset.t_charset", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_modify_table_charset`.`t_charset` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t_charset_r`"}, + forbiddenFragments: []string{"`source_modify_table_charset`.`t_charset`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "modify table charset", + action: timodel.ActionModifyTableCharsetAndCollate, + ddl: helper.DDL2Event("ALTER TABLE `source_modify_table_charset`.`t_charset` COLLATE utf8mb4_general_ci"), + requiredFragments: []string{"`target_db`.`t_charset_r`"}, + forbiddenFragments: []string{"`source_modify_table_charset`.`t_charset`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_create_view", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_create_view`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_create_view`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_create_view.t_view_src", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_create_view`.`t_view_src` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t_view_src_r`"}, + forbiddenFragments: []string{"`source_create_view`.`t_view_src`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "create view", + action: timodel.ActionCreateView, + ddl: helper.DDL2Event("CREATE VIEW `source_create_view`.`v1` AS SELECT * FROM `source_create_view`.`t_view_src`"), + requiredFragments: []string{"`target_db`.`v1_r`", "`target_db`.`t_view_src_r`"}, + forbiddenFragments: []string{"`source_create_view`.`v1`", "`source_create_view`.`t_view_src`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_drop_view", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_drop_view`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_drop_view`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_drop_view.t_view_src", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_drop_view`.`t_view_src` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t_view_src_r`"}, + forbiddenFragments: []string{"`source_drop_view`.`t_view_src`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create view source_drop_view.v1", + action: timodel.ActionCreateView, + ddl: helper.DDL2Event("CREATE VIEW `source_drop_view`.`v1` AS SELECT * FROM `source_drop_view`.`t_view_src`"), + requiredFragments: []string{"`target_db`.`v1_r`", "`target_db`.`t_view_src_r`"}, + forbiddenFragments: []string{"`source_drop_view`.`v1`", "`source_drop_view`.`t_view_src`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "drop view", + action: timodel.ActionDropView, + ddl: helper.DDL2Event("DROP VIEW `source_drop_view`.`v1`"), + requiredFragments: []string{"`target_db`.`v1_r`"}, + forbiddenFragments: []string{"`source_drop_view`.`v1`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_add_partition", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_add_partition`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_add_partition`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create partition table source_add_partition.pt_add", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_add_partition`.`pt_add` (`id` INT PRIMARY KEY) PARTITION BY RANGE (`id`) (PARTITION `p0` VALUES LESS THAN (10), PARTITION `p1` VALUES LESS THAN (20))"), + requiredFragments: []string{"`target_db`.`pt_add_r`"}, + forbiddenFragments: []string{"`source_add_partition`.`pt_add`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "add table partition", + action: timodel.ActionAddTablePartition, + ddl: helper.DDL2Event("ALTER TABLE `source_add_partition`.`pt_add` ADD PARTITION (PARTITION `p2` VALUES LESS THAN (30))"), + requiredFragments: []string{"`target_db`.`pt_add_r`"}, + forbiddenFragments: []string{"`source_add_partition`.`pt_add`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_drop_partition", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_drop_partition`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_drop_partition`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create partition table source_drop_partition.pt_drop", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_drop_partition`.`pt_drop` (`id` INT PRIMARY KEY) PARTITION BY RANGE (`id`) (PARTITION `p0` VALUES LESS THAN (10), PARTITION `p1` VALUES LESS THAN (20))"), + requiredFragments: []string{"`target_db`.`pt_drop_r`"}, + forbiddenFragments: []string{"`source_drop_partition`.`pt_drop`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "drop table partition", + action: timodel.ActionDropTablePartition, + ddl: helper.DDL2Event("ALTER TABLE `source_drop_partition`.`pt_drop` DROP PARTITION `p0`"), + requiredFragments: []string{"`target_db`.`pt_drop_r`"}, + forbiddenFragments: []string{"`source_drop_partition`.`pt_drop`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_truncate_partition", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_truncate_partition`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_truncate_partition`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create partition table source_truncate_partition.pt_truncate", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_truncate_partition`.`pt_truncate` (`id` INT PRIMARY KEY) PARTITION BY RANGE (`id`) (PARTITION `p0` VALUES LESS THAN (10), PARTITION `p1` VALUES LESS THAN (20))"), + requiredFragments: []string{"`target_db`.`pt_truncate_r`"}, + forbiddenFragments: []string{"`source_truncate_partition`.`pt_truncate`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "truncate table partition", + action: timodel.ActionTruncateTablePartition, + ddl: helper.DDL2Event("ALTER TABLE `source_truncate_partition`.`pt_truncate` TRUNCATE PARTITION `p0`"), + requiredFragments: []string{"`target_db`.`pt_truncate_r`"}, + forbiddenFragments: []string{"`source_truncate_partition`.`pt_truncate`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_exchange_partition", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_exchange_partition`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_exchange_partition`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create partition table source_exchange_partition.pt_exchange", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_exchange_partition`.`pt_exchange` (`id` INT PRIMARY KEY) PARTITION BY RANGE (`id`) (PARTITION `p0` VALUES LESS THAN (10), PARTITION `p1` VALUES LESS THAN (20))"), + requiredFragments: []string{"`target_db`.`pt_exchange_r`"}, + forbiddenFragments: []string{"`source_exchange_partition`.`pt_exchange`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_exchange_partition.t_exchange", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_exchange_partition`.`t_exchange` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t_exchange_r`"}, + forbiddenFragments: []string{"`source_exchange_partition`.`t_exchange`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "exchange table partition", + action: timodel.ActionExchangeTablePartition, + ddl: helper.DDL2Event("ALTER TABLE `source_exchange_partition`.`pt_exchange` EXCHANGE PARTITION `p0` WITH TABLE `source_exchange_partition`.`t_exchange`"), + requiredFragments: []string{"`target_db`.`pt_exchange_r`", "`target_db`.`t_exchange_r`"}, + forbiddenFragments: []string{"`source_exchange_partition`.`pt_exchange`", "`source_exchange_partition`.`t_exchange`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_reorganize_partition", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_reorganize_partition`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_reorganize_partition`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create partition table source_reorganize_partition.pt_reorganize", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_reorganize_partition`.`pt_reorganize` (`id` INT PRIMARY KEY) PARTITION BY RANGE (`id`) (PARTITION `p0` VALUES LESS THAN (10), PARTITION `p1` VALUES LESS THAN (20))"), + requiredFragments: []string{"`target_db`.`pt_reorganize_r`"}, + forbiddenFragments: []string{"`source_reorganize_partition`.`pt_reorganize`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "reorganize partition", + action: timodel.ActionReorganizePartition, + ddl: helper.DDL2Event("ALTER TABLE `source_reorganize_partition`.`pt_reorganize` REORGANIZE PARTITION `p0`, `p1` INTO (PARTITION `p01` VALUES LESS THAN (20))"), + requiredFragments: []string{"`target_db`.`pt_reorganize_r`"}, + forbiddenFragments: []string{"`source_reorganize_partition`.`pt_reorganize`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_alter_partitioning", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_alter_partitioning`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_alter_partitioning`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_alter_partitioning.t_partitioning", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_alter_partitioning`.`t_partitioning` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t_partitioning_r`"}, + forbiddenFragments: []string{"`source_alter_partitioning`.`t_partitioning`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "alter table partitioning", + action: timodel.ActionAlterTablePartitioning, + ddl: helper.DDL2Event("ALTER TABLE `source_alter_partitioning`.`t_partitioning` PARTITION BY HASH(`id`) PARTITIONS 4"), + requiredFragments: []string{"`target_db`.`t_partitioning_r`"}, + forbiddenFragments: []string{"`source_alter_partitioning`.`t_partitioning`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_remove_partitioning", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_remove_partitioning`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_remove_partitioning`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create partition table source_remove_partitioning.pt_remove", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_remove_partitioning`.`pt_remove` (`id` INT PRIMARY KEY) PARTITION BY RANGE (`id`) (PARTITION `p0` VALUES LESS THAN (10), PARTITION `p1` VALUES LESS THAN (20))"), + requiredFragments: []string{"`target_db`.`pt_remove_r`"}, + forbiddenFragments: []string{"`source_remove_partitioning`.`pt_remove`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "remove partitioning", + action: timodel.ActionRemovePartitioning, + ddl: helper.DDL2Event("ALTER TABLE `source_remove_partitioning`.`pt_remove` REMOVE PARTITIONING"), + requiredFragments: []string{"`target_db`.`pt_remove_r`"}, + forbiddenFragments: []string{"`source_remove_partitioning`.`pt_remove`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_add_column", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_add_column`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_add_column`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_add_column.t_add_column", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_add_column`.`t_add_column` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t_add_column_r`"}, + forbiddenFragments: []string{"`source_add_column`.`t_add_column`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "add column", + action: timodel.ActionAddColumn, + ddl: helper.DDL2Event("ALTER TABLE `source_add_column`.`t_add_column` ADD COLUMN `c1` INT"), + requiredFragments: []string{"`target_db`.`t_add_column_r`"}, + forbiddenFragments: []string{"`source_add_column`.`t_add_column`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_drop_column", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_drop_column`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_drop_column`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_drop_column.t_drop_column", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_drop_column`.`t_drop_column` (`id` INT PRIMARY KEY, `c1` INT)"), + requiredFragments: []string{"`target_db`.`t_drop_column_r`"}, + forbiddenFragments: []string{"`source_drop_column`.`t_drop_column`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "drop column", + action: timodel.ActionDropColumn, + ddl: helper.DDL2Event("ALTER TABLE `source_drop_column`.`t_drop_column` DROP COLUMN `c1`"), + requiredFragments: []string{"`target_db`.`t_drop_column_r`"}, + forbiddenFragments: []string{"`source_drop_column`.`t_drop_column`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_modify_column", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_modify_column`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_modify_column`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_modify_column.t_modify_column", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_modify_column`.`t_modify_column` (`id` INT PRIMARY KEY, `c1` INT)"), + requiredFragments: []string{"`target_db`.`t_modify_column_r`"}, + forbiddenFragments: []string{"`source_modify_column`.`t_modify_column`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "modify column", + action: timodel.ActionModifyColumn, + ddl: helper.DDL2Event("ALTER TABLE `source_modify_column`.`t_modify_column` MODIFY COLUMN `c1` BIGINT"), + requiredFragments: []string{"`target_db`.`t_modify_column_r`"}, + forbiddenFragments: []string{"`source_modify_column`.`t_modify_column`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_set_default", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_set_default`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_set_default`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_set_default.t_set_default", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_set_default`.`t_set_default` (`id` INT PRIMARY KEY, `c1` INT)"), + requiredFragments: []string{"`target_db`.`t_set_default_r`"}, + forbiddenFragments: []string{"`source_set_default`.`t_set_default`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "set default value", + action: timodel.ActionSetDefaultValue, + ddl: helper.DDL2Event("ALTER TABLE `source_set_default`.`t_set_default` ALTER COLUMN `c1` SET DEFAULT 5"), + requiredFragments: []string{"`target_db`.`t_set_default_r`"}, + forbiddenFragments: []string{"`source_set_default`.`t_set_default`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_rebase_auto_id", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_rebase_auto_id`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_rebase_auto_id`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_rebase_auto_id.t_rebase", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_rebase_auto_id`.`t_rebase` (`id` INT PRIMARY KEY AUTO_INCREMENT)"), + requiredFragments: []string{"`target_db`.`t_rebase_r`"}, + forbiddenFragments: []string{"`source_rebase_auto_id`.`t_rebase`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "rebase auto id", + action: timodel.ActionRebaseAutoID, + ddl: helper.DDL2Event("ALTER TABLE `source_rebase_auto_id`.`t_rebase` AUTO_INCREMENT = 100"), + requiredFragments: []string{"`target_db`.`t_rebase_r`"}, + forbiddenFragments: []string{"`source_rebase_auto_id`.`t_rebase`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_add_primary_key", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_add_primary_key`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_add_primary_key`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_add_primary_key.t_add_pk", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_add_primary_key`.`t_add_pk` (`id` INT)"), + requiredFragments: []string{"`target_db`.`t_add_pk_r`"}, + forbiddenFragments: []string{"`source_add_primary_key`.`t_add_pk`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "add primary key", + action: timodel.ActionAddPrimaryKey, + ddl: helper.DDL2Event("ALTER TABLE `source_add_primary_key`.`t_add_pk` ADD PRIMARY KEY(`id`)"), + requiredFragments: []string{"`target_db`.`t_add_pk_r`"}, + forbiddenFragments: []string{"`source_add_primary_key`.`t_add_pk`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_drop_primary_key", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_drop_primary_key`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_drop_primary_key`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_drop_primary_key.t_drop_pk", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_drop_primary_key`.`t_drop_pk` (`id` INT, PRIMARY KEY(`id`) NONCLUSTERED)"), + requiredFragments: []string{"`target_db`.`t_drop_pk_r`"}, + forbiddenFragments: []string{"`source_drop_primary_key`.`t_drop_pk`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "drop primary key", + action: timodel.ActionDropPrimaryKey, + ddl: helper.DDL2Event("ALTER TABLE `source_drop_primary_key`.`t_drop_pk` DROP PRIMARY KEY"), + requiredFragments: []string{"`target_db`.`t_drop_pk_r`"}, + forbiddenFragments: []string{"`source_drop_primary_key`.`t_drop_pk`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_add_index", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_add_index`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_add_index`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_add_index.t_add_index", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_add_index`.`t_add_index` (`id` INT PRIMARY KEY, `c1` INT)"), + requiredFragments: []string{"`target_db`.`t_add_index_r`"}, + forbiddenFragments: []string{"`source_add_index`.`t_add_index`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "add index", + action: timodel.ActionAddIndex, + ddl: helper.DDL2Event("CREATE INDEX `idx_c1` ON `source_add_index`.`t_add_index`(`c1`)"), + requiredFragments: []string{"`target_db`.`t_add_index_r`"}, + forbiddenFragments: []string{"`source_add_index`.`t_add_index`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_drop_index", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_drop_index`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_drop_index`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_drop_index.t_drop_index", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_drop_index`.`t_drop_index` (`id` INT PRIMARY KEY, `c1` INT, KEY `idx_c1` (`c1`))"), + requiredFragments: []string{"`target_db`.`t_drop_index_r`"}, + forbiddenFragments: []string{"`source_drop_index`.`t_drop_index`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "drop index", + action: timodel.ActionDropIndex, + ddl: helper.DDL2Event("DROP INDEX `idx_c1` ON `source_drop_index`.`t_drop_index`"), + requiredFragments: []string{"`target_db`.`t_drop_index_r`"}, + forbiddenFragments: []string{"`source_drop_index`.`t_drop_index`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_rename_index", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_rename_index`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_rename_index`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_rename_index.t_rename_index", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_rename_index`.`t_rename_index` (`id` INT PRIMARY KEY, `c1` INT, KEY `idx_c1` (`c1`))"), + requiredFragments: []string{"`target_db`.`t_rename_index_r`"}, + forbiddenFragments: []string{"`source_rename_index`.`t_rename_index`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "rename index", + action: timodel.ActionRenameIndex, + ddl: helper.DDL2Event("ALTER TABLE `source_rename_index`.`t_rename_index` RENAME INDEX `idx_c1` TO `idx_c2`"), + requiredFragments: []string{"`target_db`.`t_rename_index_r`"}, + forbiddenFragments: []string{"`source_rename_index`.`t_rename_index`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_alter_index_visibility", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_alter_index_visibility`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_alter_index_visibility`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_alter_index_visibility.t_alter_index", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_alter_index_visibility`.`t_alter_index` (`id` INT PRIMARY KEY, `c1` INT, KEY `idx_c1` (`c1`))"), + requiredFragments: []string{"`target_db`.`t_alter_index_r`"}, + forbiddenFragments: []string{"`source_alter_index_visibility`.`t_alter_index`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "alter index visibility", + action: timodel.ActionAlterIndexVisibility, + ddl: helper.DDL2Event("ALTER TABLE `source_alter_index_visibility`.`t_alter_index` ALTER INDEX `idx_c1` INVISIBLE"), + requiredFragments: []string{"`target_db`.`t_alter_index_r`"}, + forbiddenFragments: []string{"`source_alter_index_visibility`.`t_alter_index`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_alter_ttl_info", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_alter_ttl_info`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_alter_ttl_info`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create ttl table source_alter_ttl_info.t_ttl_info", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_alter_ttl_info`.`t_ttl_info` (`id` INT PRIMARY KEY, `created_at` DATETIME) TTL = `created_at` + INTERVAL 1 DAY TTL_ENABLE = 'OFF'"), + requiredFragments: []string{"`target_db`.`t_ttl_info_r`"}, + forbiddenFragments: []string{"`source_alter_ttl_info`.`t_ttl_info`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "alter ttl info", + action: timodel.ActionAlterTTLInfo, + ddl: helper.DDL2Event("ALTER TABLE `source_alter_ttl_info`.`t_ttl_info` TTL_ENABLE = 'ON'"), + requiredFragments: []string{"`target_db`.`t_ttl_info_r`"}, + forbiddenFragments: []string{"`source_alter_ttl_info`.`t_ttl_info`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_alter_ttl_remove", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_alter_ttl_remove`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_alter_ttl_remove`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create ttl table source_alter_ttl_remove.t_ttl_remove", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_alter_ttl_remove`.`t_ttl_remove` (`id` INT PRIMARY KEY, `created_at` DATETIME) TTL = `created_at` + INTERVAL 1 DAY TTL_ENABLE = 'OFF'"), + requiredFragments: []string{"`target_db`.`t_ttl_remove_r`"}, + forbiddenFragments: []string{"`source_alter_ttl_remove`.`t_ttl_remove`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "alter ttl remove", + action: timodel.ActionAlterTTLRemove, + ddl: helper.DDL2Event("ALTER TABLE `source_alter_ttl_remove`.`t_ttl_remove` REMOVE TTL"), + requiredFragments: []string{"`target_db`.`t_ttl_remove_r`"}, + forbiddenFragments: []string{"`source_alter_ttl_remove`.`t_ttl_remove`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_multi_schema_change", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_multi_schema_change`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_multi_schema_change`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_multi_schema_change.t_multi", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_multi_schema_change`.`t_multi` (`id` INT PRIMARY KEY, `c2` INT)"), + requiredFragments: []string{"`target_db`.`t_multi_r`"}, + forbiddenFragments: []string{"`source_multi_schema_change`.`t_multi`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "multi schema change", + action: timodel.ActionMultiSchemaChange, + ddl: helper.DDL2Event("ALTER TABLE `source_multi_schema_change`.`t_multi` ADD COLUMN `c1` INT, DROP COLUMN `c2`"), + requiredFragments: []string{"`target_db`.`t_multi_r`"}, + forbiddenFragments: []string{"`source_multi_schema_change`.`t_multi`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_add_foreign_key", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_add_foreign_key`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_add_foreign_key`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_add_foreign_key.t2", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_add_foreign_key`.`t2` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t2_r`"}, + forbiddenFragments: []string{"`source_add_foreign_key`.`t2`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_add_foreign_key.t1", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_add_foreign_key`.`t1` (`id` INT PRIMARY KEY, `t2_id` INT)"), + requiredFragments: []string{"`target_db`.`t1_r`"}, + forbiddenFragments: []string{"`source_add_foreign_key`.`t1`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "add foreign key", + action: timodel.ActionMultiSchemaChange, + ddl: helper.DDL2Event("ALTER TABLE `source_add_foreign_key`.`t1` ADD CONSTRAINT `fk_t2` FOREIGN KEY (`t2_id`) REFERENCES `source_add_foreign_key`.`t2`(`id`)"), + requiredFragments: []string{"`target_db`.`t1_r`", "`target_db`.`t2_r`"}, + forbiddenFragments: []string{"`source_add_foreign_key`.`t1`", "`source_add_foreign_key`.`t2`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_drop_foreign_key", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_drop_foreign_key`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_drop_foreign_key`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_drop_foreign_key.t2", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_drop_foreign_key`.`t2` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t2_r`"}, + forbiddenFragments: []string{"`source_drop_foreign_key`.`t2`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_drop_foreign_key.t1", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_drop_foreign_key`.`t1` (`id` INT PRIMARY KEY, `t2_id` INT, CONSTRAINT `fk_t2` FOREIGN KEY (`t2_id`) REFERENCES `t2`(`id`))"), + requiredFragments: []string{"`target_db`.`t1_r`"}, + forbiddenFragments: []string{"`source_drop_foreign_key`.`t1`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "drop foreign key", + action: timodel.ActionDropForeignKey, + ddl: helper.DDL2Event("ALTER TABLE `source_drop_foreign_key`.`t1` DROP FOREIGN KEY `fk_t2`"), + requiredFragments: []string{"`target_db`.`t1_r`"}, + forbiddenFragments: []string{"`source_drop_foreign_key`.`t1`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_add_columns", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_add_columns`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_add_columns`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_add_columns.t_add_columns", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_add_columns`.`t_add_columns` (`id` INT PRIMARY KEY)"), + requiredFragments: []string{"`target_db`.`t_add_columns_r`"}, + forbiddenFragments: []string{"`source_add_columns`.`t_add_columns`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "add columns as multi schema change", + action: timodel.ActionMultiSchemaChange, + ddl: helper.DDL2Event("ALTER TABLE `source_add_columns`.`t_add_columns` ADD COLUMN (`c1` INT, `c2` INT)"), + requiredFragments: []string{"`target_db`.`t_add_columns_r`"}, + forbiddenFragments: []string{"`source_add_columns`.`t_add_columns`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create schema source_drop_columns", + action: timodel.ActionCreateSchema, + ddl: helper.DDL2Event("CREATE DATABASE `source_drop_columns`"), + requiredFragments: []string{"`target_db`"}, + forbiddenFragments: []string{"`source_drop_columns`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "setup create table source_drop_columns.t_drop_columns", + action: timodel.ActionCreateTable, + ddl: helper.DDL2Event("CREATE TABLE `source_drop_columns`.`t_drop_columns` (`id` INT PRIMARY KEY, `c1` INT, `c2` INT)"), + requiredFragments: []string{"`target_db`.`t_drop_columns_r`"}, + forbiddenFragments: []string{"`source_drop_columns`.`t_drop_columns`"}, + }) + + cases = append(cases, supportedDDLRewriteCase{ + name: "drop columns as multi schema change", + action: timodel.ActionMultiSchemaChange, + ddl: helper.DDL2Event("ALTER TABLE `source_drop_columns`.`t_drop_columns` DROP COLUMN `c1`, DROP COLUMN `c2`"), + requiredFragments: []string{"`target_db`.`t_drop_columns_r`"}, + forbiddenFragments: []string{"`source_drop_columns`.`t_drop_columns`"}, + }) + + require.GreaterOrEqual(t, len(cases), 39) + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, byte(tc.action), tc.ddl.Type) + + routed, err := router.ApplyToDDLEvent(tc.ddl) + require.NoError(t, err) + for _, fragment := range tc.requiredFragments { + require.Contains(t, routed.Query, fragment) + } + for _, fragment := range tc.forbiddenFragments { + require.NotContains(t, routed.Query, fragment) + } + }) + } +} + +func TestApplyToDDLEventRoutesDDLEventMetadata(t *testing.T) { + router := newTestRouter(t, false, []*config.DispatchRule{{ + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + TargetTable: "{table}_r", + }}) + + helper := event.NewEventTestHelper(t) + defer helper.Close() + + schemaDDL := helper.DDL2Event("CREATE DATABASE `source_db`") + routedSchema, err := router.ApplyToDDLEvent(schemaDDL) + require.NoError(t, err) + require.Contains(t, routedSchema.Query, "`target_db`") + + helper.Tk().MustExec("USE `source_db`") + singleCreateDDL := helper.DDL2Event("CREATE TABLE `source_table` (`id` INT PRIMARY KEY)") + singleCreateDDL.DispatcherID = common.NewDispatcherID() + singleCreateDDL.Seq = 1 + singleCreateDDL.Epoch = 2 + singleCreateDDL.TiDBOnly = true + singleCreateDDL.BDRMode = string(ast.BDRRolePrimary) + singleCreateDDL.PostTxnFlushed = []func(){func() {}, func() {}} + + originalQuery := singleCreateDDL.Query + originalTableInfo := singleCreateDDL.TableInfo + require.Equal(t, "source_db", singleCreateDDL.SchemaName) + require.NotContains(t, originalQuery, "`source_db`") + routedSingleCreate, err := router.ApplyToDDLEvent(singleCreateDDL) + require.NoError(t, err) + require.NotSame(t, singleCreateDDL, routedSingleCreate) + require.Equal(t, singleCreateDDL.Version, routedSingleCreate.Version) + require.Equal(t, singleCreateDDL.DispatcherID, routedSingleCreate.DispatcherID) + require.Equal(t, singleCreateDDL.Type, routedSingleCreate.Type) + require.Equal(t, singleCreateDDL.SchemaID, routedSingleCreate.SchemaID) + require.Equal(t, singleCreateDDL.SchemaName, routedSingleCreate.SchemaName) + require.Equal(t, singleCreateDDL.TableName, routedSingleCreate.TableName) + require.Equal(t, singleCreateDDL.FinishedTs, routedSingleCreate.FinishedTs) + require.Equal(t, singleCreateDDL.Seq, routedSingleCreate.Seq) + require.Equal(t, singleCreateDDL.Epoch, routedSingleCreate.Epoch) + require.Equal(t, singleCreateDDL.TiDBOnly, routedSingleCreate.TiDBOnly) + require.Equal(t, singleCreateDDL.BDRMode, routedSingleCreate.BDRMode) + require.Equal(t, originalQuery, singleCreateDDL.Query) + require.Same(t, originalTableInfo, singleCreateDDL.TableInfo) + require.Equal(t, "source_db", singleCreateDDL.GetTargetSchemaName()) + require.Equal(t, "source_table", singleCreateDDL.GetTargetTableName()) + require.Equal(t, "target_db", routedSingleCreate.GetTargetSchemaName()) + require.Equal(t, "source_table_r", routedSingleCreate.GetTargetTableName()) + require.Contains(t, routedSingleCreate.Query, "`target_db`.`source_table_r`") + require.NotContains(t, routedSingleCreate.Query, "`source_db`") + require.NotSame(t, originalTableInfo, routedSingleCreate.TableInfo) + require.Equal(t, "target_db", routedSingleCreate.TableInfo.GetTargetSchemaName()) + require.Equal(t, "source_table_r", routedSingleCreate.TableInfo.GetTargetTableName()) + require.Len(t, routedSingleCreate.PostTxnFlushed, 2) + require.Len(t, singleCreateDDL.PostTxnFlushed, 2) + require.NotEqual(t, &singleCreateDDL.PostTxnFlushed[0], &routedSingleCreate.PostTxnFlushed[0]) + routedSingleCreate.AddPostFlushFunc(func() {}) + require.Len(t, routedSingleCreate.PostTxnFlushed, 3) + require.Len(t, singleCreateDDL.PostTxnFlushed, 2) + + addIndexDDL := helper.DDL2Event("ALTER TABLE `source_table` ADD INDEX (`id`)") + routedAddIndex, err := router.ApplyToDDLEvent(addIndexDDL) + require.NoError(t, err) + require.NotSame(t, addIndexDDL, routedAddIndex) + + createTablesDDL := helper.BatchCreateTableDDLs2Event("source_db", + "CREATE TABLE `source_db`.`t1` (`id` INT PRIMARY KEY)", + "CREATE TABLE `source_db`.`t2` (`id` INT PRIMARY KEY)", + ) + routedCreateTables, err := router.ApplyToDDLEvent(createTablesDDL) + require.NoError(t, err) + require.Contains(t, routedCreateTables.Query, "CREATE TABLE `target_db`.`t1_r`") + require.Contains(t, routedCreateTables.Query, "CREATE TABLE `target_db`.`t2_r`") + require.Len(t, createTablesDDL.MultipleTableInfos, 2) + require.Len(t, routedCreateTables.MultipleTableInfos, 2) + require.Equal(t, "source_db", createTablesDDL.MultipleTableInfos[0].GetTargetSchemaName()) + require.Equal(t, "t1", createTablesDDL.MultipleTableInfos[0].GetTargetTableName()) + require.Equal(t, "source_db", createTablesDDL.MultipleTableInfos[1].GetTargetSchemaName()) + require.Equal(t, "t2", createTablesDDL.MultipleTableInfos[1].GetTargetTableName()) + require.Equal(t, "target_db", routedCreateTables.MultipleTableInfos[0].GetTargetSchemaName()) + require.Equal(t, "t1_r", routedCreateTables.MultipleTableInfos[0].GetTargetTableName()) + require.Equal(t, "target_db", routedCreateTables.MultipleTableInfos[1].GetTargetSchemaName()) + require.Equal(t, "t2_r", routedCreateTables.MultipleTableInfos[1].GetTargetTableName()) +} diff --git a/downstreamadapter/routing/router_test.go b/downstreamadapter/routing/router_test.go new file mode 100644 index 0000000000..4b0c956971 --- /dev/null +++ b/downstreamadapter/routing/router_test.go @@ -0,0 +1,396 @@ +// Copyright 2026 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 routing + +import ( + "testing" + + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/errors" + "github.com/stretchr/testify/require" +) + +func TestSubstituteExpression(t *testing.T) { + t.Parallel() + + testCases := []struct { + name string + expr string + sourceSchema string + sourceTable string + defaultValue string + expected string + }{ + { + name: "empty expression falls back to default", + expr: "", + sourceSchema: "mydb", + sourceTable: "mytable", + defaultValue: "mydb", + expected: "mydb", + }, + { + name: "schema placeholder", + expr: SchemaPlaceholder, + sourceSchema: "mydb", + sourceTable: "mytable", + defaultValue: "unused", + expected: "mydb", + }, + { + name: "table placeholder", + expr: TablePlaceholder + "_bak", + sourceSchema: "mydb", + sourceTable: "mytable", + defaultValue: "unused", + expected: "mytable_bak", + }, + { + name: "literal with both placeholders", + expr: "db_" + SchemaPlaceholder + "_" + TablePlaceholder + "_v2", + sourceSchema: "prod", + sourceTable: "users", + defaultValue: "unused", + expected: "db_prod_users_v2", + }, + { + name: "table placeholder in source schema stays literal", + expr: "{schema}_{table}", + sourceSchema: "db{table}", + sourceTable: "orders", + expected: "db{table}_orders", + }, + { + name: "table placeholder in source table stays literal", + expr: "{schema}_{table}", + sourceSchema: "sales", + sourceTable: "table{table}", + expected: "sales_table{table}", + }, + { + name: "repeated placeholders preserve literal source names", + expr: "{table}_{schema}_{table}_{schema}", + sourceSchema: "db{table}", + sourceTable: "table{schema}", + expected: "table{schema}_db{table}_table{schema}_db{table}", + }, + { + name: "empty expression preserves literal default", + defaultValue: "db{table}", + sourceTable: "orders", + expected: "db{table}", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + result := substituteExpression(tc.expr, tc.sourceSchema, tc.sourceTable, tc.defaultValue) + require.Equal(t, tc.expected, result) + }) + } +} + +func TestNewRouter(t *testing.T) { + t.Parallel() + + t.Run("nil or empty rules return zero value router", func(t *testing.T) { + t.Parallel() + + router, err := NewRouter(newTestChangefeedID(), true, nil) + require.NoError(t, err) + require.Empty(t, router.rules) + binding, err := router.route("db1", "t1") + require.NoError(t, err) + require.Equal(t, "db1", binding.Target.Schema) + require.Equal(t, "t1", binding.Target.Table) + require.False(t, binding.routed()) + + router, err = NewRouter(newTestChangefeedID(), true, []*config.DispatchRule{}) + require.NoError(t, err) + require.Empty(t, router.rules) + binding, err = router.route("db1", "t1") + require.NoError(t, err) + require.Equal(t, "db1", binding.Target.Schema) + require.Equal(t, "t1", binding.Target.Table) + require.False(t, binding.routed()) + }) + + t.Run("rules without routing targets are skipped", func(t *testing.T) { + t.Parallel() + + router, err := NewRouter(newTestChangefeedID(), true, []*config.DispatchRule{ + nil, + {Matcher: []string{"db1.*"}}, + }) + require.NoError(t, err) + require.Empty(t, router.rules) + }) + + t.Run("invalid matcher returns error", func(t *testing.T) { + t.Parallel() + + router, err := NewRouter(newTestChangefeedID(), true, []*config.DispatchRule{ + { + Matcher: []string{"[invalid"}, + TargetSchema: "target", + TargetTable: TablePlaceholder, + }, + }) + require.Error(t, err) + code, ok := errors.RFCCode(err) + require.True(t, ok) + require.Equal(t, errors.ErrInvalidTableRoutingRule.RFCCode(), code) + require.Empty(t, router.rules) + }) + + t.Run("builds router from rules with target fields and ignores pure dispatch rules", func(t *testing.T) { + t.Parallel() + + router, err := NewRouter(newTestChangefeedID(), true, []*config.DispatchRule{ + { + Matcher: []string{"db1.*"}, + DispatcherRule: "ts", + }, + { + Matcher: []string{"db2.*"}, + TargetSchema: "archive", + TargetTable: TablePlaceholder, + }, + { + Matcher: []string{"db3.users"}, + TargetSchema: SchemaPlaceholder, + TargetTable: "users_bak", + }, + }) + require.NoError(t, err) + require.Len(t, router.rules, 2) + + binding, err := router.route("db1", "orders") + require.NoError(t, err) + require.Equal(t, "db1", binding.Target.Schema) + require.Equal(t, "orders", binding.Target.Table) + require.False(t, binding.routed()) + + binding, err = router.route("db2", "orders") + require.NoError(t, err) + require.Equal(t, "archive", binding.Target.Schema) + require.Equal(t, "orders", binding.Target.Table) + require.True(t, binding.routed()) + + binding, err = router.route("db3", "users") + require.NoError(t, err) + require.Equal(t, "db3", binding.Target.Schema) + require.Equal(t, "users_bak", binding.Target.Table) + require.True(t, binding.routed()) + }) +} + +func TestRouterRoute(t *testing.T) { + t.Parallel() + + var zeroRouter Router + binding, err := zeroRouter.route("source_db", "source_table") + require.NoError(t, err) + require.Equal(t, "source_db", binding.Target.Schema) + require.Equal(t, "source_table", binding.Target.Table) + require.False(t, binding.routed()) + + router, err := NewRouter(newTestChangefeedID(), true, []*config.DispatchRule{ + {Matcher: []string{"db1.specific"}, TargetSchema: "specific_db", TargetTable: "specific_table"}, + {Matcher: []string{"db1.*"}, TargetSchema: "db1_archive", TargetTable: TablePlaceholder}, + {Matcher: []string{"staging.*"}, TargetSchema: "prod", TargetTable: SchemaPlaceholder + "_" + TablePlaceholder}, + {Matcher: []string{"*.*"}, TargetSchema: "fallback", TargetTable: TablePlaceholder}, + }) + require.NoError(t, err) + require.Len(t, router.rules, 4) + + testCases := []struct { + name string + sourceSchema string + sourceTable string + expectedSchema string + expectedTable string + expectedChanged bool + }{ + { + name: "specific matcher rewrites both names", + sourceSchema: "db1", + sourceTable: "specific", + expectedSchema: "specific_db", + expectedTable: "specific_table", + expectedChanged: true, + }, + { + name: "schema wildcard rewrites schema only", + sourceSchema: "db1", + sourceTable: "orders", + expectedSchema: "db1_archive", + expectedTable: "orders", + expectedChanged: true, + }, + { + name: "placeholders use source names", + sourceSchema: "staging", + sourceTable: "events", + expectedSchema: "prod", + expectedTable: "staging_events", + expectedChanged: true, + }, + { + name: "fallback matcher applies when no prior rule matches", + sourceSchema: "db2", + sourceTable: "products", + expectedSchema: "fallback", + expectedTable: "products", + expectedChanged: true, + }, + { + name: "empty schema and table do not match any rule", + sourceSchema: "", + sourceTable: "", + expectedSchema: "", + expectedTable: "", + expectedChanged: false, + }, + { + name: "empty schema with table does not match any rule", + sourceSchema: "", + sourceTable: "products", + expectedSchema: "", + expectedTable: "products", + expectedChanged: false, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + binding, err := router.route(tc.sourceSchema, tc.sourceTable) + require.NoError(t, err) + require.Equal(t, tc.expectedSchema, binding.Target.Schema) + require.Equal(t, tc.expectedTable, binding.Target.Table) + require.Equal(t, tc.expectedChanged, binding.routed()) + }) + } + + t.Run("schema only routing does not produce target table", func(t *testing.T) { + router, err := NewRouter(newTestChangefeedID(), true, []*config.DispatchRule{ + {Matcher: []string{"db1.*"}, TargetSchema: "db1_archive", TargetTable: "should_not_apply"}, + }) + require.NoError(t, err) + + binding, err := router.route("db1", "") + require.NoError(t, err) + require.Equal(t, "db1_archive", binding.Target.Schema) + require.Empty(t, binding.Target.Table) + require.True(t, binding.routed()) + }) + + t.Run("schema only routing allows table rules with same target schema", func(t *testing.T) { + router, err := NewRouter(newTestChangefeedID(), true, []*config.DispatchRule{ + {Matcher: []string{"db1.orders"}, TargetSchema: "db1_archive", TargetTable: "orders_archive"}, + {Matcher: []string{"db1.users"}, TargetSchema: "db1_archive", TargetTable: "users_archive"}, + }) + require.NoError(t, err) + + binding, err := router.route("db1", "") + require.NoError(t, err) + require.Equal(t, "db1_archive", binding.Target.Schema) + require.Empty(t, binding.Target.Table) + require.True(t, binding.routed()) + }) + + t.Run("schema only routing rejects table rules with different target schemas", func(t *testing.T) { + router, err := NewRouter(newTestChangefeedID(), true, []*config.DispatchRule{ + {Matcher: []string{"db1.orders"}, TargetSchema: "orders_db", TargetTable: "orders"}, + {Matcher: []string{"db1.users"}, TargetSchema: "users_db", TargetTable: "users"}, + }) + require.NoError(t, err) + + _, err = router.route("db1", "") + require.Error(t, err) + require.True(t, errors.ErrTableRoutingFailed.Equal(err)) + require.Contains(t, err.Error(), "ambiguous schema routing") + }) + + t.Run("empty schema and table do not trigger routing", func(t *testing.T) { + router, err := NewRouter(newTestChangefeedID(), true, []*config.DispatchRule{ + {Matcher: []string{"*.*"}, TargetSchema: "fallback", TargetTable: "should_not_apply"}, + }) + require.NoError(t, err) + + binding, err := router.route("", "") + require.NoError(t, err) + require.Empty(t, binding.Target.Schema) + require.Empty(t, binding.Target.Table) + require.False(t, binding.routed()) + }) +} + +func TestRouterFirstMatchWins(t *testing.T) { + t.Parallel() + + router, err := NewRouter(newTestChangefeedID(), true, []*config.DispatchRule{ + {Matcher: []string{"*.*"}, TargetSchema: "catch_all", TargetTable: TablePlaceholder}, + {Matcher: []string{"db1.*"}, TargetSchema: "db1_only", TargetTable: TablePlaceholder}, + {Matcher: []string{"db1.users"}, TargetSchema: "users_only", TargetTable: "users_bak"}, + }) + require.NoError(t, err) + require.Len(t, router.rules, 3) + + binding, err := router.route("db1", "users") + require.NoError(t, err) + require.Equal(t, "catch_all", binding.Target.Schema) + require.Equal(t, "users", binding.Target.Table) + require.True(t, binding.routed()) +} + +func TestRouterCaseSensitivity(t *testing.T) { + t.Parallel() + + t.Run("case sensitive router requires exact match", func(t *testing.T) { + t.Parallel() + + router, err := NewRouter(newTestChangefeedID(), true, []*config.DispatchRule{ + {Matcher: []string{"MyDB.MyTable"}, TargetSchema: "target_db", TargetTable: "target_table"}, + }) + require.NoError(t, err) + + binding, err := router.route("MyDB", "MyTable") + require.NoError(t, err) + require.Equal(t, "target_db", binding.Target.Schema) + require.Equal(t, "target_table", binding.Target.Table) + require.True(t, binding.routed()) + + binding, err = router.route("mydb", "mytable") + require.NoError(t, err) + require.Equal(t, "mydb", binding.Target.Schema) + require.Equal(t, "mytable", binding.Target.Table) + require.False(t, binding.routed()) + }) + + t.Run("case insensitive router preserves source case in placeholders", func(t *testing.T) { + t.Parallel() + + router, err := NewRouter(newTestChangefeedID(), false, []*config.DispatchRule{ + {Matcher: []string{"MyDB.*"}, TargetSchema: "backup_" + SchemaPlaceholder, TargetTable: TablePlaceholder}, + }) + require.NoError(t, err) + + binding, err := router.route("mydb", "MyTable") + require.NoError(t, err) + require.Equal(t, "backup_mydb", binding.Target.Schema) + require.Equal(t, "MyTable", binding.Target.Table) + require.True(t, binding.routed()) + }) +} diff --git a/downstreamadapter/sink/cloudstorage/sink.go b/downstreamadapter/sink/cloudstorage/sink.go index 223136f53a..520209aff6 100644 --- a/downstreamadapter/sink/cloudstorage/sink.go +++ b/downstreamadapter/sink/cloudstorage/sink.go @@ -78,7 +78,7 @@ type sink struct { ctx context.Context } -func Verify(ctx context.Context, changefeedID common.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, enableTableAcrossNodes bool) error { +func Verify(ctx context.Context, changefeedID common.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, caseSensitive bool, enableTableAcrossNodes bool) error { cfg := cloudstorage.NewConfig() err := cfg.Apply(ctx, sinkURI, sinkConfig, enableTableAcrossNodes) if err != nil { @@ -88,7 +88,7 @@ func Verify(ctx context.Context, changefeedID common.ChangeFeedID, sinkURI *url. if err != nil { return err } - if _, err = columnselector.New(sinkConfig); err != nil { + if _, err = columnselector.New(sinkConfig, caseSensitive); err != nil { return err } _, err = helper.GetEncoderConfig(changefeedID, sinkURI, protocol, sinkConfig, math.MaxInt) @@ -104,7 +104,7 @@ func Verify(ctx context.Context, changefeedID common.ChangeFeedID, sinkURI *url. } func New( - ctx context.Context, changefeedID common.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, enableTableAcrossNodes bool, + ctx context.Context, changefeedID common.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, caseSensitive bool, enableTableAcrossNodes bool, cleanupJobs []func(), /* only for test */ keyspaceID uint32, ) (*sink, error) { @@ -127,7 +127,7 @@ func New( if err != nil { return nil, err } - columnSelectors, err := columnselector.New(sinkConfig) + columnSelectors, err := columnselector.New(sinkConfig, caseSensitive) if err != nil { return nil, err } diff --git a/downstreamadapter/sink/cloudstorage/sink_test.go b/downstreamadapter/sink/cloudstorage/sink_test.go index f04891ced2..ba1862486c 100644 --- a/downstreamadapter/sink/cloudstorage/sink_test.go +++ b/downstreamadapter/sink/cloudstorage/sink_test.go @@ -45,7 +45,7 @@ func newSinkForTest( cleanUpJobs []func(), ) (*sink, error) { changefeedID := common.NewChangefeedID4Test("test", "test") - result, err := New(ctx, changefeedID, sinkURI, replicaConfig.Sink, true, cleanUpJobs, common.DefaultKeyspaceID) + result, err := New(ctx, changefeedID, sinkURI, replicaConfig.Sink, util.GetOrZero(replicaConfig.CaseSensitive), true, cleanUpJobs, common.DefaultKeyspaceID) if err != nil { return nil, err } @@ -137,73 +137,88 @@ func TestBasicFunctionality(t *testing.T) { } func TestCloudStorageSinkWithColumnSelector(t *testing.T) { - parentDir := t.TempDir() - uri := fmt.Sprintf("file:///%s?protocol=csv&flush-interval=3600s&file-size=1024", parentDir) - sinkURI, err := url.Parse(uri) - require.NoError(t, err) - - replicaConfig := config.GetDefaultReplicaConfig() - replicaConfig.Sink.ColumnSelectors = []*config.ColumnSelector{ - {Matcher: []string{"test.table1"}, Columns: []string{"c1"}}, - } - err = replicaConfig.ValidateAndAdjust(sinkURI) - require.NoError(t, err) - replicaConfig.Sink.DateSeparator = util.AddressOf(config.DateSeparatorNone.String()) + for _, tc := range []struct { + name string + caseSensitive *bool + matcher string + wantPayload bool + }{ + {name: "unset", matcher: "Test.Table1"}, + {name: "insensitive", caseSensitive: util.AddressOf(false), matcher: "Test.Table1"}, + {name: "sensitive mismatch", caseSensitive: util.AddressOf(true), matcher: "Test.Table1", wantPayload: true}, + {name: "sensitive match", caseSensitive: util.AddressOf(true), matcher: "test.table1"}, + } { + t.Run(tc.name, func(t *testing.T) { + parentDir := t.TempDir() + uri := fmt.Sprintf("file:///%s?protocol=csv&flush-interval=3600s&file-size=1024", parentDir) + sinkURI, err := url.Parse(uri) + require.NoError(t, err) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + replicaConfig := config.GetDefaultReplicaConfig() + replicaConfig.CaseSensitive = tc.caseSensitive + replicaConfig.Sink.ColumnSelectors = []*config.ColumnSelector{ + {Matcher: []string{tc.matcher}, Columns: []string{"c1"}}, + } + err = replicaConfig.ValidateAndAdjust(sinkURI) + require.NoError(t, err) + replicaConfig.Sink.DateSeparator = util.AddressOf(config.DateSeparatorNone.String()) - setPDClockForTest(t, pdutil.NewClock4Test()) - cloudStorageSink, err := newSinkForTest(ctx, replicaConfig, sinkURI, nil) - require.NoError(t, err) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() - runDone := runSinkInBackground(t, ctx, cloudStorageSink) - defer cancelAndWaitSink(t, cancel, runDone) + setPDClockForTest(t, pdutil.NewClock4Test()) + cloudStorageSink, err := newSinkForTest(ctx, replicaConfig, sinkURI, nil) + require.NoError(t, err) - helper := commonEvent.NewEventTestHelper(t) - defer helper.Close() + runDone := runSinkInBackground(t, ctx, cloudStorageSink) + defer cancelAndWaitSink(t, cancel, runDone) - helper.Tk().MustExec("use test") - job := helper.DDL2Job("create table table1(c1 int primary key, c2 varchar(255))") - require.NotNil(t, job) - helper.ApplyJob(job) + helper := commonEvent.NewEventTestHelper(t) + defer helper.Close() - dispatcherID := common.NewDispatcherID() - event := helper.DML2Event(job.SchemaName, job.TableName, `insert into table1 values (1, "filtered")`) - event.TableInfoVersion = job.BinlogInfo.FinishedTS - event.DispatcherID = dispatcherID + helper.Tk().MustExec("use test") + job := helper.DDL2Job("create table table1(c1 int primary key, c2 varchar(255))") + require.NotNil(t, job) + helper.ApplyJob(job) - var flushed atomic.Uint64 - event.AddPostFlushFunc(func() { - flushed.Add(1) - }) + dispatcherID := common.NewDispatcherID() + event := helper.DML2Event(job.SchemaName, job.TableName, `insert into table1 values (1, "filtered")`) + event.TableInfoVersion = job.BinlogInfo.FinishedTS + event.DispatcherID = dispatcherID - cloudStorageSink.AddDMLEvent(event) - err = cloudStorageSink.FlushDMLBeforeBlock(&commonEvent.DDLEvent{ - DispatcherID: dispatcherID, - FinishedTs: event.CommitTs + 1, - }) - require.NoError(t, err) - require.Equal(t, uint64(1), flushed.Load()) + var flushed atomic.Uint64 + event.AddPostFlushFunc(func() { + flushed.Add(1) + }) - tableDir := path.Join(parentDir, job.SchemaName, job.TableName, fmt.Sprint(event.TableInfoVersion)) - var content []byte - require.Eventually(t, func() bool { - files, err := os.ReadDir(tableDir) - if err != nil { - return false - } - for _, file := range files { - if file.IsDir() || !strings.HasSuffix(file.Name(), ".csv") { - continue - } - content, err = os.ReadFile(path.Join(tableDir, file.Name())) - return err == nil - } - return false - }, testEventuallyTimeout, testEventuallyTick) - require.Contains(t, string(content), "1") - require.NotContains(t, string(content), "filtered") + cloudStorageSink.AddDMLEvent(event) + err = cloudStorageSink.FlushDMLBeforeBlock(&commonEvent.DDLEvent{ + DispatcherID: dispatcherID, + FinishedTs: event.CommitTs + 1, + }) + require.NoError(t, err) + require.Equal(t, uint64(1), flushed.Load()) + + tableDir := path.Join(parentDir, job.SchemaName, job.TableName, fmt.Sprint(event.TableInfoVersion)) + var content []byte + require.Eventually(t, func() bool { + files, err := os.ReadDir(tableDir) + if err != nil { + return false + } + for _, file := range files { + if file.IsDir() || !strings.HasSuffix(file.Name(), ".csv") { + continue + } + content, err = os.ReadFile(path.Join(tableDir, file.Name())) + return err == nil + } + return false + }, testEventuallyTimeout, testEventuallyTick) + require.Contains(t, string(content), "1") + require.Equal(t, tc.wantPayload, strings.Contains(string(content), "filtered")) + }) + } } func TestIgnoreCallsAfterRunError(t *testing.T) { @@ -606,7 +621,7 @@ func TestCloseBeforeRunDoesNotPanicAndCleansSpool(t *testing.T) { appcontext.SetService(appcontext.DefaultPDClock, mockPDClock) changefeedID := common.NewChangefeedID4Test("test", "close-before-run") - cloudStorageSink, err := New(ctx, changefeedID, sinkURI, replicaConfig.Sink, true, nil, common.DefaultKeyspaceID) + cloudStorageSink, err := New(ctx, changefeedID, sinkURI, replicaConfig.Sink, util.GetOrZero(replicaConfig.CaseSensitive), true, nil, common.DefaultKeyspaceID) require.NoError(t, err) spoolDir := filepath.Join(spoolBaseDir, changefeedID.Keyspace(), changefeedID.Name()) diff --git a/downstreamadapter/sink/columnselector/column_selector.go b/downstreamadapter/sink/columnselector/column_selector.go index df3342f6a9..d21af022e1 100644 --- a/downstreamadapter/sink/columnselector/column_selector.go +++ b/downstreamadapter/sink/columnselector/column_selector.go @@ -21,7 +21,6 @@ import ( "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/config" "github.com/pingcap/ticdc/pkg/errors" - "github.com/pingcap/ticdc/pkg/util" "github.com/pingcap/tidb/pkg/meta/model" filter "github.com/pingcap/tidb/pkg/util/table-filter" ) @@ -77,10 +76,10 @@ type ColumnSelectors struct { } // New return a column selectors -func New(sinkConfig *config.SinkConfig) (*ColumnSelectors, error) { +func New(sinkConfig *config.SinkConfig, caseSensitive bool) (*ColumnSelectors, error) { selectors := make([]*ColumnSelector, 0, len(sinkConfig.ColumnSelectors)) for _, r := range sinkConfig.ColumnSelectors { - selector, err := newColumnSelector(r, util.GetOrZero(sinkConfig.CaseSensitive)) + selector, err := newColumnSelector(r, caseSensitive) if err != nil { return nil, err } diff --git a/downstreamadapter/sink/columnselector/column_selector_test.go b/downstreamadapter/sink/columnselector/column_selector_test.go index 2a051b982d..3287ec81a6 100644 --- a/downstreamadapter/sink/columnselector/column_selector_test.go +++ b/downstreamadapter/sink/columnselector/column_selector_test.go @@ -29,7 +29,7 @@ import ( func TestNewColumnSelector(t *testing.T) { // the column selector is not set replicaConfig := config.GetDefaultReplicaConfig() - selectors, err := New(replicaConfig.Sink) + selectors, err := New(replicaConfig.Sink, false) require.NoError(t, err) require.NotNil(t, selectors) require.Len(t, selectors.selectors, 0) @@ -52,7 +52,7 @@ func TestNewColumnSelector(t *testing.T) { Columns: []string{"co?1"}, }, } - selectors, err = New(replicaConfig.Sink) + selectors, err = New(replicaConfig.Sink, false) require.NoError(t, err) require.Len(t, selectors.selectors, 4) } @@ -77,7 +77,7 @@ func TestColumnSelectorGetSelector(t *testing.T) { Columns: []string{"co?1"}, }, } - selectors, err := New(replicaConfig.Sink) + selectors, err := New(replicaConfig.Sink, false) require.NoError(t, err) { @@ -197,7 +197,7 @@ func TestVerifyTablesRequiresFullUniqueKey(t *testing.T) { Columns: []string{"a"}, }, } - selectors, err := New(replicaConfig.Sink) + selectors, err := New(replicaConfig.Sink, false) require.NoError(t, err) tableInfo := commonType.WrapTableInfo("test", &model.TableInfo{ @@ -224,7 +224,7 @@ func TestVerifyTablesRequiresFullUniqueKey(t *testing.T) { require.True(t, errors.ErrColumnSelectorFailed.Equal(err)) replicaConfig.Sink.ColumnSelectors[0].Columns = []string{"a", "b"} - selectors, err = New(replicaConfig.Sink) + selectors, err = New(replicaConfig.Sink, false) require.NoError(t, err) require.NoError(t, selectors.VerifyTables([]*commonType.TableInfo{tableInfo}, nil)) } @@ -239,3 +239,24 @@ func newColumnInfoForSelectorTest(id int64, name string, flag uint) *model.Colum State: model.StatePublic, } } + +func TestColumnSelectorCaseSensitive(t *testing.T) { + sinkConfig := &config.SinkConfig{ + ColumnSelectors: []*config.ColumnSelector{{ + Matcher: []string{"Sales.Orders"}, + Columns: []string{"*", "!payload"}, + }}, + } + payload := &model.ColumnInfo{Name: ast.NewCIStr("payload")} + id := &model.ColumnInfo{Name: ast.NewCIStr("id")} + for _, caseSensitive := range []bool{false, true} { + selectors, err := New(sinkConfig, caseSensitive) + require.NoError(t, err) + require.False(t, selectors.Get("Sales", "Orders").Select(payload)) + for _, table := range [][2]string{{"sales", "Orders"}, {"Sales", "orders"}} { + selector := selectors.Get(table[0], table[1]) + require.Equal(t, caseSensitive, selector.Select(payload)) + require.True(t, selector.Select(id)) + } + } +} diff --git a/downstreamadapter/sink/eventrouter/event_router.go b/downstreamadapter/sink/eventrouter/event_router.go index c29f94c22a..5b52004ac8 100644 --- a/downstreamadapter/sink/eventrouter/event_router.go +++ b/downstreamadapter/sink/eventrouter/event_router.go @@ -21,7 +21,6 @@ import ( commonEvent "github.com/pingcap/ticdc/pkg/common/event" "github.com/pingcap/ticdc/pkg/config" cerror "github.com/pingcap/ticdc/pkg/errors" - "github.com/pingcap/ticdc/pkg/util" tableFilter "github.com/pingcap/tidb/pkg/util/table-filter" ) @@ -40,7 +39,7 @@ type EventRouter struct { // NewEventRouter creates a new EventRouter. func NewEventRouter( - sinkConfig *config.SinkConfig, defaultTopic string, isPulsar bool, isAvro bool, + sinkConfig *config.SinkConfig, caseSensitive bool, defaultTopic string, isPulsar bool, isAvro bool, ) (*EventRouter, error) { // If an event does not match any dispatching rules in the config file, // it will be dispatched by the default partition dispatcher and @@ -53,11 +52,17 @@ func NewEventRouter( rules := make([]Rule, 0, len(ruleConfigs)) for _, ruleConfig := range ruleConfigs { + // Table routing alone must not select the default MQ dispatchers. + if (ruleConfig.TargetSchema != "" || ruleConfig.TargetTable != "") && + ruleConfig.DispatcherRule == "" && ruleConfig.PartitionRule == "" && + ruleConfig.IndexName == "" && len(ruleConfig.Columns) == 0 && ruleConfig.TopicRule == "" { + continue + } f, err := tableFilter.Parse(ruleConfig.Matcher) if err != nil { return nil, cerror.WrapError(cerror.ErrFilterRuleInvalid, err, ruleConfig.Matcher) } - if !util.GetOrZero(sinkConfig.CaseSensitive) { + if !caseSensitive { f = tableFilter.CaseInsensitive(f) } d := partition.NewGenerator(ruleConfig.PartitionRule, isPulsar, ruleConfig.IndexName, ruleConfig.Columns) diff --git a/downstreamadapter/sink/eventrouter/event_router_test.go b/downstreamadapter/sink/eventrouter/event_router_test.go index 1c3c0f33c1..429ded198d 100644 --- a/downstreamadapter/sink/eventrouter/event_router_test.go +++ b/downstreamadapter/sink/eventrouter/event_router_test.go @@ -75,7 +75,7 @@ func TestEventRouter(t *testing.T) { t.Parallel() sinkConfig := &config.SinkConfig{} - d, err := NewEventRouter(sinkConfig, "test", false, false) + d, err := NewEventRouter(sinkConfig, false, "test", false, false) require.NoError(t, err) require.Equal(t, "test", d.GetDefaultTopic()) @@ -88,7 +88,7 @@ func TestEventRouter(t *testing.T) { require.Equal(t, d.defaultTopic, actual) sinkConfig = newSinkConfig4Test() - d, err = NewEventRouter(sinkConfig, "", false, false) + d, err = NewEventRouter(sinkConfig, false, "", false, false) require.NoError(t, err) // no matched, use the default @@ -140,11 +140,70 @@ func TestEventRouter(t *testing.T) { require.IsType(t, &partition.TablePartitionGenerator{}, partitionDispatcher) } +func TestRoutingRuleIsolation(t *testing.T) { + for _, tc := range []struct { + name string + rule config.DispatchRule + expectedTopic string + expectedTs bool + }{ + { + name: "schema routing only", rule: config.DispatchRule{TargetSchema: "archive"}, + expectedTopic: "sales-events", expectedTs: true, + }, + { + name: "table routing only", rule: config.DispatchRule{TargetTable: "orders_archive"}, + expectedTopic: "sales-events", expectedTs: true, + }, + { + name: "routing and topic", rule: config.DispatchRule{TargetSchema: "archive", TopicRule: "archive-events"}, + expectedTopic: "archive-events", + }, + { + name: "routing and partition", rule: config.DispatchRule{TargetSchema: "archive", PartitionRule: "ts"}, + expectedTopic: "default-topic", expectedTs: true, + }, + { + name: "routing and explicit default", rule: config.DispatchRule{TargetSchema: "archive", PartitionRule: "default"}, + expectedTopic: "default-topic", + }, + { + name: "matcher only", rule: config.DispatchRule{}, + expectedTopic: "default-topic", + }, + } { + t.Run(tc.name, func(t *testing.T) { + for _, isPulsar := range []bool{false, true} { + rule := tc.rule + rule.Matcher = []string{"sales.orders"} + sinkConfig := &config.SinkConfig{DispatchRules: []*config.DispatchRule{ + &rule, + {Matcher: []string{"sales.*"}, TopicRule: "sales-events", PartitionRule: "ts"}, + }} + router, err := NewEventRouter(sinkConfig, false, "default-topic", isPulsar, false) + require.NoError(t, err) + require.Equal(t, tc.expectedTopic, router.GetTopicForRowChange("sales", "orders")) + require.Equal(t, tc.expectedTopic, router.GetTopicForDDL(&commonEvent.DDLEvent{ + SchemaName: "sales", TableName: "orders", + })) + generator := router.GetPartitionGenerator("sales", "orders") + if tc.expectedTs { + require.IsType(t, &partition.TsPartitionGenerator{}, generator) + } else if isPulsar && rule.PartitionRule == "" { + require.IsType(t, &partition.KeyPartitionGenerator{}, generator) + } else { + require.IsType(t, &partition.TablePartitionGenerator{}, generator) + } + } + }) + } +} + func TestGetActiveTopics(t *testing.T) { t.Parallel() sinkConfig := newSinkConfig4Test() - d, err := NewEventRouter(sinkConfig, "test", false, false) + d, err := NewEventRouter(sinkConfig, false, "test", false, false) require.NoError(t, err) names := []*commonEvent.SchemaTableName{ {SchemaName: "test_default1", TableName: "table"}, @@ -162,7 +221,7 @@ func TestGetTopicForRowChange(t *testing.T) { t.Parallel() sinkConfig := newSinkConfig4Test() - d, err := NewEventRouter(sinkConfig, "test", false, false) + d, err := NewEventRouter(sinkConfig, false, "test", false, false) require.NoError(t, err) topicName := d.GetTopicForRowChange("test_default1", "table") @@ -185,7 +244,7 @@ func TestGetPartitionForRowChange(t *testing.T) { t.Parallel() sinkConfig := newSinkConfig4Test() - d, err := NewEventRouter(sinkConfig, "test", false, false) + d, err := NewEventRouter(sinkConfig, false, "test", false, false) require.NoError(t, err) // default partition @@ -268,7 +327,7 @@ func TestGetTopicForDDL(t *testing.T) { }, } - d, err := NewEventRouter(sinkConfig, "test", false, false) + d, err := NewEventRouter(sinkConfig, false, "test", false, false) require.NoError(t, err) tests := []struct { @@ -317,3 +376,27 @@ func TestGetTopicForDDL(t *testing.T) { require.Equal(t, test.expectedTopic, d.GetTopicForDDL(test.ddl)) } } + +func TestEventRouterCaseSensitive(t *testing.T) { + for _, caseSensitive := range []bool{false, true} { + sinkConfig := &config.SinkConfig{ + DispatchRules: []*config.DispatchRule{{ + Matcher: []string{"Sales.Orders"}, + TopicRule: "sales-events", + PartitionRule: "ts", + }}, + } + router, err := NewEventRouter(sinkConfig, caseSensitive, "default-topic", false, false) + require.NoError(t, err) + require.Equal(t, "sales-events", router.GetTopicForRowChange("Sales", "Orders")) + for _, table := range [][2]string{{"sales", "Orders"}, {"Sales", "orders"}} { + if caseSensitive { + require.Equal(t, "default-topic", router.GetTopicForRowChange(table[0], table[1])) + require.IsType(t, &partition.TablePartitionGenerator{}, router.GetPartitionGenerator(table[0], table[1])) + } else { + require.Equal(t, "sales-events", router.GetTopicForRowChange(table[0], table[1])) + require.IsType(t, &partition.TsPartitionGenerator{}, router.GetPartitionGenerator(table[0], table[1])) + } + } + } +} diff --git a/downstreamadapter/sink/kafka/helper.go b/downstreamadapter/sink/kafka/helper.go index efd35aec57..e8f619571d 100644 --- a/downstreamadapter/sink/kafka/helper.go +++ b/downstreamadapter/sink/kafka/helper.go @@ -53,6 +53,7 @@ func newKafkaSinkComponentWithFactory(ctx context.Context, changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, + caseSensitive bool, factoryCreator kafka.FactoryCreator, ) (components, config.Protocol, error) { kafkaComponent := components{} @@ -79,12 +80,12 @@ func newKafkaSinkComponentWithFactory(ctx context.Context, isAvroLike := protocol == config.ProtocolAvro || protocol == config.ProtocolDebeziumAvro kafkaComponent.eventRouter, err = eventrouter.NewEventRouter( - sinkConfig, topic, false, isAvroLike) + sinkConfig, caseSensitive, topic, false, isAvroLike) if err != nil { return kafkaComponent, protocol, errors.Trace(err) } - kafkaComponent.columnSelector, err = columnselector.New(sinkConfig) + kafkaComponent.columnSelector, err = columnselector.New(sinkConfig, caseSensitive) if err != nil { return kafkaComponent, protocol, errors.Trace(err) } @@ -135,8 +136,9 @@ func newKafkaSinkComponent( changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, + caseSensitive bool, ) (components, config.Protocol, error) { - return newKafkaSinkComponentWithFactory(ctx, changefeedID, sinkURI, sinkConfig, kafka.NewSaramaFactory) + return newKafkaSinkComponentWithFactory(ctx, changefeedID, sinkURI, sinkConfig, caseSensitive, kafka.NewSaramaFactory) } func newKafkaSinkComponentForTest( @@ -144,6 +146,7 @@ func newKafkaSinkComponentForTest( changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, + caseSensitive bool, ) (components, config.Protocol, error) { - return newKafkaSinkComponentWithFactory(ctx, changefeedID, sinkURI, sinkConfig, kafka.NewMockFactory) + return newKafkaSinkComponentWithFactory(ctx, changefeedID, sinkURI, sinkConfig, caseSensitive, kafka.NewMockFactory) } diff --git a/downstreamadapter/sink/kafka/sink.go b/downstreamadapter/sink/kafka/sink.go index ab3590c6a7..326a8e48ce 100644 --- a/downstreamadapter/sink/kafka/sink.go +++ b/downstreamadapter/sink/kafka/sink.go @@ -67,16 +67,16 @@ func (s *sink) SinkType() commonType.SinkType { return commonType.KafkaSinkType } -func Verify(ctx context.Context, changefeedID commonType.ChangeFeedID, uri *url.URL, sinkConfig *config.SinkConfig) error { - comp, _, err := newKafkaSinkComponent(ctx, changefeedID, uri, sinkConfig) +func Verify(ctx context.Context, changefeedID commonType.ChangeFeedID, uri *url.URL, sinkConfig *config.SinkConfig, caseSensitive bool) error { + comp, _, err := newKafkaSinkComponent(ctx, changefeedID, uri, sinkConfig, caseSensitive) defer comp.close() return err } func New( - ctx context.Context, changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, keyspaceID uint32, + ctx context.Context, changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, caseSensitive bool, keyspaceID uint32, ) (*sink, error) { - comp, protocol, err := newKafkaSinkComponent(ctx, changefeedID, sinkURI, sinkConfig) + comp, protocol, err := newKafkaSinkComponent(ctx, changefeedID, sinkURI, sinkConfig, caseSensitive) if err != nil { return nil, errors.Trace(err) } diff --git a/downstreamadapter/sink/kafka/sink_test.go b/downstreamadapter/sink/kafka/sink_test.go index 2e02784f5e..d9ae3ef9fc 100644 --- a/downstreamadapter/sink/kafka/sink_test.go +++ b/downstreamadapter/sink/kafka/sink_test.go @@ -51,7 +51,7 @@ func newKafkaSinkForTestWithProducers(ctx context.Context, return nil, errors.Trace(err) } statistics := metrics.NewStatistics(changefeedID, common.DefaultKeyspaceID, "sink") - comp, protocol, err := newKafkaSinkComponentForTest(ctx, changefeedID, sinkURI, sinkConfig) + comp, protocol, err := newKafkaSinkComponentForTest(ctx, changefeedID, sinkURI, sinkConfig, false) if err != nil { return nil, errors.Trace(err) } diff --git a/downstreamadapter/sink/pulsar/helper.go b/downstreamadapter/sink/pulsar/helper.go index fe11751162..5a689236f8 100644 --- a/downstreamadapter/sink/pulsar/helper.go +++ b/downstreamadapter/sink/pulsar/helper.go @@ -57,8 +57,9 @@ func newPulsarSinkComponent( changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, + caseSensitive bool, ) (component, config.Protocol, error) { - return newPulsarSinkComponentWithFactory(ctx, changefeedID, sinkURI, sinkConfig, pulsar.NewCreatorFactory) + return newPulsarSinkComponentWithFactory(ctx, changefeedID, sinkURI, sinkConfig, caseSensitive, pulsar.NewCreatorFactory) } func newPulsarSinkComponentForTest( @@ -66,14 +67,16 @@ func newPulsarSinkComponentForTest( changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, + caseSensitive bool, ) (component, config.Protocol, error) { - return newPulsarSinkComponentWithFactory(ctx, changefeedID, sinkURI, sinkConfig, pulsar.NewMockCreatorFactory) + return newPulsarSinkComponentWithFactory(ctx, changefeedID, sinkURI, sinkConfig, caseSensitive, pulsar.NewMockCreatorFactory) } func newPulsarSinkComponentWithFactory(ctx context.Context, changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, + caseSensitive bool, factoryCreator pulsar.FactoryCreator, ) (component, config.Protocol, error) { pulsarComponent := component{} @@ -108,12 +111,12 @@ func newPulsarSinkComponentWithFactory(ctx context.Context, } // pulsar only support canal-json, so we don't need to check the protocol - pulsarComponent.eventRouter, err = eventrouter.NewEventRouter(sinkConfig, topic, true, false) + pulsarComponent.eventRouter, err = eventrouter.NewEventRouter(sinkConfig, caseSensitive, topic, true, false) if err != nil { return pulsarComponent, protocol, errors.Trace(err) } - pulsarComponent.columnSelector, err = columnselector.New(sinkConfig) + pulsarComponent.columnSelector, err = columnselector.New(sinkConfig, caseSensitive) if err != nil { return pulsarComponent, protocol, errors.Trace(err) } diff --git a/downstreamadapter/sink/pulsar/sink.go b/downstreamadapter/sink/pulsar/sink.go index aaf961abd4..9610fbfcc4 100644 --- a/downstreamadapter/sink/pulsar/sink.go +++ b/downstreamadapter/sink/pulsar/sink.go @@ -70,16 +70,16 @@ func (s *sink) SinkType() commonType.SinkType { return commonType.PulsarSinkType } -func Verify(ctx context.Context, changefeedID commonType.ChangeFeedID, uri *url.URL, sinkConfig *config.SinkConfig) error { - comp, _, err := newPulsarSinkComponent(ctx, changefeedID, uri, sinkConfig) +func Verify(ctx context.Context, changefeedID commonType.ChangeFeedID, uri *url.URL, sinkConfig *config.SinkConfig, caseSensitive bool) error { + comp, _, err := newPulsarSinkComponent(ctx, changefeedID, uri, sinkConfig, caseSensitive) defer comp.close() return err } func New( - ctx context.Context, changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, keyspaceID uint32, + ctx context.Context, changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, caseSensitive bool, keyspaceID uint32, ) (*sink, error) { - comp, protocol, err := newPulsarSinkComponent(ctx, changefeedID, sinkURI, sinkConfig) + comp, protocol, err := newPulsarSinkComponent(ctx, changefeedID, sinkURI, sinkConfig, caseSensitive) if err != nil { return nil, err } diff --git a/downstreamadapter/sink/pulsar/sink_test.go b/downstreamadapter/sink/pulsar/sink_test.go index fac2aaf871..688558ab3c 100644 --- a/downstreamadapter/sink/pulsar/sink_test.go +++ b/downstreamadapter/sink/pulsar/sink_test.go @@ -45,7 +45,7 @@ func newPulsarSinkForTest(t *testing.T) (*sink, error) { ctx := context.Background() changefeedID := common.NewChangefeedID4Test("test", "test") - comp, protocol, err := newPulsarSinkComponentForTest(ctx, changefeedID, sinkURI, replicaConfig.Sink) + comp, protocol, err := newPulsarSinkComponentForTest(ctx, changefeedID, sinkURI, replicaConfig.Sink, false) require.NoError(t, err) statistics := metrics.NewStatistics(changefeedID, common.DefaultKeyspaceID, "sink") diff --git a/downstreamadapter/sink/sink.go b/downstreamadapter/sink/sink.go index 382b9f09d1..7cc00b85ec 100644 --- a/downstreamadapter/sink/sink.go +++ b/downstreamadapter/sink/sink.go @@ -57,11 +57,11 @@ func New(ctx context.Context, cfg *config.ChangefeedConfig, changefeedID common. case config.MySQLScheme, config.MySQLSSLScheme, config.TiDBScheme, config.TiDBSSLScheme: return mysql.New(ctx, changefeedID, cfg, sinkURI, keyspaceID) case config.KafkaScheme, config.KafkaSSLScheme: - return kafka.New(ctx, changefeedID, sinkURI, cfg.SinkConfig, keyspaceID) + return kafka.New(ctx, changefeedID, sinkURI, cfg.SinkConfig, cfg.CaseSensitive, keyspaceID) case config.PulsarScheme, config.PulsarSSLScheme, config.PulsarHTTPScheme, config.PulsarHTTPSScheme: - return pulsar.New(ctx, changefeedID, sinkURI, cfg.SinkConfig, keyspaceID) + return pulsar.New(ctx, changefeedID, sinkURI, cfg.SinkConfig, cfg.CaseSensitive, keyspaceID) case config.S3Scheme, config.FileScheme, config.GCSScheme, config.GSScheme, config.AzblobScheme, config.AzureScheme, config.CloudStorageNoopScheme: - return cloudstorage.New(ctx, changefeedID, sinkURI, cfg.SinkConfig, cfg.EnableTableAcrossNodes, nil, keyspaceID) + return cloudstorage.New(ctx, changefeedID, sinkURI, cfg.SinkConfig, cfg.CaseSensitive, cfg.EnableTableAcrossNodes, nil, keyspaceID) case config.BlackHoleScheme: return blackhole.New() } @@ -78,11 +78,11 @@ func Verify(ctx context.Context, cfg *config.ChangefeedConfig, changefeedID comm case config.MySQLScheme, config.MySQLSSLScheme, config.TiDBScheme, config.TiDBSSLScheme: return mysql.Verify(ctx, sinkURI, cfg) case config.KafkaScheme, config.KafkaSSLScheme: - return kafka.Verify(ctx, changefeedID, sinkURI, cfg.SinkConfig) + return kafka.Verify(ctx, changefeedID, sinkURI, cfg.SinkConfig, cfg.CaseSensitive) case config.PulsarScheme, config.PulsarSSLScheme, config.PulsarHTTPScheme, config.PulsarHTTPSScheme: - return pulsar.Verify(ctx, changefeedID, sinkURI, cfg.SinkConfig) + return pulsar.Verify(ctx, changefeedID, sinkURI, cfg.SinkConfig, cfg.CaseSensitive) case config.S3Scheme, config.FileScheme, config.GCSScheme, config.GSScheme, config.AzblobScheme, config.AzureScheme, config.CloudStorageNoopScheme: - return cloudstorage.Verify(ctx, changefeedID, sinkURI, cfg.SinkConfig, cfg.EnableTableAcrossNodes) + return cloudstorage.Verify(ctx, changefeedID, sinkURI, cfg.SinkConfig, cfg.CaseSensitive, cfg.EnableTableAcrossNodes) case config.BlackHoleScheme: return nil } diff --git a/heartbeatpb/heartbeat.proto b/heartbeatpb/heartbeat.proto index ae44abe775..3c322769df 100644 --- a/heartbeatpb/heartbeat.proto +++ b/heartbeatpb/heartbeat.proto @@ -73,7 +73,7 @@ message CheckpointTsMessage { uint64 checkpointTs = 2; } -// RedoMetaMessage used to send unflushed ts to update redo meta +// RedoMetaMessage used to send unflushed ts to update redo meta // from maintainer to dispatcher manager message RedoMetaMessage { ChangefeedID changefeedID = 1; @@ -81,14 +81,14 @@ message RedoMetaMessage { uint64 checkpointTs = 3; } -// RedoResolvedTsProgressMessage used to send redo meta flushed resolvedTs +// RedoResolvedTsProgressMessage used to send redo meta flushed resolvedTs // from dispatcher manager to maintainer message RedoResolvedTsProgressMessage { ChangefeedID changefeedID = 1; uint64 resolvedTs = 2; } -// RedoResolvedTsForwardMessage used to send redoGlobalTs (redo meta flushed resolvedTs) +// RedoResolvedTsForwardMessage used to send redoGlobalTs (redo meta flushed resolvedTs) // from maintainer to dispatcher manager message RedoResolvedTsForwardMessage { ChangefeedID changefeedID = 1; @@ -360,7 +360,7 @@ enum ChecksumState { message ChecksumMeta { ChecksumState state = 1; - // checksumStateSeq is a monotonic version for checksumState, + // checksumStateSeq is a monotonic version for checksumState, // used to discard out-of-order meta info. uint64 checksumStateSeq = 2; } diff --git a/logservice/schemastore/persist_storage_ddl_handlers.go b/logservice/schemastore/persist_storage_ddl_handlers.go index d4fbee6efd..a3f45c798c 100644 --- a/logservice/schemastore/persist_storage_ddl_handlers.go +++ b/logservice/schemastore/persist_storage_ddl_handlers.go @@ -590,6 +590,7 @@ func buildPersistedDDLEventForCreateView(args buildPersistedDDLEventFuncArgs) Pe event := buildPersistedDDLEventCommon(args) event.SchemaName = getSchemaName(args.databaseMap, event.SchemaID) event.TableName = args.job.TableName + normalizeCreateViewQueryWithStoredSelect(&event) return event } @@ -603,6 +604,34 @@ func buildPersistedDDLEventForDropView(args buildPersistedDDLEventFuncArgs) Pers return event } +// TiDB persists the normalized SELECT body of a view in +// event.TableInfo.View.SelectStmt when executing CREATE VIEW, so this field can +// carry fully resolved source-table references even if job.Query keeps the +// original session-level text. +// Field definition: +// https://github.com/pingcap/tidb/blob/8f2630e53d5d/pkg/meta/model/table.go#L762-L770 +// Value assignment in CREATE VIEW: +// https://github.com/pingcap/tidb/blob/8f2630e53d5d/pkg/ddl/create_table.go#L1668-L1678 +func normalizeCreateViewQueryWithStoredSelect(event *PersistedDDLEvent) { + if event.TableInfo == nil || event.TableInfo.View == nil { + return + } + + query, err := commonEvent.NormalizeCreateViewQueryWithStoredSelect( + event.Query, + event.TableInfo.View.SelectStmt, + event.SchemaName, + ) + if err != nil { + log.Warn("normalize create view query with stored select failed", + zap.String("query", event.Query), + zap.String("selectStmt", event.TableInfo.View.SelectStmt), + zap.Error(err)) + return + } + event.Query = query +} + func buildPersistedDDLEventForCreateTable(args buildPersistedDDLEventFuncArgs) PersistedDDLEvent { event := buildPersistedDDLEventCommon(args) event.SchemaName = getSchemaName(args.databaseMap, event.SchemaID) @@ -611,6 +640,13 @@ func buildPersistedDDLEventForCreateTable(args buildPersistedDDLEventFuncArgs) P return event } +type createTableLikeReferSchemaInfo struct { + schemaName string + schemaID int64 + // true when the source schema was inferred and should be written back to query. + qualifyQuery bool +} + func setReferTableForCreateTableLike(event *PersistedDDLEvent, args buildPersistedDDLEventFuncArgs) { if event.Query == "" { return @@ -627,22 +663,33 @@ func setReferTableForCreateTableLike(event *PersistedDDLEvent, args buildPersist return } refTable := createStmt.ReferTable.Name.O - refSchema := createStmt.ReferTable.Schema.O - if refSchema == "" { - refSchema = event.SchemaName - } - refSchemaID, ok := findSchemaIDByName(args.databaseMap, refSchema) + // refSchema is the schema name of the table referenced by + // CREATE TABLE ... LIKE. It can be absent in the original query. + refSchemaInQuery := createStmt.ReferTable.Schema.O + referSchemaInfo, ok := resolveCreateTableLikeReferSchema(args, refSchemaInQuery, refTable) if !ok { log.Warn("refer schema not found for create table like", - zap.String("schema", refSchema), + zap.String("schema", referSchemaInfo.schemaName), zap.String("table", refTable), zap.String("query", event.Query)) return } - refTableID, ok := findTableIDByName(args.tableMap, refSchemaID, refTable) + if referSchemaInfo.qualifyQuery { + createStmt.ReferTable.Schema = ast.NewCIStr(referSchemaInfo.schemaName) + query, err := commonEvent.Restore(createStmt) + if err != nil { + log.Warn("restore create table like ddl failed", + zap.String("schema", referSchemaInfo.schemaName), + zap.String("query", event.Query), + zap.Error(err)) + return + } + event.Query = query + } + refTableID, ok := findTableIDByName(args.tableMap, referSchemaInfo.schemaID, refTable) if !ok { log.Warn("refer table not found for create table like", - zap.String("schema", refSchema), + zap.String("schema", referSchemaInfo.schemaName), zap.String("table", refTable), zap.String("query", event.Query)) return @@ -656,6 +703,50 @@ func setReferTableForCreateTableLike(event *PersistedDDLEvent, args buildPersist } } +func resolveCreateTableLikeReferSchema( + args buildPersistedDDLEventFuncArgs, + refSchemaInQuery string, + refTable string, +) (createTableLikeReferSchemaInfo, bool) { + if refSchemaInQuery != "" { + schemaID, ok := findSchemaIDByName(args.databaseMap, refSchemaInQuery) + return createTableLikeReferSchemaInfo{ + schemaName: refSchemaInQuery, + schemaID: schemaID, + }, ok + } + + for _, info := range args.job.InvolvingSchemaInfo { + // TiDB records the LIKE source table as a shared involving table. + // For CREATE TABLE db2.t LIKE db1.t, the target db2.t is also in + // InvolvingSchemaInfo, but it is exclusive. Without this mode check, + // the target table may be mistaken as the referenced table. + // https://github.com/pingcap/tidb/blob/8f2630e53d5d/pkg/ddl/executor.go#L1009-L1023 + if info.Mode != model.SharedInvolving || + info.Database == "" || + !strings.EqualFold(info.Table, refTable) { + continue + } + schemaID, ok := findSchemaIDByName(args.databaseMap, info.Database) + if !ok { + continue + } + refSchema := getSchemaName(args.databaseMap, schemaID) + return createTableLikeReferSchemaInfo{ + schemaName: refSchema, + schemaID: schemaID, + qualifyQuery: !strings.EqualFold(refSchema, getSchemaName(args.databaseMap, args.job.SchemaID)), + }, true + } + + // If TiDB does not provide the referenced schema, fall back to the schema + // that the CREATE TABLE event belongs to, matching MySQL/TiDB resolution. + return createTableLikeReferSchemaInfo{ + schemaName: getSchemaName(args.databaseMap, args.job.SchemaID), + schemaID: args.job.SchemaID, + }, true +} + func buildPersistedDDLEventForDropTable(args buildPersistedDDLEventFuncArgs) PersistedDDLEvent { event := buildPersistedDDLEventCommon(args) event.SchemaName = getSchemaName(args.databaseMap, event.SchemaID) @@ -2615,38 +2706,17 @@ func buildDDLEventForExchangeTablePartition(rawEvent *PersistedDDLEvent, tableFi } // For exchange table partition, we only set NotSync to true when the partition table is filtered. ddlEvent.NotSync = notSyncPartitionTable + // The default event (including the DDL trigger) describes the partition table. + // Keep the old normal table info for storage sinks to emit its column schema. + ddlEvent.TableInfo = common.WrapTableInfo(rawEvent.ExtraSchemaName, rawEvent.TableInfo) ddlEvent.MultipleTableInfos = []*common.TableInfo{ - common.WrapTableInfo(rawEvent.SchemaName, rawEvent.TableInfo), + ddlEvent.TableInfo, rawEvent.ExtraTableInfo, } - if tableID != 0 { - // Here we set TableInfo to the table info of tableID. - // First, check whether the tableID is a normal table after exchange. - // If false, set TableInfo to rawEvent.TableInfo, because the rawEvent.TableInfo is the partition table info after exchange. - // NOTE: ddlEvent.TableInfo is already the rawEvent.TableInfo in buildDDLEventCommon. So we don't need to set it again if false. - // If true, set TableInfo to rawEvent.ExtraTableInfo, - // because the rawEvent.ExtraTableInfo is the normal table info before exchange, - // but the tableID is the normal table after exchange, so we need to get a new TableInfo for it. - // NOTE: We can't just check tableID == rawEvent.ExtraTableInfo.TableName.TableID, - // because rawEvent.ExtraTableInfo is the table info before exchange, - // and the tableID is the table id after exchange. - isNormalTableAfterExchange := true - for _, id := range physicalIDs { - if id == tableID { - isNormalTableAfterExchange = false - break - } - } - if isNormalTableAfterExchange { - ddlEvent.TableInfo = common.NewTableInfo( - rawEvent.ExtraSchemaName, - ast.NewCIStr(rawEvent.ExtraTableName).O, - tableID, - false, - rawEvent.ExtraTableInfo.ShadowCopyColumnSchema(), - rawEvent.ExtraTableInfo.ToTiDBTableInfo(), - ) - } + if tableID == targetPartitionID { + // The old partition is now the normal table. Use the same identity and + // column schema as a fresh table-info lookup after the exchange. + ddlEvent.TableInfo, _ = extractTableInfoFuncForExchangeTablePartition(rawEvent, tableID) } return ddlEvent, true, err } diff --git a/logservice/schemastore/persist_storage_test.go b/logservice/schemastore/persist_storage_test.go index 47cc4d2763..34a4d03ecf 100644 --- a/logservice/schemastore/persist_storage_test.go +++ b/logservice/schemastore/persist_storage_test.go @@ -3648,26 +3648,166 @@ func TestParseRenameTablesQueryInfos(t *testing.T) { } } +func TestBuildPersistedDDLEventForCreateViewUsesStoredSelectStmt(t *testing.T) { + job := buildCreateViewJobForTest(101, 100) + job.TableName = "v" + job.Query = "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `id` FROM `users`" + job.BinlogInfo.TableInfo = &model.TableInfo{ + Name: ast.NewCIStr("v"), + View: &model.ViewInfo{ + SelectStmt: "SELECT `id` FROM `source_db`.`users`", + }, + } + + ddl := buildPersistedDDLEventForCreateView(buildPersistedDDLEventFuncArgs{ + job: job, + databaseMap: map[int64]*BasicDatabaseInfo{ + 101: {Name: "target_db", Tables: map[int64]bool{}}, + }, + }) + + require.Equal(t, + "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `id` FROM `source_db`.`users`", + ddl.Query) + require.Equal(t, "target_db", ddl.SchemaName) + require.Equal(t, "v", ddl.TableName) +} + +func TestBuildPersistedDDLEventForCreateViewKeepsOriginalQueryForSameSchemaSelect(t *testing.T) { + job := buildCreateViewJobForTest(101, 100) + job.TableName = "v" + job.Query = "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `id` FROM `users`" + job.BinlogInfo.TableInfo = &model.TableInfo{ + Name: ast.NewCIStr("v"), + View: &model.ViewInfo{ + SelectStmt: "SELECT `id` FROM `target_db`.`users`", + }, + } + + ddl := buildPersistedDDLEventForCreateView(buildPersistedDDLEventFuncArgs{ + job: job, + databaseMap: map[int64]*BasicDatabaseInfo{ + 101: {Name: "target_db", Tables: map[int64]bool{}}, + }, + }) + + require.Equal(t, + "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `id` FROM `users`", + ddl.Query) + require.Equal(t, "target_db", ddl.SchemaName) + require.Equal(t, "v", ddl.TableName) +} + +func TestBuildPersistedDDLEventForCreateViewQualifiesTableColumnReferences(t *testing.T) { + cases := []struct { + name string + query string + selectStmt string + expected string + }{ + { + name: "cross schema unaliased table qualifier", + query: "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `orders`.`id` FROM `orders`", + selectStmt: "SELECT `orders`.`id` AS `id` FROM `source_db`.`orders`", + expected: "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `source_db`.`orders`.`id` AS `id` FROM `source_db`.`orders`", + }, + { + name: "same schema unaliased table qualifier", + query: "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `users`.`id` FROM `users`", + selectStmt: "SELECT `users`.`id` AS `id` FROM `target_db`.`users`", + expected: "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `target_db`.`users`.`id` AS `id` FROM `target_db`.`users`", + }, + { + name: "alias is preserved", + query: "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `orders`.`id` FROM `orders` AS `orders`", + selectStmt: "SELECT `orders`.`id` AS `id` FROM `source_db`.`orders` AS `orders`", + expected: "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `orders`.`id` AS `id` FROM `source_db`.`orders` AS `orders`", + }, + { + name: "ambiguous table qualifier is preserved", + query: "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `t`.`id` FROM `t`", + selectStmt: "SELECT `t`.`id` AS `id` FROM `db1`.`t`, `db2`.`t`", + expected: "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `t`.`id` AS `id` FROM (`db1`.`t`) JOIN `db2`.`t`", + }, + { + name: "subquery scopes are independent", + query: "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `q`.`id` FROM (SELECT `t`.`id` FROM `t`) AS `q`", + selectStmt: "SELECT `q`.`id` AS `id` FROM (SELECT `t`.`id` AS `id` FROM `source_db`.`t`) AS `q`", + expected: "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `q`.`id` AS `id` FROM (SELECT `source_db`.`t`.`id` AS `id` FROM `source_db`.`t`) AS `q`", + }, + { + name: "join table qualifier", + query: "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `orders`.`id`, `customers`.`name` FROM `orders` JOIN `customers` ON `orders`.`customer_id` = `customers`.`id`", + selectStmt: "SELECT `orders`.`id` AS `id`, `customers`.`name` AS `name` FROM `source_db`.`orders` JOIN `crm_db`.`customers` ON `orders`.`customer_id` = `customers`.`id`", + expected: "CREATE ALGORITHM = UNDEFINED DEFINER = CURRENT_USER SQL SECURITY DEFINER VIEW `target_db`.`v` AS SELECT `source_db`.`orders`.`id` AS `id`,`crm_db`.`customers`.`name` AS `name` FROM `source_db`.`orders` JOIN `crm_db`.`customers` ON `source_db`.`orders`.`customer_id`=`crm_db`.`customers`.`id`", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + job := buildCreateViewJobForTest(101, 100) + job.TableName = "v" + job.Query = tc.query + job.BinlogInfo.TableInfo = &model.TableInfo{ + Name: ast.NewCIStr("v"), + View: &model.ViewInfo{ + SelectStmt: tc.selectStmt, + }, + } + + ddl := buildPersistedDDLEventForCreateView(buildPersistedDDLEventFuncArgs{ + job: job, + databaseMap: map[int64]*BasicDatabaseInfo{ + 101: {Name: "target_db", Tables: map[int64]bool{}}, + }, + }) + + require.Equal(t, tc.expected, ddl.Query) + require.Equal(t, "target_db", ddl.SchemaName) + require.Equal(t, "v", ddl.TableName) + }) + } +} + func TestBuildDDLEventForNewTableDDL_CreateTableLikeBlockedTableNames(t *testing.T) { cases := []struct { - name string - query string - expected []commonEvent.SchemaTableName + name string + query string + schemaName string + expected []commonEvent.SchemaTableName }{ { - name: "default schema", - query: "CREATE TABLE `b` LIKE `a`", + name: "default schema", + query: "CREATE TABLE `b` LIKE `a`", + schemaName: "test", expected: []commonEvent.SchemaTableName{ {SchemaName: "test", TableName: "a"}, }, }, { - name: "explicit schema", - query: "CREATE TABLE `b` LIKE `other`.`a`", + name: "explicit schema", + query: "CREATE TABLE `b` LIKE `other`.`a`", + schemaName: "test", expected: []commonEvent.SchemaTableName{ {SchemaName: "other", TableName: "a"}, }, }, + { + name: "explicit target schema with persisted refer table", + query: "CREATE TABLE `extra`.`b` LIKE `test`.`a`", + schemaName: "extra", + expected: []commonEvent.SchemaTableName{ + {SchemaName: "test", TableName: "a"}, + }, + }, + { + name: "explicit target schema in same schema", + query: "CREATE TABLE `test`.`b` LIKE `a`", + schemaName: "test", + expected: []commonEvent.SchemaTableName{ + {SchemaName: "test", TableName: "a"}, + }, + }, } for _, tc := range cases { @@ -3675,7 +3815,7 @@ func TestBuildDDLEventForNewTableDDL_CreateTableLikeBlockedTableNames(t *testing Type: byte(model.ActionCreateTable), SchemaID: 1, TableID: 2, - SchemaName: "test", + SchemaName: tc.schemaName, TableName: "b", Query: tc.query, TableInfo: &model.TableInfo{}, @@ -3694,6 +3834,7 @@ func TestBuildPersistedDDLEventForCreateTableLikeSetsReferTableID(t *testing.T) query string partitionIDs []int64 expectedReferID int64 + expectedQuery string }{ { name: "non partition refer table", @@ -3718,6 +3859,7 @@ func TestBuildPersistedDDLEventForCreateTableLikeSetsReferTableID(t *testing.T) query: "CREATE TABLE `b` LIKE `TeSt`.`A`", partitionIDs: nil, expectedReferID: 101, + expectedQuery: "CREATE TABLE `b` LIKE `TeSt`.`A`", }, } @@ -3744,12 +3886,97 @@ func TestBuildPersistedDDLEventForCreateTableLikeSetsReferTableID(t *testing.T) partitionMap: partitionMap, }) require.Equal(t, tc.expectedReferID, ddl.ExtraTableID, tc.name) + if tc.expectedQuery != "" { + require.Equal(t, tc.expectedQuery, ddl.Query, tc.name) + } if len(tc.partitionIDs) > 0 { require.ElementsMatch(t, tc.partitionIDs, ddl.ReferTablePartitionIDs, tc.name) } else { require.Empty(t, ddl.ReferTablePartitionIDs, tc.name) } } + + job := buildCreateTableJobForTest(200, 300, "b", 1010) + job.Query = "CREATE TABLE `extra`.`b` LIKE `a`" + job.InvolvingSchemaInfo = []model.InvolvingSchemaInfo{ + {Database: "extra", Table: "b"}, + {Database: "test", Table: "a", Mode: model.SharedInvolving}, + } + ddl := buildPersistedDDLEventForCreateTable(buildPersistedDDLEventFuncArgs{ + job: job, + databaseMap: map[int64]*BasicDatabaseInfo{ + 100: {Name: "test", Tables: map[int64]bool{101: true}}, + 200: {Name: "extra", Tables: map[int64]bool{300: true}}, + }, + tableMap: map[int64]*BasicTableInfo{ + 101: {SchemaID: 100, Name: "a"}, + 300: {SchemaID: 200, Name: "b"}, + }, + }) + require.Equal(t, int64(101), ddl.ExtraTableID) +} + +func TestBuildPersistedDDLEventForCreateTableLikeUsesInvolvingReferSchema(t *testing.T) { + job := buildCreateTableJobForTest(100, 200, "t", 1010) + job.Query = "CREATE TABLE `dst_db`.`t` LIKE `t`" + job.InvolvingSchemaInfo = []model.InvolvingSchemaInfo{ + {Database: "dst_db", Table: "t"}, + {Database: "src_db", Table: "t", Mode: model.SharedInvolving}, + } + + ddl := buildPersistedDDLEventForCreateTable(buildPersistedDDLEventFuncArgs{ + job: job, + databaseMap: map[int64]*BasicDatabaseInfo{ + 100: {Name: "dst_db", Tables: map[int64]bool{200: true}}, + 101: {Name: "src_db", Tables: map[int64]bool{201: true}}, + }, + tableMap: map[int64]*BasicTableInfo{ + 200: {SchemaID: 100, Name: "t"}, + 201: {SchemaID: 101, Name: "t"}, + }, + }) + + require.Equal(t, int64(201), ddl.ExtraTableID) + require.Equal(t, "CREATE TABLE `dst_db`.`t` LIKE `src_db`.`t`", ddl.Query) +} + +func TestBuildPersistedDDLEventForCreateTableLikeKeepsOriginalQueryInSameSchema(t *testing.T) { + cases := []struct { + name string + query string + }{ + { + name: "unqualified target table", + query: "CREATE TABLE `dst` LIKE `src`", + }, + { + name: "explicit target schema", + query: "CREATE TABLE `test`.`dst` LIKE `src`", + }, + } + + for _, tc := range cases { + job := buildCreateTableJobForTest(100, 200, "dst", 1010) + job.Query = tc.query + job.InvolvingSchemaInfo = []model.InvolvingSchemaInfo{ + {Database: "test", Table: "dst"}, + {Database: "test", Table: "src", Mode: model.SharedInvolving}, + } + + ddl := buildPersistedDDLEventForCreateTable(buildPersistedDDLEventFuncArgs{ + job: job, + databaseMap: map[int64]*BasicDatabaseInfo{ + 100: {Name: "test", Tables: map[int64]bool{101: true, 200: true}}, + }, + tableMap: map[int64]*BasicTableInfo{ + 101: {SchemaID: 100, Name: "src"}, + 200: {SchemaID: 100, Name: "dst"}, + }, + }) + + require.Equal(t, int64(101), ddl.ExtraTableID, tc.name) + require.Equal(t, tc.query, ddl.Query, tc.name) + } } func TestBuildDDLEventForNewTableDDL_CreateTableLikeBlockedTables(t *testing.T) { @@ -3827,3 +4054,43 @@ func TestExtractTableInfoFuncForSingleTableDDL_CreateTableLikeReferTableIgnored( require.False(t, deleted) }) } + +func TestExchangeTableInfo(t *testing.T) { + for _, partitionSchema := range []string{"normal_db", "partition_db"} { + t.Run(partitionSchema, func(t *testing.T) { + normal := common.WrapTableInfo("normal_db", newEligibleTableInfoForTest(200, "nt")) + partition := newEligiblePartitionTableInfoForTest(100, "pt", []model.PartitionDefinition{{ID: 200}, {ID: 102}}) + raw := &PersistedDDLEvent{ + Type: byte(model.ActionExchangeTablePartition), SchemaName: "normal_db", TableName: "nt", TableID: 200, + ExtraSchemaName: partitionSchema, ExtraTableName: "pt", ExtraTableID: 100, + TableInfo: partition, ExtraTableInfo: normal, PrevPartitions: []int64{101, 102}, + } + for _, tc := range []struct { + physical, logical int64 + schema, table string + partition bool + }{ + {0, 100, partitionSchema, "pt", true}, + {200, 100, partitionSchema, "pt", true}, + {101, 101, "normal_db", "nt", false}, + } { + ddl, ok, err := buildDDLEventForExchangeTablePartition(raw, nil, tc.physical) + require.NoError(t, err) + require.True(t, ok) + require.Equal(t, tc.schema, ddl.TableInfo.GetSchemaName()) + require.Equal(t, tc.table, ddl.TableInfo.GetTableName()) + require.Equal(t, tc.logical, ddl.TableInfo.TableName.TableID) + require.Equal(t, tc.partition, ddl.TableInfo.TableName.IsPartition) + require.Equal(t, partitionSchema, ddl.MultipleTableInfos[0].GetSchemaName()) + require.Same(t, normal, ddl.MultipleTableInfos[1]) + if tc.physical != 0 { + stored, deleted := extractTableInfoFuncForExchangeTablePartition(raw, tc.physical) + require.False(t, deleted) + require.Equal(t, stored.TableName, ddl.TableInfo.TableName) + require.Equal(t, stored.GetColumns(), ddl.TableInfo.GetColumns()) + } + } + require.Equal(t, int64(200), normal.TableName.TableID) + }) + } +} diff --git a/logservice/schemastore/validator.go b/logservice/schemastore/validator.go index 80575f9f8d..4c46bb9646 100644 --- a/logservice/schemastore/validator.go +++ b/logservice/schemastore/validator.go @@ -226,5 +226,6 @@ dbLoop: if verifier.firstErr != nil { return nil, nil, nil, nil, verifier.firstErr } + log.Info("table replication eligibility verified", zap.Int("tableCount", len(verifier.tableInfos)), zap.Uint64("startTs", startTs)) return verifier.tableInfos, verifier.ineligibleTables, verifier.eligibleTables, verifier.allTables, nil } diff --git a/logservice/schemastore/validator_test.go b/logservice/schemastore/validator_test.go new file mode 100644 index 0000000000..4bf787631d --- /dev/null +++ b/logservice/schemastore/validator_test.go @@ -0,0 +1,95 @@ +// Copyright 2022 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 schemastore + +import ( + "context" + "encoding/json" + "testing" + + "github.com/pingcap/errors" + "github.com/pingcap/log" + "github.com/pingcap/ticdc/pkg/config" + "github.com/pingcap/ticdc/pkg/filter" + "github.com/pingcap/tidb/pkg/kv" + "github.com/pingcap/tidb/pkg/meta" + "github.com/pingcap/tidb/pkg/meta/model" + "github.com/pingcap/tidb/pkg/parser/ast" + "github.com/pingcap/tidb/pkg/store/mockstore" + "github.com/pingcap/tidb/pkg/structure" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + "go.uber.org/zap/zaptest/observer" +) + +func TestVerifyTablesCompletionLog(t *testing.T) { + for _, tc := range []struct { + name string + tableCount int + corrupt bool + }{ + {name: "empty"}, + {name: "success", tableCount: 1}, + {name: "worker error", tableCount: 1, corrupt: true}, + } { + t.Run(tc.name, func(t *testing.T) { + store, err := mockstore.NewMockStore() + require.NoError(t, err) + defer func() { require.NoError(t, store.Close()) }() + err = kv.RunInNewTxn(context.Background(), store, false, func(_ context.Context, txn kv.Transaction) error { + m := meta.NewMutator(txn) + if err := m.CreateDatabase(&model.DBInfo{ID: 1, Name: ast.NewCIStr("sales")}); err != nil { + return err + } + if tc.tableCount == 0 { + return nil + } + if tc.corrupt { + // Supply malformed table JSON to the real verifier worker. + return structure.NewStructure(txn, txn, []byte("m")).HSet([]byte("DB:1"), []byte("Table:2"), []byte("{")) + } + return m.CreateTableOrView(1, &model.TableInfo{ID: 2, Name: ast.NewCIStr("orders")}) + }) + require.NoError(t, err) + version, err := store.CurrentVersion(kv.GlobalTxnScope) + require.NoError(t, err) + f, err := filter.NewFilter(config.GetDefaultReplicaConfig().Filter, "", false, false) + require.NoError(t, err) + core, logs := observer.New(zapcore.InfoLevel) + restore := log.ReplaceGlobals(zap.New(core), &log.ZapProperties{Core: core}) + defer restore() + + infos, ineligible, eligible, all, err := VerifyTables(f, store, version.Ver) + if tc.corrupt { + require.Error(t, err) + require.IsType(t, &json.SyntaxError{}, errors.Cause(err)) + require.EqualError(t, err, "unexpected end of JSON input") + require.Nil(t, infos) + require.Nil(t, ineligible) + require.Nil(t, eligible) + require.Nil(t, all) + require.Empty(t, logs.All()) + return + } + require.NoError(t, err) + require.Len(t, infos, tc.tableCount) + require.Len(t, all, tc.tableCount) + entries := logs.FilterMessage("table replication eligibility verified").All() + require.Len(t, entries, 1) + require.EqualValues(t, tc.tableCount, entries[0].ContextMap()["tableCount"]) + require.Equal(t, version.Ver, entries[0].ContextMap()["startTs"]) + }) + } +} diff --git a/pkg/common/event/active_active_test.go b/pkg/common/event/active_active_test.go index 83ac73a466..5b00fd8fcb 100644 --- a/pkg/common/event/active_active_test.go +++ b/pkg/common/event/active_active_test.go @@ -369,7 +369,6 @@ func newTestTableInfo(t *testing.T, activeActive, softDelete bool) *commonpkg.Ta ti := commonpkg.WrapTableInfo("test", table) ti.ActiveActiveTable = activeActive ti.SoftDeleteTable = softDelete - ti.InitPrivateFields() return ti } diff --git a/pkg/common/event/ddl_event.go b/pkg/common/event/ddl_event.go index 1d7ad3262b..b1889b5e04 100644 --- a/pkg/common/event/ddl_event.go +++ b/pkg/common/event/ddl_event.go @@ -18,10 +18,13 @@ import ( "encoding/json" "errors" "fmt" + "slices" "github.com/pingcap/log" "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/tidb/pkg/meta/model" + "github.com/pingcap/tidb/pkg/parser" + "github.com/pingcap/tidb/pkg/parser/ast" "go.uber.org/zap" ) @@ -41,14 +44,23 @@ type DDLEvent struct { SchemaID int64 `json:"schema_id"` SchemaName string `json:"schema_name"` TableName string `json:"table_name"` + // the following two fields are just used for RenameTable, // they are the old schema/table name of the table - ExtraSchemaName string `json:"extra_schema_name"` - ExtraTableName string `json:"extra_table_name"` - Query string `json:"query"` - TableInfo *common.TableInfo `json:"-"` - StartTs uint64 `json:"start_ts"` - FinishedTs uint64 `json:"finished_ts"` + ExtraSchemaName string `json:"extra_schema_name"` + ExtraTableName string `json:"extra_table_name"` + + // target related fields carry routed names. + // They are set after the unmarshal, so no need to be serialized. + targetSchemaName string `json:"-"` + targetTableName string `json:"-"` + targetExtraSchemaName string `json:"-"` + targetExtraTableName string `json:"-"` + + Query string `json:"query"` + TableInfo *common.TableInfo `json:"-"` + StartTs uint64 `json:"start_ts"` + FinishedTs uint64 `json:"finished_ts"` // The seq of the event. It is set by event service. Seq uint64 `json:"seq"` // The epoch of the event. It is set by event service. @@ -205,6 +217,34 @@ func (d *DDLEvent) GetExtraTableName() string { return d.ExtraTableName } +func (d *DDLEvent) GetTargetSchemaName() string { + if d.targetSchemaName != "" { + return d.targetSchemaName + } + return d.SchemaName +} + +func (d *DDLEvent) GetTargetTableName() string { + if d.targetTableName != "" { + return d.targetTableName + } + return d.TableName +} + +func (d *DDLEvent) GetTargetExtraSchemaName() string { + if d.targetExtraSchemaName != "" { + return d.targetExtraSchemaName + } + return d.ExtraSchemaName +} + +func (d *DDLEvent) GetTargetExtraTableName() string { + if d.targetExtraTableName != "" { + return d.targetExtraTableName + } + return d.ExtraTableName +} + // GetTableID returns the logic table ID of the event. // it returns 0 when there is no tableinfo func (d *DDLEvent) GetTableID() int64 { @@ -214,6 +254,7 @@ func (d *DDLEvent) GetTableID() int64 { return 0 } +// GetEvents split the multi tables DDL into single table DDLs. func (d *DDLEvent) GetEvents() []*DDLEvent { // Some ddl event may be multi-events, we need to split it into multiple messages. // Such as rename table test.table1 to test.table10, test.table2 to test.table20 @@ -234,18 +275,23 @@ func (d *DDLEvent) GetEvents() []*DDLEvent { } for i, info := range d.MultipleTableInfos { event := &DDLEvent{ - Version: d.Version, - Type: byte(t), - SchemaName: info.GetSchemaName(), - TableName: info.GetTableName(), - TableInfo: info, - Query: queries[i], - StartTs: d.StartTs, - FinishedTs: d.FinishedTs, + Version: d.Version, + Type: byte(t), + SchemaName: info.GetSchemaName(), + TableName: info.GetTableName(), + targetSchemaName: info.GetTargetSchemaName(), + targetTableName: info.GetTargetTableName(), + TableInfo: info, + Query: queries[i], + StartTs: d.StartTs, + FinishedTs: d.FinishedTs, } if model.ActionType(d.Type) == model.ActionRenameTables { event.ExtraSchemaName = d.TableNameChange.DropName[i].SchemaName event.ExtraTableName = d.TableNameChange.DropName[i].TableName + targetExtraSchemaName, targetExtraTableName := extractRenameTargetExtraFromQuery(queries[i]) + event.targetExtraSchemaName = targetExtraSchemaName + event.targetExtraTableName = targetExtraTableName } events = append(events, event) } @@ -255,6 +301,19 @@ func (d *DDLEvent) GetEvents() []*DDLEvent { return []*DDLEvent{d} } +func extractRenameTargetExtraFromQuery(query string) (string, string) { + stmt, err := parser.New().ParseOneStmt(query, "", "") + if err != nil { + log.Panic("parse split rename query failed", zap.String("query", query), zap.Error(err)) + } + renameStmt, ok := stmt.(*ast.RenameTableStmt) + if !ok || len(renameStmt.TableToTables) == 0 { + log.Panic("unexpected split rename query", zap.String("query", query), zap.Any("stmt", stmt)) + } + oldTable := renameStmt.TableToTables[0].OldTable + return oldTable.Schema.O, oldTable.Name.O +} + func (d *DDLEvent) GetSeq() uint64 { return d.Seq } @@ -464,13 +523,6 @@ func (t *DDLEvent) decodeV1(data []byte) error { return err } - for _, info := range t.MultipleTableInfos { - info.InitPrivateFields() - } - if t.TableInfo != nil { - t.TableInfo.InitPrivateFields() - } - return nil } @@ -482,6 +534,61 @@ func (t *DDLEvent) IsPaused() bool { return false } +// NewRoutedDDLEvent builds a routed DDL event from the origin event and final routed fields. +func NewRoutedDDLEvent( + d *DDLEvent, + query string, + targetSchemaName, targetTableName string, + targetExtraSchemaName, targetExtraTableName string, + tableInfo *common.TableInfo, + multipleTableInfos []*common.TableInfo, + blockedTableNames []SchemaTableName, +) *DDLEvent { + if d == nil { + return nil + } + + return &DDLEvent{ + Version: d.Version, + DispatcherID: d.DispatcherID, + Type: d.Type, + SchemaID: d.SchemaID, + SchemaName: d.SchemaName, + TableName: d.TableName, + ExtraSchemaName: d.ExtraSchemaName, + ExtraTableName: d.ExtraTableName, + targetSchemaName: targetSchemaName, + targetTableName: targetTableName, + targetExtraSchemaName: targetExtraSchemaName, + targetExtraTableName: targetExtraTableName, + Query: query, + TableInfo: tableInfo, + StartTs: d.StartTs, + FinishedTs: d.FinishedTs, + Seq: d.Seq, + Epoch: d.Epoch, + // MultipleTableInfos and BlockedTableNames carry table names used by downstream + // execution paths, so the routed versions must be passed in explicitly. + MultipleTableInfos: multipleTableInfos, + BlockedTableNames: blockedTableNames, + // The following fields do not participate in table route name rewriting, + // so the routed event keeps the original values from the source event. + BlockedTables: d.BlockedTables, + NeedDroppedTables: d.NeedDroppedTables, + NeedAddedTables: d.NeedAddedTables, + UpdatedSchemas: d.UpdatedSchemas, + TableNameChange: d.TableNameChange, + TiDBOnly: d.TiDBOnly, + BDRMode: d.BDRMode, + Err: d.Err, + PostTxnFlushed: slices.Clone(d.PostTxnFlushed), + IndexIDs: slices.Clone(d.IndexIDs), + eventSize: d.eventSize, + IsBootstrap: d.IsBootstrap, + NotSync: d.NotSync, + } +} + func (t *DDLEvent) Len() int32 { return 1 } diff --git a/pkg/common/event/ddl_event_test.go b/pkg/common/event/ddl_event_test.go index 6cb58852e8..40aa19638c 100644 --- a/pkg/common/event/ddl_event_test.go +++ b/pkg/common/event/ddl_event_test.go @@ -240,8 +240,6 @@ func TestDDLEvent(t *testing.T) { }, Err: errors.ErrDDLEventError.GenWithStackByArgs("test").Error(), } - ddlEvent.TableInfo.InitPrivateFields() - // Test normal marshal/unmarshal data, err := ddlEvent.Marshal() require.Nil(t, err) @@ -417,6 +415,14 @@ INSERT INTO test VALUES ('This; is; a test'); }, expectedError: false, }, + { + name: "DDL with semicolons inside default string", + input: "CREATE TABLE test (c VARCHAR(100) DEFAULT 'a;b;c');", + expected: []string{ + "CREATE TABLE `test` (`c` VARCHAR(100) DEFAULT _UTF8MB4'a;b;c');", + }, + expectedError: false, + }, { name: "Query with escaped quotes inside strings", input: ` @@ -474,14 +480,24 @@ INSERT INTO test VALUES (1); }, expectedError: false, }, + { + name: "Queries with semicolons inside comments", + input: ` +/* comment; not a statement */ +CREATE TABLE test1 (id INT); -- inline; comment +CREATE TABLE test2 (id INT); +`, + expected: []string{ + "CREATE TABLE `test1` (`id` INT);", + "CREATE TABLE `test2` (`id` INT);", + }, + expectedError: false, + }, { name: "Queries with whitespace and newlines", input: ` - CREATE TABLE test (id INT); - INSERT INTO test VALUES (1); - `, expected: []string{ "CREATE TABLE `test` (`id` INT);", diff --git a/pkg/common/event/ddl_query_normalizer.go b/pkg/common/event/ddl_query_normalizer.go new file mode 100644 index 0000000000..da944d2871 --- /dev/null +++ b/pkg/common/event/ddl_query_normalizer.go @@ -0,0 +1,237 @@ +// Copyright 2026 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 event + +import ( + "strings" + + "github.com/pingcap/ticdc/pkg/errors" + "github.com/pingcap/tidb/pkg/parser" + "github.com/pingcap/tidb/pkg/parser/ast" + "github.com/pingcap/tidb/pkg/parser/format" +) + +// Restore serializes a DDL statement with CDC's TiDB comment and TTL handling. +func Restore(stmt ast.StmtNode) (string, error) { + var sb strings.Builder + flags := format.RestoreTiDBSpecialComment | format.RestoreNameBackQuotes | + format.RestoreKeyWordUppercase | format.RestoreStringSingleQuotes | + format.SkipPlacementRuleForRestore | format.RestoreWithTTLEnableOff + if err := stmt.Restore(format.NewRestoreCtx(flags, &sb)); err != nil { + return "", errors.Trace(err) + } + return sb.String(), nil +} + +// NormalizeCreateViewQueryWithStoredSelect replaces the SELECT body in a +// CREATE VIEW query with TiDB's stored View.SelectStmt when the stored SELECT +// carries information that the original query text does not carry. +// +// TiDB persists the normalized SELECT body of a view in TableInfo.View.SelectStmt +// when executing CREATE VIEW, so this field can carry resolved source-table +// references even if job.Query keeps the original session-level text. +// +// Example: +// +// query = "CREATE VIEW `target_db`.`v` AS SELECT `id` FROM `users`" +// storedSelectStmt = "SELECT `id` FROM `source_db`.`users`" +// currentSchema = "target_db" +// +// → "CREATE VIEW `target_db`.`v` AS SELECT `id` FROM `source_db`.`users`" +// +// Example: +// +// query = "CREATE VIEW `other_db`.`v` AS SELECT `orders`.`id` FROM `orders`" +// storedSelectStmt = "SELECT `orders`.`id` AS `id` FROM `source_db`.`orders`" +// currentSchema = "other_db" +// +// → "CREATE VIEW `other_db`.`v` AS SELECT `source_db`.`orders`.`id` AS `id` FROM `source_db`.`orders`" +func NormalizeCreateViewQueryWithStoredSelect(query string, storedSelectStmt string, currentSchema string) (string, error) { + if query == "" || storedSelectStmt == "" { + return query, nil + } + + stmt, err := parser.New().ParseOneStmt(query, "", "") + if err != nil { + return query, errors.WrapError(errors.ErrDDLEventError, err) + } + createViewStmt, ok := stmt.(*ast.CreateViewStmt) + if !ok { + return query, nil + } + + selectStmt, err := parser.New().ParseOneStmt(storedSelectStmt, "", "") + if err != nil { + return query, errors.WrapError(errors.ErrDDLEventError, err) + } + if !normalizeCreateViewSelect(selectStmt, currentSchema) { + return query, nil + } + + createViewStmt.Select = selectStmt + normalizedQuery, err := Restore(createViewStmt) + if err != nil { + return query, errors.WrapError(errors.ErrDDLEventError, err) + } + return normalizedQuery, nil +} + +type createViewSelectNormalizer struct { + changed bool + scopes []createViewSelectScope +} + +type createViewSelectScope struct { + aliases map[string]struct{} + tableByName map[string]string + ambiguousTables map[string]struct{} +} + +// normalizeCreateViewSelect returns true when CREATE VIEW should use the stored +// SELECT body. It also turns unaliased table-qualified column references into +// schema-qualified references: `orders`.`id` with FROM `source_db`.`orders` +// becomes `source_db`.`orders`.`id`. Explicit alias references are preserved. +func normalizeCreateViewSelect(selectStmt ast.StmtNode, currentSchema string) bool { + currentSchemaOnly := createViewSelectUsesCurrentSchemaOnly(selectStmt, currentSchema) + normalizer := &createViewSelectNormalizer{ + scopes: make([]createViewSelectScope, 0), + } + selectStmt.Accept(normalizer) + return !currentSchemaOnly || normalizer.changed +} + +func createViewSelectUsesCurrentSchemaOnly(selectStmt ast.StmtNode, currentSchema string) bool { + for _, schema := range extractTableSchemas(selectStmt) { + if schema != "" && !strings.EqualFold(schema, currentSchema) { + return false + } + } + return true +} + +func (n *createViewSelectNormalizer) Enter(in ast.Node) (ast.Node, bool) { + switch v := in.(type) { + case *ast.SelectStmt: + n.scopes = append(n.scopes, buildCreateViewSelectScope(v)) + case *ast.ColumnName: + n.qualifyColumnName(v) + } + return in, false +} + +func (n *createViewSelectNormalizer) Leave(in ast.Node) (ast.Node, bool) { + if _, ok := in.(*ast.SelectStmt); ok { + n.scopes = n.scopes[:len(n.scopes)-1] + } + return in, true +} + +func (n *createViewSelectNormalizer) qualifyColumnName(c *ast.ColumnName) { + if len(n.scopes) == 0 || c == nil || c.Schema.O != "" || c.Table.O == "" { + return + } + + tableKey := strings.ToLower(c.Table.O) + // Resolve correlated references from the innermost SELECT outward. + for i := len(n.scopes) - 1; i >= 0; i-- { + scope := n.scopes[i] + if _, ok := scope.aliases[tableKey]; ok { + return + } + if _, ok := scope.ambiguousTables[tableKey]; ok { + return + } + if schema, ok := scope.tableByName[tableKey]; ok { + if schema != "" { + c.Schema = ast.NewCIStr(schema) + n.changed = true + } + return + } + } +} + +func buildCreateViewSelectScope(selectStmt *ast.SelectStmt) createViewSelectScope { + scope := createViewSelectScope{ + aliases: make(map[string]struct{}), + tableByName: make(map[string]string), + ambiguousTables: make(map[string]struct{}), + } + if selectStmt == nil || selectStmt.From == nil || selectStmt.From.TableRefs == nil { + return scope + } + collectCreateViewSelectTables(selectStmt.From.TableRefs, &scope) + return scope +} + +func collectCreateViewSelectTables(node ast.ResultSetNode, scope *createViewSelectScope) { + switch v := node.(type) { + case *ast.Join: + if v.Left != nil { + collectCreateViewSelectTables(v.Left, scope) + } + if v.Right != nil { + collectCreateViewSelectTables(v.Right, scope) + } + case *ast.TableSource: + if v.AsName.O != "" { + scope.aliases[strings.ToLower(v.AsName.O)] = struct{}{} + return + } + tableName, ok := v.Source.(*ast.TableName) + if !ok || tableName.Name.O == "" { + return + } + tableKey := strings.ToLower(tableName.Name.O) + if _, ambiguous := scope.ambiguousTables[tableKey]; ambiguous { + return + } + if _, exists := scope.tableByName[tableKey]; exists { + delete(scope.tableByName, tableKey) + scope.ambiguousTables[tableKey] = struct{}{} + return + } + scope.tableByName[tableKey] = tableName.Schema.O + } +} + +type tableSchemaExtractor struct { + schemas []string +} + +func (e *tableSchemaExtractor) Enter(in ast.Node) (ast.Node, bool) { + if t, ok := in.(*ast.TableName); ok { + e.schemas = append(e.schemas, t.Schema.O) + return in, true + } + return in, false +} + +func (e *tableSchemaExtractor) Leave(in ast.Node) (ast.Node, bool) { + return in, true +} + +// extractTableSchemas returns schema qualifiers from all *ast.TableName nodes in +// AST visit order. Unqualified tables contribute an empty schema name. +func extractTableSchemas(node ast.Node) []string { + if node == nil { + return nil + } + + extractor := &tableSchemaExtractor{ + schemas: make([]string, 0), + } + node.Accept(extractor) + return extractor.schemas +} diff --git a/pkg/common/event/ddl_query_normalizer_test.go b/pkg/common/event/ddl_query_normalizer_test.go new file mode 100644 index 0000000000..70e5974b3c --- /dev/null +++ b/pkg/common/event/ddl_query_normalizer_test.go @@ -0,0 +1,81 @@ +// Copyright 2026 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 event + +import ( + "testing" + + "github.com/pingcap/tidb/pkg/parser" + "github.com/stretchr/testify/require" +) + +func TestExtractTableSchemas(t *testing.T) { + cases := []struct { + name string + query string + expected []string + }{ + { + name: "unqualified table", + query: "SELECT * FROM `t`", + expected: []string{""}, + }, + { + name: "mixed qualified tables", + query: "SELECT * FROM `db1`.`t1` JOIN `t2` ON `db1`.`t1`.`id` = `t2`.`id`", + expected: []string{"db1", ""}, + }, + { + name: "subquery preserves visit order", + query: "SELECT * FROM `db1`.`t1` WHERE EXISTS (SELECT 1 FROM `db2`.`t2`)", + expected: []string{"db1", "db2"}, + }, + } + + p := parser.New() + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + stmt, err := p.ParseOneStmt(tc.query, "", "") + require.NoError(t, err) + require.Equal(t, tc.expected, extractTableSchemas(stmt)) + }) + } + + require.Nil(t, extractTableSchemas(nil)) +} + +func TestNormalizeCorrelatedViewColumns(t *testing.T) { + for _, tc := range []struct { + name string + query string + want string + }{ + {"outer table", "SELECT * FROM source_db.orders WHERE EXISTS (SELECT 1 FROM source_db.lines WHERE lines.id = orders.id)", "`source_db`.`lines`.`id`=`source_db`.`orders`.`id`"}, + {"multiple levels", "SELECT * FROM source_db.orders WHERE EXISTS (SELECT 1 FROM source_db.lines WHERE EXISTS (SELECT 1 WHERE orders.id = 1))", "`source_db`.`orders`.`id`=1"}, + {"alias shadows outer", "SELECT * FROM source_db.orders WHERE EXISTS (SELECT 1 FROM source_db.lines AS orders WHERE orders.id = 1)", "WHERE `orders`.`id`=1"}, + {"local table shadows outer", "SELECT * FROM source_db.orders WHERE EXISTS (SELECT 1 FROM other_db.orders WHERE orders.id = 1)", "WHERE `other_db`.`orders`.`id`=1"}, + {"unqualified local table", "SELECT * FROM source_db.orders WHERE EXISTS (SELECT 1 FROM orders WHERE orders.id = 1)", "WHERE `orders`.`id`=1"}, + {"CTE shadows outer", "SELECT * FROM source_db.orders WHERE EXISTS (WITH orders AS (SELECT 1 AS id) SELECT 1 FROM orders WHERE orders.id = 1)", "WHERE `orders`.`id`=1"}, + {"ambiguous local table", "SELECT * FROM source_db.orders WHERE EXISTS (SELECT 1 FROM a.orders JOIN b.orders WHERE orders.id = 1)", "WHERE `orders`.`id`=1"}, + } { + t.Run(tc.name, func(t *testing.T) { + stmt, err := parser.New().ParseOneStmt(tc.query, "", "") + require.NoError(t, err) + normalizeCreateViewSelect(stmt, "source_db") + query, err := Restore(stmt) + require.NoError(t, err) + require.Contains(t, query, tc.want) + }) + } +} diff --git a/pkg/common/event/dml_event.go b/pkg/common/event/dml_event.go index f30a944a15..fcb1b29412 100644 --- a/pkg/common/event/dml_event.go +++ b/pkg/common/event/dml_event.go @@ -279,16 +279,19 @@ func (b *BatchDMLEvent) encodeV1() ([]byte, error) { // AssembleRows assembles the Rows from the RawRows. // It also sets the TableInfo and clears the RawRows. func (b *BatchDMLEvent) AssembleRows(tableInfo *common.TableInfo) { - defer func() { - b.TableInfo.InitPrivateFields() - }() - // rows is already set, no need to assemble again - // When the event is passed from the same node, the Rows is already set. - if b.Rows != nil { - return - } if tableInfo == nil { log.Panic("DMLEvent: TableInfo is nil") + } + + // For local events (same node), rows are already set. + if b.Rows != nil { + if !tableInfo.TableName.IsRouted() { + return + } + b.TableInfo = tableInfo + for _, dml := range b.DMLEvents { + dml.TableInfo = tableInfo + } return } @@ -297,10 +300,16 @@ func (b *BatchDMLEvent) AssembleRows(tableInfo *common.TableInfo) { return } - if b.TableInfo != nil && b.TableInfo.GetUpdateTS() != tableInfo.GetUpdateTS() { - log.Panic("DMLEvent: TableInfoVersion mismatch", zap.Uint64("dmlEventTableInfoVersion", b.TableInfo.GetUpdateTS()), zap.Uint64("tableInfoVersion", tableInfo.GetUpdateTS())) - return + if b.TableInfo != nil { + originVersion := b.TableInfo.GetUpdateTS() + version := tableInfo.GetUpdateTS() + if originVersion != version { + log.Panic("table version mismatch when decode remote raw rows", + zap.Uint64("originTableVersion", originVersion), + zap.Uint64("tableVersion", version)) + } } + decoder := chunk.NewCodec(tableInfo.GetFieldSlice()) b.Rows, _ = decoder.Decode(b.RawRows) b.TableInfo = tableInfo diff --git a/pkg/common/event/dml_event_test.go b/pkg/common/event/dml_event_test.go index f1693e3705..ef614a2ff5 100644 --- a/pkg/common/event/dml_event_test.go +++ b/pkg/common/event/dml_event_test.go @@ -150,6 +150,104 @@ func TestBatchDMLEvent(t *testing.T) { require.Contains(t, err.Error(), "unsupported BatchDMLEvent version") } +func TestBatchDMLEventAssembleRowsRebindsRoutedTableInfoForLocalRows(t *testing.T) { + helper := NewEventTestHelper(t) + defer helper.Close() + + helper.tk.MustExec("use test") + helper.DDL2Job(createTableSQL) + + dmlEvent := helper.DML2Event("test", "t", insertDataSQL) + require.NotNil(t, dmlEvent) + + originTableInfo := dmlEvent.TableInfo + routedTableInfo := originTableInfo.CloneWithRouting("target_schema", "target_table") + require.NotNil(t, routedTableInfo) + + batchDMLEvent := &BatchDMLEvent{ + Version: BatchDMLEventVersion1, + DMLEventCount: 1, + DMLEvents: []*DMLEvent{dmlEvent}, + Rows: dmlEvent.Rows, + TableInfo: originTableInfo, + } + + batchDMLEvent.AssembleRows(routedTableInfo) + + require.Same(t, dmlEvent.Rows, batchDMLEvent.Rows) + require.Same(t, routedTableInfo, batchDMLEvent.TableInfo) + require.Same(t, routedTableInfo, batchDMLEvent.DMLEvents[0].TableInfo) + require.Equal(t, "target_schema", batchDMLEvent.TableInfo.GetTargetSchemaName()) + require.Equal(t, "target_table", batchDMLEvent.TableInfo.GetTargetTableName()) + require.Contains(t, batchDMLEvent.TableInfo.GetPreInsertSQL(), common.QuoteSchema("target_schema", "target_table")) +} + +func TestBatchDMLEventAssembleRowsKeepsOriginalTableInfoForLocalRowsWithoutRouting(t *testing.T) { + helper := NewEventTestHelper(t) + defer helper.Close() + + helper.tk.MustExec("use test") + helper.DDL2Job(createTableSQL) + + dmlEvent := helper.DML2Event("test", "t", insertDataSQL) + require.NotNil(t, dmlEvent) + + originTableInfo := dmlEvent.TableInfo + notRoutedTableInfo := originTableInfo.CloneWithRouting("", "") + require.NotNil(t, notRoutedTableInfo) + require.False(t, notRoutedTableInfo.TableName.IsRouted()) + notRoutedTableInfo.UpdateTS++ + + batchDMLEvent := &BatchDMLEvent{ + Version: BatchDMLEventVersion1, + DMLEventCount: 1, + DMLEvents: []*DMLEvent{dmlEvent}, + Rows: dmlEvent.Rows, + TableInfo: originTableInfo, + } + + batchDMLEvent.AssembleRows(notRoutedTableInfo) + + require.Same(t, dmlEvent.Rows, batchDMLEvent.Rows) + require.Same(t, originTableInfo, batchDMLEvent.TableInfo) + require.Same(t, originTableInfo, batchDMLEvent.DMLEvents[0].TableInfo) + require.Equal(t, "test", batchDMLEvent.TableInfo.GetTargetSchemaName()) + require.Equal(t, "t", batchDMLEvent.TableInfo.GetTargetTableName()) +} + +func TestBatchDMLEventAssembleRowsDecodesRemoteRawRows(t *testing.T) { + helper := NewEventTestHelper(t) + defer helper.Close() + + helper.tk.MustExec("use test") + helper.DDL2Job(createTableSQL) + + dmlEvent := helper.DML2Event("test", "t", insertDataSQL) + require.NotNil(t, dmlEvent) + + batchDMLEvent := &BatchDMLEvent{ + Version: BatchDMLEventVersion1, + DMLEventCount: 1, + DMLEvents: []*DMLEvent{dmlEvent}, + Rows: dmlEvent.Rows, + TableInfo: dmlEvent.TableInfo, + } + data, err := batchDMLEvent.Marshal() + require.NoError(t, err) + + reverseEvents := &BatchDMLEvent{} + err = reverseEvents.Unmarshal(data) + require.NoError(t, err) + require.Nil(t, reverseEvents.Rows) + require.NotEmpty(t, reverseEvents.RawRows) + + reverseEvents.AssembleRows(batchDMLEvent.TableInfo) + + require.Nil(t, reverseEvents.RawRows) + require.Same(t, batchDMLEvent.TableInfo, reverseEvents.TableInfo) + require.Equal(t, batchDMLEvent.Rows.ToString(batchDMLEvent.TableInfo.GetFieldSlice()), reverseEvents.Rows.ToString(batchDMLEvent.TableInfo.GetFieldSlice())) +} + func TestEncodeAnddecodeV1(t *testing.T) { helper := NewEventTestHelper(t) defer helper.Close() diff --git a/pkg/common/event/handshake_event.go b/pkg/common/event/handshake_event.go index 9c0c0cb1f1..a8b1f3b01d 100644 --- a/pkg/common/event/handshake_event.go +++ b/pkg/common/event/handshake_event.go @@ -205,8 +205,5 @@ func (e *HandshakeEvent) decodeV1(data []byte) error { return err } - // Initialize private fields after unmarshaling - e.TableInfo.InitPrivateFields() - return nil } diff --git a/pkg/common/event/util.go b/pkg/common/event/util.go index 78bfe28cca..a1691d85d0 100644 --- a/pkg/common/event/util.go +++ b/pkg/common/event/util.go @@ -20,6 +20,7 @@ import ( "testing" "time" + "github.com/pingcap/failpoint" "github.com/pingcap/log" "github.com/pingcap/ticdc/pkg/common" "github.com/pingcap/ticdc/pkg/config" @@ -27,16 +28,17 @@ import ( ticonfig "github.com/pingcap/tidb/pkg/config" tiddl "github.com/pingcap/tidb/pkg/ddl" "github.com/pingcap/tidb/pkg/domain" + tidbexecutor "github.com/pingcap/tidb/pkg/executor" "github.com/pingcap/tidb/pkg/kv" "github.com/pingcap/tidb/pkg/meta" timodel "github.com/pingcap/tidb/pkg/meta/model" "github.com/pingcap/tidb/pkg/parser" "github.com/pingcap/tidb/pkg/parser/ast" - "github.com/pingcap/tidb/pkg/parser/format" // NOTE: Do not remove the `test_driver` import. // For details, refer to: https://github.com/pingcap/parser/issues/43 _ "github.com/pingcap/tidb/pkg/parser/test_driver" "github.com/pingcap/tidb/pkg/session" + "github.com/pingcap/tidb/pkg/sessionctx" "github.com/pingcap/tidb/pkg/sessionctx/vardef" "github.com/pingcap/tidb/pkg/store/mockstore" "github.com/pingcap/tidb/pkg/testkit" @@ -46,6 +48,8 @@ import ( "go.uber.org/zap" ) +const disableTiDBDistTaskFailpoint = "github.com/pingcap/tidb/pkg/domain/MockDisableDistTask" + // CAUTION: // ALL METHODS IN THIS FILE ARE FOR TESTING ONLY!!! // DO NOT USE THEM IN OTHER PLACES. @@ -58,6 +62,8 @@ type EventTestHelper struct { domain *domain.Domain mounter Mounter + originalEnableDistTask bool + tableInfos map[string]*common.TableInfo // each partition table's partition ID, Name -> ID. partitionIDs map[string]map[string]int64 @@ -72,18 +78,30 @@ func NewEventTestHelperWithTimeZone(t testing.TB, tz *time.Location) *EventTestH }) vardef.SetSchemaLease(time.Second) session.DisableStats4Test() + + // EventTestHelper executes TiDB DDL only to synthesize CDC test events. + // mockstore does not provide managed dist task nodes, so keep reorg DDLs + // off the dist task path and skip the bootstrap DXF loop when failpoints are active. + originalEnableDistTask := vardef.EnableDistTask.Load() + vardef.EnableDistTask.Store(false) + require.NoError(t, failpoint.Enable(disableTiDBDistTaskFailpoint, "return(true)")) + defer func() { + require.NoError(t, failpoint.Disable(disableTiDBDistTaskFailpoint)) + }() + domain, err := session.BootstrapSession(store) require.NoError(t, err) domain.SetStatsUpdating(true) tk := testkit.NewTestKit(t, store) return &EventTestHelper{ - t: t, - tk: tk, - storage: store, - domain: domain, - mounter: NewMounter(tz, config.GetDefaultReplicaConfig().Integrity), - tableInfos: make(map[string]*common.TableInfo), - partitionIDs: make(map[string]map[string]int64), + t: t, + tk: tk, + storage: store, + domain: domain, + mounter: NewMounter(tz, config.GetDefaultReplicaConfig().Integrity), + originalEnableDistTask: originalEnableDistTask, + tableInfos: make(map[string]*common.TableInfo), + partitionIDs: make(map[string]map[string]int64), } } @@ -93,6 +111,15 @@ func NewEventTestHelper(t testing.TB) *EventTestHelper { } func (s *EventTestHelper) ApplyJob(job *timodel.Job) { + if job.BinlogInfo != nil && len(job.BinlogInfo.MultipleTableInfos) > 0 { + for _, tableInfo := range job.BinlogInfo.MultipleTableInfos { + s.storeTableInfo(job.SchemaName, tableInfo) + } + if job.BinlogInfo.TableInfo == nil { + return + } + } + var tableInfo *timodel.TableInfo if job.BinlogInfo != nil && job.BinlogInfo.TableInfo != nil { tableInfo = job.BinlogInfo.TableInfo @@ -105,8 +132,14 @@ func (s *EventTestHelper) ApplyJob(job *timodel.Job) { } } - info := common.WrapTableInfo(job.SchemaName, tableInfo) - info.InitPrivateFields() + s.storeTableInfo(job.SchemaName, tableInfo) +} + +func (s *EventTestHelper) storeTableInfo(schemaName string, tableInfo *timodel.TableInfo) { + info := common.WrapTableInfo(schemaName, tableInfo) + if info == nil { + return + } key := toTableInfosKey(info.GetSchemaName(), info.GetTableName()) if tableInfo.Partition != nil { if _, ok := s.partitionIDs[key]; !ok { @@ -116,7 +149,7 @@ func (s *EventTestHelper) ApplyJob(job *timodel.Job) { s.partitionIDs[key][partition.Name.O] = partition.ID } } - log.Info("apply job", zap.String("jobKey", key), zap.Any("job", job)) + log.Info("store table info", zap.String("jobKey", key)) s.tableInfos[key] = info } @@ -136,6 +169,16 @@ func (s *EventTestHelper) GetTableInfo(job *timodel.Job) *common.TableInfo { // DDL2Job executes the DDL stmt and returns the DDL job func (s *EventTestHelper) DDL2Job(ddl string) *timodel.Job { + requireSingleDDLStmt(s.t, ddl) + + // EventTestHelper uses mockstore only to synthesize CDC test events from TiDB DDL jobs. + // In TiDB NextGen, reorg DDLs such as ADD INDEX and REORGANIZE PARTITION calculate + // DXF resources through managed dist task nodes. mockstore has no such nodes, so run + // the helper DDL in TiDB's bootstrap/upgrade test mode. TiDB upstream uses the same + // sessionctx.Initing marker in bootstrap tests to avoid NextGen resource calculation. + s.tk.Session().SetValue(sessionctx.Initing, true) + defer s.tk.Session().ClearValue(sessionctx.Initing) + vardef.EnableDistTask.Store(false) s.tk.MustExec(ddl) jobs, err := tiddl.GetLastNHistoryDDLJobs(s.GetCurrentMeta(), 1) require.Nil(s.t, err) @@ -203,8 +246,61 @@ func (s *EventTestHelper) DDL2Job(ddl string) *timodel.Job { func (s *EventTestHelper) DDL2Event(ddl string) *DDLEvent { job := s.DDL2Job(ddl) - info := s.GetTableInfo(job) - return &DDLEvent{ + return s.job2Event(job) +} + +// BatchCreateTableDDLs2Event executes CREATE TABLE DDLs through TiDB's batch +// create table path and returns the resulting ActionCreateTables event. +// TiDB only merges CREATE TABLE jobs in the same schema: +// https://github.com/pingcap/tidb/blob/8f2630e53d5d/pkg/ddl/job_submitter.go#L152-L159 +func (s *EventTestHelper) BatchCreateTableDDLs2Event(schema string, ddls ...string) *DDLEvent { + require.NotEmpty(s.t, ddls) + + tableInfos := make([]*timodel.TableInfo, 0, len(ddls)) + queries, err := SplitQueries(strings.Join(ddls, ";")) + require.NoError(s.t, err) + for _, ddl := range ddls { + requireSingleDDLStmt(s.t, ddl) + + stmt, err := parser.New().ParseOneStmt(ddl, "", "") + require.NoError(s.t, err) + createStmt, ok := stmt.(*ast.CreateTableStmt) + require.True(s.t, ok) + + tableSchema := createStmt.Table.Schema.O + if tableSchema != "" { + require.Equal(s.t, schema, tableSchema) + } + tableInfo, err := tiddl.MockTableInfo(s.tk.Session(), createStmt, 0) + require.NoError(s.t, err) + tableInfos = append(tableInfos, tableInfo) + } + + s.tk.Session().SetValue(sessionctx.Initing, true) + defer s.tk.Session().ClearValue(sessionctx.Initing) + err = tidbexecutor.BRIECreateTables(s.tk.Session(), map[string][]*timodel.TableInfo{ + schema: tableInfos, + }, "") + require.NoError(s.t, err) + + jobs, err := tiddl.GetLastNHistoryDDLJobs(s.GetCurrentMeta(), 1) + require.Nil(s.t, err) + require.Len(s.t, jobs, 1) + jobs[0].State = timodel.JobStateDone + require.Equal(s.t, timodel.ActionCreateTables, jobs[0].Type) + jobs[0].Query = strings.Join(queries, "") + + s.ApplyJob(jobs[0]) + return s.job2Event(jobs[0]) +} + +func (s *EventTestHelper) job2Event(job *timodel.Job) *DDLEvent { + var info *common.TableInfo + if job.BinlogInfo != nil && job.BinlogInfo.TableInfo != nil { + info = s.GetTableInfo(job) + } + ddlEvent := &DDLEvent{ + Version: DDLEventVersion1, SchemaID: job.SchemaID, SchemaName: job.SchemaName, TableName: job.TableName, @@ -214,6 +310,259 @@ func (s *EventTestHelper) DDL2Event(ddl string) *DDLEvent { StartTs: job.StartTS, FinishedTs: job.BinlogInfo.FinishedTS, } + s.fillDDLEventMetadata(ddlEvent, job) + return ddlEvent +} + +func requireSingleDDLStmt(t testing.TB, ddl string) { + stmts, _, err := parser.New().Parse(ddl, "", "") + require.NoError(t, err) + require.Len(t, stmts, 1) +} + +func (s *EventTestHelper) fillDDLEventMetadata(ddlEvent *DDLEvent, job *timodel.Job) { + switch job.Type { + case timodel.ActionDropSchema: + ddlEvent.TableNameChange = &TableNameChange{DropDatabaseName: ddlEvent.SchemaName} + case timodel.ActionCreateTable: + ddlEvent.TableNameChange = &TableNameChange{ + AddName: []SchemaTableName{{SchemaName: ddlEvent.SchemaName, TableName: ddlEvent.TableName}}, + } + s.fillCreateTableLikeBlockedTableNames(ddlEvent, job) + case timodel.ActionRecoverTable: + ddlEvent.TableNameChange = &TableNameChange{ + AddName: []SchemaTableName{{SchemaName: ddlEvent.SchemaName, TableName: ddlEvent.TableName}}, + } + case timodel.ActionCreateTables: + s.fillCreateTablesEventMetadata(ddlEvent, job) + case timodel.ActionDropTable: + ddlEvent.TableNameChange = &TableNameChange{ + DropName: []SchemaTableName{{SchemaName: ddlEvent.SchemaName, TableName: ddlEvent.TableName}}, + } + ddlEvent.BlockedTableNames = []SchemaTableName{{SchemaName: ddlEvent.SchemaName, TableName: ddlEvent.TableName}} + case timodel.ActionRenameTable: + s.fillRenameTableEventMetadata(ddlEvent) + case timodel.ActionRenameTables: + s.fillRenameTablesEventMetadata(ddlEvent, job) + case timodel.ActionCreateView: + s.normalizeCreateViewQueryWithStoredSelect(ddlEvent) + case timodel.ActionCreateSchema, timodel.ActionModifySchemaCharsetAndCollate, + timodel.ActionDropView: + default: + if ddlEvent.SchemaName != "" && ddlEvent.TableName != "" { + ddlEvent.BlockedTableNames = []SchemaTableName{{SchemaName: ddlEvent.SchemaName, TableName: ddlEvent.TableName}} + } + } +} + +// fillCreateTableLikeBlockedTableNames populates BlockedTableNames for a +// CREATE TABLE ... LIKE event. It first checks the query for an explicit +// refer schema, then falls back to job.InvolvingSchemaInfo, and finally to +// the event SchemaName. When the refer schema differs from the event schema, +// it rewrites the query to include the qualified schema name so that +// downstream routing can correctly resolve the cross-schema reference. +func (s *EventTestHelper) fillCreateTableLikeBlockedTableNames(ddlEvent *DDLEvent, job *timodel.Job) { + stmt, err := parser.New().ParseOneStmt(ddlEvent.Query, "", "") + require.NoError(s.t, err) + + createStmt, ok := stmt.(*ast.CreateTableStmt) + if !ok || createStmt.ReferTable == nil { + return + } + + refSchema := createStmt.ReferTable.Schema.O + if refSchema == "" { + refSchema = findCreateTableLikeReferSchema(job, ddlEvent.SchemaName, ddlEvent.TableName, createStmt.ReferTable.Name.O) + } + if refSchema == "" && createStmt.Table != nil && createStmt.Table.Schema.O == "" { + refSchema = ddlEvent.SchemaName + } + if refSchema == "" { + return + } + if createStmt.ReferTable.Schema.O == "" && !strings.EqualFold(refSchema, ddlEvent.SchemaName) { + createStmt.ReferTable.Schema = ast.NewCIStr(refSchema) + query, err := Restore(createStmt) + require.NoError(s.t, err) + ddlEvent.Query = query + } + ddlEvent.BlockedTableNames = []SchemaTableName{{ + SchemaName: refSchema, + TableName: createStmt.ReferTable.Name.O, + }} +} + +func (s *EventTestHelper) normalizeCreateViewQueryWithStoredSelect(ddlEvent *DDLEvent) { + if ddlEvent.TableInfo == nil || ddlEvent.TableInfo.View == nil { + return + } + + query, err := NormalizeCreateViewQueryWithStoredSelect( + ddlEvent.Query, + ddlEvent.TableInfo.View.SelectStmt, + ddlEvent.SchemaName, + ) + require.NoError(s.t, err) + ddlEvent.Query = query +} + +// findCreateTableLikeReferSchema resolves the source schema for CREATE TABLE +// ... LIKE by inspecting job.InvolvingSchemaInfo. +// +// Example — "CREATE TABLE extra.t2 LIKE t1" with session in db1: +// +// InvolvingSchemaInfo = [ +// {Database: "extra", Table: "t2"}, // target (exclusive) +// {Database: "db1", Table: "t1", SharedInvolving}, // refer source +// ] +// → returns "db1" (SharedInvolving match on table "t1") +// +// SharedInvolving entries are preferred because TiDB marks the LIKE source +// table with this mode. Without the mode check, the DDL target table may be +// mistaken for the refer table when both happen to share the same name. +func findCreateTableLikeReferSchema(job *timodel.Job, targetSchema, targetTable, referTable string) string { + for _, info := range job.InvolvingSchemaInfo { + if info.Mode == timodel.SharedInvolving && strings.EqualFold(info.Table, referTable) { + return info.Database + } + } + for _, info := range job.InvolvingSchemaInfo { + if !strings.EqualFold(info.Table, referTable) { + continue + } + if strings.EqualFold(info.Database, targetSchema) && strings.EqualFold(info.Table, targetTable) { + continue + } + return info.Database + } + return "" +} + +func (s *EventTestHelper) fillCreateTablesEventMetadata(ddlEvent *DDLEvent, job *timodel.Job) { + tableInfos := wrapMultipleTableInfos(job.SchemaName, job.BinlogInfo.MultipleTableInfos) + ddlEvent.MultipleTableInfos = tableInfos + ddlEvent.TableNameChange = &TableNameChange{ + AddName: make([]SchemaTableName, 0, len(tableInfos)), + } + for _, tableInfo := range tableInfos { + ddlEvent.TableNameChange.AddName = append(ddlEvent.TableNameChange.AddName, SchemaTableName{ + SchemaName: tableInfo.GetSchemaName(), + TableName: tableInfo.GetTableName(), + }) + } +} + +func (s *EventTestHelper) fillRenameTableEventMetadata(ddlEvent *DDLEvent) { + pairs := s.parseRenameTablePairs(ddlEvent.Query, ddlEvent.SchemaName) + require.Len(s.t, pairs, 1) + + pair := pairs[0] + ddlEvent.ExtraSchemaName = pair.oldSchemaName + ddlEvent.ExtraTableName = pair.oldTableName + ddlEvent.SchemaName = pair.newSchemaName + ddlEvent.TableName = pair.newTableName + ddlEvent.BlockedTableNames = []SchemaTableName{{SchemaName: pair.oldSchemaName, TableName: pair.oldTableName}} + ddlEvent.TableNameChange = &TableNameChange{ + AddName: []SchemaTableName{{SchemaName: pair.newSchemaName, TableName: pair.newTableName}}, + DropName: []SchemaTableName{{SchemaName: pair.oldSchemaName, TableName: pair.oldTableName}}, + } +} + +func (s *EventTestHelper) fillRenameTablesEventMetadata(ddlEvent *DDLEvent, job *timodel.Job) { + pairs := s.parseRenameTablePairs(ddlEvent.Query, ddlEvent.SchemaName) + require.Len(s.t, pairs, len(job.BinlogInfo.MultipleTableInfos)) + + ddlEvent.MultipleTableInfos = make([]*common.TableInfo, 0, len(job.BinlogInfo.MultipleTableInfos)) + ddlEvent.BlockedTableNames = make([]SchemaTableName, 0, len(pairs)) + ddlEvent.TableNameChange = &TableNameChange{ + AddName: make([]SchemaTableName, 0, len(pairs)), + DropName: make([]SchemaTableName, 0, len(pairs)), + } + for i, pair := range pairs { + ddlEvent.MultipleTableInfos = append( + ddlEvent.MultipleTableInfos, + common.WrapTableInfo(pair.newSchemaName, job.BinlogInfo.MultipleTableInfos[i]), + ) + ddlEvent.BlockedTableNames = append(ddlEvent.BlockedTableNames, SchemaTableName{ + SchemaName: pair.oldSchemaName, + TableName: pair.oldTableName, + }) + ddlEvent.TableNameChange.AddName = append(ddlEvent.TableNameChange.AddName, SchemaTableName{ + SchemaName: pair.newSchemaName, + TableName: pair.newTableName, + }) + ddlEvent.TableNameChange.DropName = append(ddlEvent.TableNameChange.DropName, SchemaTableName{ + SchemaName: pair.oldSchemaName, + TableName: pair.oldTableName, + }) + } +} + +type renameTableNamePair struct { + oldSchemaName string + oldTableName string + newSchemaName string + newTableName string +} + +func (s *EventTestHelper) parseRenameTablePairs(query string, defaultSchema string) []renameTableNamePair { + stmt, err := parser.New().ParseOneStmt(query, "", "") + require.NoError(s.t, err) + + switch renameStmt := stmt.(type) { + case *ast.RenameTableStmt: + pairs := make([]renameTableNamePair, 0, len(renameStmt.TableToTables)) + for _, tableToTable := range renameStmt.TableToTables { + pairs = append(pairs, buildRenameTableNamePair( + tableToTable.OldTable, + tableToTable.NewTable, + defaultSchema, + )) + } + return pairs + case *ast.AlterTableStmt: + pairs := make([]renameTableNamePair, 0, 1) + for _, spec := range renameStmt.Specs { + if spec.Tp != ast.AlterTableRenameTable { + continue + } + pairs = append(pairs, buildRenameTableNamePair(renameStmt.Table, spec.NewTable, defaultSchema)) + } + require.NotEmpty(s.t, pairs) + return pairs + default: + require.Failf(s.t, "unexpected rename table statement", "query: %s, stmt: %T", query, stmt) + return nil + } +} + +func buildRenameTableNamePair(oldTable, newTable *ast.TableName, defaultSchema string) renameTableNamePair { + oldSchemaName := oldTable.Schema.O + if oldSchemaName == "" { + oldSchemaName = defaultSchema + } + newSchemaName := newTable.Schema.O + if newSchemaName == "" { + newSchemaName = oldSchemaName + } + return renameTableNamePair{ + oldSchemaName: oldSchemaName, + oldTableName: oldTable.Name.O, + newSchemaName: newSchemaName, + newTableName: newTable.Name.O, + } +} + +func wrapMultipleTableInfos(schemaName string, tableInfos []*timodel.TableInfo) []*common.TableInfo { + if len(tableInfos) == 0 { + return nil + } + + wrapped := make([]*common.TableInfo, 0, len(tableInfos)) + for _, tableInfo := range tableInfos { + wrapped = append(wrapped, common.WrapTableInfo(schemaName, tableInfo)) + } + return wrapped } func (s *EventTestHelper) DML2BatchEvent(schema, table string, dmls ...string) *BatchDMLEvent { @@ -430,33 +779,13 @@ func (s *EventTestHelper) GetCurrentMeta() meta.Reader { func (s *EventTestHelper) Close() { s.domain.Close() s.storage.Close() //nolint:errcheck + vardef.EnableDistTask.Store(s.originalEnableDistTask) } func toTableInfosKey(schema, table string) string { return schema + "." + table } -func Restore(stmt ast.StmtNode) (string, error) { - var sb strings.Builder - // translate TiDB feature to special comment - restoreFlags := format.RestoreTiDBSpecialComment - // escape the keyword - restoreFlags |= format.RestoreNameBackQuotes - // upper case keyword - restoreFlags |= format.RestoreKeyWordUppercase - // wrap string with single quote - restoreFlags |= format.RestoreStringSingleQuotes - // remove placement rule - restoreFlags |= format.SkipPlacementRuleForRestore - // force disable ttl - restoreFlags |= format.RestoreWithTTLEnableOff - err := stmt.Restore(format.NewRestoreCtx(restoreFlags, &sb)) - if err != nil { - return "", errors.Trace(err) - } - return sb.String(), nil -} - // SplitQueries takes a string containing multiple SQL statements and splits them into individual SQL statements. // This function is designed for scenarios like batch creation of tables, where multiple `CREATE TABLE` statements // might be combined into a single query string. @@ -481,7 +810,7 @@ func SplitQueries(queries string) ([]string, error) { // The (ast.Node).Restore function generates a SQL string representation of the AST (Abstract Syntax Tree) node. // By default, the resulting SQL string does not include a trailing semicolon ";". // Therefore, we explicitly append a semicolon here to ensure the SQL statement is complete. - res = append(res, fmt.Sprintf("%s;", query)) + res = append(res, query+";") } return res, nil diff --git a/pkg/common/event/util_test.go b/pkg/common/event/util_test.go index 37be239877..4b1cd5c6ca 100644 --- a/pkg/common/event/util_test.go +++ b/pkg/common/event/util_test.go @@ -17,6 +17,7 @@ import ( "testing" "github.com/pingcap/ticdc/pkg/common" + timodel "github.com/pingcap/tidb/pkg/meta/model" "github.com/stretchr/testify/require" ) @@ -105,3 +106,137 @@ func TestIsSplitable(t *testing.T) { }) } } + +func TestDDL2EventFillsSingleTableMetadata(t *testing.T) { + helper := NewEventTestHelper(t) + defer helper.Close() + + helper.Tk().MustExec("CREATE DATABASE `test_db`") + helper.Tk().MustExec("CREATE TABLE `test_db`.`t1` (`id` INT PRIMARY KEY)") + ddlEvent := helper.DDL2Event("ALTER TABLE `test_db`.`t1` ADD COLUMN `c1` INT") + + require.Equal(t, []SchemaTableName{{SchemaName: "test_db", TableName: "t1"}}, ddlEvent.BlockedTableNames) + require.NotNil(t, ddlEvent.TableInfo) + require.Equal(t, "test_db", ddlEvent.TableInfo.GetSchemaName()) + require.Equal(t, "t1", ddlEvent.TableInfo.GetTableName()) +} + +func TestDDL2EventFillsAddIndexMetadata(t *testing.T) { + helper := NewEventTestHelper(t) + defer helper.Close() + + helper.Tk().MustExec("CREATE DATABASE `test_db`") + helper.Tk().MustExec("CREATE TABLE `test_db`.`t1` (`id` INT PRIMARY KEY)") + ddlEvent := helper.DDL2Event("ALTER TABLE `test_db`.`t1` ADD INDEX `idx_id`(`id`)") + + require.Equal(t, byte(timodel.ActionAddIndex), ddlEvent.Type) + require.Equal(t, "test_db", ddlEvent.SchemaName) + require.Equal(t, "t1", ddlEvent.TableName) + require.Equal(t, []SchemaTableName{{SchemaName: "test_db", TableName: "t1"}}, ddlEvent.BlockedTableNames) + require.NotNil(t, ddlEvent.TableInfo) + require.Equal(t, "test_db", ddlEvent.TableInfo.GetSchemaName()) + require.Equal(t, "t1", ddlEvent.TableInfo.GetTableName()) +} + +func TestDDL2EventFillsCreateTableLikeMetadata(t *testing.T) { + helper := NewEventTestHelper(t) + defer helper.Close() + + helper.Tk().MustExec("CREATE DATABASE `test_db`") + helper.Tk().MustExec("CREATE TABLE `test_db`.`src` (`id` INT PRIMARY KEY)") + ddlEvent := helper.DDL2Event("CREATE TABLE `test_db`.`dst` LIKE `test_db`.`src`") + + require.Equal(t, []SchemaTableName{{SchemaName: "test_db", TableName: "src"}}, ddlEvent.BlockedTableNames) + require.Equal(t, []SchemaTableName{{SchemaName: "test_db", TableName: "dst"}}, ddlEvent.TableNameChange.AddName) + + helper.Tk().MustExec("CREATE DATABASE `extra_db`") + helper.Tk().MustExec("USE `test_db`") + ddlEvent = helper.DDL2Event("CREATE TABLE `extra_db`.`dst` LIKE `src`") + + require.Equal(t, "CREATE TABLE `extra_db`.`dst` LIKE `test_db`.`src`", ddlEvent.Query) + require.Equal(t, []SchemaTableName{{SchemaName: "test_db", TableName: "src"}}, ddlEvent.BlockedTableNames) + require.Equal(t, []SchemaTableName{{SchemaName: "extra_db", TableName: "dst"}}, ddlEvent.TableNameChange.AddName) +} + +func TestDDL2EventNormalizesCrossSchemaCreateView(t *testing.T) { + helper := NewEventTestHelper(t) + defer helper.Close() + + helper.Tk().MustExec("CREATE DATABASE `test_db`") + helper.Tk().MustExec("CREATE DATABASE `extra_db`") + helper.Tk().MustExec("CREATE TABLE `test_db`.`src` (`id` INT PRIMARY KEY)") + helper.Tk().MustExec("USE `test_db`") + ddlEvent := helper.DDL2Event("CREATE VIEW `extra_db`.`v` AS SELECT `id` FROM `src`") + + require.Contains(t, ddlEvent.Query, "FROM `test_db`.`src`") +} + +func TestDDL2EventFillsRenameTableMetadata(t *testing.T) { + helper := NewEventTestHelper(t) + defer helper.Close() + + helper.Tk().MustExec("CREATE DATABASE `old_db`") + helper.Tk().MustExec("CREATE DATABASE `new_db`") + helper.Tk().MustExec("CREATE TABLE `old_db`.`orders` (`id` INT PRIMARY KEY)") + ddlEvent := helper.DDL2Event("RENAME TABLE `old_db`.`orders` TO `new_db`.`orders_archive`") + + require.Equal(t, "old_db", ddlEvent.ExtraSchemaName) + require.Equal(t, "orders", ddlEvent.ExtraTableName) + require.Equal(t, "new_db", ddlEvent.SchemaName) + require.Equal(t, "orders_archive", ddlEvent.TableName) + require.Equal(t, []SchemaTableName{{SchemaName: "old_db", TableName: "orders"}}, ddlEvent.BlockedTableNames) + require.Equal(t, []SchemaTableName{{SchemaName: "new_db", TableName: "orders_archive"}}, ddlEvent.TableNameChange.AddName) + require.Equal(t, []SchemaTableName{{SchemaName: "old_db", TableName: "orders"}}, ddlEvent.TableNameChange.DropName) +} + +func TestDDL2EventFillsRenameTablesMetadata(t *testing.T) { + helper := NewEventTestHelper(t) + defer helper.Close() + + helper.Tk().MustExec("CREATE DATABASE `test_db`") + helper.Tk().MustExec("CREATE TABLE `test_db`.`t1` (`id` INT PRIMARY KEY)") + helper.Tk().MustExec("CREATE TABLE `test_db`.`t2` (`id` INT PRIMARY KEY)") + ddlEvent := helper.DDL2Event("RENAME TABLE `test_db`.`t1` TO `test_db`.`t1_new`, `test_db`.`t2` TO `test_db`.`t2_new`") + + require.Len(t, ddlEvent.MultipleTableInfos, 2) + require.Equal(t, "test_db", ddlEvent.MultipleTableInfos[0].GetSchemaName()) + require.Equal(t, "t1_new", ddlEvent.MultipleTableInfos[0].GetTableName()) + require.Equal(t, "test_db", ddlEvent.MultipleTableInfos[1].GetSchemaName()) + require.Equal(t, "t2_new", ddlEvent.MultipleTableInfos[1].GetTableName()) + require.Equal(t, []SchemaTableName{ + {SchemaName: "test_db", TableName: "t1"}, + {SchemaName: "test_db", TableName: "t2"}, + }, ddlEvent.BlockedTableNames) + require.Equal(t, []SchemaTableName{ + {SchemaName: "test_db", TableName: "t1_new"}, + {SchemaName: "test_db", TableName: "t2_new"}, + }, ddlEvent.TableNameChange.AddName) + require.Equal(t, []SchemaTableName{ + {SchemaName: "test_db", TableName: "t1"}, + {SchemaName: "test_db", TableName: "t2"}, + }, ddlEvent.TableNameChange.DropName) +} + +func TestBatchCreateTableDDLs2EventFillsMetadata(t *testing.T) { + helper := NewEventTestHelper(t) + defer helper.Close() + + helper.Tk().MustExec("CREATE DATABASE `test_db`") + ddlEvent := helper.BatchCreateTableDDLs2Event("test_db", + "CREATE TABLE `test_db`.`t1` (`id` INT PRIMARY KEY)", + "CREATE TABLE `test_db`.`t2` (`id` INT PRIMARY KEY)", + ) + + require.Equal(t, byte(timodel.ActionCreateTables), ddlEvent.Type) + require.Equal(t, "test_db", ddlEvent.SchemaName) + require.Nil(t, ddlEvent.TableInfo) + require.Len(t, ddlEvent.MultipleTableInfos, 2) + require.Equal(t, "test_db", ddlEvent.MultipleTableInfos[0].GetSchemaName()) + require.Equal(t, "t1", ddlEvent.MultipleTableInfos[0].GetTableName()) + require.Equal(t, "test_db", ddlEvent.MultipleTableInfos[1].GetSchemaName()) + require.Equal(t, "t2", ddlEvent.MultipleTableInfos[1].GetTableName()) + require.Equal(t, []SchemaTableName{ + {SchemaName: "test_db", TableName: "t1"}, + {SchemaName: "test_db", TableName: "t2"}, + }, ddlEvent.TableNameChange.AddName) +} diff --git a/pkg/common/table_info.go b/pkg/common/table_info.go index 8af5ebdc77..d23fdb747a 100644 --- a/pkg/common/table_info.go +++ b/pkg/common/table_info.go @@ -116,8 +116,8 @@ type TableInfo struct { } `json:"-"` } -func (ti *TableInfo) InitPrivateFields() { - if ti == nil { +func (ti *TableInfo) initPreSQLs() { + if ti == nil || ti.columnSchema == nil { return } @@ -133,13 +133,54 @@ func (ti *TableInfo) InitPrivateFields() { return } - ti.preSQLs.m[preSQLInsert] = fmt.Sprintf(ti.columnSchema.PreSQLs[preSQLInsert], ti.TableName.QuoteString()) - ti.preSQLs.m[preSQLReplace] = fmt.Sprintf(ti.columnSchema.PreSQLs[preSQLReplace], ti.TableName.QuoteString()) - ti.preSQLs.m[preSQLUpdate] = fmt.Sprintf(ti.columnSchema.PreSQLs[preSQLUpdate], ti.TableName.QuoteString()) + ti.preSQLs.m[preSQLInsert] = fmt.Sprintf(ti.columnSchema.PreSQLs[preSQLInsert], ti.TableName.QuoteTargetString()) + ti.preSQLs.m[preSQLReplace] = fmt.Sprintf(ti.columnSchema.PreSQLs[preSQLReplace], ti.TableName.QuoteTargetString()) + ti.preSQLs.m[preSQLUpdate] = fmt.Sprintf(ti.columnSchema.PreSQLs[preSQLUpdate], ti.TableName.QuoteTargetString()) ti.preSQLs.isInitialized.Store(true) } +// CloneWithRouting creates a shallow copy of TableInfo with routing applied. +// The new TableInfo shares the same columnSchema, View, Sequence pointers +// but has its own TableName (with TargetSchema/TargetTable set) and preSQLs. +// This is safe because: +// - columnSchema, View, Sequence are read-only after creation +// - preSQLs will be initialized lazily using the new TableName +// - TableName is a value type that gets copied +func (ti *TableInfo) CloneWithRouting(targetSchema, targetTable string) *TableInfo { + if ti == nil { + return nil + } + // Create a new TableInfo with copied basic fields + cloned := &TableInfo{ + TableName: ti.TableName, // Value copy of TableName struct + Charset: ti.Charset, + Collate: ti.Collate, + Comment: ti.Comment, + columnSchema: ti.columnSchema, // Share the pointer (read-only) + HasPKOrNotNullUK: ti.HasPKOrNotNullUK, + View: ti.View, // Share the pointer (read-only) + Sequence: ti.Sequence, // Share the pointer (read-only) + UpdateTS: ti.UpdateTS, + ActiveActiveTable: ti.ActiveActiveTable, + SoftDeleteTable: ti.SoftDeleteTable, + } + cloned.TableName.TargetSchema = targetSchema + cloned.TableName.TargetTable = targetTable + + // Increment refcount for the shared columnSchema and set finalizer to decrement + // when the clone is garbage collected. This prevents use-after-free if the + // original TableInfo is GC'd before the clone. + if ti.columnSchema != nil { + GetSharedColumnSchemaStorage().incColumnSchemaCount(ti.columnSchema) + runtime.SetFinalizer(cloned, func(ti *TableInfo) { + GetSharedColumnSchemaStorage().tryReleaseColumnSchema(ti.columnSchema) + }) + } + + return cloned +} + func (ti *TableInfo) Marshal() ([]byte, error) { // otherField | columnSchemaData | columnSchemaDataSize data, err := json.Marshal(ti) @@ -245,6 +286,7 @@ func (ti *TableInfo) GetUpdateTS() uint64 { } func (ti *TableInfo) GetPreInsertSQL() string { + ti.initPreSQLs() if ti.preSQLs.m[preSQLInsert] == "" { log.Panic("preSQLs[preSQLInsert] is not initialized") } @@ -252,6 +294,7 @@ func (ti *TableInfo) GetPreInsertSQL() string { } func (ti *TableInfo) GetPreReplaceSQL() string { + ti.initPreSQLs() if ti.preSQLs.m[preSQLReplace] == "" { log.Panic("preSQLs[preSQLReplace] is not initialized") } @@ -259,6 +302,7 @@ func (ti *TableInfo) GetPreReplaceSQL() string { } func (ti *TableInfo) GetPreUpdateSQL() string { + ti.initPreSQLs() if ti.preSQLs.m[preSQLUpdate] == "" { log.Panic("preSQLs[preSQLUpdate] is not initialized") } @@ -343,16 +387,16 @@ func (ti *TableInfo) MustGetColumnOffsetByID(id int64) int { // GetSchemaName returns the schema name of the table func (ti *TableInfo) GetSchemaName() string { - return ti.TableName.Schema + return ti.TableName.GetSchema() } // GetTableName returns the table name of the table func (ti *TableInfo) GetTableName() string { - return ti.TableName.Table + return ti.TableName.GetTable() } func (ti *TableInfo) GetTableNameCIStr() ast.CIStr { - return ast.NewCIStr(ti.TableName.Table) + return ast.NewCIStr(ti.GetTableName()) } // GetSchemaNamePtr returns the pointer to the schema name of the table @@ -370,6 +414,18 @@ func (ti *TableInfo) IsPartitionTable() bool { return ti.TableName.IsPartition } +// GetTargetSchemaName returns the target schema name for routing. +// If TargetSchema is empty, returns Schema. +func (ti *TableInfo) GetTargetSchemaName() string { + return ti.TableName.GetTargetSchema() +} + +// GetTargetTableName returns the target table name for routing. +// If TargetTable is empty, returns Table. +func (ti *TableInfo) GetTargetTableName() string { + return ti.TableName.GetTargetTable() +} + // IsView checks if TableInfo is a view. func (t *TableInfo) IsView() bool { return t.View != nil @@ -642,7 +698,5 @@ func WrapTableInfo(schemaName string, info *model.TableInfo) *TableInfo { // do not call this method on the production code. func NewTableInfo4Decoder(schema string, tableInfo *model.TableInfo) *TableInfo { cs := NewColumnSchema4Decoder(tableInfo) - result := newTableInfo(schema, tableInfo.Name.O, tableInfo.ID, tableInfo.GetPartitionInfo() != nil, cs, tableInfo) - result.InitPrivateFields() - return result + return newTableInfo(schema, tableInfo.Name.O, tableInfo.ID, tableInfo.GetPartitionInfo() != nil, cs, tableInfo) } diff --git a/pkg/common/table_info_test.go b/pkg/common/table_info_test.go index 55c7e3fb22..0091d3be50 100644 --- a/pkg/common/table_info_test.go +++ b/pkg/common/table_info_test.go @@ -24,6 +24,77 @@ import ( "github.com/stretchr/testify/require" ) +func TestCloneWithRouting(t *testing.T) { + t.Parallel() + + t.Run("nil TableInfo", func(t *testing.T) { + var ti *TableInfo + cloned := ti.CloneWithRouting("target_schema", "target_table") + require.Nil(t, cloned) + }) + + t.Run("basic cloning with routing", func(t *testing.T) { + original := &TableInfo{ + TableName: TableName{ + Schema: "source_db", + Table: "source_table", + TableID: 123, + }, + Charset: "utf8mb4", + Collate: "utf8mb4_bin", + Comment: "test table", + HasPKOrNotNullUK: true, + UpdateTS: 1000, + } + + cloned := original.CloneWithRouting("target_db", "target_table") + + // Verify cloned has routing applied + require.Equal(t, "source_db", cloned.TableName.Schema) + require.Equal(t, "source_table", cloned.TableName.Table) + require.Equal(t, "target_db", cloned.TableName.TargetSchema) + require.Equal(t, "target_table", cloned.TableName.TargetTable) + require.Equal(t, int64(123), cloned.TableName.TableID) + require.Equal(t, "source_db", cloned.GetSchemaName()) + require.Equal(t, "source_table", cloned.GetTableName()) + require.Equal(t, "target_db", cloned.GetTargetSchemaName()) + require.Equal(t, "target_table", cloned.GetTargetTableName()) + require.Equal(t, "source_db.source_table", cloned.TableName.String()) + require.Equal(t, "`target_db`.`target_table`", cloned.TableName.QuoteTargetString()) + require.True(t, cloned.TableName.IsRouted()) + require.Same(t, &cloned.TableName.Schema, cloned.GetSchemaNamePtr()) + require.Same(t, &cloned.TableName.Table, cloned.GetTableNamePtr()) + + // Verify other fields are copied + require.Equal(t, "utf8mb4", cloned.Charset) + require.Equal(t, "utf8mb4_bin", cloned.Collate) + require.Equal(t, "test table", cloned.Comment) + require.Equal(t, true, cloned.HasPKOrNotNullUK) + require.Equal(t, uint64(1000), cloned.UpdateTS) + + // Verify original is NOT modified + require.Equal(t, "", original.TableName.TargetSchema) + require.Equal(t, "", original.TableName.TargetTable) + }) + + t.Run("target getters remain available without changing source fields", func(t *testing.T) { + original := &TableInfo{ + TableName: TableName{ + Schema: "source_db", + Table: "source_table", + TableID: 123, + }, + } + + cloned := original.CloneWithRouting("target_db", "target_table") + + require.Equal(t, "source_db", cloned.GetSchemaName()) + require.Equal(t, "source_table", cloned.GetTableName()) + require.Equal(t, "target_db", cloned.GetTargetSchemaName()) + require.Equal(t, "target_table", cloned.GetTargetTableName()) + }) +} + func TestUnmarshalJSONToTableInfoInvalidData(t *testing.T) { t.Parallel() @@ -64,6 +135,57 @@ func TestUnmarshalJSONToTableInfoInvalidData(t *testing.T) { func TestUnmarshalJSONToTableInfoRoundTrip(t *testing.T) { t.Parallel() + source := WrapTableInfo("test", newPreSQLTestModelTableInfo("t_roundtrip")) + require.NotNil(t, source) + require.Contains(t, source.GetPreInsertSQL(), QuoteSchema("test", "t_roundtrip")) + + routed := source.CloneWithRouting("target_db", "target_table") + require.Contains(t, routed.GetPreInsertSQL(), QuoteSchema("target_db", "target_table")) + + data, err := source.Marshal() + require.NoError(t, err) + + decoded, err := UnmarshalJSONToTableInfo(data) + require.NoError(t, err) + require.NotNil(t, decoded) + + require.Equal(t, source.TableName.Schema, decoded.TableName.Schema) + require.Equal(t, source.TableName.Table, decoded.TableName.Table) + require.Equal(t, source.TableName.TableID, decoded.TableName.TableID) + require.Equal(t, len(source.GetColumns()), len(decoded.GetColumns())) + require.Equal(t, source.GetColumns()[0].Name.O, decoded.GetColumns()[0].Name.O) + require.Equal(t, source.GetColumns()[1].Name.O, decoded.GetColumns()[1].Name.O) + require.Contains(t, decoded.GetPreInsertSQL(), QuoteSchema("test", "t_roundtrip")) +} + +func TestPreSQLsAreInitializedLazily(t *testing.T) { + t.Parallel() + + source := WrapTableInfo("source_db", newPreSQLTestModelTableInfo("source_table")) + require.NotNil(t, source) + require.False(t, source.preSQLs.isInitialized.Load()) + + routed := source.CloneWithRouting("target_db", "target_table") + require.False(t, source.preSQLs.isInitialized.Load()) + require.False(t, routed.preSQLs.isInitialized.Load()) + + require.Contains(t, routed.GetPreInsertSQL(), QuoteSchema("target_db", "target_table")) + require.True(t, routed.preSQLs.isInitialized.Load()) + require.False(t, source.preSQLs.isInitialized.Load()) + + data, err := source.Marshal() + require.NoError(t, err) + require.False(t, source.preSQLs.isInitialized.Load()) + + decoded, err := UnmarshalJSONToTableInfo(data) + require.NoError(t, err) + require.False(t, decoded.preSQLs.isInitialized.Load()) + + require.Contains(t, decoded.GetPreUpdateSQL(), QuoteSchema("source_db", "source_table")) + require.True(t, decoded.preSQLs.isInitialized.Load()) +} + +func newPreSQLTestModelTableInfo(table string) *model.TableInfo { idCol := &model.ColumnInfo{ ID: 1, Name: ast.NewCIStr("id"), @@ -83,27 +205,12 @@ func TestUnmarshalJSONToTableInfoRoundTrip(t *testing.T) { } nameCol.FieldType = *types.NewFieldType(mysql.TypeVarchar) - source := WrapTableInfo("test", &model.TableInfo{ + return &model.TableInfo{ ID: 1001, - Name: ast.NewCIStr("t_roundtrip"), + Name: ast.NewCIStr(table), PKIsHandle: true, Columns: []*model.ColumnInfo{idCol, nameCol}, - }) - require.NotNil(t, source) - - data, err := source.Marshal() - require.NoError(t, err) - - decoded, err := UnmarshalJSONToTableInfo(data) - require.NoError(t, err) - require.NotNil(t, decoded) - - require.Equal(t, source.TableName.Schema, decoded.TableName.Schema) - require.Equal(t, source.TableName.Table, decoded.TableName.Table) - require.Equal(t, source.TableName.TableID, decoded.TableName.TableID) - require.Equal(t, len(source.GetColumns()), len(decoded.GetColumns())) - require.Equal(t, source.GetColumns()[0].Name.O, decoded.GetColumns()[0].Name.O) - require.Equal(t, source.GetColumns()[1].Name.O, decoded.GetColumns()[1].Name.O) + } } func TestUnquoteName(t *testing.T) { diff --git a/pkg/common/table_name.go b/pkg/common/table_name.go index 646a18c6a7..10b7a9ff24 100644 --- a/pkg/common/table_name.go +++ b/pkg/common/table_name.go @@ -19,21 +19,59 @@ import ( //go:generate msgp -// TableName represents name of a table, includes table name and schema name. +// TableName represents name of a table, includes table name and schema name type TableName struct { Schema string `toml:"db-name" msg:"db-name"` Table string `toml:"tbl-name" msg:"tbl-name"` // TableID is the logic table ID TableID int64 `toml:"tbl-id" msg:"tbl-id"` IsPartition bool `toml:"is-partition" msg:"is-partition"` + + // TargetSchema and TargetTable are used as an in-memory routing overlay. + // They are excluded from msgpack serialization to preserve the wire format. + TargetSchema string `toml:"target-db-name" msg:"-"` + TargetTable string `toml:"target-tbl-name" msg:"-"` } -// String implements fmt.Stringer interface. +// String implements fmt.Stringer interface func (t TableName) String() string { return fmt.Sprintf("%s.%s", t.Schema, t.Table) } -// QuoteString returns quoted full table name -func (t TableName) QuoteString() string { - return QuoteSchema(t.Schema, t.Table) +// GetSchema returns the schema name +func (t *TableName) GetSchema() string { + return t.Schema +} + +// GetTable returns the table name +func (t *TableName) GetTable() string { + return t.Table +} + +// IsRouted returns whether table routing is enabled +func (t *TableName) IsRouted() bool { + return t.TargetSchema != "" || t.TargetTable != "" +} + +// GetTargetSchema returns the target schema name for routing. +// If TargetSchema is empty, returns Schema +func (t *TableName) GetTargetSchema() string { + if t.TargetSchema != "" { + return t.TargetSchema + } + return t.Schema +} + +// GetTargetTable returns the target table name for routing +// If TargetTable is empty, returns Table. +func (t *TableName) GetTargetTable() string { + if t.TargetTable != "" { + return t.TargetTable + } + return t.Table +} + +// QuoteTargetString returns quoted full target table name for routing +func (t TableName) QuoteTargetString() string { + return QuoteSchema(t.GetTargetSchema(), t.GetTargetTable()) } diff --git a/pkg/common/table_name_test.go b/pkg/common/table_name_test.go new file mode 100644 index 0000000000..54a2f914cb --- /dev/null +++ b/pkg/common/table_name_test.go @@ -0,0 +1,118 @@ +// Copyright 2026 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 common + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestTableNameIsRouted(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + tableName TableName + expected bool + }{ + { + name: "not routed", + tableName: TableName{Schema: "test", Table: "t"}, + expected: false, + }, + { + name: "target schema only", + tableName: TableName{Schema: "test", Table: "t", TargetSchema: "target"}, + expected: true, + }, + { + name: "target table only", + tableName: TableName{Schema: "test", Table: "t", TargetTable: "target_t"}, + expected: true, + }, + { + name: "target schema and table", + tableName: TableName{Schema: "test", Table: "t", TargetSchema: "target", TargetTable: "target_t"}, + expected: true, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if got := tt.tableName.IsRouted(); got != tt.expected { + t.Fatalf("IsRouted() = %v, expected %v", got, tt.expected) + } + }) + } +} + +func TestTableNameTargetAccessors(t *testing.T) { + t.Parallel() + + t.Run("fallback to source names", func(t *testing.T) { + tableName := TableName{ + Schema: "source_db", + Table: "source_table", + } + + require.Equal(t, "source_db", tableName.GetTargetSchema()) + require.Equal(t, "source_table", tableName.GetTargetTable()) + require.Equal(t, "`source_db`.`source_table`", tableName.QuoteTargetString()) + }) + + t.Run("use routed names when present", func(t *testing.T) { + tableName := TableName{ + Schema: "source_db", + Table: "source_table", + TargetSchema: "target_db", + TargetTable: "target_table", + } + + require.Equal(t, "target_db", tableName.GetTargetSchema()) + require.Equal(t, "target_table", tableName.GetTargetTable()) + require.Equal(t, "`target_db`.`target_table`", tableName.QuoteTargetString()) + }) +} + +func TestTableNameMsgpackRoundTripDropsRoutingOverlay(t *testing.T) { + t.Parallel() + + original := TableName{ + Schema: "source_db", + Table: "source_table", + TableID: 42, + IsPartition: true, + TargetSchema: "target_db", + TargetTable: "target_table", + } + + data, err := original.MarshalMsg(nil) + require.NoError(t, err) + + var decoded TableName + rest, err := decoded.UnmarshalMsg(data) + require.NoError(t, err) + require.Empty(t, rest) + require.Equal(t, original.Schema, decoded.Schema) + require.Equal(t, original.Table, decoded.Table) + require.Equal(t, original.TableID, decoded.TableID) + require.Equal(t, original.IsPartition, decoded.IsPartition) + require.Empty(t, decoded.TargetSchema) + require.Empty(t, decoded.TargetTable) + require.Equal(t, original.Schema, decoded.GetTargetSchema()) + require.Equal(t, original.Table, decoded.GetTargetTable()) +} diff --git a/pkg/config/changefeed.go b/pkg/config/changefeed.go index 64d80f01d6..b16b4fc70e 100644 --- a/pkg/config/changefeed.go +++ b/pkg/config/changefeed.go @@ -498,10 +498,18 @@ func (info *ChangeFeedInfo) RmUnusedFields() { } func (info *ChangeFeedInfo) rmMQOnlyFields() { - log.Info("since the downstream is not a MQ, remove MQ only fields", - zap.String("keyspace", info.ChangefeedID.Keyspace()), - zap.String("changefeed", info.ChangefeedID.Name())) - info.Config.Sink.DispatchRules = nil + // Don't nil out DispatchRules entirely - it may contain routing rules (TargetSchema/TargetTable) + // Remove only MQ-specific fields from each rule. + for _, rule := range info.Config.Sink.DispatchRules { + if rule == nil { + continue + } + rule.DispatcherRule = "" + rule.PartitionRule = "" + rule.IndexName = "" + rule.Columns = nil + rule.TopicRule = "" + } info.Config.Sink.SchemaRegistry = nil info.Config.Sink.EncoderConcurrency = nil info.Config.Sink.OnlyOutputUpdatedColumns = nil diff --git a/pkg/config/changefeed_test.go b/pkg/config/changefeed_test.go index 837ae8ce6f..8a08ba2709 100644 --- a/pkg/config/changefeed_test.go +++ b/pkg/config/changefeed_test.go @@ -54,3 +54,36 @@ func TestChangeFeedInfoRmUnusedFieldsKeepsSchemaRegistryForAvroProtocols(t *test }) } } + +func TestChangeFeedInfoRmUnusedFieldsKeepsTableRouting(t *testing.T) { + for _, sinkURI := range []string{"mysql://127.0.0.1:3306", "file:///tmp/cdc"} { + t.Run(sinkURI, func(t *testing.T) { + cfg := GetDefaultReplicaConfig() + cfg.Sink.DispatchRules = []*DispatchRule{ + nil, + { + Matcher: []string{"sales.*", "!sales.tmp"}, + TargetSchema: "archive", + TargetTable: "{schema}_{table}", + DispatcherRule: "ts", + PartitionRule: "index-value", + IndexName: "primary", + Columns: []string{"id"}, + TopicRule: "sales-events", + }, + } + info := &ChangeFeedInfo{SinkURI: sinkURI, Config: cfg} + + info.RmUnusedFields() + + require.Equal(t, []*DispatchRule{ + nil, + { + Matcher: []string{"sales.*", "!sales.tmp"}, + TargetSchema: "archive", + TargetTable: "{schema}_{table}", + }, + }, info.Config.Sink.DispatchRules) + }) + } +} diff --git a/pkg/config/replica_config.go b/pkg/config/replica_config.go index b41783619e..4ffa4fd53d 100644 --- a/pkg/config/replica_config.go +++ b/pkg/config/replica_config.go @@ -274,6 +274,12 @@ func (c *replicaConfig) fillFromV1(v1 *outdated.ReplicaConfigV1) { // ValidateAndAdjust verifies and adjusts the replica configuration. func (c *ReplicaConfig) ValidateAndAdjust(sinkURI *url.URL) error { // check sink uri + if c.Sink.TableRouteEnabled() { + if c.Consistent != nil && redo.IsConsistentEnabled(util.GetOrZero(c.Consistent.Level)) { + return cerror.ErrInvalidReplicaConfig.FastGenByArgs("table routing is incompatible with redo log/consistency feature") + } + } + enableRedoIOCheck := true if c.EnableRedoIOCheck != nil { enableRedoIOCheck = *c.EnableRedoIOCheck diff --git a/pkg/config/replica_config_test.go b/pkg/config/replica_config_test.go index a3fa3f3e8b..283c0e76f0 100644 --- a/pkg/config/replica_config_test.go +++ b/pkg/config/replica_config_test.go @@ -219,3 +219,52 @@ func TestReplicaConfig_EnableRedoIOCheck_CanDisableForCLI(t *testing.T) { require.NoError(t, err) require.NoError(t, config.ValidateAndAdjust(sinkURI)) } + +func TestReplicaConfigTableRouteSupport(t *testing.T) { + cases := []struct { + name string + uri string + routed bool + redoEnabled bool + activeActive bool + wantError string + }{ + {name: "mysql routing", uri: "mysql://localhost:3306", routed: true}, + {name: "tidb routing", uri: "tidb://localhost:4000", routed: true}, + {name: "kafka routing", uri: "kafka://localhost:9092/topic?protocol=open-protocol", routed: true, wantError: "table routing only supports MySQL-compatible sinks"}, + {name: "storage routing", uri: "file:///tmp/table-route", routed: true, wantError: "table routing only supports MySQL-compatible sinks"}, + {name: "blackhole routing", uri: "blackhole://", routed: true, wantError: "table routing only supports MySQL-compatible sinks"}, + {name: "redo with routing", uri: "mysql://localhost:3306", routed: true, redoEnabled: true, wantError: "table routing is incompatible with redo"}, + {name: "redo without routing", uri: "mysql://localhost:3306", redoEnabled: true}, + {name: "active active with routing", uri: "tidb://localhost:4000", routed: true, activeActive: true}, + {name: "active active without routing", uri: "tidb://localhost:4000", activeActive: true}, + {name: "kafka dispatch without routing", uri: "kafka://localhost:9092/topic?protocol=open-protocol"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + cfg := GetDefaultReplicaConfig() + cfg.EnableRedoIOCheck = util.AddressOf(false) + cfg.EnableActiveActive = util.AddressOf(tc.activeActive) + cfg.BDRMode = util.AddressOf(tc.activeActive) + if tc.redoEnabled { + cfg.Consistent.Level = util.AddressOf("eventual") + cfg.Consistent.Storage = util.AddressOf("file:///tmp/table-route-redo") + } + rule := &DispatchRule{Matcher: []string{"db.*"}, PartitionRule: "table", TopicRule: "topic"} + if tc.routed { + rule.TargetSchema = "archive" + } + cfg.Sink.DispatchRules = []*DispatchRule{rule} + sinkURI, err := url.Parse(tc.uri) + require.NoError(t, err) + err = cfg.ValidateAndAdjust(sinkURI) + if tc.wantError != "" { + require.ErrorContains(t, err, tc.wantError) + } else { + require.NoError(t, err) + require.Equal(t, "table", rule.PartitionRule) + require.Equal(t, "topic", rule.TopicRule) + } + }) + } +} diff --git a/pkg/config/sink.go b/pkg/config/sink.go index f7599235a1..3995ef0783 100644 --- a/pkg/config/sink.go +++ b/pkg/config/sink.go @@ -16,6 +16,7 @@ package config import ( "fmt" "net/url" + "regexp" "strconv" "strings" "time" @@ -140,7 +141,6 @@ type SinkConfig struct { // Protocol is NOT available when the downstream is DB. Protocol *string `toml:"protocol" json:"protocol,omitempty"` - // DispatchRules is only available when the downstream is MQ. DispatchRules []*DispatchRule `toml:"dispatchers" json:"dispatchers,omitempty"` ColumnSelectors []*ColumnSelector `toml:"column-selectors" json:"column-selectors,omitempty"` @@ -208,7 +208,6 @@ type SinkConfig struct { // DebeziumConfig related configurations Debezium *DebeziumConfig `toml:"debezium" json:"debezium,omitempty"` - CaseSensitive *bool `toml:"case-sensitive" json:"case-sensitive,omitempty"` // Integrity is only available when the downstream is MQ. Integrity *IntegrityConfig `toml:"integrity" json:"integrity"` ForceReplicate *bool `toml:"force-replicate" json:"force-replicate,omitempty"` @@ -387,8 +386,13 @@ func (d DateSeparator) String() string { } } -// DispatchRule represents partition rule for a table. +// DispatchRules configures event routing. +// For MQ sinks, rules control topic / partition dispatching. +// TargetSchema and TargetTable configure table routing. type DispatchRule struct { + // Rules are evaluated in order, and the first matching rule wins. + // MQ dispatching skips rules that only configure target schema or table names. + // A matcher-only rule selects the default MQ topic and partition strategy. Matcher []string `toml:"matcher" json:"matcher"` // Deprecated, please use PartitionRule. DispatcherRule string `toml:"dispatcher" json:"dispatcher"` @@ -403,6 +407,22 @@ type DispatchRule struct { Columns []string `toml:"columns" json:"columns"` TopicRule string `toml:"topic" json:"topic"` + + // TargetSchema sets the routed downstream schema name. + // Leave it empty to keep the source schema name. + // For example, if the source table is `sales`.`orders`, `target-schema = "sales_bak"` + // writes to `sales_bak`.`orders`. + // You can also use placeholders. For example, `target-schema = "{schema}_bak"` + // becomes `sales_bak`. + TargetSchema string `toml:"target-schema" json:"target-schema"` + + // TargetTable sets the routed downstream table name. + // Leave it empty to keep the source table name. + // For example, if the source table is `sales`.`orders`, `target-table = "orders_bak"` + // writes to `sales`.`orders_bak`. + // You can also use placeholders. For example, `target-table = "{schema}_{table}"` + // becomes `sales_orders`. + TargetTable string `toml:"target-table" json:"target-table"` } // ColumnSelector represents a column selector for a table. @@ -740,10 +760,18 @@ func CheckUseTableIDAsPathCompatibility( } func (s *SinkConfig) validateAndAdjust(sinkURI *url.URL) error { + if s.TableRouteEnabled() && !IsMySQLCompatibleScheme(GetScheme(sinkURI)) { + return cerror.ErrInvalidReplicaConfig.FastGenByArgs("table routing only supports MySQL-compatible sinks") + } + if err := s.validateAndAdjustSinkURI(sinkURI); err != nil { return err } + if err := s.validateTableRoute(); err != nil { + return err + } + if IsMySQLCompatibleScheme(sinkURI.Scheme) { return nil } @@ -862,6 +890,34 @@ func (s *SinkConfig) validateAndAdjust(sinkURI *url.URL) error { return nil } +// TableRouteEnabled reports whether any dispatch rule specifies a target name. +func (s *SinkConfig) TableRouteEnabled() bool { + if s == nil { + return false + } + for _, rule := range s.DispatchRules { + if rule != nil && (rule.TargetSchema != "" || rule.TargetTable != "") { + return true + } + } + return false +} + +func (s *SinkConfig) validateTableRoute() error { + for _, rule := range s.DispatchRules { + if rule == nil || (rule.TargetSchema == "" && rule.TargetTable == "") { + continue + } + if err := validateRoutingExpression("target-schema", rule.TargetSchema); err != nil { + return err + } + if err := validateRoutingExpression("target-table", rule.TargetTable); err != nil { + return err + } + } + return nil +} + // validateAndAdjustSinkURI validate and adjust `Protocol` and `TxnAtomicity` by sinkURI. func (s *SinkConfig) validateAndAdjustSinkURI(sinkURI *url.URL) error { if sinkURI == nil { @@ -1114,3 +1170,20 @@ type OpenProtocolConfig struct { type DebeziumConfig struct { OutputOldValue bool `toml:"output-old-value" json:"output-old-value"` } + +// validRoutingExpressionRegexp accepts routing expressions made of literal text +// and the {schema}/{table} placeholders, such as "archive", "{table}_bak", or "{schema}_{table}". +var validRoutingExpressionRegexp = regexp.MustCompile(`^(?:[^{}]|\{schema\}|\{table\})*$`) + +// validateRoutingExpression validates a routing expression for a single routing field. +// Valid expressions can contain literal text and {schema} or {table} placeholders. +func validateRoutingExpression(fieldName, expr string) error { + if expr == "" || validRoutingExpressionRegexp.MatchString(expr) { + return nil + } + return cerror.ErrInvalidTableRoutingRule.GenWithStack( + "%s %q must contain only literal text, {schema}, and {table}", + fieldName, + expr, + ) +} diff --git a/pkg/config/sink_test.go b/pkg/config/sink_test.go index 20c0d9075c..507bb250ef 100644 --- a/pkg/config/sink_test.go +++ b/pkg/config/sink_test.go @@ -17,6 +17,7 @@ import ( "net/url" "testing" + "github.com/pingcap/ticdc/pkg/errors" "github.com/pingcap/ticdc/pkg/util" "github.com/stretchr/testify/require" ) @@ -294,6 +295,124 @@ func TestCheckCompatibilityWithSinkURI(t *testing.T) { } } +func TestValidateTableRoute(t *testing.T) { + t.Parallel() + + testCases := []struct { + name string + cfg *SinkConfig + wantErr string + }{ + { + name: "valid routing rule", + cfg: &SinkConfig{ + DispatchRules: []*DispatchRule{ + { + Matcher: []string{"db1.*"}, + TargetSchema: "archive", + TargetTable: "{table}_bak", + }, + }, + }, + }, + { + name: "invalid target schema expression", + cfg: &SinkConfig{ + DispatchRules: []*DispatchRule{ + { + Matcher: []string{"db1.*"}, + TargetSchema: "{bad}", + TargetTable: "{table}_bak", + }, + }, + }, + wantErr: "target-schema", + }, + { + name: "mq dispatch rule ignored", + cfg: &SinkConfig{ + DispatchRules: []*DispatchRule{ + { + Matcher: []string{"db1.*"}, + PartitionRule: "columns", + Columns: []string{"id"}, + }, + }, + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + err := tc.cfg.validateTableRoute() + if tc.wantErr == "" { + require.NoError(t, err) + } else { + require.ErrorContains(t, err, tc.wantErr) + } + }) + } +} + +func TestValidateRoutingExpression(t *testing.T) { + t.Parallel() + + validExpressions := []string{ + "", + "archive", + "orders_bak", + "archive_v2", + "db-01.table_02", + "{schema}", + "{table}", + "{schema}_{table}", + "{table}_bak", + "bak_{table}_v2", + "{schema}_backup", + "archive_{schema}_{table}_v2", + "prefix_{schema}_middle_{table}_suffix", + "{schema}_{schema}_{table}", + } + + for _, expr := range validExpressions { + name := expr + if name == "" { + name = "empty" + } + t.Run(name, func(t *testing.T) { + require.NoError(t, validateRoutingExpression("target-table", expr)) + }) + } +} + +func TestValidateRoutingExpressionRejectsInvalidExpressions(t *testing.T) { + t.Parallel() + + invalidExpressions := []string{ + "{invalid}", + "{Schema}", + "{TABLE}", + "{schema", + "schema}", + "{table", + "{", + "}", + "{{schema}}", + "{schema}{bad}", + "prefix_{schema}_{bad}", + } + + for _, expr := range invalidExpressions { + t.Run(expr, func(t *testing.T) { + err := validateRoutingExpression("target-table", expr) + require.Error(t, err) + code, ok := errors.RFCCode(err) + require.True(t, ok) + require.Equal(t, errors.ErrInvalidTableRoutingRule.RFCCode(), code) + }) + } +} + func TestValidateAndAdjustCSVConfig(t *testing.T) { t.Parallel() tests := []struct { diff --git a/pkg/errors/error.go b/pkg/errors/error.go index a37a0049c9..06472999fc 100644 --- a/pkg/errors/error.go +++ b/pkg/errors/error.go @@ -257,6 +257,18 @@ var ( "sink config invalid", errors.RFCCodeText("CDC:ErrSinkInvalidConfig"), ) + ErrInvalidTableRoutingRule = errors.Normalize( + "invalid table routing rule", + errors.RFCCodeText("CDC:ErrInvalidTableRoutingRule"), + ) + ErrTableRoutingFailed = errors.Normalize( + "table routing failed", + errors.RFCCodeText("CDC:ErrTableRoutingFailed"), + ) + ErrTableRouteConflict = errors.Normalize( + "table route conflict: target `%s`.`%s` is mapped by both source `%s`.`%s` and source `%s`.`%s`", + errors.RFCCodeText("CDC:ErrTableRouteConflict"), + ) ErrMessageTooLarge = errors.Normalize( "message is too large. table:%s, length:%d, maxMessageBytes:%d", errors.RFCCodeText("CDC:ErrMessageTooLarge"), diff --git a/pkg/errors/error_test.go b/pkg/errors/error_test.go index 777570d547..e040eedc67 100644 --- a/pkg/errors/error_test.go +++ b/pkg/errors/error_test.go @@ -108,6 +108,16 @@ func TestShouldFailChangefeed(t *testing.T) { err: ErrStorageSinkInvalidConfig.GenWithStackByArgs("invalid config"), expected: true, }, + { + name: "ErrInvalidTableRoutingRule should return true", + err: ErrInvalidTableRoutingRule.GenWithStackByArgs("invalid matcher"), + expected: true, + }, + { + name: "ErrTableRoutingFailed should return true", + err: ErrTableRoutingFailed.GenWithStackByArgs("failed to rewrite ddl"), + expected: true, + }, { name: "Error with RFC code matching should return true", err: errors.New("CDC:ErrGCTTLExceeded some error message"), diff --git a/pkg/errors/helper.go b/pkg/errors/helper.go index 3fd77ca3ba..bd8f3cf934 100644 --- a/pkg/errors/helper.go +++ b/pkg/errors/helper.go @@ -24,6 +24,9 @@ import ( tmysql "github.com/pingcap/tidb/pkg/parser/mysql" ) +// RFCErrorCode identifies a normalized error code. +type RFCErrorCode = errors.RFCErrorCode + // WrapError generates a new error based on given `*errors.Error`, wraps the err // as cause error. // If given `err` is nil, returns a nil error, which a the different behavior @@ -117,6 +120,9 @@ var changefeedUnRetryableErrors = []*errors.Error{ ErrKafkaInvalidConfig, ErrMySQLInvalidConfig, ErrStorageSinkInvalidConfig, + ErrInvalidTableRoutingRule, + ErrTableRoutingFailed, + ErrTableRouteConflict, // gc related errors ErrGCTTLExceeded, diff --git a/pkg/errors/helper_test.go b/pkg/errors/helper_test.go index b282a956fb..2fb4c557a3 100644 --- a/pkg/errors/helper_test.go +++ b/pkg/errors/helper_test.go @@ -109,6 +109,19 @@ func TestChangefeedFastFailError(t *testing.T) { require.Equal(t, false, IsChangefeedGCFastFailErrorCode(rfcCode)) } +func TestErrorCodeForTableRoutingErrors(t *testing.T) { + t.Parallel() + + err := ErrInvalidTableRoutingRule.GenWithStackByArgs("invalid matcher") + require.Equal(t, ErrChangefeedUnretryable.RFCCode(), ErrorCode(err)) + + err = WrapError(ErrInvalidTableRoutingRule, errors.New("invalid matcher")) + require.Equal(t, ErrChangefeedUnretryable.RFCCode(), ErrorCode(err)) + + err = ErrTableRoutingFailed.GenWithStackByArgs("failed to rewrite ddl") + require.Equal(t, ErrChangefeedUnretryable.RFCCode(), ErrorCode(err)) +} + func TestIsCliUnprintableError(t *testing.T) { t.Parallel() tests := []struct { diff --git a/pkg/filter/ddl.go b/pkg/filter/ddl.go index d3ec745725..3898dd45ac 100644 --- a/pkg/filter/ddl.go +++ b/pkg/filter/ddl.go @@ -20,12 +20,18 @@ import ( // TODO: clean this file -// ALTER TABLE t2 ADD FULLTEXT INDEX (b) WITH PARSER standard; -// TODO: remove this after ADD FULLTEXT INDEX has a dedicated action type in tidb repo +// ActionAddFullTextIndex represents a CDC-local action for: +// ALTER TABLE t2 ADD FULLTEXT INDEX (b) WITH PARSER standard. +// TODO: remove this after ADD FULLTEXT INDEX has a dedicated action type in tidb repo. +// When this DDL is officially supported by TiDB parser, table routing support +// must be added at the same time. const ActionAddFullTextIndex = timodel.ActionType(230) -// CREATE HYBRID INDEX i_idx ON t(b, c, d, e, g) PARAMETER -// TODO: remove this after CREATE HYBRID INDEX has a dedicated action type in tidb repo +// ActionCreateHybridIndex represents a CDC-local action for: +// CREATE HYBRID INDEX i_idx ON t(b, c, d, e, g) PARAMETER ... +// TODO: remove this after CREATE HYBRID INDEX has a dedicated action type in tidb repo. +// When this DDL is officially supported by TiDB parser, table routing support +// must be added at the same time. const ActionCreateHybridIndex = timodel.ActionType(231) // ddlWhiteListMap is a map of all DDL types that can be applied to cdc's schema storage. diff --git a/pkg/sink/codec/canal/canal_json_test.go b/pkg/sink/codec/canal/canal_json_test.go index 8483c8c3af..c727467a6e 100644 --- a/pkg/sink/codec/canal/canal_json_test.go +++ b/pkg/sink/codec/canal/canal_json_test.go @@ -518,7 +518,7 @@ func TestDMLEventWithColumnSelector(t *testing.T) { Columns: []string{"a"}, }, } - selectors, err := columnselector.New(replicaConfig.Sink) + selectors, err := columnselector.New(replicaConfig.Sink, false) require.NoError(t, err) rowEvent := &commonEvent.RowEvent{ diff --git a/pkg/sink/codec/canal/canal_json_txn_encoder_test.go b/pkg/sink/codec/canal/canal_json_txn_encoder_test.go index 052f45c736..11330c7c7f 100644 --- a/pkg/sink/codec/canal/canal_json_txn_encoder_test.go +++ b/pkg/sink/codec/canal/canal_json_txn_encoder_test.go @@ -109,7 +109,7 @@ func TestCanalJSONTxnEventEncoderWithColumnSelector(t *testing.T) { ColumnSelectors: []*config.ColumnSelector{ {Matcher: []string{"test.t"}, Columns: []string{"col1"}}, }, - }) + }, false) require.NoError(t, err) encoder := NewJSONTxnEventEncoder(common.NewConfig(config.ProtocolCanalJSON)) diff --git a/pkg/sink/codec/csv/csv_decoder_test.go b/pkg/sink/codec/csv/csv_decoder_test.go index 17ddfb1a33..4e537f212a 100644 --- a/pkg/sink/codec/csv/csv_decoder_test.go +++ b/pkg/sink/codec/csv/csv_decoder_test.go @@ -73,7 +73,7 @@ func TestCSVBatchDecoderWithColumnSelector(t *testing.T) { ColumnSelectors: []*config.ColumnSelector{ {Matcher: []string{"test.t"}, Columns: []string{"id", "visible"}}, }, - }) + }, false) require.NoError(t, err) codecConfig := &common.Config{ diff --git a/pkg/sink/codec/csv/csv_encoder_test.go b/pkg/sink/codec/csv/csv_encoder_test.go index 9482b9c868..efced565d6 100644 --- a/pkg/sink/codec/csv/csv_encoder_test.go +++ b/pkg/sink/codec/csv/csv_encoder_test.go @@ -149,7 +149,7 @@ func TestCSVTxnEventEncoderWithColumnSelector(t *testing.T) { ColumnSelectors: []*config.ColumnSelector{ {Matcher: []string{"test.table1"}, Columns: []string{"col1"}}, }, - }) + }, false) require.NoError(t, err) cfg := &common.Config{ @@ -191,7 +191,7 @@ func TestCSVTxnEventEncoderWithColumnSelectorForUpdateAndDelete(t *testing.T) { ColumnSelectors: []*config.ColumnSelector{ {Matcher: []string{"test.table1"}, Columns: []string{"id", "visible"}}, }, - }) + }, false) require.NoError(t, err) cfg := &common.Config{ diff --git a/pkg/sink/codec/open/encoder_test.go b/pkg/sink/codec/open/encoder_test.go index 132844db09..adc208ec21 100644 --- a/pkg/sink/codec/open/encoder_test.go +++ b/pkg/sink/codec/open/encoder_test.go @@ -940,7 +940,7 @@ func TestDMLEventWithColumnSelector(t *testing.T) { Columns: []string{"a"}, }, } - selectors, err := columnselector.New(replicaConfig.Sink) + selectors, err := columnselector.New(replicaConfig.Sink, false) require.NoError(t, err) rowEvent := &commonEvent.RowEvent{ diff --git a/pkg/sink/mysql/helper.go b/pkg/sink/mysql/helper.go index 45904af9fc..aa3855c8fe 100644 --- a/pkg/sink/mysql/helper.go +++ b/pkg/sink/mysql/helper.go @@ -406,7 +406,7 @@ func CreateMysqlDBConn(dsnStr string) (*sql.DB, error) { } func needSwitchDB(event *commonEvent.DDLEvent) bool { - if len(event.GetSchemaName()) == 0 { + if len(event.GetTargetSchemaName()) == 0 { return false } if event.GetDDLType() == timodel.ActionCreateSchema || event.GetDDLType() == timodel.ActionDropSchema { diff --git a/pkg/sink/mysql/mysql_writer_ddl.go b/pkg/sink/mysql/mysql_writer_ddl.go index 6b06d71781..48009fcf5f 100644 --- a/pkg/sink/mysql/mysql_writer_ddl.go +++ b/pkg/sink/mysql/mysql_writer_ddl.go @@ -106,7 +106,7 @@ func (w *Writer) execDDL(event *commonEvent.DDLEvent) error { } if shouldSwitchDB { - _, err = tx.ExecContext(ctx, "USE "+common.QuoteName(event.GetSchemaName())+";") + _, err = tx.ExecContext(ctx, "USE "+common.QuoteName(event.GetTargetSchemaName())+";") if err != nil { if rbErr := tx.Rollback(); rbErr != nil { log.Error("Failed to rollback", zap.Error(err)) diff --git a/pkg/sink/mysql/mysql_writer_dml_active_active_test.go b/pkg/sink/mysql/mysql_writer_dml_active_active_test.go index f3cea842a1..e33a1da614 100644 --- a/pkg/sink/mysql/mysql_writer_dml_active_active_test.go +++ b/pkg/sink/mysql/mysql_writer_dml_active_active_test.go @@ -48,6 +48,26 @@ func TestBuildActiveActiveUpsertSQLMultiRows(t *testing.T) { require.Equal(t, common.RowTypeInsert, rowTypes) } +func TestBuildActiveActiveUpsertSQLUsesRoutedTargetTable(t *testing.T) { + writer, _, _ := newTestMysqlWriter(t) + defer writer.db.Close() + + helper := commonEvent.NewEventTestHelper(t) + defer helper.Close() + + helper.Tk().MustExec("use test") + job := helper.DDL2Job("create table t (id int primary key, name varchar(32), _tidb_origin_ts bigint unsigned null, _tidb_softdelete_time timestamp null);") + require.NotNil(t, job) + + event := helper.DML2Event("test", "t", "insert into t values (1, 'alice', 10, NULL)") + event.TableInfo = helper.GetTableInfo(job).CloneWithRouting("target_db", "target_table") + + rows, commitTs := writer.collectActiveActiveRows(event) + sql, _, _ := buildActiveActiveUpsertSQL(event.TableInfo, rows, commitTs) + require.Contains(t, sql, "INSERT INTO `target_db`.`target_table`") + require.NotContains(t, sql, "`test`.`t`") +} + func TestActiveActiveNormalSQLs(t *testing.T) { writer, _, _ := newTestMysqlWriter(t) defer writer.db.Close() diff --git a/pkg/sink/mysql/mysql_writer_test.go b/pkg/sink/mysql/mysql_writer_test.go index 7f7b8b8a93..a9d6ccdec6 100644 --- a/pkg/sink/mysql/mysql_writer_test.go +++ b/pkg/sink/mysql/mysql_writer_test.go @@ -25,9 +25,11 @@ import ( lru "github.com/hashicorp/golang-lru" "github.com/pingcap/errors" "github.com/pingcap/log" + "github.com/pingcap/ticdc/downstreamadapter/routing" "github.com/pingcap/ticdc/heartbeatpb" "github.com/pingcap/ticdc/pkg/common" commonEvent "github.com/pingcap/ticdc/pkg/common/event" + "github.com/pingcap/ticdc/pkg/config" "github.com/pingcap/ticdc/pkg/config/kerneltype" cerror "github.com/pingcap/ticdc/pkg/errors" "github.com/pingcap/ticdc/pkg/metrics" @@ -354,6 +356,52 @@ func TestMysqlWriter_Flush_EmptyEvents(t *testing.T) { require.NoError(t, err) } +func TestMysqlWriterExecDDLUsesRoutedSchemaName(t *testing.T) { + router, err := routing.NewRouter( + common.NewChangefeedID4Test("test", "test"), + true, + []*config.DispatchRule{{ + Matcher: []string{"source_db.*"}, + TargetSchema: "target_db", + TargetTable: "{table}_routed", + }}, + ) + require.NoError(t, err) + + helper := commonEvent.NewEventTestHelper(t) + defer helper.Close() + + createSchemaDDL := helper.DDL2Event("CREATE DATABASE `source_db`") + routedCreateSchemaDDL, err := router.ApplyToDDLEvent(createSchemaDDL) + require.NoError(t, err) + require.Equal(t, "target_db", routedCreateSchemaDDL.GetTargetSchemaName()) + + writer, db, mock := newTestMysqlWriter(t) + defer db.Close() + mock.ExpectBegin() + mock.ExpectExec("SET TIMESTAMP = DEFAULT").WillReturnResult(sqlmock.NewResult(1, 1)) + mock.ExpectExec(routedCreateSchemaDDL.Query).WillReturnResult(sqlmock.NewResult(1, 1)) + mock.ExpectCommit() + require.NoError(t, writer.execDDL(routedCreateSchemaDDL)) + require.NoError(t, mock.ExpectationsWereMet()) + + createTableDDL := helper.DDL2Event("CREATE TABLE `source_db`.`source_table` (`id` INT PRIMARY KEY)") + routedCreateTableDDL, err := router.ApplyToDDLEvent(createTableDDL) + require.NoError(t, err) + require.Equal(t, "target_db", routedCreateTableDDL.GetTargetSchemaName()) + require.Equal(t, "source_table_routed", routedCreateTableDDL.GetTargetTableName()) + + writer, db, mock = newTestMysqlWriter(t) + defer db.Close() + mock.ExpectBegin() + mock.ExpectExec("USE `target_db`;").WillReturnResult(sqlmock.NewResult(1, 1)) + mock.ExpectExec("SET TIMESTAMP = DEFAULT").WillReturnResult(sqlmock.NewResult(1, 1)) + mock.ExpectExec(routedCreateTableDDL.Query).WillReturnResult(sqlmock.NewResult(1, 1)) + mock.ExpectCommit() + require.NoError(t, writer.execDDL(routedCreateTableDDL)) + require.NoError(t, mock.ExpectationsWereMet()) +} + func TestMysqlWriter_FlushSyncPointEvent(t *testing.T) { writer, db, mock := newTestMysqlWriter(t) defer db.Close() diff --git a/pkg/sink/mysql/sql_builder.go b/pkg/sink/mysql/sql_builder.go index cc48c02bb3..e126f3f606 100644 --- a/pkg/sink/mysql/sql_builder.go +++ b/pkg/sink/mysql/sql_builder.go @@ -180,7 +180,7 @@ func buildInsert( // sql: `DELETE FROM `test`.`t` WHERE x = ? AND y >= ? LIMIT 1` func buildDelete(tableInfo *common.TableInfo, row commonEvent.RowChange) (string, []interface{}) { var builder strings.Builder - quoteTable := tableInfo.TableName.QuoteString() + quoteTable := tableInfo.TableName.QuoteTargetString() builder.WriteString("DELETE FROM ") builder.WriteString(quoteTable) builder.WriteString(" WHERE ") @@ -308,7 +308,7 @@ func buildActiveActiveUpsertSQL( var builder strings.Builder builder.WriteString("INSERT INTO ") - builder.WriteString(tableInfo.TableName.QuoteString()) + builder.WriteString(tableInfo.TableName.QuoteTargetString()) builder.WriteString(" (") for i, colName := range insertColumns { if i > 0 { diff --git a/pkg/sink/mysql/sql_builder_test.go b/pkg/sink/mysql/sql_builder_test.go index c88dc06830..5dde1c1e00 100644 --- a/pkg/sink/mysql/sql_builder_test.go +++ b/pkg/sink/mysql/sql_builder_test.go @@ -182,6 +182,23 @@ func TestBuildInsert(t *testing.T) { require.Equal(t, exportedArgs, args) } +func TestBuildDMLUsesRoutedTargetTable(t *testing.T) { + insert, deleteRow, updateRow, tableInfo := getRowForTest(t) + routedTableInfo := tableInfo.CloneWithRouting("target_db", "target_table") + + insertSQL, _ := buildInsert(routedTableInfo, insert, false) + require.Contains(t, insertSQL, "INSERT INTO `target_db`.`target_table`") + require.NotContains(t, insertSQL, "`test`.`t`") + + deleteSQL, _ := buildDelete(routedTableInfo, deleteRow) + require.Contains(t, deleteSQL, "DELETE FROM `target_db`.`target_table`") + require.NotContains(t, deleteSQL, "`test`.`t`") + + updateSQL, _ := buildUpdate(routedTableInfo, updateRow) + require.Contains(t, updateSQL, "UPDATE `target_db`.`target_table`") + require.NotContains(t, updateSQL, "`test`.`t`") +} + func TestBuildDelete(t *testing.T) { helper := event.NewEventTestHelper(t) defer helper.Close() diff --git a/pkg/sink/sqlmodel/multi_row.go b/pkg/sink/sqlmodel/multi_row.go index e7f31eb6b0..14a5277e88 100644 --- a/pkg/sink/sqlmodel/multi_row.go +++ b/pkg/sink/sqlmodel/multi_row.go @@ -161,7 +161,7 @@ func GenInsertSQL(tp DMLType, changes ...*RowChange) (string, []interface{}) { } else { buf.WriteString("INSERT INTO ") } - buf.WriteString(first.targetTable.QuoteString()) + buf.WriteString(first.targetTable.QuoteTargetString()) buf.WriteString(" (") columnNum := 0 var skipColIdx []int @@ -273,7 +273,7 @@ func genDeleteSQLV2(changes ...*RowChange) (string, []interface{}) { var buf strings.Builder buf.Grow(1024) buf.WriteString("DELETE FROM ") - buf.WriteString(first.targetTable.QuoteString()) + buf.WriteString(first.targetTable.QuoteTargetString()) buf.WriteString(" WHERE (") // v2 uses the first row to define the tuple shape of the trailing IN list. @@ -327,7 +327,7 @@ func genUpdateSQLV2(changes ...*RowChange) (string, []any) { // Generate UPDATE `db`.`table` SET first := changes[0] buf.WriteString("UPDATE ") - buf.WriteString(first.targetTable.QuoteString()) + buf.WriteString(first.targetTable.QuoteTargetString()) buf.WriteString(" SET ") // Pre-generate essential sub statements used after WHEN, WHERE. diff --git a/pkg/sink/sqlmodel/multi_row_test.go b/pkg/sink/sqlmodel/multi_row_test.go index b2e474c4d4..f552d9cf86 100644 --- a/pkg/sink/sqlmodel/multi_row_test.go +++ b/pkg/sink/sqlmodel/multi_row_test.go @@ -41,6 +41,69 @@ func TestGenDeleteMultiRows(t *testing.T) { require.Equal(t, []interface{}{1, 3}, args) } +func TestGenMultiRowSQLUsesRoutedTargetTable(t *testing.T) { + t.Parallel() + + sourceTableInfo, routedTableInfo := mockRoutedTableInfo( + t, + "CREATE TABLE tb1 (id INT PRIMARY KEY, name INT)", + "target_db", + "target_tb", + ) + + sourceTable := &sourceTableInfo.TableName + targetTable := &routedTableInfo.TableName + + insertChanges := []*RowChange{ + NewRowChange(sourceTable, targetTable, nil, []interface{}{1, 2}, sourceTableInfo, routedTableInfo, nil), + NewRowChange(sourceTable, targetTable, nil, []interface{}{3, 4}, sourceTableInfo, routedTableInfo, nil), + } + insertSQL, _ := GenInsertSQL(DMLInsert, insertChanges...) + require.Contains(t, insertSQL, "INSERT INTO `target_db`.`target_tb`") + require.NotContains(t, insertSQL, "`db`.`tb1`") + + deleteV2Changes := []*RowChange{ + NewRowChange(sourceTable, targetTable, []interface{}{1, 2}, nil, sourceTableInfo, routedTableInfo, nil), + NewRowChange(sourceTable, targetTable, []interface{}{3, 4}, nil, sourceTableInfo, routedTableInfo, nil), + } + deleteV2SQL, _ := GenDeleteSQL(DefaultWhereClause, deleteV2Changes...) + require.Contains(t, deleteV2SQL, "DELETE FROM `target_db`.`target_tb`") + require.NotContains(t, deleteV2SQL, "`db`.`tb1`") + + updateV2Changes := []*RowChange{ + NewRowChange(sourceTable, targetTable, []interface{}{1, 2}, []interface{}{1, 20}, sourceTableInfo, routedTableInfo, nil), + NewRowChange(sourceTable, targetTable, []interface{}{3, 4}, []interface{}{3, 40}, sourceTableInfo, routedTableInfo, nil), + } + updateV2SQL, _ := GenUpdateSQL(DefaultWhereClause, updateV2Changes...) + require.Contains(t, updateV2SQL, "UPDATE `target_db`.`target_tb`") + require.NotContains(t, updateV2SQL, "`db`.`tb1`") + + nullSourceTableInfo, nullRoutedTableInfo := mockRoutedTableInfo( + t, + "CREATE TABLE tb2 (id INT, name INT)", + "target_db", + "target_tb_v1", + ) + nullSourceTable := &nullSourceTableInfo.TableName + nullTargetTable := &nullRoutedTableInfo.TableName + + deleteV1Changes := []*RowChange{ + NewRowChange(nullSourceTable, nullTargetTable, []interface{}{1, nil}, nil, nullSourceTableInfo, nullRoutedTableInfo, nil), + NewRowChange(nullSourceTable, nullTargetTable, []interface{}{3, 4}, nil, nullSourceTableInfo, nullRoutedTableInfo, nil), + } + deleteV1SQL, _ := GenDeleteSQL(DefaultWhereClause, deleteV1Changes...) + require.Contains(t, deleteV1SQL, "DELETE FROM `target_db`.`target_tb_v1`") + require.NotContains(t, deleteV1SQL, "`db`.`tb2`") + + updateV1Changes := []*RowChange{ + NewRowChange(nullSourceTable, nullTargetTable, []interface{}{1, nil}, []interface{}{1, 20}, nullSourceTableInfo, nullRoutedTableInfo, nil), + NewRowChange(nullSourceTable, nullTargetTable, []interface{}{3, 4}, []interface{}{3, 40}, nullSourceTableInfo, nullRoutedTableInfo, nil), + } + updateV1SQL, _ := GenUpdateSQL(DefaultWhereClause, updateV1Changes...) + require.Contains(t, updateV1SQL, "UPDATE `target_db`.`target_tb_v1`") + require.NotContains(t, updateV1SQL, "`db`.`tb2`") +} + func TestGenDeleteMultiRowsWithNullFallbackToV1(t *testing.T) { t.Parallel() diff --git a/pkg/sink/sqlmodel/multi_row_v1.go b/pkg/sink/sqlmodel/multi_row_v1.go index fbb15f97fb..f9b2b3d38e 100644 --- a/pkg/sink/sqlmodel/multi_row_v1.go +++ b/pkg/sink/sqlmodel/multi_row_v1.go @@ -38,7 +38,7 @@ func genDeleteSQLV1(changes ...*RowChange) (string, []interface{}) { var buf strings.Builder buf.Grow(1024) buf.WriteString("DELETE FROM ") - buf.WriteString(first.targetTable.QuoteString()) + buf.WriteString(first.targetTable.QuoteTargetString()) buf.WriteString(" WHERE (") allArgs := make([]interface{}, 0, len(changes)*CommonIndexColumnsCount) @@ -67,7 +67,7 @@ func genUpdateSQLV1(changes ...*RowChange) (string, []any) { // Generate UPDATE `db`.`table` SET first := changes[0] buf.WriteString("UPDATE ") - buf.WriteString(first.targetTable.QuoteString()) + buf.WriteString(first.targetTable.QuoteTargetString()) buf.WriteString(" SET ") // Pre-generate essential sub statements used after WHEN and in the final WHERE. diff --git a/pkg/sink/sqlmodel/row_change.go b/pkg/sink/sqlmodel/row_change.go index 9f41b3dd91..80c7e353f7 100644 --- a/pkg/sink/sqlmodel/row_change.go +++ b/pkg/sink/sqlmodel/row_change.go @@ -171,7 +171,7 @@ func (r *RowChange) String() string { // TargetTableID returns a ID string for target table. func (r *RowChange) TargetTableID() string { - return r.targetTable.QuoteString() + return r.targetTable.QuoteTargetString() } // ColumnCount returns the number of columns of this RowChange. @@ -277,7 +277,7 @@ func (r *RowChange) genDeleteSQL() (string, []interface{}) { var buf strings.Builder buf.Grow(1024) buf.WriteString("DELETE FROM ") - buf.WriteString(r.targetTable.QuoteString()) + buf.WriteString(r.targetTable.QuoteTargetString()) buf.WriteString(" WHERE ") whereArgs := r.genWhere(&buf) buf.WriteString(" LIMIT 1") @@ -296,7 +296,7 @@ func (r *RowChange) genUpdateSQL() (string, []interface{}) { var buf strings.Builder buf.Grow(2048) buf.WriteString("UPDATE ") - buf.WriteString(r.targetTable.QuoteString()) + buf.WriteString(r.targetTable.QuoteTargetString()) buf.WriteString(" SET ") // Build target generated columns lower names set to accelerate following check diff --git a/pkg/sink/sqlmodel/row_change_test.go b/pkg/sink/sqlmodel/row_change_test.go index b9b67c9eaa..cd4480335f 100644 --- a/pkg/sink/sqlmodel/row_change_test.go +++ b/pkg/sink/sqlmodel/row_change_test.go @@ -40,6 +40,11 @@ func mockTableInfo(t *testing.T, sql string) *common.TableInfo { return common.WrapTableInfo("db", rawTi) } +func mockRoutedTableInfo(t *testing.T, createTableSQL, targetSchema, targetTable string) (*common.TableInfo, *common.TableInfo) { + sourceTableInfo := mockTableInfo(t, createTableSQL) + return sourceTableInfo, sourceTableInfo.CloneWithRouting(targetSchema, targetTable) +} + type dpanicSuite struct { suite.Suite } @@ -92,6 +97,34 @@ func TestNewRowChange(t *testing.T) { require.Equal(t, expected, actual) } +func TestGenSQLUsesRoutedTargetTable(t *testing.T) { + sourceTableInfo, routedTableInfo := mockRoutedTableInfo( + t, + "CREATE TABLE tb1 (id INT PRIMARY KEY, name INT)", + "target_db", + "target_tb", + ) + + sourceTable := &sourceTableInfo.TableName + targetTable := &routedTableInfo.TableName + + insertChange := NewRowChange(sourceTable, targetTable, nil, []interface{}{1, 2}, sourceTableInfo, routedTableInfo, nil) + insertSQL, _ := insertChange.GenSQL(DMLInsert) + require.Contains(t, insertSQL, "`target_db`.`target_tb`") + require.NotContains(t, insertSQL, "`db`.`tb1`") + require.Equal(t, "`target_db`.`target_tb`", insertChange.TargetTableID()) + + deleteChange := NewRowChange(sourceTable, targetTable, []interface{}{1, 2}, nil, sourceTableInfo, routedTableInfo, nil) + deleteSQL, _ := deleteChange.GenSQL(DMLDelete) + require.Contains(t, deleteSQL, "DELETE FROM `target_db`.`target_tb`") + require.NotContains(t, deleteSQL, "`db`.`tb1`") + + updateChange := NewRowChange(sourceTable, targetTable, []interface{}{1, 2}, []interface{}{1, 3}, sourceTableInfo, routedTableInfo, nil) + updateSQL, _ := updateChange.GenSQL(DMLUpdate) + require.Contains(t, updateSQL, "UPDATE `target_db`.`target_tb`") + require.NotContains(t, updateSQL, "`db`.`tb1`") +} + func (s *dpanicSuite) TestRowChangeType() { change := &RowChange{preValues: []interface{}{1}} change.calculateType() diff --git a/tests/integration_tests/api_v2/model.go b/tests/integration_tests/api_v2/model.go index 59d2b9f3ad..14e2c2e90c 100644 --- a/tests/integration_tests/api_v2/model.go +++ b/tests/integration_tests/api_v2/model.go @@ -256,6 +256,8 @@ type DispatchRule struct { TopicRule string `json:"topic"` IndexName string `json:"index,omitempty"` Columns []string `json:"columns,omitempty"` + TargetSchema string `json:"target-schema,omitempty"` + TargetTable string `json:"target-table,omitempty"` } // ColumnSelector represents a column selector for a table. diff --git a/tests/integration_tests/common_1/data/test.sql b/tests/integration_tests/common_1/data/test.sql index 47ae223f7e..67340db829 100644 --- a/tests/integration_tests/common_1/data/test.sql +++ b/tests/integration_tests/common_1/data/test.sql @@ -88,6 +88,11 @@ SELECT * FROM t1 WHERE c1 > 2; +CREATE TABLE users +( + id INT PRIMARY KEY +); + -- uk without pk -- https://internal.pingcap.net/jira/browse/TOOL-714 -- CDC don't support UK is null diff --git a/tests/integration_tests/common_1/data/test_finish.sql b/tests/integration_tests/common_1/data/test_finish.sql index 1e55f56d53..d8a8f4e043 100644 --- a/tests/integration_tests/common_1/data/test_finish.sql +++ b/tests/integration_tests/common_1/data/test_finish.sql @@ -2,6 +2,10 @@ USE common_1; create database common; +CREATE VIEW common.v AS +SELECT id +FROM users; + create table a (a bigint primary key, b int); create table b like a; rename table a to common.c, b to a, common.c to b; diff --git a/tests/integration_tests/common_1/run.sh b/tests/integration_tests/common_1/run.sh index 8f5e42cea6..d12ef272ca 100755 --- a/tests/integration_tests/common_1/run.sh +++ b/tests/integration_tests/common_1/run.sh @@ -65,6 +65,8 @@ EOF # sync_diff can't check non-exist table, so we check expected tables are created in downstream first check_table_exists common_1.v1 ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} + check_table_exists common_1.users ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} + check_table_exists common.v ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} check_table_exists common_1.recover_and_insert ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} check_table_exists common_1.finish_mark ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} check_sync_diff $WORK_DIR $CUR/conf/diff_config.toml diff --git a/tests/integration_tests/consistent_replicate_ddl/run.sh b/tests/integration_tests/consistent_replicate_ddl/run.sh index 8d3969507d..2ae592cd3f 100755 --- a/tests/integration_tests/consistent_replicate_ddl/run.sh +++ b/tests/integration_tests/consistent_replicate_ddl/run.sh @@ -38,6 +38,14 @@ function run() { run_sql "CREATE TABLE consistent_replicate_ddl.usertable2 like consistent_replicate_ddl.usertable" ${UP_TIDB_HOST} ${UP_TIDB_PORT} run_sql "CREATE TABLE consistent_replicate_ddl.usertable3 like consistent_replicate_ddl.usertable" ${UP_TIDB_HOST} ${UP_TIDB_PORT} run_sql "CREATE TABLE consistent_replicate_ddl.usertable_bak like consistent_replicate_ddl.usertable" ${UP_TIDB_HOST} ${UP_TIDB_PORT} + run_sql "CREATE DATABASE consistent_replicate_ddl_like_src" ${UP_TIDB_HOST} ${UP_TIDB_PORT} + run_sql "CREATE TABLE consistent_replicate_ddl_like_src.src (id INT PRIMARY KEY, value VARCHAR(32))" ${UP_TIDB_HOST} ${UP_TIDB_PORT} + run_sql "USE consistent_replicate_ddl_like_src; CREATE TABLE consistent_replicate_ddl.table_cross_db_like_dst LIKE src" ${UP_TIDB_HOST} ${UP_TIDB_PORT} + run_sql "CREATE TABLE consistent_replicate_ddl_like_src.src_partition (id INT PRIMARY KEY, value VARCHAR(32)) PARTITION BY RANGE (id) (PARTITION p0 VALUES LESS THAN (10), PARTITION p1 VALUES LESS THAN (MAXVALUE))" ${UP_TIDB_HOST} ${UP_TIDB_PORT} + run_sql "USE consistent_replicate_ddl_like_src; CREATE TABLE consistent_replicate_ddl.table_cross_db_partition_like_dst LIKE src_partition" ${UP_TIDB_HOST} ${UP_TIDB_PORT} + run_sql "INSERT INTO consistent_replicate_ddl.table_cross_db_partition_like_dst VALUES (1, 'before truncate'), (11, 'p1')" ${UP_TIDB_HOST} ${UP_TIDB_PORT} + run_sql "ALTER TABLE consistent_replicate_ddl.table_cross_db_partition_like_dst TRUNCATE PARTITION p0" ${UP_TIDB_HOST} ${UP_TIDB_PORT} + run_sql "INSERT INTO consistent_replicate_ddl.table_cross_db_partition_like_dst VALUES (2, 'after truncate')" ${UP_TIDB_HOST} ${UP_TIDB_PORT} for i in {1..100}; do run_sql "CREATE TABLE IF NOT EXISTS consistent_replicate_ddl.table_$i (id INT AUTO_INCREMENT PRIMARY KEY, data VARCHAR(255));" ${UP_TIDB_HOST} ${UP_TIDB_PORT} done @@ -45,6 +53,8 @@ function run() { check_table_exists "consistent_replicate_ddl.usertable2" ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} 120 check_table_exists "consistent_replicate_ddl.usertable3" ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} 120 check_table_exists "consistent_replicate_ddl.usertable_bak" ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} 120 + check_table_exists "consistent_replicate_ddl.table_cross_db_like_dst" ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} 120 + check_table_exists "consistent_replicate_ddl.table_cross_db_partition_like_dst" ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} 120 for i in {1..100}; do check_table_exists "consistent_replicate_ddl.table_$i" ${DOWN_TIDB_HOST} ${DOWN_TIDB_PORT} 120 done diff --git a/tests/integration_tests/run_light_it_in_ci.sh b/tests/integration_tests/run_light_it_in_ci.sh index cdc0ffa376..c61f608a1b 100755 --- a/tests/integration_tests/run_light_it_in_ci.sh +++ b/tests/integration_tests/run_light_it_in_ci.sh @@ -48,7 +48,7 @@ mysql_groups=( # G07 'http_api_tls_with_user_auth fail_over_ddl_H changefeed_update_config synced_status_with_redo' # G08 - 'capture_session_done_during_task changefeed_dup_error_restart mysql_sink_retry fail_over_ddl_I' + 'capture_session_done_during_task changefeed_dup_error_restart mysql_sink_retry fail_over_ddl_I table_route' # G09 'sequence cdc_server_tips ddl_sequence server_config_compatibility log_redaction fail_over_ddl_J' # G10 diff --git a/tests/integration_tests/table_route/conf/changefeed.toml b/tests/integration_tests/table_route/conf/changefeed.toml new file mode 100644 index 0000000000..0e9f9193b9 --- /dev/null +++ b/tests/integration_tests/table_route/conf/changefeed.toml @@ -0,0 +1,18 @@ +# Changefeed configuration for table route integration test +# This tests schema and table routing for MySQL sinks + +[filter] +rules = ['source_db.*', 'source_extra_db.*'] + +[sink] +# Dispatch rules with schema and table routing +# Route source_db.* to target_db.* with table suffix "_routed" +[[sink.dispatchers]] +matcher = ['source_db.*'] +target-schema = 'target_db' +target-table = '{table}_routed' + +[[sink.dispatchers]] +matcher = ['source_extra_db.*'] +target-schema = 'target_extra_db' +target-table = '{table}_routed' diff --git a/tests/integration_tests/table_route/conf/diff_config.toml b/tests/integration_tests/table_route/conf/diff_config.toml new file mode 100644 index 0000000000..4eaeea70a8 --- /dev/null +++ b/tests/integration_tests/table_route/conf/diff_config.toml @@ -0,0 +1,160 @@ +# diff Configuration. + +check-thread-count = 4 + +export-fix-sql = true + +check-struct-only = false + +[task] + output-dir = "/tmp/tidb_cdc_test/table_route/sync_diff/output" + + source-instances = ["tidb0"] + + target-instance = "mysql1" + + target-check-tables = [ + "target_db.users_routed", + "target_db.orders_routed", + "target_db.products_routed", + "target_db.products_backup_routed", + "target_db.renamed_table_routed", + "target_db.multi_rename_a_new_routed", + "target_db.multi_rename_b_new_routed", + "target_db.partitioned_events_routed", + "target_db.truncate_test_routed", + "target_db.finish_mark_routed", + "target_db.exchange_partitioned_routed", + "target_extra_db.exchange_normal_routed", + "target_extra_db.external_users_routed", + "target_extra_db.external_users_from_default_routed", + "target_extra_db.cross_move_target_routed", + "target_extra_db.partitioned_events_like_from_default_routed", + ] + +[data-sources] +[data-sources.tidb0] + host = "127.0.0.1" + port = 4000 + user = "root" + password = "" + route-rules = [ + "users", + "orders", + "products", + "products_backup", + "renamed_table", + "multi_rename_a_new", + "multi_rename_b_new", + "partitioned_events", + "truncate_test", + "finish_mark", + "exchange_partitioned", + "exchange_normal", + "external_users", + "external_users_from_default", + "cross_move_target", + "partitioned_events_like_from_default", + ] + +[data-sources.mysql1] + host = "127.0.0.1" + port = 3306 + user = "root" + password = "" + +[routes.users] +schema-pattern = "source_db" +table-pattern = "users" +target-schema = "target_db" +target-table = "users_routed" + +[routes.orders] +schema-pattern = "source_db" +table-pattern = "orders" +target-schema = "target_db" +target-table = "orders_routed" + +[routes.products] +schema-pattern = "source_db" +table-pattern = "products" +target-schema = "target_db" +target-table = "products_routed" + +[routes.products_backup] +schema-pattern = "source_db" +table-pattern = "products_backup" +target-schema = "target_db" +target-table = "products_backup_routed" + +[routes.renamed_table] +schema-pattern = "source_db" +table-pattern = "renamed_table" +target-schema = "target_db" +target-table = "renamed_table_routed" + +[routes.multi_rename_a_new] +schema-pattern = "source_db" +table-pattern = "multi_rename_a_new" +target-schema = "target_db" +target-table = "multi_rename_a_new_routed" + +[routes.multi_rename_b_new] +schema-pattern = "source_db" +table-pattern = "multi_rename_b_new" +target-schema = "target_db" +target-table = "multi_rename_b_new_routed" + +[routes.partitioned_events] +schema-pattern = "source_db" +table-pattern = "partitioned_events" +target-schema = "target_db" +target-table = "partitioned_events_routed" + +[routes.truncate_test] +schema-pattern = "source_db" +table-pattern = "truncate_test" +target-schema = "target_db" +target-table = "truncate_test_routed" + +[routes.finish_mark] +schema-pattern = "source_db" +table-pattern = "finish_mark" +target-schema = "target_db" +target-table = "finish_mark_routed" + +[routes.external_users] +schema-pattern = "source_extra_db" +table-pattern = "external_users" +target-schema = "target_extra_db" +target-table = "external_users_routed" + +[routes.external_users_from_default] +schema-pattern = "source_extra_db" +table-pattern = "external_users_from_default" +target-schema = "target_extra_db" +target-table = "external_users_from_default_routed" + +[routes.cross_move_target] +schema-pattern = "source_extra_db" +table-pattern = "cross_move_target" +target-schema = "target_extra_db" +target-table = "cross_move_target_routed" + +[routes.partitioned_events_like_from_default] +schema-pattern = "source_extra_db" +table-pattern = "partitioned_events_like_from_default" +target-schema = "target_extra_db" +target-table = "partitioned_events_like_from_default_routed" + +[routes.exchange_partitioned] +schema-pattern = "source_db" +table-pattern = "exchange_partitioned" +target-schema = "target_db" +target-table = "exchange_partitioned_routed" + +[routes.exchange_normal] +schema-pattern = "source_extra_db" +table-pattern = "exchange_normal" +target-schema = "target_extra_db" +target-table = "exchange_normal_routed" diff --git a/tests/integration_tests/table_route/data/cte_query.sql b/tests/integration_tests/table_route/data/cte_query.sql new file mode 100644 index 0000000000..f3b8b21349 --- /dev/null +++ b/tests/integration_tests/table_route/data/cte_query.sql @@ -0,0 +1,2 @@ +SELECT 'cte', id FROM cte_view_routed ORDER BY id; +SELECT 'shadow', id FROM cte_shadow_view_routed ORDER BY id; diff --git a/tests/integration_tests/table_route/data/exchange_partition.sql b/tests/integration_tests/table_route/data/exchange_partition.sql new file mode 100644 index 0000000000..499329360b --- /dev/null +++ b/tests/integration_tests/table_route/data/exchange_partition.sql @@ -0,0 +1,6 @@ +ALTER TABLE source_db.exchange_partitioned + EXCHANGE PARTITION p0 WITH TABLE source_extra_db.exchange_normal; + +-- Both directions must continue using the current source table's route. +INSERT INTO source_db.exchange_partitioned VALUES (3, 'partition_after'); +INSERT INTO source_extra_db.exchange_normal VALUES (4, 'normal_after'); diff --git a/tests/integration_tests/table_route/data/test.sql b/tests/integration_tests/table_route/data/test.sql new file mode 100644 index 0000000000..001a6d6b70 --- /dev/null +++ b/tests/integration_tests/table_route/data/test.sql @@ -0,0 +1,273 @@ +-- Test mixed DDL and DML operations for table route. +DROP DATABASE IF EXISTS source_db; +DROP DATABASE IF EXISTS source_extra_db; +CREATE DATABASE source_db; +CREATE DATABASE source_extra_db; +USE source_db; + +-- ============================================ +-- DDL: CREATE TABLE with initial DML +-- ============================================ +CREATE TABLE users ( + id INT PRIMARY KEY, + name VARCHAR(100), + email VARCHAR(100) +); + +CREATE TABLE orders ( + id INT PRIMARY KEY, + user_id INT, + amount DECIMAL(10, 2) +); + +INSERT INTO users VALUES (1, 'Alice', 'alice@example.com'); +INSERT INTO users VALUES (2, 'Bob', 'bob@example.com'); + +INSERT INTO orders VALUES (1, 1, 100.00); +INSERT INTO orders VALUES (2, 2, 200.00); + +-- ============================================ +-- DML: INSERT more data +-- ============================================ +INSERT INTO users VALUES (3, 'Charlie', 'charlie@example.com'); +INSERT INTO orders VALUES (3, 3, 300.00); + +-- ============================================ +-- DML: UPDATE data +-- ============================================ +UPDATE users SET email = 'alice_updated@example.com' WHERE id = 1; +UPDATE orders SET amount = 150.00 WHERE id = 1; + +-- ============================================ +-- DML: DELETE data +-- ============================================ +DELETE FROM orders WHERE id = 2; + +-- ============================================ +-- DDL: ALTER TABLE ADD COLUMN +-- ============================================ +ALTER TABLE users ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP; + +-- ============================================ +-- DDL: CREATE TABLE (new table should be routed) +-- ============================================ +CREATE TABLE products ( + id INT PRIMARY KEY, + name VARCHAR(100), + price DECIMAL(10, 2) +); + +-- Widget starts at 29.99 (>= 15.00), so DELETE WHERE price < 15.00 won't affect it +-- unless the UPDATE (price = 12.99) is applied first +INSERT INTO products VALUES (1, 'Widget', 29.99); +INSERT INTO products VALUES (2, 'Gadget', 19.99); + +-- ============================================ +-- DDL: CREATE TABLE LIKE +-- ============================================ +CREATE TABLE products_backup LIKE products; + +INSERT INTO products_backup VALUES (1, 'Widget', 29.99); + +-- ============================================ +-- DDL: ALTER TABLE DROP COLUMN +-- ============================================ +ALTER TABLE users DROP COLUMN created_at; + +-- ============================================ +-- DDL: ALTER TABLE ADD INDEX +-- ============================================ +ALTER TABLE orders ADD INDEX idx_user_id (user_id); + +-- ============================================ +-- DDL: CROSS DATABASE +-- ============================================ +CREATE TABLE `source_extra_db`.`external_users` LIKE `source_db`.`users`; +INSERT INTO `source_extra_db`.`external_users` + SELECT `id`, `name`, `email` FROM `source_db`.`users` WHERE `id` <= 2; +UPDATE `source_extra_db`.`external_users` SET `email` = 'external_alice@example.com' WHERE `id` = 1; + +-- The referenced table `users` is unqualified. It must be resolved with the +-- session default schema `source_db`, not the explicit target table schema +-- `source_extra_db`. +CREATE TABLE `source_extra_db`.`external_users_from_default` LIKE `users`; +INSERT INTO `source_extra_db`.`external_users_from_default` + SELECT `id`, `name`, `email` FROM `source_db`.`users` WHERE `id` IN (1, 3); +UPDATE `source_extra_db`.`external_users_from_default` SET `email` = 'default_charlie@example.com' WHERE `id` = 3; + +-- The view target is in `source_extra_db`, but the unqualified source table +-- must be resolved from the session default schema `source_db`. +CREATE VIEW `source_extra_db`.`users_view_from_default` AS + SELECT `id`, `name`, `email` FROM `users` WHERE `id` <= 2; + +-- TiDB stores the FROM table as `source_db`.`orders`, but keeps the table +-- qualifier `orders`.`id` unless CDC normalizes it before table routing. +CREATE VIEW `source_extra_db`.`orders_column_view_from_default` AS + SELECT `orders`.`id`, `orders`.`amount` FROM `orders` WHERE `orders`.`id` IN (1, 3); + +-- The inner SELECT references the unaliased outer users table. Routing must +-- resolve this correlated column through the outer SELECT scope. +CREATE VIEW `source_extra_db`.`correlated_users_view` AS + SELECT `users`.`id` FROM `users` + WHERE EXISTS ( + SELECT 1 FROM `orders` WHERE `orders`.`user_id` = `users`.`id` + ); + +CREATE TABLE `source_db`.`cross_move_source` ( + id INT PRIMARY KEY, + value VARCHAR(50) +); +INSERT INTO `source_db`.`cross_move_source` VALUES (1, 'move_source'); +RENAME TABLE `source_db`.`cross_move_source` TO `source_extra_db`.`cross_move_target`; +INSERT INTO `source_extra_db`.`cross_move_target` VALUES (2, 'move_target'); + +-- ============================================ +-- DDL: RENAME TABLE +-- ============================================ +CREATE TABLE temp_table ( + id INT PRIMARY KEY, + value VARCHAR(50) +); +INSERT INTO temp_table VALUES (1, 'test'); + +RENAME TABLE temp_table TO renamed_table; + +-- Verify renamed table works with DML +INSERT INTO renamed_table VALUES (2, 'test2'); +UPDATE renamed_table SET value = 'updated' WHERE id = 1; + +-- ============================================ +-- DDL: RENAME TABLE with multiple table pairs +-- ============================================ +CREATE TABLE multi_rename_a ( + id INT PRIMARY KEY, + value VARCHAR(50) +); +CREATE TABLE multi_rename_b ( + id INT PRIMARY KEY, + value VARCHAR(50) +); +INSERT INTO multi_rename_a VALUES (1, 'a'); +INSERT INTO multi_rename_b VALUES (1, 'b'); + +RENAME TABLE multi_rename_a TO multi_rename_a_new, multi_rename_b TO multi_rename_b_new; + +INSERT INTO multi_rename_a_new VALUES (2, 'a2'); +UPDATE multi_rename_b_new SET value = 'b2' WHERE id = 1; + +-- ============================================ +-- DDL: CREATE VIEW and DROP VIEW +-- ============================================ +CREATE VIEW `source_db`.`user_order_view` AS + SELECT `u`.`id`, `u`.`name`, `o`.`amount` + FROM `source_db`.`users` AS `u` + JOIN `source_db`.`orders` AS `o` ON `u`.`id` = `o`.`user_id`; + +CREATE VIEW `source_db`.`transient_view` AS + SELECT `id`, `name` FROM `source_db`.`users`; + +DROP VIEW `source_db`.`transient_view`; + +-- CTE references must retain their names while the underlying users table is routed. +CREATE VIEW source_db.cte_view AS + WITH selected_users AS (SELECT id FROM users WHERE id <= 2) + SELECT id FROM selected_users; + +-- The CTE shadows the real orders table, whose rows differ from users. +CREATE VIEW source_db.cte_shadow_view AS + WITH orders AS (SELECT id FROM users WHERE id <= 2) + SELECT id FROM orders; + +-- ============================================ +-- DDL: PARTITION TABLE +-- ============================================ +CREATE TABLE partitioned_events ( + id INT, + bucket INT NOT NULL, + value VARCHAR(50), + PRIMARY KEY (id, bucket) +) PARTITION BY RANGE (bucket) ( + PARTITION p0 VALUES LESS THAN (10), + PARTITION p1 VALUES LESS THAN (20) +); + +INSERT INTO partitioned_events VALUES (1, 5, 'p0'); +INSERT INTO partitioned_events VALUES (2, 15, 'p1'); +ALTER TABLE partitioned_events ADD PARTITION (PARTITION p2 VALUES LESS THAN (30)); +INSERT INTO partitioned_events VALUES (3, 25, 'p2'); +ALTER TABLE partitioned_events TRUNCATE PARTITION p0; +INSERT INTO partitioned_events VALUES (4, 6, 'p0_after_truncate'); +ALTER TABLE partitioned_events DROP PARTITION p1; +INSERT INTO partitioned_events VALUES (5, 26, 'p2_more'); + +-- Partitioned CREATE TABLE ... LIKE with an unqualified source table should +-- resolve the LIKE source from `source_db`, not from `source_extra_db`. +CREATE TABLE `source_extra_db`.`partitioned_events_like_from_default` LIKE `partitioned_events`; +INSERT INTO `source_extra_db`.`partitioned_events_like_from_default` VALUES (6, 6, 'like_p0'); +INSERT INTO `source_extra_db`.`partitioned_events_like_from_default` VALUES (7, 27, 'like_p2'); + +-- ============================================ +-- DDL: TRUNCATE TABLE +-- ============================================ +CREATE TABLE truncate_test ( + id INT PRIMARY KEY, + data VARCHAR(100) +); +INSERT INTO truncate_test VALUES (1, 'will be truncated'); +INSERT INTO truncate_test VALUES (2, 'also truncated'); + +TRUNCATE TABLE truncate_test; + +-- Insert new data after truncate +INSERT INTO truncate_test VALUES (10, 'after truncate'); + +-- ============================================ +-- DDL: DROP TABLE +-- ============================================ +CREATE TABLE to_be_dropped ( + id INT PRIMARY KEY +); +INSERT INTO to_be_dropped VALUES (1); + +DROP TABLE to_be_dropped; + +-- ============================================ +-- Mixed operations on existing tables +-- ============================================ +-- More inserts +INSERT INTO users VALUES (4, 'Diana', 'diana@example.com'); +INSERT INTO users VALUES (5, 'Eve', 'eve@example.com'); + +-- Batch update +UPDATE users SET name = CONCAT(name, '_v2') WHERE id IN (3, 4); + +-- More deletes +DELETE FROM users WHERE id = 5; + +-- Update with multiple columns +UPDATE products SET name = 'Super Widget', price = 12.99 WHERE id = 1; + +-- Delete with condition +DELETE FROM products WHERE price < 15.00; + +-- Prepare both sides of EXCHANGE PARTITION. The MySQL case waits for the +-- initial sync-diff before executing exchange_partition.sql. +CREATE TABLE source_db.exchange_partitioned ( + id INT PRIMARY KEY, + note VARCHAR(64) +) PARTITION BY RANGE (id) ( + PARTITION p0 VALUES LESS THAN (100), + PARTITION p1 VALUES LESS THAN MAXVALUE +); +CREATE TABLE source_extra_db.exchange_normal ( + id INT PRIMARY KEY, + note VARCHAR(64) +); +INSERT INTO source_db.exchange_partitioned VALUES (1, 'partition_before'); +INSERT INTO source_extra_db.exchange_normal VALUES (2, 'normal_before'); + +-- ============================================ +-- Create finish marker table +-- ============================================ +CREATE TABLE finish_mark (id INT PRIMARY KEY); +INSERT INTO finish_mark VALUES (1); diff --git a/tests/integration_tests/table_route/run.sh b/tests/integration_tests/table_route/run.sh new file mode 100755 index 0000000000..eec472179d --- /dev/null +++ b/tests/integration_tests/table_route/run.sh @@ -0,0 +1,86 @@ +#!/bin/bash + +set -eu + +CUR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +source "$CUR/../_utils/test_prepare" +WORK_DIR="$OUT_DIR/$TEST_NAME" +CDC_BINARY=cdc.test +SINK_TYPE="$1" + +function run() { + if [ "$SINK_TYPE" != "mysql" ]; then + return + fi + + rm -rf "$WORK_DIR" && mkdir -p "$WORK_DIR" + + start_tidb_cluster --workdir "$WORK_DIR" + + run_cdc_server --workdir "$WORK_DIR" --binary "$CDC_BINARY" --cluster-id "$KEYSPACE_NAME" + + SINK_URI="mysql://normal:123456@${DOWN_TIDB_HOST}:${DOWN_TIDB_PORT}/" + cdc_cli_changefeed create --sink-uri="$SINK_URI" --config="$CUR/conf/changefeed.toml" + + run_sql_file "$CUR/data/test.sql" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + + check_table_exists target_db.finish_mark_routed "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" 90 + check_sync_diff "$WORK_DIR" "$CUR/conf/diff_config.toml" 120 + + check_table_not_exists source_db.users "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_table_not_exists source_db.orders "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_table_not_exists source_extra_db.external_users "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_table_not_exists source_extra_db.external_users_from_default "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_table_not_exists source_extra_db.users_view_from_default "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_table_not_exists source_extra_db.orders_column_view_from_default "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_table_not_exists source_extra_db.partitioned_events_like_from_default "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_table_not_exists target_db.temp_table_routed "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_table_not_exists target_db.cross_move_source_routed "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_table_not_exists target_db.multi_rename_a_routed "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_table_not_exists target_db.multi_rename_b_routed "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_table_not_exists target_db.to_be_dropped_routed "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + run_sql "SHOW CREATE VIEW target_db.user_order_view_routed" "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_contains "user_order_view_routed" + check_contains "users_routed" + check_contains "orders_routed" + run_sql "SHOW CREATE VIEW target_extra_db.users_view_from_default_routed" "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_contains "users_view_from_default_routed" + check_contains "target_db" + check_contains "users_routed" + run_sql "SHOW CREATE VIEW target_extra_db.orders_column_view_from_default_routed" "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_contains "orders_column_view_from_default_routed" + check_contains 'target_db`.`orders_routed`.`id' + check_contains 'FROM `target_db`.`orders_routed`' + check_table_not_exists source_extra_db.correlated_users_view "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + run_sql "SHOW CREATE VIEW target_extra_db.correlated_users_view_routed" "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_contains 'target_db`.`orders_routed`.`user_id' + check_contains 'target_db`.`users_routed`.`id' + # Users 2 and 4 have no orders: the result also detects a lost correlation. + run_sql "SELECT GROUP_CONCAT(id ORDER BY id) AS matched_ids FROM source_extra_db.correlated_users_view" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + check_contains 'matched_ids: 1,3' + run_sql "SELECT GROUP_CONCAT(id ORDER BY id) AS matched_ids FROM target_extra_db.correlated_users_view_routed" "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + check_contains 'matched_ids: 1,3' + check_table_not_exists target_db.transient_view_routed "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" + + # Compare actual CTE results, including a CTE that shadows a physical table. + sed 's/_routed//g' "$CUR/data/cte_query.sql" | + mysql -uroot -h"$UP_TIDB_HOST" -P"$UP_TIDB_PORT" -Dsource_db -N -B >"$WORK_DIR/cte_upstream.txt" + mysql -uroot -h"$DOWN_TIDB_HOST" -P"$DOWN_TIDB_PORT" -Dtarget_db -N -B \ + <"$CUR/data/cte_query.sql" >"$WORK_DIR/cte_downstream.txt" + diff -u "$WORK_DIR/cte_upstream.txt" "$WORK_DIR/cte_downstream.txt" + + run_sql_file "$CUR/data/exchange_partition.sql" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + check_sync_diff "$WORK_DIR" "$CUR/conf/diff_config.toml" 120 + + run_sql "DROP DATABASE source_extra_db" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + run_sql "DROP DATABASE source_db" "$UP_TIDB_HOST" "$UP_TIDB_PORT" + check_db_not_exists target_extra_db "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" 90 + check_db_not_exists target_db "$DOWN_TIDB_HOST" "$DOWN_TIDB_PORT" 90 + + cleanup_process "$CDC_BINARY" +} + +trap 'stop_test "$WORK_DIR"' EXIT +run "$@" +check_logs "$WORK_DIR" +echo "[$(date)] <<<<<< run test case $TEST_NAME success! >>>>>>" diff --git a/tests/utils/checksum_checker/main.go b/tests/utils/checksum_checker/main.go index c9df72c330..14b1e48d03 100644 --- a/tests/utils/checksum_checker/main.go +++ b/tests/utils/checksum_checker/main.go @@ -26,6 +26,7 @@ import ( "github.com/pingcap/ticdc/downstreamadapter/sink/columnselector" "github.com/pingcap/ticdc/pkg/config" "github.com/pingcap/ticdc/pkg/errors" + putil "github.com/pingcap/ticdc/pkg/util" "github.com/pingcap/tidb/pkg/meta/model" "github.com/pingcap/tidb/pkg/parser/ast" "go.uber.org/zap" @@ -84,7 +85,7 @@ func main() { } } - columnFilter, err := columnselector.New(replicaConfig.Sink) + columnFilter, err := columnselector.New(replicaConfig.Sink, putil.GetOrZero(replicaConfig.CaseSensitive)) if err != nil { log.Panic("cannot create column filter", zap.Error(err)) }