Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore(mysql/structurer): better mysql get design schema syntax (#10276)
h3n4lc85fa46d1d1c
diff --git a/backend/plugin/schema/mysql/get_design_schema.go b/backend/plugin/schema/mysql/get_design_schema.goindex 15b9c9f796..06b7bea614 100644--- a/backend/plugin/schema/mysql/get_design_schema.go+++ b/backend/plugin/schema/mysql/get_design_schema.go@@ -2,6 +2,7 @@ package mysqlimport ("fmt"+ "io""slices""sort""strings"@@ -29,6 +30,7 @@ func GetDesignSchema(baselineSchema string, to *storepb.DatabaseSchemaMetadata)listener := &mysqlDesignSchemaGenerator{lastTokenIndex: 0,to: toState,+ desired: to,}for _, stmt := range list {@@ -51,39 +53,22 @@ func GetDesignSchema(baselineSchema string, to *storepb.DatabaseSchemaMetadata)return "", listener.err}- firstTable := true-- // Follow the order of the input schemas.- for _, schema := range to.Schemas {- schemaState, ok := toState.schemas[schema.Name]- if !ok {- continue- }- // Follow the order of the input tables.- for _, table := range schema.Tables {- table, ok := schemaState.tables[table.Name]- if !ok {- continue- }- if firstTable {- firstTable = false- if _, err := listener.result.WriteString("\n\n"); err != nil {- return "", err- }- }- if err := table.toString(&listener.result); err != nil {- return "", err- }- }- }-- // The last statement of the result is SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;- // We should append a 0xa to the end of the result to avoid the extra newline diff.- // TODO(rebelice/zp): find a more elegant way to do this.- if err := listener.result.WriteByte('\n'); err != nil {+ // Expectedly, EnterSetStatement is called when production setStatement is entered.+ // And we would like to generate the remaining tables before the set statement mentioned above.+ // But users can remove the set statement during the rebase process.+ if err := writeRemainingTables(&listener.result, to, toState); err != nil {return "", err}+ result := listener.result.String()+ if !strings.HasSuffix(result, "\n") {+ // The last statement of the result is SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;+ // We should append a 0xa to the end of the result to avoid the extra newline diff.+ // TODO(rebelice/zp): find a more elegant way to do this.+ if err := listener.result.WriteByte('\n'); err != nil {+ return "", err+ }+ }return listener.result.String(), nil}@@ -101,6 +86,8 @@ type mysqlDesignSchemaGenerator struct {lastTokenIndex inttableOptionTokenIndex int++ desired *storepb.DatabaseSchemaMetadata}// EnterCreateTable is called when production createTable is entered.@@ -882,3 +869,71 @@ func (g *mysqlDesignSchemaGenerator) EnterColumnDefinition(ctx *mysql.ColumnDefireturn}}++// EnterSetStatement is called when production setStatement is entered.+//+// mysqldump generate `SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;` statement at the end of the file,+// to provide the better user experience, we generate the remaining tables before the set statement mentioned above.+func (g *mysqlDesignSchemaGenerator) EnterSetStatement(ctx *mysql.SetStatementContext) {+ if g.err != nil {+ return+ }++ curSet := strings.TrimSpace(ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx))+ if curSet != `SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS` {+ return+ }++ if err := writeRemainingTables(&g.result, g.desired, g.to); err != nil {+ g.err = err+ return+ }+}++func writeRemainingTables(w io.StringWriter, to *storepb.DatabaseSchemaMetadata, state *databaseState) error {+ firstTable := true+ // Follow the order of the input schemas.+ for _, schema := range to.Schemas {+ schemaState, ok := state.schemas[schema.Name]+ if !ok {+ continue+ }+ // Follow the order of the input tables.+ for idx, table := range schema.Tables {+ table, ok := schemaState.tables[table.Name]+ if !ok {+ continue+ }+ if firstTable {+ firstTable = false+ if _, err := w.WriteString("\n"); err != nil {+ return err+ }+ }+ if _, err := w.WriteString(getTableAnnouncement(table.name)); err != nil {+ return err+ }++ // Avoid new line.+ buf := &strings.Builder{}+ if err := table.toString(buf); err != nil {+ return err+ }+ if idx == len(schema.Tables)-1 && buf.String()[len(buf.String())-1] == '\n' {+ if _, err := w.WriteString(buf.String()[:len(buf.String())-1]); err != nil {+ return err+ }+ } else {+ if _, err := w.WriteString(buf.String()); err != nil {+ return err+ }+ }+ delete(schemaState.tables, table.name)+ }+ }+ return nil+}++func getTableAnnouncement(name string) string {+ return fmt.Sprintf("\n--\n-- Table structure for table `%s`\n--\n", name)+}diff --git a/backend/plugin/schema/mysql/state.go b/backend/plugin/schema/mysql/state.goindex 6a6163e080..7bf879c0b2 100644--- a/backend/plugin/schema/mysql/state.go+++ b/backend/plugin/schema/mysql/state.go@@ -2,6 +2,7 @@ package mysqlimport ("fmt"+ "io""slices""sort""strings"@@ -104,7 +105,7 @@ type tableState struct {comment string}-func (t *tableState) toString(buf *strings.Builder) error {+func (t *tableState) toString(buf io.StringWriter) error {if _, err := buf.WriteString(fmt.Sprintf("CREATE TABLE `%s` (\n ", t.name)); err != nil {return err}@@ -278,7 +279,7 @@ func convertToForeignKeyState(id int, foreignKey *storepb.ForeignKeyMetadata) *f}}-func (f *foreignKeyState) toString(buf *strings.Builder) error {+func (f *foreignKeyState) toString(buf io.StringWriter) error {if _, err := buf.WriteString("CONSTRAINT `"); err != nil {return err}@@ -370,7 +371,7 @@ func convertToIndexState(id int, index *storepb.IndexMetadata) *indexState {}}-func (i *indexState) toString(buf *strings.Builder) error {+func (i *indexState) toString(buf io.StringWriter) error {if i.primary {if _, err := buf.WriteString("PRIMARY KEY ("); err != nil {return err@@ -487,7 +488,7 @@ type columnState struct {nullable bool}-func (c *columnState) toString(buf *strings.Builder) error {+func (c *columnState) toString(buf io.StringWriter) error {if _, err := buf.WriteString(fmt.Sprintf("`%s` %s", c.name, c.tp)); err != nil {return err}diff --git a/backend/plugin/schema/mysql/testdata/get_design_schema.yaml b/backend/plugin/schema/mysql/testdata/get_design_schema.yamlindex 1e88162f8e..bf07300623 100644--- a/backend/plugin/schema/mysql/testdata/get_design_schema.yaml+++ b/backend/plugin/schema/mysql/testdata/get_design_schema.yaml@@ -1,4 +1,9 @@- 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 `t`+ --CREATE TABLE `t` (`a` int,`b` text,@@ -8,6 +13,10 @@CREATE TABLE `t3` (`a` int);++ --+ -- Table structure for `t4`+ --CREATE TABLE `t4` (`a` int,`c` int,@@ -16,6 +25,9 @@PRIMARY KEY (`a`, `c`, `d`),CONSTRAINT fk1 FOREIGN KEY (`a`) REFERENCES `t2` (`b`));++ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;target: |-{"schemas": [@@ -234,7 +246,12 @@}]}- result: |++ 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 `t`+ --CREATE TABLE `t` (`a` int NOT NULL,`b` text,@@ -242,6 +259,10 @@`d` text DEFAULT (NULL),UNIQUE KEY `t_a_uniq_idx` (`a`) COMMENT 'this is my comment ''!!') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;++ --+ -- Table structure for `t4`+ --CREATE TABLE `t4` (`a` varchar(10) NOT NULL DEFAULT 'default value' COMMENT 'this is comment, aha',`c` int NOT NULL AUTO_INCREMENT,@@ -251,12 +272,19 @@CONSTRAINT `fk1` FOREIGN KEY (`b`) REFERENCES `t2` (`b`));+ --+ -- Table structure for table `t2`+ --CREATE TABLE `t2` (`b` int NULL,`a` int NULL,PRIMARY KEY (`b`),CONSTRAINT `fk1` FOREIGN KEY (`b`) REFERENCES `t4` (`b`));++ --+ -- Table structure for table `t5`+ --CREATE TABLE `t5` (`a` int NOT NULL COMMENT 'this is comment',`b` VARCHAR(20) NOT NULL,@@ -271,6 +299,8 @@KEY `t_d_fulltext_idx` (`d`)) COMMENT 'this is comment with '' escaped';+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;- baseline: |-CREATE TABLE `t` (`a` int