Skip to content

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

feat: get design schema for mysql views (#11309)

h3n4l8ea38e59edea
diff --git a/backend/plugin/db/mysql/sync.go b/backend/plugin/db/mysql/sync.go
index b3dca347d2..66ecd81c33 100644
--- a/backend/plugin/db/mysql/sync.go
+++ b/backend/plugin/db/mysql/sync.go
@@ -54,6 +54,8 @@ var (
}
return strings.Join(l, ", ")
}()
+
+ viewDefMatcher = regexp.MustCompile("CREATE ALGORITHM=(UNDEFINED|MERGE|TEMPTABLE) DEFINER=`([^`]+)`@`([^`]+)` SQL SECURITY DEFINER VIEW `([^`]+)` AS (?P<def>.+)")
)
// SyncInstance syncs the instance.
@@ -310,6 +312,13 @@ func (driver *Driver) SyncDBSchema(ctx context.Context) (*storepb.DatabaseSchema
if err := viewRows.Err(); err != nil {
return nil, util.FormatErrorWithQuery(err, viewQuery)
}
+ for key := range viewMap {
+ def, err := driver.reconcileViewDefinition(ctx, driver.databaseName, key.Table)
+ if err != nil {
+ return nil, err
+ }
+ viewMap[key].Definition = def
+ }
// Query foreign key info.
foreignKeysMap, err := driver.getForeignKeyList(ctx, driver.databaseName)
@@ -483,6 +492,36 @@ func isCurrentTimestampLike(s string) bool {
return false
}
+func (driver *Driver) reconcileViewDefinition(ctx context.Context, databaseName, viewName string) (string, error) {
+ query := fmt.Sprintf("SHOW CREATE VIEW `%s`.`%s`", databaseName, viewName)
+ viewDefRows, err := driver.db.QueryContext(ctx, query)
+ if err != nil {
+ return "", util.FormatErrorWithQuery(err, query)
+ }
+ defer viewDefRows.Close()
+ for viewDefRows.Next() {
+ var createStmt, unused string
+ if err := viewDefRows.Scan(&unused, &createStmt, &unused, &unused); err != nil {
+ return "", err
+ }
+ viewDefMatching := viewDefMatcher.FindStringSubmatch(createStmt)
+ if len(viewDefMatching) == 0 {
+ slog.Warn("failed to match view definition", slog.String("query", query), slog.String("createStmt", createStmt))
+ }
+ // Get the def group
+ for i, name := range viewDefMatcher.SubexpNames() {
+ if name == "def" {
+ return viewDefMatching[i], nil
+ }
+ }
+ }
+ if err := viewDefRows.Err(); err != nil {
+ return "", util.FormatErrorWithQuery(err, query)
+ }
+
+ return "", nil
+}
+
func (driver *Driver) listPartitionTables(ctx context.Context, databaseName string) (map[db.TableKey][]*storepb.TablePartitionMetadata, error) {
const query string = `
SELECT
diff --git a/backend/plugin/parser/mysql/equal.go b/backend/plugin/parser/mysql/equal.go
new file mode 100644
index 0000000000..a9fc0502b2
--- /dev/null
+++ b/backend/plugin/parser/mysql/equal.go
@@ -0,0 +1,67 @@
+package mysql
+
+import (
+ "github.com/antlr4-go/antlr/v4"
+ parser "github.com/bytebase/mysql-parser"
+ "github.com/pkg/errors"
+)
+
+// IsViewTailEqual returns true if the two view tails are equal.
+func IsViewTailEqual(a, b parser.IViewTailContext) bool {
+ return a.GetText() == b.GetText()
+}
+
+type isViewTailEqualViewStmtListener struct {
+ *parser.BaseMySQLParserListener
+
+ target parser.IViewTailContext
+ equal bool
+ err error
+}
+
+func (l *isViewTailEqualViewStmtListener) EnterCreateView(ctx *parser.CreateViewContext) {
+ if l.err != nil {
+ return
+ }
+ p := ctx.GetParent()
+ if _, ok := p.(*parser.CreateStatementContext); !ok {
+ l.err = errors.New("Expecting CreateStatementContext as parent")
+ return
+ }
+ pp := p.GetParent()
+ if _, ok := pp.(*parser.SimpleStatementContext); !ok {
+ l.err = errors.New("Expecting SimpleStatementContext as parent")
+ return
+ }
+ ppp := pp.GetParent()
+ if _, ok := ppp.(*parser.QueryContext); !ok {
+ l.err = errors.New("Expecting QueryContext as parent")
+ return
+ }
+
+ if IsViewTailEqual(l.target, ctx.ViewTail()) {
+ l.equal = true
+ }
+}
+
+// IsViewTailEqualViewStmt returns true if the view tail is equal to the view statement.
+func IsViewTailEqualViewStmt(a parser.IViewTailContext, b string) (bool, error) {
+ parseResults, err := ParseMySQL(b)
+ if err != nil {
+ return false, err
+ }
+ if len(parseResults) != 1 {
+ return false, errors.Errorf("Expecting one statement, but got %d", len(parseResults))
+ }
+
+ stmt := parseResults[0]
+ listener := &isViewTailEqualViewStmtListener{
+ target: a,
+ }
+ antlr.ParseTreeWalkerDefault.Walk(listener, stmt.Tree)
+ if listener.err != nil {
+ return false, listener.err
+ }
+
+ return listener.equal, nil
+}
diff --git a/backend/plugin/parser/mysql/normalize.go b/backend/plugin/parser/mysql/normalize.go
index 70eeb4e078..d0201b7e91 100644
--- a/backend/plugin/parser/mysql/normalize.go
+++ b/backend/plugin/parser/mysql/normalize.go
@@ -145,6 +145,16 @@ func NormalizeMySQLIdentifierList(ctx parser.IIdentifierListContext) []string {
return result
}
+func NormalizeMySQLViewRef(ctx parser.IViewRefContext) (string, string) {
+ if ctx.QualifiedIdentifier() != nil {
+ return normalizeMySQLQualifiedIdentifier(ctx.QualifiedIdentifier())
+ }
+ if ctx.DotIdentifier() != nil {
+ return "", NormalizeMySQLIdentifier(ctx.DotIdentifier().Identifier())
+ }
+ return "", ""
+}
+
// NormalizeMySQLViewName normalizes the given view name.
func NormalizeMySQLViewName(ctx parser.IViewNameContext) (string, string) {
if ctx.QualifiedIdentifier() != nil {
diff --git a/backend/plugin/schema/mysql/get_design_schema.go b/backend/plugin/schema/mysql/get_design_schema.go
index bafec70a68..4b04f0a585 100644
--- a/backend/plugin/schema/mysql/get_design_schema.go
+++ b/backend/plugin/schema/mysql/get_design_schema.go
@@ -30,13 +30,26 @@ func GetDesignSchema(_, baselineSchema string, to *storepb.DatabaseSchemaMetadat
}
listener := &mysqlDesignSchemaGenerator{
- lastTokenIndex: 0,
- to: toState,
- desired: to,
+ lastTokenIndex: 0,
+ to: toState,
+ desired: to,
+ hasTemporaryView: false,
}
- for _, stmt := range list {
+ finalViewTailGetter := &finalViewTailGetter{
+ finalViewTails: make(map[string]mysql.IViewTailContext),
+ finalViewStatementIndex: make(map[string]int),
+ }
+ for i, stmt := range list {
+ finalViewTailGetter.currentStatementIndex = i
+ antlr.ParseTreeWalkerDefault.Walk(finalViewTailGetter, stmt.Tree)
+ }
+ listener.finalViewTail = finalViewTailGetter.finalViewTails
+ listener.finalViewStatementIndex = finalViewTailGetter.finalViewStatementIndex
+
+ for i, stmt := range list {
listener.lastTokenIndex = 0
+ listener.currentStatementIndex = i
antlr.ParseTreeWalkerDefault.Walk(listener, stmt.Tree)
if listener.err != nil {
break
@@ -62,6 +75,10 @@ func GetDesignSchema(_, baselineSchema string, to *storepb.DatabaseSchemaMetadat
return "", err
}
+ if err := writeRemainingViews(&listener.result, to, toState); err != nil {
+ return "", err
+ }
+
s := listener.result.String()
if !strings.HasSuffix(s, "\n") {
// The last statement of the result is SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
@@ -81,12 +98,46 @@ func GetDesignSchema(_, baselineSchema string, to *storepb.DatabaseSchemaMetadat
return result, nil
}
+type finalViewTailGetter struct {
+ *mysql.BaseMySQLParserListener
+ currentStatementIndex int
+
+ finalViewTails map[string]mysql.IViewTailContext
+ finalViewStatementIndex map[string]int
+}
+
+func (g *finalViewTailGetter) EnterCreateView(ctx *mysql.CreateViewContext) {
+ p := ctx.GetParent()
+ if _, ok := p.(*mysql.CreateStatementContext); !ok {
+ return
+ }
+ pp := p.GetParent()
+ if _, ok := pp.(*mysql.SimpleStatementContext); !ok {
+ return
+ }
+ ppp := pp.GetParent()
+ if _, ok := ppp.(*mysql.QueryContext); !ok {
+ return
+ }
+
+ _, viewName := mysqlparser.NormalizeMySQLViewName(ctx.ViewName())
+
+ g.finalViewTails[viewName] = ctx.ViewTail()
+ g.finalViewStatementIndex[viewName] = g.currentStatementIndex
+}
+
type mysqlDesignSchemaGenerator struct {
*mysql.BaseMySQLParserListener
+ currentStatementIndex int
+ finalViewTail map[string]mysql.IViewTailContext
+ finalViewStatementIndex map[string]int
+ hasTemporaryView bool
+
to *databaseState
result strings.Builder
currentTable *tableState
+ firstTable bool
firstElementInTable bool
columnDefine strings.Builder
tableConstraints strings.Builder
@@ -99,6 +150,87 @@ type mysqlDesignSchemaGenerator struct {
desired *storepb.DatabaseSchemaMetadata
}
+func (g *mysqlDesignSchemaGenerator) EnterCreateView(ctx *mysql.CreateViewContext) {
+ if g.err != nil {
+ return
+ }
+
+ p := ctx.GetParent()
+ pCtx, ok := p.(*mysql.CreateStatementContext)
+ if !ok {
+ return
+ }
+ pp := p.GetParent()
+ if _, ok := pp.(*mysql.SimpleStatementContext); !ok {
+ return
+ }
+ ppp := pp.GetParent()
+ if _, ok := ppp.(*mysql.QueryContext); !ok {
+ return
+ }
+
+ _, viewName := mysqlparser.NormalizeMySQLViewName(pCtx.CreateView().ViewName())
+ schema, ok := g.to.schemas[""]
+ if !ok || schema == nil {
+ return
+ }
+
+ schema.handledViews[viewName] = true
+ // Our dump of MySQL contains the pseudo view definition at the top, the following strategies
+ // describe how we handle the view definition:
+ // 1. If the view is not found in the desired schema, we drop the view definition.
+ // 2. If the view can be found in the desired schema, we compare the final view definition with the desired view definition,
+ // if they are the same, we keep the view definition, otherwise, we should drop the pseudo/final view definition and write the desired view definition.
+ if viewDef, ok := schema.views[viewName]; !ok {
+ // Drop the dropped view definition.
+ g.lastTokenIndex = skipAfterSemicolon(pCtx, pCtx.GetParser())
+ } else {
+ if viewTail, ok := g.finalViewTail[viewName]; ok {
+ // Compare the final view definition with the desired view definition.
+ buf := &strings.Builder{}
+ if err := viewDef.toString(buf); err != nil {
+ g.err = err
+ return
+ }
+ equal, err := mysqlparser.IsViewTailEqualViewStmt(viewTail, buf.String())
+ if err != nil {
+ g.err = err
+ return
+ }
+ if equal {
+ // View do not change, keep the view definition, both for pseudo and final view definition.
+ if _, err := g.result.WriteString(pCtx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{
+ Start: g.lastTokenIndex,
+ Stop: pCtx.GetStop().GetTokenIndex(),
+ })); err != nil {
+ g.err = err
+ return
+ }
+ g.lastTokenIndex = pCtx.GetStop().GetTokenIndex() + 1
+ g.hasTemporaryView = true
+ } else {
+ // Drop the pseudo view definition.
+ if g.currentStatementIndex != g.finalViewStatementIndex[viewName] {
+ g.lastTokenIndex = skipAfterSemicolon(pCtx, pCtx.GetParser())
+ } else {
+ if _, err := g.result.WriteString(pCtx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{
+ Start: g.lastTokenIndex,
+ Stop: pCtx.CreateView().ViewTail().ViewSelect().GetStart().GetTokenIndex() - 1,
+ })); err != nil {
+ g.err = err
+ return
+ }
+ if _, err := g.result.WriteString(viewDef.definition); err != nil {
+ g.err = err
+ return
+ }
+ g.lastTokenIndex = pCtx.GetStop().GetTokenIndex() + 1
+ }
+ }
+ }
+ }
+}
+
// EnterCreateTable is called when production createTable is entered.
func (g *mysqlDesignSchemaGenerator) EnterCreateTable(ctx *mysql.CreateTableContext) {
if g.err != nil {
@@ -121,6 +253,13 @@ func (g *mysqlDesignSchemaGenerator) EnterCreateTable(ctx *mysql.CreateTableCont
return
}
+ if !g.firstTable {
+ g.firstTable = true
+ if !g.hasTemporaryView {
+ g.lastTokenIndex = skipPrefixSpace(0, ctx.GetParser(), 1)
+ }
+ }
+
if _, err := g.result.WriteString(
ctx.GetParser().GetTokenStream().GetTextFromInterval(antlr.Interval{
Start: g.lastTokenIndex,
@@ -944,7 +1083,7 @@ func normalizeOnUpdate(s string) string {
//
// mysqldump generate drop view if exists statement after all create table statement.
// To provide the better ux, we generate the new tables before the drop view statement.
-func (g *mysqlDesignSchemaGenerator) EnterDropView(*mysql.DropViewContext) {
+func (g *mysqlDesignSchemaGenerator) EnterDropView(ctx *mysql.DropViewContext) {
if g.err != nil {
return
}
@@ -953,6 +1092,27 @@ func (g *mysqlDesignSchemaGenerator) EnterDropView(*mysql.DropViewContext) {
g.err = err
return
}
+
+ p := ctx.GetParent()
+ pctx, ok := p.(*mysql.DropStatementContext)
+ if !ok {
+ return
+ }
+
+ viewRefs := ctx.ViewRefList().AllViewRef()
+ if len(viewRefs) != 1 {
+ g.err = errors.New("Expecting one view reference")
+ }
+ viewRef := viewRefs[0]
+
+ _, viewName := mysqlparser.NormalizeMySQLViewRef(viewRef)
+ schema, ok := g.to.schemas[""]
+ if !ok || schema == nil {
+ return
+ }
+ if _, ok := schema.views[viewName]; !ok {
+ g.lastTokenIndex = skipAfterSemicolon(pctx, pctx.GetParser())
+ }
}
func (g *mysqlDesignSchemaGenerator) EnterCreateProcedure(*mysql.CreateProcedureContext) {
@@ -964,6 +1124,11 @@ func (g *mysqlDesignSchemaGenerator) EnterCreateProcedure(*mysql.CreateProcedure
g.err = err
return
}
+
+ if err := writeRemainingViews(&g.result, g.desired, g.to); err != nil {
+ g.err = err
+ return
+ }
}
func (g *mysqlDesignSchemaGenerator) EnterCreateFunction(*mysql.CreateFunctionContext) {
@@ -975,6 +1140,11 @@ func (g *mysqlDesignSchemaGenerator) EnterCreateFunction(*mysql.CreateFunctionCo
g.err = err
return
}
+
+ if err := writeRemainingViews(&g.result, g.desired, g.to); err != nil {
+ g.err = err
+ return
+ }
}
func (g *mysqlDesignSchemaGenerator) EnterCreateEvent(*mysql.CreateEventContext) {
@@ -986,6 +1156,11 @@ func (g *mysqlDesignSchemaGenerator) EnterCreateEvent(*mysql.CreateEventContext)
g.err = err
return
}
+
+ if err := writeRemainingViews(&g.result, g.desired, g.to); err != nil {
+ g.err = err
+ return
+ }
}
func (g *mysqlDesignSchemaGenerator) EnterCreateTriggers(*mysql.CreateTriggerContext) {
@@ -997,6 +1172,11 @@ func (g *mysqlDesignSchemaGenerator) EnterCreateTriggers(*mysql.CreateTriggerCon
g.err = err
return
}
+
+ if err := writeRemainingViews(&g.result, g.desired, g.to); err != nil {
+ g.err = err
+ return
+ }
}
// EnterSetStatement is called when production setStatement is entered.
@@ -1018,6 +1198,11 @@ func (g *mysqlDesignSchemaGenerator) EnterSetStatement(ctx *mysql.SetStatementCo
g.err = err
return
}
+
+ if err := writeRemainingViews(&g.result, g.desired, g.to); err != nil {
+ g.err = err
+ return
+ }
}
func writeRemainingTables(w io.StringWriter, to *storepb.DatabaseSchemaMetadata, state *databaseState) error {
@@ -1064,6 +1249,58 @@ func writeRemainingTables(w io.StringWriter, to *storepb.DatabaseSchemaMetadata,
return nil
}
+func writeRemainingViews(w io.StringWriter, to *storepb.DatabaseSchemaMetadata, state *databaseState) error {
+ firstView := 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 views.
+ for idx, view := range schema.Views {
+ _, handled := schemaState.handledViews[view.Name]
+ if handled {
+ continue
+ }
+ view, ok := schemaState.views[view.Name]
+ if !ok {
+ continue
+ }
+ if firstView {
+ firstView = false
+ if _, err := w.WriteString("\n"); err != nil {
+ return err
+ }
+ }
+ if _, err := w.WriteString(getViewAnnouncement(view.name)); err != nil {
+ return err
+ }
+
+ // Avoid new line.
+ buf := &strings.Builder{}
+ if err := view.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.views, view.name)
+ }
+ }
+ return nil
+}
+
+func getViewAnnouncement(name string) string {
+ return fmt.Sprintf("\nDROP VIEW IF EXISTS `%s`;\n--\n-- View structure for `%s`\n--\n", name, name)
+}
+
func getTableAnnouncement(name string) string {
return fmt.Sprintf("\n--\n-- Table structure for `%s`\n--\n", name)
}
@@ -1095,3 +1332,38 @@ func getDataTypePlainText(typeCtx mysql.IDataTypeContext) string {
Stop: end,
})
}
+
+// skipPrefixSpace skips the space tokens until the first non-space token, if specify `keep`, it will keep at most `keep` continuous space before the first non-space token.
+func skipPrefixSpace(start int, parser antlr.Parser, keep uint8) int {
+ end := parser.GetTokenStream().Size() - 1
+ previous := make([]int, 0, keep)
+ for i := start; i <= end; i++ {
+ if parser.GetTokenStream().Get(i).GetChannel() == antlr.TokenHiddenChannel && len(strings.TrimSpace(parser.GetTokenStream().Get(i).GetText())) == 0 {
+ // If the queue is full, pop the first element.
+ if len(previous) == int(keep) && keep != 0 {
+ previous = previous[1:]
+ }
+ if keep != 0 {
+ previous = append(previous, i)
+ }
+ continue
+ }
+ // If the queue has any element, return the first element.
+ if len(previous) > 0 {
+ return previous[0]
+ }
+ return i
+ }
+ return end + 1
+}
+
+func skipAfterSemicolon(ctx antlr.ParserRuleContext, parser antlr.Parser) int {
+ begin := ctx.GetStop().GetTokenIndex() + 1
+ end := parser.GetTokenStream().Size() - 1
+ for i := begin; i <= end; i++ {
+ if parser.GetTokenStream().Get(i).GetChannel() == antlr.TokenDefaultChannel && parser.GetTokenStream().Get(i).GetText() == ";" {
+ return i + 1
+ }
+ }
+ return end + 1
+}
diff --git a/backend/plugin/schema/mysql/get_design_schema_test.go b/backend/plugin/schema/mysql/get_design_schema_test.go
index 48718df09f..fdd231e4f7 100644
--- a/backend/plugin/schema/mysql/get_design_schema_test.go
+++ b/backend/plugin/schema/mysql/get_design_schema_test.go
@@ -13,30 +13,50 @@ import (
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
-func TestGetDesignSchema(t *testing.T) {
- type designTest struct {
- Description string
- Baseline string
- Target string
- Result string
+func TestGetDesignSchema_Debug(t *testing.T) {
+ if true {
+ t.Skip()
}
- const (
- record = false
- )
- var (
- filepaths = []string{
- "testdata/get-design-schema/get_design_schema.yaml",
- "testdata/get-design-schema/partition/range.yaml",
- "testdata/get-design-schema/partition/list.yaml",
- "testdata/get-design-schema/partition/hash.yaml",
- "testdata/get-design-schema/partition/key.yaml",
- "testdata/get-design-schema/partition/write-default.yaml",
- "testdata/get-design-schema/partition/keep-algorithm.yaml",
- "testdata/get-design-schema/partition/keep-version-comment.yaml",
- }
- )
+ TestGetDesignSchema_Basic(t)
+ TestGetDesignSchema_Partition(t)
+ TestGetDesignSchema_View(t)
+}
+
+func TestGetDesignSchema_Basic(t *testing.T) {
+ testGetDesignSchema(t, []string{
+ "testdata/get-design-schema/get_design_schema.yaml",
+ }, false)
+}
+
+func TestGetDesignSchema_Partition(t *testing.T) {
+ testGetDesignSchema(t, []string{
+ "testdata/get-design-schema/partition/range.yaml",
+ "testdata/get-design-schema/partition/list.yaml",
+ "testdata/get-design-schema/partition/hash.yaml",
+ "testdata/get-design-schema/partition/key.yaml",
+ "testdata/get-design-schema/partition/write-default.yaml",
+ "testdata/get-design-schema/partition/keep-algorithm.yaml",
+ "testdata/get-design-schema/partition/keep-version-comment.yaml",
+ }, false)
+}
+
+func TestGetDesignSchema_View(t *testing.T) {
+ testGetDesignSchema(t, []string{
+ "testdata/get-design-schema/view/add-new-view.yaml",
+ "testdata/get-design-schema/view/drop-view.yaml",
+ "testdata/get-design-schema/view/modify-view.yaml",
+ }, false)
+}
+
+type designTest struct {
+ Description string
+ Baseline string
+ Target string
+ Result string
+}
+func testGetDesignSchema(t *testing.T, filepaths []string, writeback bool) {
a := require.New(t)
for _, filepath := range filepaths {
yamlFile, err := os.Open(filepath)
@@ -58,14 +78,14 @@ func TestGetDesignSchema(t *testing.T) {
_, err = parser.ParseMySQL(result)
a.NoErrorf(err, "[%s] test case %d: %s\n content:\n%s", filepath, i, t.Description, result)
- if record {
+ if writeback {
tests[i].Result = result
} else {
a.Equalf(t.Result, result, "[%s] test case %d: %s", filepath, i, t.Description)
}
}
- if record {
+ if writeback {
byteValue, err := yaml.Marshal(tests)
a.NoError(err)
err = os.WriteFile(filepath, byteValue, 0644)
diff --git a/backend/plugin/schema/mysql/state.go b/backend/plugin/schema/mysql/state.go
index 1f499a5050..0ce9571572 100644
--- a/backend/plugin/schema/mysql/state.go
+++ b/backend/plugin/schema/mysql/state.go
@@ -60,14 +60,18 @@ func (s *databaseState) convertToDatabaseMetadata() *storepb.DatabaseSchemaMetad
}
type schemaState struct {
- id int
- name string
- tables map[string]*tableState
+ id int
+ name string
+ tables map[string]*tableState
+ views map[string]*viewState
+ handledViews map[string]bool
}
func newSchemaState() *schemaState {
return &schemaState{
- tables: make(map[string]*tableState),
+ tables: make(map[string]*tableState),
+ views: make(map[string]*viewState),
+ handledViews: make(map[string]bool),
}
}
@@ -77,6 +81,9 @@ func convertToSchemaState(schema *storepb.SchemaMetadata) *schemaState {
for i, table := range schema.Tables {
state.tables[table.Name] = convertToTableState(i, table)
}
+ for i, view := range schema.Views {
+ state.views[view.Name] = convertToViewState(i, view)
+ }
return state
}
@@ -92,11 +99,16 @@ func (s *schemaState) convertToSchemaMetadata() *storepb.SchemaMetadata {
for _, table := range tableStates {
tables = append(tables, table.convertToTableMetadata())
}
+ var views []*storepb.ViewMetadata
+ for _, view := range s.views {
+ views = append(views, view.convertToViewMetadata())
+ }
+
return &storepb.SchemaMetadata{
Name: s.name,
Tables: tables,
+ Views: views,
// Unsupported, for tests only.
- Views: []*storepb.ViewMetadata{},
Functions: []*storepb.FunctionMetadata{},
Streams: []*storepb.StreamMetadata{},
Tasks: []*storepb.TaskMetadata{},
@@ -381,6 +393,38 @@ func (f *foreignKeyState) toString(buf io.StringWriter) error {
return nil
}
+type viewState struct {
+ id int
+ name string
+ definition string
+}
+
+func (v *viewState) convertToViewMetadata() *storepb.ViewMetadata {
+ return &storepb.ViewMetadata{
+ Name: v.name,
+ Definition: v.definition,
+ }
+}
+
+func convertToViewState(id int, view *storepb.ViewMetadata) *viewState {
+ return &viewState{
+ id: id,
+ name: view.Name,
+ definition: view.Definition,
+ }
+}
+
+func (v *viewState) toString(buf io.StringWriter) error {
+ stmt := fmt.Sprintf("CREATE VIEW `%s` AS %s", v.name, v.definition)
+ if !strings.HasSuffix(stmt, ";") {
+ stmt += ";"
+ }
+ if _, err := buf.WriteString(stmt); err != nil {
+ return err
+ }
+ return nil
+}
+
type indexState struct {
id int
name string
diff --git a/backend/plugin/schema/mysql/testdata/get-design-schema/view/add-new-view.yaml b/backend/plugin/schema/mysql/testdata/get-design-schema/view/add-new-view.yaml
new file mode 100644
index 0000000000..87ea81a24d
--- /dev/null
+++ b/backend/plugin/schema/mysql/testdata/get-design-schema/view/add-new-view.yaml
@@ -0,0 +1,166 @@
+- description: Add new view in schema with view
+ baseline: |-
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Temporary view structure for `v1`
+ --
+ CREATE VIEW `v1` AS SELECT
+ 1 AS `id`;
+
+
+ --
+ -- Table structure for `t`
+ --
+ CREATE TABLE `t` (
+ `id` int DEFAULT NULL
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ DROP VIEW IF EXISTS `v1`;
+ --
+ -- View structure for `v1`
+ --
+ CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `v1` AS select `t`.`id` AS `id` from `t`;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+ target: |-
+ {
+ "name": "test_view",
+ "schemas": [
+ {
+ "views": [
+ {
+ "name": "v1",
+ "comment": "VIEW",
+ "definition": "select `t`.`id` AS `id` from `t`"
+ },
+ {
+ "name": "v2",
+ "comment": "VIEW",
+ "definition": "select (`t`.`id` + 1) AS `id + 1` from `t`"
+ }
+ ],
+ "tables": [
+ {
+ "name": "t",
+ "engine": "InnoDB",
+ "columns": [
+ {
+ "name": "id",
+ "type": "int",
+ "nullable": true,
+ "position": 1,
+ "defaultNull": true
+ }
+ ],
+ "dataSize": "16384",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ]
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "characterSet": "utf8mb4"
+ }
+ result: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Temporary view structure for `v1`
+ --
+ CREATE VIEW `v1` AS SELECT
+ 1 AS `id`;
+
+
+ --
+ -- Table structure for `t`
+ --
+ CREATE TABLE `t` (
+ `id` int DEFAULT NULL
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ DROP VIEW IF EXISTS `v1`;
+ --
+ -- View structure for `v1`
+ --
+ CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `v1` AS select `t`.`id` AS `id` from `t`;
+
+ DROP VIEW IF EXISTS `v2`;
+ --
+ -- View structure for `v2`
+ --
+ CREATE VIEW `v2` AS select (`t`.`id` + 1) AS `id + 1` from `t`;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Add new view in schema without views
+ 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` (
+ `qty` int DEFAULT NULL,
+ `price` int 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": "t",
+ "engine": "InnoDB",
+ "columns": [
+ {
+ "name": "qty",
+ "type": "int",
+ "nullable": true,
+ "position": 1,
+ "defaultNull": true
+ },
+ {
+ "name": "price",
+ "type": "int",
+ "nullable": true,
+ "position": 2,
+ "defaultNull": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ],
+ "views": [
+ {
+ "name": "v",
+ "comment": "VIEW",
+ "definition": "select * from `test_view`.`t`"
+ }
+ ]
+ }
+ ]
+ }
+ 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` (
+ `qty` int DEFAULT NULL,
+ `price` int DEFAULT NULL
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ DROP VIEW IF EXISTS `v`;
+ --
+ -- View structure for `v`
+ --
+ CREATE VIEW `v` AS select * from `test_view`.`t`;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
diff --git a/backend/plugin/schema/mysql/testdata/get-design-schema/view/drop-view.yaml b/backend/plugin/schema/mysql/testdata/get-design-schema/view/drop-view.yaml
new file mode 100644
index 0000000000..215eefb77e
--- /dev/null
+++ b/backend/plugin/schema/mysql/testdata/get-design-schema/view/drop-view.yaml
@@ -0,0 +1,176 @@
+- description: Drop view in schema with multiple views
+ baseline: |-
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Temporary view structure for `v1`
+ --
+ CREATE VIEW `v1` AS SELECT
+ 1 AS `id`;
+
+
+ --
+ -- Temporary view structure for `v2`
+ --
+ CREATE VIEW `v2` AS SELECT
+ 1 AS `id + 1`;
+
+
+ --
+ -- Table structure for `t`
+ --
+ CREATE TABLE `t` (
+ `id` int DEFAULT NULL
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ DROP VIEW IF EXISTS `v1`;
+ --
+ -- View structure for `v1`
+ --
+ CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `v1` AS select `t`.`id` AS `id` from `t`;
+
+ DROP VIEW IF EXISTS `v2`;
+ --
+ -- View structure for `v2`
+ --
+ CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `v2` AS select (`t`.`id` + 1) AS `id + 1` from `t`;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+ target: |-
+ {
+ "name": "test_view",
+ "schemas": [
+ {
+ "views": [
+ {
+ "name": "v1",
+ "comment": "VIEW",
+ "definition": "select `t`.`id` AS `id` from `t`"
+ }
+ ],
+ "tables": [
+ {
+ "name": "t",
+ "engine": "InnoDB",
+ "columns": [
+ {
+ "name": "id",
+ "type": "int",
+ "nullable": true,
+ "position": 1,
+ "defaultNull": true
+ }
+ ],
+ "dataSize": "16384",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ]
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "characterSet": "utf8mb4"
+ }
+ result: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Temporary view structure for `v1`
+ --
+ CREATE VIEW `v1` AS SELECT
+ 1 AS `id`;
+
+
+ --
+ -- Table structure for `t`
+ --
+ CREATE TABLE `t` (
+ `id` int DEFAULT NULL
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ DROP VIEW IF EXISTS `v1`;
+ --
+ -- View structure for `v1`
+ --
+ CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `v1` AS select `t`.`id` AS `id` from `t`;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+- description: Drop all views
+ baseline: |-
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Temporary view structure for `v1`
+ --
+ CREATE VIEW `v1` AS SELECT
+ 1 AS `id`;
+
+
+ --
+ -- Temporary view structure for `v2`
+ --
+ CREATE VIEW `v2` AS SELECT
+ 1 AS `id + 1`;
+
+
+ --
+ -- Table structure for `t`
+ --
+ CREATE TABLE `t` (
+ `id` int DEFAULT NULL
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ DROP VIEW IF EXISTS `v1`;
+ --
+ -- View structure for `v1`
+ --
+ CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `v1` AS select `t`.`id` AS `id` from `t`;
+
+ DROP VIEW IF EXISTS `v2`;
+ --
+ -- View structure for `v2`
+ --
+ CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `v2` AS select (`t`.`id` + 1) AS `id + 1` from `t`;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+ target: |-
+ {
+ "name": "test_view",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "t",
+ "engine": "InnoDB",
+ "columns": [
+ {
+ "name": "id",
+ "type": "int",
+ "nullable": true,
+ "position": 1,
+ "defaultNull": true
+ }
+ ],
+ "dataSize": "16384",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ]
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "characterSet": "utf8mb4"
+ }
+ 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` (
+ `id` int 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;
diff --git a/backend/plugin/schema/mysql/testdata/get-design-schema/view/modify-view.yaml b/backend/plugin/schema/mysql/testdata/get-design-schema/view/modify-view.yaml
new file mode 100644
index 0000000000..654cbb325b
--- /dev/null
+++ b/backend/plugin/schema/mysql/testdata/get-design-schema/view/modify-view.yaml
@@ -0,0 +1,102 @@
+- description: Modify views
+ baseline: |-
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Temporary view structure for `v1`
+ --
+ CREATE VIEW `v1` AS SELECT
+ 1 AS `id`;
+
+
+ --
+ -- Temporary view structure for `v2`
+ --
+ CREATE VIEW `v2` AS SELECT
+ 1 AS `id + 1`;
+
+
+ --
+ -- Table structure for `t`
+ --
+ CREATE TABLE `t` (
+ `id` int DEFAULT NULL
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ DROP VIEW IF EXISTS `v1`;
+ --
+ -- View structure for `v1`
+ --
+ CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `v1` AS select `t`.`id` AS `id` from `t`;
+
+ DROP VIEW IF EXISTS `v2`;
+ --
+ -- View structure for `v2`
+ --
+ CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `v2` AS select (`t`.`id` + 1) AS `id + 1` from `t`;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+ target: |-
+ {
+ "name": "test_view",
+ "schemas": [
+ {
+ "views": [
+ {
+ "name": "v1",
+ "comment": "VIEW",
+ "definition": "select `t`.`id` + 20 AS `id` from `t`"
+ },
+ {
+ "name": "v2",
+ "comment": "VIEW",
+ "definition": "select (`t`.`id` + 30) AS `id + 30` from `t`"
+ }
+ ],
+ "tables": [
+ {
+ "name": "t",
+ "engine": "InnoDB",
+ "columns": [
+ {
+ "name": "id",
+ "type": "int",
+ "nullable": true,
+ "position": 1,
+ "defaultNull": true
+ }
+ ],
+ "dataSize": "16384",
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ]
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci",
+ "characterSet": "utf8mb4"
+ }
+ 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` (
+ `id` int DEFAULT NULL
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ DROP VIEW IF EXISTS `v1`;
+ --
+ -- View structure for `v1`
+ --
+ CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `v1` AS select `t`.`id` + 20 AS `id` from `t`;
+
+ DROP VIEW IF EXISTS `v2`;
+ --
+ -- View structure for `v2`
+ --
+ CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `v2` AS select (`t`.`id` + 30) AS `id + 30` from `t`;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;