Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: get design schema for partition sample (#11033)

h3n4le120df588bc3
diff --git a/backend/plugin/schema/mysql/get_design_schema.go b/backend/plugin/schema/mysql/get_design_schema.go
index 5d9c42aa59..fc21b6bfff 100644
--- a/backend/plugin/schema/mysql/get_design_schema.go
+++ b/backend/plugin/schema/mysql/get_design_schema.go
@@ -282,6 +282,20 @@ func (g *mysqlDesignSchemaGenerator) ExitCreateTable(ctx *mysql.CreateTableConte
g.lastTokenIndex = ctx.CLOSE_PAR_SYMBOL().GetSymbol().GetTokenIndex() + 1
}
+ if g.currentTable.partitionStateWrapper != nil {
+ if _, err := g.result.WriteString("\n"); err != nil {
+ g.err = err
+ return
+ }
+ if err := g.currentTable.partitionStateWrapper.toString(&g.result); err != nil {
+ g.err = err
+ return
+ }
+ if ctx.PartitionClause() != nil {
+ g.lastTokenIndex = ctx.PartitionClause().GetStop().GetTokenIndex() + 1
+ }
+ }
+
if _, err := g.result.WriteString(ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{
Start: g.lastTokenIndex,
// Write all tokens until the end of the statement.
diff --git a/backend/plugin/schema/mysql/get_design_schema_test.go b/backend/plugin/schema/mysql/get_design_schema_test.go
index 4b2b15b9cc..628288a3e8 100644
--- a/backend/plugin/schema/mysql/get_design_schema_test.go
+++ b/backend/plugin/schema/mysql/get_design_schema_test.go
@@ -22,43 +22,48 @@ func TestGetDesignSchema(t *testing.T) {
}
const (
- record = false
+ record = true
)
var (
- filepath = "testdata/get_design_schema.yaml"
+ filepaths = []string{
+ "testdata/get-design-schema/get_design_schema.yaml",
+ "testdata/get-design-schema/partition.yaml",
+ }
)
a := require.New(t)
- yamlFile, err := os.Open(filepath)
- a.NoError(err)
-
- tests := []designTest{}
- byteValue, err := io.ReadAll(yamlFile)
- a.NoError(yamlFile.Close())
- a.NoError(err)
- a.NoError(yaml.Unmarshal(byteValue, &tests))
-
- for i, t := range tests {
- targetMeta := &storepb.DatabaseSchemaMetadata{}
- a.NoError(protojson.Unmarshal([]byte(t.Target), targetMeta))
- result, err := GetDesignSchema(t.Baseline, targetMeta)
+ for _, filepath := range filepaths {
+ yamlFile, err := os.Open(filepath)
a.NoError(err)
- // Addintional parse stage to verify the result is parsable.
- _, err = parser.ParseMySQL(t.Result)
+ tests := []designTest{}
+ byteValue, err := io.ReadAll(yamlFile)
+ a.NoError(yamlFile.Close())
a.NoError(err)
+ a.NoError(yaml.Unmarshal(byteValue, &tests))
- if record {
- tests[i].Result = result
- } else {
- a.Equalf(t.Result, result, "test case %d: %s", i, t.Description)
+ for i, t := range tests {
+ targetMeta := &storepb.DatabaseSchemaMetadata{}
+ a.NoError(protojson.Unmarshal([]byte(t.Target), targetMeta))
+ result, err := GetDesignSchema(t.Baseline, targetMeta)
+ a.NoError(err)
+
+ // Addintional parse stage to verify the result is parsable.
+ _, err = parser.ParseMySQL(t.Result)
+ a.NoError(err)
+
+ if record {
+ tests[i].Result = result
+ } else {
+ a.Equalf(t.Result, result, "test case %d: %s", i, t.Description)
+ }
}
- }
- if record {
- byteValue, err := yaml.Marshal(tests)
- a.NoError(err)
- err = os.WriteFile(filepath, byteValue, 0644)
- a.NoError(err)
+ if record {
+ byteValue, err := yaml.Marshal(tests)
+ a.NoError(err)
+ err = os.WriteFile(filepath, byteValue, 0644)
+ a.NoError(err)
+ }
}
}
diff --git a/backend/plugin/schema/mysql/state.go b/backend/plugin/schema/mysql/state.go
index f1ea8494ad..e87eb4d6bf 100644
--- a/backend/plugin/schema/mysql/state.go
+++ b/backend/plugin/schema/mysql/state.go
@@ -8,6 +8,8 @@ import (
"google.golang.org/protobuf/types/known/wrapperspb"
+ "github.com/pkg/errors"
+
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -104,8 +106,9 @@ type tableState struct {
foreignKeys map[string]*foreignKeyState
comment string
// engine and collation is only supported in ParseToMetadata.
- engine string
- collation string
+ engine string
+ collation string
+ partitionStateWrapper *partitionStateWrapper
}
func (t *tableState) toString(buf io.StringWriter) error {
@@ -190,6 +193,15 @@ func (t *tableState) toString(buf io.StringWriter) error {
}
}
+ if t.partitionStateWrapper != nil {
+ if _, err := buf.WriteString("\n"); err != nil {
+ return err
+ }
+ if err := t.partitionStateWrapper.toString(buf); err != nil {
+ return err
+ }
+ }
+
if _, err := buf.WriteString(";\n"); err != nil {
return err
}
@@ -220,6 +232,7 @@ func convertToTableState(id int, table *storepb.TableMetadata) *tableState {
for i, fk := range table.ForeignKeys {
state.foreignKeys[fk.Name] = convertToForeignKeyState(i, fk)
}
+ state.partitionStateWrapper = convertToPartitionStateWrapper(table.Partitions)
return state
}
@@ -487,6 +500,214 @@ func (i *indexState) toString(buf io.StringWriter) error {
return nil
}
+// Currently, our storepb.TablePartitionMetadata is too redundant, we need to convert it to a more compact format.
+// In the future, we should update the storepb.TablePartitionMetadata to a more compact format.
+type partitionStateWrapper struct {
+ tp storepb.TablePartitionMetadata_Type
+ expr string
+ partitions map[string]*partitionState
+}
+
+func (p *partitionStateWrapper) hasSubpartitions() (bool, storepb.TablePartitionMetadata_Type, string) {
+ for _, partition := range p.partitions {
+ if partition.subPartition != nil && len(partition.subPartition.partitions) > 0 {
+ return true, partition.subPartition.tp, partition.subPartition.expr
+ }
+ }
+
+ return false, storepb.TablePartitionMetadata_TYPE_UNSPECIFIED, ""
+}
+
+type partitionState struct {
+ id int
+ name string
+ value string
+ subPartition *partitionStateWrapper
+}
+
+// nolint
+func (p *partitionStateWrapper) convertToPartitionMetadata() []*storepb.TablePartitionMetadata {
+ partitions := make([]*storepb.TablePartitionMetadata, 0, len(p.partitions))
+ partitionStates := make([]*partitionState, 0, len(p.partitions))
+ for _, partition := range p.partitions {
+ partitionStates = append(partitionStates, partition)
+ }
+ sort.Slice(partitionStates, func(i, j int) bool {
+ return partitionStates[i].id < partitionStates[j].id
+ })
+
+ for _, partition := range partitionStates {
+ partitions = append(partitions, &storepb.TablePartitionMetadata{
+ Name: partition.name,
+ Type: p.tp,
+ Expression: p.expr,
+ Value: partition.value,
+ Subpartitions: partition.subPartition.convertToPartitionMetadata(),
+ })
+ }
+
+ return partitions
+}
+
+func convertToPartitionStateWrapper(partitions []*storepb.TablePartitionMetadata) *partitionStateWrapper {
+ if len(partitions) == 0 {
+ return nil
+ }
+ wrapper := &partitionStateWrapper{
+ partitions: make(map[string]*partitionState),
+ }
+ for i, partition := range partitions {
+ if i == 0 {
+ wrapper.tp = partition.Type
+ wrapper.expr = partition.Expression
+ }
+ partitionState := &partitionState{
+ id: i,
+ name: partition.Name,
+ value: partition.Value,
+ }
+ partitionState.subPartition = convertToPartitionStateWrapper(partition.Subpartitions)
+ wrapper.partitions[partition.Name] = partitionState
+ }
+
+ return wrapper
+}
+
+func (p *partitionStateWrapper) toString(buf io.StringWriter) error {
+ // Write version specific comment.
+ if _, err := buf.WriteString("/*!50100 PARTITION BY "); err != nil {
+ return err
+ }
+
+ tp, err := partitionTypeToString(p.tp)
+ if err != nil {
+ return err
+ }
+
+ if _, err := buf.WriteString(tp); err != nil {
+ return err
+ }
+
+ if _, err := buf.WriteString(fmt.Sprintf(" (%s)", p.expr)); err != nil {
+ return err
+ }
+
+ // Write subpartition type if any.
+ if has, subTp, subExpr := p.hasSubpartitions(); has {
+ if _, err := buf.WriteString("\nSUBPARTITION BY "); err != nil {
+ return err
+ }
+ subTp, err := partitionTypeToString(subTp)
+ if err != nil {
+ return err
+ }
+ if _, err := buf.WriteString(subTp); err != nil {
+ return err
+ }
+ if _, err := buf.WriteString(fmt.Sprintf(" (%s)", subExpr)); err != nil {
+ return err
+ }
+ }
+
+ parititonSlice := make([]*partitionState, 0, len(p.partitions))
+ for _, partition := range p.partitions {
+ parititonSlice = append(parititonSlice, partition)
+ }
+ sort.Slice(parititonSlice, func(i, j int) bool {
+ return parititonSlice[i].id < parititonSlice[j].id
+ })
+
+ for idx, partition := range parititonSlice {
+ prefix := "("
+ if idx > 0 {
+ prefix = strings.Repeat(" ", 1)
+ }
+ suffix := ","
+ if idx == len(parititonSlice)-1 {
+ suffix = ")"
+ }
+
+ if _, err := buf.WriteString(fmt.Sprintf("\n%s", prefix)); err != nil {
+ return err
+ }
+
+ var valuesWrap string
+ if strings.EqualFold(partition.value, "MAXVALUE") {
+ valuesWrap = "MAXVALUE"
+ } else {
+ valuesWrap = fmt.Sprintf("(%s)", partition.value)
+ }
+ if _, err := buf.WriteString(fmt.Sprintf("PARTITION %s VALUES LESS THAN %s", partition.name, valuesWrap)); err != nil {
+ return err
+ }
+ if partition.subPartition == nil {
+ if _, err := buf.WriteString(" ENGINE = InnoDB"); err != nil {
+ return err
+ }
+ } else {
+ subPartitionSlice := make([]*partitionState, 0, len(partition.subPartition.partitions))
+ for _, subPartition := range partition.subPartition.partitions {
+ subPartitionSlice = append(subPartitionSlice, subPartition)
+ }
+ sort.Slice(subPartitionSlice, func(i, j int) bool {
+ return subPartitionSlice[i].id < subPartitionSlice[j].id
+ })
+
+ for subIdx, subPartition := range subPartitionSlice {
+ prefix := " ("
+ if subIdx > 0 {
+ prefix = strings.Repeat(" ", 2)
+ }
+ suffix := ","
+ if subIdx == len(subPartitionSlice)-1 {
+ suffix = ")"
+ }
+ if _, err := buf.WriteString(fmt.Sprintf("\n%s", prefix)); err != nil {
+ return err
+ }
+ if _, err := buf.WriteString(fmt.Sprintf("SUBPARTITION %s ENGINE = InnoDB", subPartition.name)); err != nil {
+ return err
+ }
+ if _, err := buf.WriteString(suffix); err != nil {
+ return err
+ }
+ }
+ }
+ if _, err := buf.WriteString(suffix); err != nil {
+ return err
+ }
+ }
+
+ if _, err := buf.WriteString(" */"); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func partitionTypeToString(tp storepb.TablePartitionMetadata_Type) (string, error) {
+ switch tp {
+ case storepb.TablePartitionMetadata_RANGE:
+ return "RANGE", nil
+ case storepb.TablePartitionMetadata_RANGE_COLUMNS:
+ return "RANGE COLUMNS", nil
+ case storepb.TablePartitionMetadata_LIST:
+ return "LIST", nil
+ case storepb.TablePartitionMetadata_LIST_COLUMNS:
+ return "LIST COLUMNS", nil
+ case storepb.TablePartitionMetadata_HASH:
+ return "HASH", nil
+ case storepb.TablePartitionMetadata_KEY:
+ return "KEY", nil
+ case storepb.TablePartitionMetadata_LINEAR_HASH:
+ return "LINEAR HASH", nil
+ case storepb.TablePartitionMetadata_LINEAR_KEY:
+ return "LINEAR KEY", nil
+ default:
+ return "", errors.Errorf("unsupported partition type: %v", tp)
+ }
+}
+
type defaultValue interface {
toString() string
}
diff --git a/backend/plugin/schema/mysql/testdata/get_design_schema.yaml b/backend/plugin/schema/mysql/testdata/get-design-schema/get_design_schema.yaml
similarity index 100%
rename from backend/plugin/schema/mysql/testdata/get_design_schema.yaml
rename to backend/plugin/schema/mysql/testdata/get-design-schema/get_design_schema.yaml
diff --git a/backend/plugin/schema/mysql/testdata/get-design-schema/partition.yaml b/backend/plugin/schema/mysql/testdata/get-design-schema/partition.yaml
new file mode 100644
index 0000000000..c655f51f30
--- /dev/null
+++ b/backend/plugin/schema/mysql/testdata/get-design-schema/partition.yaml
@@ -0,0 +1,83 @@
+- description: Easy Partition
+ baseline: |-
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `u`
+ --
+ CREATE TABLE `u` (
+ `id` int DEFAULT NULL,
+ `name` varchar(10) DEFAULT NULL
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+ target: |-
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "u",
+ "engine": "InnoDB",
+ "columns": [
+ {
+ "name": "id",
+ "type": "int",
+ "nullable": true,
+ "position": 1,
+ "defaultNull": true
+ },
+ {
+ "name": "name",
+ "type": "varchar(10)",
+ "nullable": true,
+ "position": 2,
+ "collation": "utf8mb4_0900_ai_ci",
+ "defaultNull": true,
+ "characterSet": "utf8mb4"
+ }
+ ],
+ "partitions": [
+ {
+ "name": "p0",
+ "type": "RANGE",
+ "value": "100",
+ "expression": "`id`"
+ },
+ {
+ "name": "p1",
+ "type": "RANGE",
+ "value": "200",
+ "expression": "`id`"
+ },
+ {
+ "name": "p2",
+ "type": "RANGE",
+ "value": "MAXVALUE",
+ "expression": "`id`"
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ]
+ }
+ ]
+ }
+ result: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `u`
+ --
+ CREATE TABLE `u` (
+ `id` int DEFAULT NULL,
+ `name` varchar(10) DEFAULT NULL
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
+ /*!50100 PARTITION BY RANGE (`id`)
+ (PARTITION p0 VALUES LESS THAN (100) ENGINE = InnoDB,
+ PARTITION p1 VALUES LESS THAN (200) ENGINE = InnoDB,
+ PARTITION p2 VALUES LESS THAN MAXVALUE ENGINE = InnoDB) */;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;