github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/dm/simulator/config/config.go (about)

     1  // Copyright 2022 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  // Package config is the configuration definitions used by the simulator.
    15  package config
    16  
    17  import (
    18  	"strconv"
    19  	"strings"
    20  
    21  	"github.com/pingcap/tidb/pkg/util/dbutil"
    22  )
    23  
    24  // TableConfig is the sub config for describing a simulating table in the data source.
    25  type TableConfig struct {
    26  	TableID              string              `yaml:"id"`
    27  	DatabaseName         string              `yaml:"db"`
    28  	TableName            string              `yaml:"table"`
    29  	Columns              []*ColumnDefinition `yaml:"columns"`
    30  	UniqueKeyColumnNames []string            `yaml:"unique_keys"`
    31  }
    32  
    33  // ColumnDefinition is the sub config for describing a column in a simulating table.
    34  type ColumnDefinition struct {
    35  	ColumnName string `yaml:"name"`
    36  	DataType   string `yaml:"type"`
    37  	DataLen    int    `yaml:"length"`
    38  }
    39  
    40  func (t *TableConfig) GenCreateTable() string {
    41  	var buf strings.Builder
    42  	buf.WriteString("CREATE TABLE ")
    43  	buf.WriteString(dbutil.TableName(t.DatabaseName, t.TableName))
    44  	buf.WriteByte('(')
    45  	for i, col := range t.Columns {
    46  		if i != 0 {
    47  			buf.WriteByte(',')
    48  		}
    49  		buf.WriteString(dbutil.ColumnName(col.ColumnName))
    50  		buf.WriteByte(' ')
    51  		buf.WriteString(col.DataType)
    52  		if col.DataLen > 0 {
    53  			buf.WriteByte('(')
    54  			buf.WriteString(strconv.Itoa(col.DataLen))
    55  			buf.WriteByte(')')
    56  		}
    57  	}
    58  	if len(t.UniqueKeyColumnNames) > 0 {
    59  		buf.WriteString(",UNIQUE KEY ")
    60  		buf.WriteString(dbutil.ColumnName(strings.Join(t.UniqueKeyColumnNames, "_")))
    61  		buf.WriteByte('(')
    62  		for i, ukColName := range t.UniqueKeyColumnNames {
    63  			if i != 0 {
    64  				buf.WriteString(",")
    65  			}
    66  			buf.WriteString(dbutil.ColumnName(ukColName))
    67  		}
    68  		buf.WriteByte(')')
    69  	}
    70  	buf.WriteByte(')')
    71  	return buf.String()
    72  }