Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: move resource change
d-bytebase863b7be393ca
diff --git a/backend/plugin/parser/mysql/query.go b/backend/plugin/parser/mysql/query.goindex 0c760c5aa2..379c630f14 100644--- a/backend/plugin/parser/mysql/query.go+++ b/backend/plugin/parser/mysql/query.go@@ -11,29 +11,26 @@ import ()func init() {- base.RegisterQueryValidator(storepb.Engine_MYSQL, ValidateSQLForEditor)- base.RegisterQueryValidator(storepb.Engine_MARIADB, ValidateSQLForEditor)- base.RegisterQueryValidator(storepb.Engine_OCEANBASE, ValidateSQLForEditor)- base.RegisterExtractChangedResourcesFunc(storepb.Engine_MYSQL, ExtractChangedResources)- base.RegisterExtractChangedResourcesFunc(storepb.Engine_MARIADB, ExtractChangedResources)- base.RegisterExtractChangedResourcesFunc(storepb.Engine_OCEANBASE, ExtractChangedResources)+ base.RegisterQueryValidator(storepb.Engine_MYSQL, validateQuery)+ base.RegisterQueryValidator(storepb.Engine_MARIADB, validateQuery)+ base.RegisterQueryValidator(storepb.Engine_OCEANBASE, validateQuery)base.RegisterExtractResourceListFunc(storepb.Engine_MYSQL, ExtractResourceList)base.RegisterExtractResourceListFunc(storepb.Engine_MARIADB, ExtractResourceList)base.RegisterExtractResourceListFunc(storepb.Engine_OCEANBASE, ExtractResourceList)}-// ValidateSQLForEditor validates the SQL statement for SQL editor.+// validateQuery validates the SQL statement for SQL editor.// We validate the statement by following steps:// 1. Remove all quoted text(quoted identifier, string literal) and comments from the statement.// 2. Use regexp to check if the statement is a normal SELECT statement and EXPLAIN statement.// 3. For CTE, use regexp to check if the statement has UPDATE, DELETE and INSERT statements.-func ValidateSQLForEditor(statement string) (bool, error) {+func validateQuery(statement string) (bool, error) {trees, err := ParseMySQL(statement)if err != nil {return false, err}for _, item := range trees {- l := &mysqlValidateForEditorListener{+ l := &queryValidateListener{validate: true,}antlr.ParseTreeWalkerDefault.Walk(l, item.Tree)@@ -44,145 +41,40 @@ func ValidateSQLForEditor(statement string) (bool, error) {return true, nil}-type mysqlValidateForEditorListener struct {+type queryValidateListener struct {*parser.BaseMySQLParserListenervalidate bool}// EnterQuery is called when production query is entered.-func (l *mysqlValidateForEditorListener) EnterQuery(ctx *parser.QueryContext) {+func (l *queryValidateListener) EnterQuery(ctx *parser.QueryContext) {if ctx.BeginWork() != nil {l.validate = false}}// EnterSimpleStatement is called when production simpleStatement is entered.-func (l *mysqlValidateForEditorListener) EnterSimpleStatement(ctx *parser.SimpleStatementContext) {+func (l *queryValidateListener) EnterSimpleStatement(ctx *parser.SimpleStatementContext) {if ctx.SelectStatement() == nil && ctx.UtilityStatement() == nil {l.validate = false}}// EnterUtilityStatement is called when production utilityStatement is entered.-func (l *mysqlValidateForEditorListener) EnterUtilityStatement(ctx *parser.UtilityStatementContext) {+func (l *queryValidateListener) EnterUtilityStatement(ctx *parser.UtilityStatementContext) {if ctx.ExplainStatement() == nil {l.validate = false}}// EnterExplainableStatement is called when production explainableStatement is entered.-func (l *mysqlValidateForEditorListener) EnterExplainableStatement(ctx *parser.ExplainableStatementContext) {+func (l *queryValidateListener) EnterExplainableStatement(ctx *parser.ExplainableStatementContext) {if ctx.DeleteStatement() != nil || ctx.UpdateStatement() != nil || ctx.InsertStatement() != nil || ctx.ReplaceStatement() != nil {l.validate = false}}-func ExtractChangedResources(currentDatabase string, _, statement string) ([]base.SchemaResource, error) {- treeList, err := ParseMySQL(statement)- if err != nil {- return nil, err- }-- l := &mysqlChangedResourceExtractListener{- currentDatabase: currentDatabase,- resourceMap: make(map[string]base.SchemaResource),- }-- var result []base.SchemaResource- for _, tree := range treeList {- if tree.Tree == nil {- continue- }- antlr.ParseTreeWalkerDefault.Walk(l, tree.Tree)- }-- for _, resource := range l.resourceMap {- result = append(result, resource)- }-- sort.Slice(result, func(i, j int) bool {- return result[i].String() < result[j].String()- })- return result, nil-}--type mysqlChangedResourceExtractListener struct {- *parser.BaseMySQLParserListener-- currentDatabase string- resourceMap map[string]base.SchemaResource-}--// EnterCreateTable is called when production createTable is entered.-func (l *mysqlChangedResourceExtractListener) EnterCreateTable(ctx *parser.CreateTableContext) {- resource := base.SchemaResource{- Database: l.currentDatabase,- }- db, table := NormalizeMySQLTableName(ctx.TableName())- if db != "" {- resource.Database = db- }- resource.Table = table- l.resourceMap[resource.String()] = resource-}--// EnterDropTable is called when production dropTable is entered.-func (l *mysqlChangedResourceExtractListener) EnterDropTable(ctx *parser.DropTableContext) {- for _, table := range ctx.TableRefList().AllTableRef() {- resource := base.SchemaResource{- Database: l.currentDatabase,- }- db, table := NormalizeMySQLTableRef(table)- if db != "" {- resource.Database = db- }- resource.Table = table- l.resourceMap[resource.String()] = resource- }-}--// EnterAlterTable is called when production alterTable is entered.-func (l *mysqlChangedResourceExtractListener) EnterAlterTable(ctx *parser.AlterTableContext) {- resource := base.SchemaResource{- Database: l.currentDatabase,- }- db, table := NormalizeMySQLTableRef(ctx.TableRef())- if db != "" {- resource.Database = db- }- resource.Table = table- l.resourceMap[resource.String()] = resource-}--// EnterRenameTableStatement is called when production renameTableStatement is entered.-func (l *mysqlChangedResourceExtractListener) EnterRenameTableStatement(ctx *parser.RenameTableStatementContext) {- for _, pair := range ctx.AllRenamePair() {- {- resource := base.SchemaResource{- Database: l.currentDatabase,- }- db, table := NormalizeMySQLTableRef(pair.TableRef())- if db != "" {- resource.Database = db- }- resource.Table = table- l.resourceMap[resource.String()] = resource- }- {- resource := base.SchemaResource{- Database: l.currentDatabase,- }- db, table := NormalizeMySQLTableName(pair.TableName())- if db != "" {- resource.Database = db- }- resource.Table = table- l.resourceMap[resource.String()] = resource- }- }-}-func ExtractResourceList(currentDatabase string, _, statement string) ([]base.SchemaResource, error) {treeList, err := ParseMySQL(statement)if err != nil {diff --git a/backend/plugin/parser/mysql/query_test.go b/backend/plugin/parser/mysql/query_test.goindex 818381ffba..a6df8e5a2c 100644--- a/backend/plugin/parser/mysql/query_test.go+++ b/backend/plugin/parser/mysql/query_test.go@@ -90,7 +90,7 @@ func TestValidateSQLForEditor(t *testing.T) {}for _, test := range tests {- got, err := ValidateSQLForEditor(test.statement)+ got, err := validateQuery(test.statement)if test.err {require.Error(t, err)} else {@@ -201,7 +201,7 @@ func TestExtractMySQLChangedResources(t *testing.T) {}for _, test := range tests {- resources, err := ExtractChangedResources("db", "", test.statement)+ resources, err := extractChangedResources("db", "", test.statement)require.NoError(t, err)require.Equal(t, test.expected, resources, test.statement)}diff --git a/backend/plugin/parser/mysql/resource_change.go b/backend/plugin/parser/mysql/resource_change.gonew file mode 100644index 0000000000..79a918458e--- /dev/null+++ b/backend/plugin/parser/mysql/resource_change.go@@ -0,0 +1,122 @@+package mysql++import (+ "sort"++ "github.com/antlr4-go/antlr/v4"+ parser "github.com/bytebase/mysql-parser"++ "github.com/bytebase/bytebase/backend/plugin/parser/base"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++func init() {+ base.RegisterExtractChangedResourcesFunc(storepb.Engine_MYSQL, extractChangedResources)+ base.RegisterExtractChangedResourcesFunc(storepb.Engine_MARIADB, extractChangedResources)+ base.RegisterExtractChangedResourcesFunc(storepb.Engine_OCEANBASE, extractChangedResources)+}++func extractChangedResources(currentDatabase string, _, statement string) ([]base.SchemaResource, error) {+ treeList, err := ParseMySQL(statement)+ if err != nil {+ return nil, err+ }++ l := &resourceChangedListener{+ currentDatabase: currentDatabase,+ resourceMap: make(map[string]base.SchemaResource),+ }++ var result []base.SchemaResource+ for _, tree := range treeList {+ if tree.Tree == nil {+ continue+ }+ antlr.ParseTreeWalkerDefault.Walk(l, tree.Tree)+ }++ for _, resource := range l.resourceMap {+ result = append(result, resource)+ }++ sort.Slice(result, func(i, j int) bool {+ return result[i].String() < result[j].String()+ })+ return result, nil+}++type resourceChangedListener struct {+ *parser.BaseMySQLParserListener++ currentDatabase string+ resourceMap map[string]base.SchemaResource+}++// EnterCreateTable is called when production createTable is entered.+func (l *resourceChangedListener) EnterCreateTable(ctx *parser.CreateTableContext) {+ resource := base.SchemaResource{+ Database: l.currentDatabase,+ }+ db, table := NormalizeMySQLTableName(ctx.TableName())+ if db != "" {+ resource.Database = db+ }+ resource.Table = table+ l.resourceMap[resource.String()] = resource+}++// EnterDropTable is called when production dropTable is entered.+func (l *resourceChangedListener) EnterDropTable(ctx *parser.DropTableContext) {+ for _, table := range ctx.TableRefList().AllTableRef() {+ resource := base.SchemaResource{+ Database: l.currentDatabase,+ }+ db, table := NormalizeMySQLTableRef(table)+ if db != "" {+ resource.Database = db+ }+ resource.Table = table+ l.resourceMap[resource.String()] = resource+ }+}++// EnterAlterTable is called when production alterTable is entered.+func (l *resourceChangedListener) EnterAlterTable(ctx *parser.AlterTableContext) {+ resource := base.SchemaResource{+ Database: l.currentDatabase,+ }+ db, table := NormalizeMySQLTableRef(ctx.TableRef())+ if db != "" {+ resource.Database = db+ }+ resource.Table = table+ l.resourceMap[resource.String()] = resource+}++// EnterRenameTableStatement is called when production renameTableStatement is entered.+func (l *resourceChangedListener) EnterRenameTableStatement(ctx *parser.RenameTableStatementContext) {+ for _, pair := range ctx.AllRenamePair() {+ {+ resource := base.SchemaResource{+ Database: l.currentDatabase,+ }+ db, table := NormalizeMySQLTableRef(pair.TableRef())+ if db != "" {+ resource.Database = db+ }+ resource.Table = table+ l.resourceMap[resource.String()] = resource+ }+ {+ resource := base.SchemaResource{+ Database: l.currentDatabase,+ }+ db, table := NormalizeMySQLTableName(pair.TableName())+ if db != "" {+ resource.Database = db+ }+ resource.Table = table+ l.resourceMap[resource.String()] = resource+ }+ }+}diff --git a/backend/plugin/parser/pg/query.go b/backend/plugin/parser/pg/query.goindex 8b163832bd..e6aab31bc0 100644--- a/backend/plugin/parser/pg/query.go+++ b/backend/plugin/parser/pg/query.go@@ -17,19 +17,19 @@ import ()func init() {- base.RegisterQueryValidator(storepb.Engine_POSTGRES, ValidateSQLForEditor)- base.RegisterQueryValidator(storepb.Engine_REDSHIFT, ValidateSQLForEditor)- base.RegisterQueryValidator(storepb.Engine_RISINGWAVE, ValidateSQLForEditor)+ base.RegisterQueryValidator(storepb.Engine_POSTGRES, validateQuery)+ base.RegisterQueryValidator(storepb.Engine_REDSHIFT, validateQuery)+ base.RegisterQueryValidator(storepb.Engine_RISINGWAVE, validateQuery)base.RegisterExtractResourceListFunc(storepb.Engine_POSTGRES, ExtractResourceList)base.RegisterExtractResourceListFunc(storepb.Engine_REDSHIFT, ExtractResourceList)base.RegisterExtractResourceListFunc(storepb.Engine_RISINGWAVE, ExtractResourceList)}-// ValidateSQLForEditor validates the SQL statement for SQL editor.+// validateQuery validates the SQL statement for SQL editor.// Consider that the tokenizer cannot handle the dollar-sign($), so that we use pg_query_go to parse the statement.// For EXPLAIN and normal SELECT statements, we can directly use regexp to check.// For CTE, we need to parse the statement to JSON and check the JSON keys.-func ValidateSQLForEditor(statement string) (bool, error) {+func validateQuery(statement string) (bool, error) {stmtList, err := pgrawparser.Parse(pgrawparser.ParseContext{}, statement)if err != nil {// Parse error again for getting a better error message.diff --git a/backend/plugin/parser/pg/query_test.go b/backend/plugin/parser/pg/query_test.goindex 89904997ff..a6b5fa6b40 100644--- a/backend/plugin/parser/pg/query_test.go+++ b/backend/plugin/parser/pg/query_test.go@@ -81,7 +81,7 @@ func TestValidateSQLForEditor(t *testing.T) {}for _, test := range tests {- ans, err := ValidateSQLForEditor(test.sql)+ ans, err := validateQuery(test.sql)require.NoError(t, err)require.Equal(t, test.ans, ans, test.sql)}diff --git a/backend/plugin/parser/plsql/plsql.go b/backend/plugin/parser/plsql/plsql.goindex 601e35f8b3..cd3b62793d 100644--- a/backend/plugin/parser/plsql/plsql.go+++ b/backend/plugin/parser/plsql/plsql.go@@ -1,6 +1,7 @@package plsqlimport (+ "fmt""strings""github.com/antlr4-go/antlr/v4"@@ -123,3 +124,158 @@ func NormalizeIndexName(indexName parser.IIndex_nameContext) (string, string) {return "", NormalizeIdentifierContext(indexName.Identifier())}++// EquivalentType returns true if the given type is equivalent to the given text.+func EquivalentType(tp parser.IDatatypeContext, text string) (bool, error) {+ tree, _, err := ParsePLSQL(fmt.Sprintf(`CREATE TABLE t(a %s);`, text))+ if err != nil {+ return false, err+ }++ listener := &typeEquivalentListener{tp: tp, equivalent: false}+ antlr.ParseTreeWalkerDefault.Walk(listener, tree)+ return listener.equivalent, nil+}++type typeEquivalentListener struct {+ *parser.BasePlSqlParserListener++ tp parser.IDatatypeContext+ equivalent bool+}++// EnterColumn_definition is called when production column_definition is entered.+func (l *typeEquivalentListener) EnterColumn_definition(ctx *parser.Column_definitionContext) {+ if ctx.Datatype() != nil {+ l.equivalent = equalDataType(l.tp, ctx.Datatype())+ }+}++func equalDataType(lType parser.IDatatypeContext, rType parser.IDatatypeContext) bool {+ if lType == nil || rType == nil {+ return false+ }+ lNative := lType.Native_datatype_element()+ rNative := rType.Native_datatype_element()++ if lNative != nil && rNative != nil {+ switch {+ case lNative.BINARY_INTEGER() != nil:+ return rNative.BINARY_INTEGER() != nil+ case lNative.PLS_INTEGER() != nil:+ return rNative.PLS_INTEGER() != nil+ case lNative.NATURAL() != nil:+ return rNative.NATURAL() != nil+ case lNative.BINARY_FLOAT() != nil:+ return rNative.BINARY_FLOAT() != nil+ case lNative.BINARY_DOUBLE() != nil:+ return rNative.BINARY_DOUBLE() != nil+ case lNative.NATURALN() != nil:+ return rNative.NATURALN() != nil+ case lNative.POSITIVE() != nil:+ return rNative.POSITIVE() != nil+ case lNative.POSITIVEN() != nil:+ return rNative.POSITIVEN() != nil+ case lNative.SIGNTYPE() != nil:+ return rNative.SIGNTYPE() != nil+ case lNative.SIMPLE_INTEGER() != nil:+ return rNative.SIMPLE_INTEGER() != nil+ case lNative.NVARCHAR2() != nil:+ return rNative.NVARCHAR2() != nil+ case lNative.DEC() != nil:+ return rNative.DEC() != nil+ case lNative.INTEGER() != nil:+ return rNative.INTEGER() != nil+ case lNative.INT() != nil:+ return rNative.INT() != nil+ case lNative.NUMERIC() != nil:+ return rNative.NUMERIC() != nil+ case lNative.SMALLINT() != nil:+ return rNative.SMALLINT() != nil+ case lNative.NUMBER() != nil:+ return rNative.NUMBER() != nil+ case lNative.DECIMAL() != nil:+ return rNative.DECIMAL() != nil+ case lNative.DOUBLE() != nil:+ return rNative.DOUBLE() != nil+ case lNative.FLOAT() != nil:+ return rNative.FLOAT() != nil+ case lNative.REAL() != nil:+ return rNative.REAL() != nil+ case lNative.NCHAR() != nil:+ return rNative.NCHAR() != nil+ case lNative.LONG() != nil:+ return rNative.LONG() != nil+ case lNative.CHAR() != nil:+ return rNative.CHAR() != nil+ case lNative.CHARACTER() != nil:+ return rNative.CHARACTER() != nil+ case lNative.VARCHAR2() != nil:+ return rNative.VARCHAR2() != nil+ case lNative.VARCHAR() != nil:+ return rNative.VARCHAR() != nil+ case lNative.STRING() != nil:+ return rNative.STRING() != nil+ case lNative.RAW() != nil:+ return rNative.RAW() != nil+ case lNative.BOOLEAN() != nil:+ return rNative.BOOLEAN() != nil+ case lNative.DATE() != nil:+ return rNative.DATE() != nil+ case lNative.ROWID() != nil:+ return rNative.ROWID() != nil+ case lNative.UROWID() != nil:+ return rNative.UROWID() != nil+ case lNative.YEAR() != nil:+ return rNative.YEAR() != nil+ case lNative.MONTH() != nil:+ return rNative.MONTH() != nil+ case lNative.DAY() != nil:+ return rNative.DAY() != nil+ case lNative.HOUR() != nil:+ return rNative.HOUR() != nil+ case lNative.MINUTE() != nil:+ return rNative.MINUTE() != nil+ case lNative.SECOND() != nil:+ return rNative.SECOND() != nil+ case lNative.TIMEZONE_HOUR() != nil:+ return rNative.TIMEZONE_HOUR() != nil+ case lNative.TIMEZONE_MINUTE() != nil:+ return rNative.TIMEZONE_MINUTE() != nil+ case lNative.TIMEZONE_REGION() != nil:+ return rNative.TIMEZONE_REGION() != nil+ case lNative.TIMEZONE_ABBR() != nil:+ return rNative.TIMEZONE_ABBR() != nil+ case lNative.TIMESTAMP() != nil:+ return rNative.TIMESTAMP() != nil+ case lNative.TIMESTAMP_UNCONSTRAINED() != nil:+ return rNative.TIMESTAMP_UNCONSTRAINED() != nil+ case lNative.TIMESTAMP_TZ_UNCONSTRAINED() != nil:+ return rNative.TIMESTAMP_TZ_UNCONSTRAINED() != nil+ case lNative.TIMESTAMP_LTZ_UNCONSTRAINED() != nil:+ return rNative.TIMESTAMP_LTZ_UNCONSTRAINED() != nil+ case lNative.YMINTERVAL_UNCONSTRAINED() != nil:+ return rNative.YMINTERVAL_UNCONSTRAINED() != nil+ case lNative.DSINTERVAL_UNCONSTRAINED() != nil:+ return rNative.DSINTERVAL_UNCONSTRAINED() != nil+ case lNative.BFILE() != nil:+ return rNative.BFILE() != nil+ case lNative.BLOB() != nil:+ return rNative.BLOB() != nil+ case lNative.CLOB() != nil:+ return rNative.CLOB() != nil+ case lNative.NCLOB() != nil:+ return rNative.NCLOB() != nil+ case lNative.MLSLABEL() != nil:+ return rNative.MLSLABEL() != nil+ default:+ return false+ }+ }++ if lNative != nil || rNative != nil {+ return false+ }++ return lType.GetText() == rType.GetText()+}diff --git a/backend/plugin/parser/plsql/query.go b/backend/plugin/parser/plsql/query.goindex ca1f3f3e16..b37238d4fa 100644--- a/backend/plugin/parser/plsql/query.go+++ b/backend/plugin/parser/plsql/query.go@@ -1,8 +1,6 @@package plsqlimport (- "errors"- "fmt""sort""github.com/antlr4-go/antlr/v4"@@ -13,128 +11,53 @@ import ()func init() {- base.RegisterQueryValidator(storepb.Engine_ORACLE, ValidateSQLForEditor)- base.RegisterQueryValidator(storepb.Engine_DM, ValidateSQLForEditor)- base.RegisterExtractChangedResourcesFunc(storepb.Engine_ORACLE, ExtractChangedResources)- base.RegisterExtractChangedResourcesFunc(storepb.Engine_DM, ExtractChangedResources)+ base.RegisterQueryValidator(storepb.Engine_ORACLE, validateQuery)+ base.RegisterQueryValidator(storepb.Engine_DM, validateQuery)base.RegisterExtractResourceListFunc(storepb.Engine_ORACLE, ExtractResourceList)base.RegisterExtractResourceListFunc(storepb.Engine_DM, ExtractResourceList)}-// ValidateSQLForEditor validates the SQL statement for SQL editor.-func ValidateSQLForEditor(statement string) (bool, error) {+// validateQuery validates the SQL statement for SQL editor.+func validateQuery(statement string) (bool, error) {tree, _, err := ParsePLSQL(statement)if err != nil {return false, err}- if err := ValidateForEditor(tree); err != nil {- return false, err- }- return true, nil-}--func ExtractChangedResources(currentDatabase string, currentSchema string, statement string) ([]base.SchemaResource, error) {- tree, _, err := ParsePLSQL(statement)- if err != nil {- return nil, err- }-- l := &plsqlChangedResourceExtractListener{- currentDatabase: currentDatabase,- currentSchema: currentSchema,- resourceMap: make(map[string]base.SchemaResource),+ l := &queryValidateListener{+ validate: true,}-- var result []base.SchemaResourceantlr.ParseTreeWalkerDefault.Walk(l, tree)- for _, resource := range l.resourceMap {- result = append(result, resource)+ if !l.validate {+ return false, nil}-- sort.Slice(result, func(i, j int) bool {- return result[i].String() < result[j].String()- })-- return result, nil+ return true, nil}-type plsqlChangedResourceExtractListener struct {+type queryValidateListener struct {*parser.BasePlSqlParserListener- currentDatabase string- currentSchema string- resourceMap map[string]base.SchemaResource-}--// EnterCreate_table is called when production create_table is entered.-func (l *plsqlChangedResourceExtractListener) EnterCreate_table(ctx *parser.Create_tableContext) {- resource := base.SchemaResource{- Database: l.currentDatabase,- Schema: l.currentSchema,- Table: NormalizeIdentifierContext(ctx.Table_name().Identifier()),- }-- if ctx.Schema_name() != nil {- resource.Schema = NormalizeIdentifierContext(ctx.Schema_name().Identifier())- }- l.resourceMap[resource.String()] = resource+ validate bool}-// EnterDrop_table is called when production drop_table is entered.-func (l *plsqlChangedResourceExtractListener) EnterDrop_table(ctx *parser.Drop_tableContext) {- result := []string{NormalizeIdentifierContext(ctx.Tableview_name().Identifier())}- if ctx.Tableview_name().Id_expression() != nil {- result = append(result, NormalizeIDExpression(ctx.Tableview_name().Id_expression()))- }- if len(result) == 1 {- result = []string{l.currentSchema, result[0]}- }-- resource := base.SchemaResource{- Database: l.currentDatabase,- Schema: result[0],- Table: result[1],+// EnterSql_script is called when production sql_script is entered.+func (l *queryValidateListener) EnterSql_script(ctx *parser.Sql_scriptContext) {+ if len(ctx.AllSql_plus_command()) > 0 {+ l.validate = false}- l.resourceMap[resource.String()] = resource}-// EnterAlter_table is called when production alter_table is entered.-func (l *plsqlChangedResourceExtractListener) EnterAlter_table(ctx *parser.Alter_tableContext) {- result := []string{NormalizeIdentifierContext(ctx.Tableview_name().Identifier())}- if ctx.Tableview_name().Id_expression() != nil {- result = append(result, NormalizeIDExpression(ctx.Tableview_name().Id_expression()))- }- if len(result) == 1 {- result = []string{l.currentSchema, result[0]}- }-- resource := base.SchemaResource{- Database: l.currentDatabase,- Schema: result[0],- Table: result[1],+// EnterUnit_statement is called when production unit_statement is entered.+func (l *queryValidateListener) EnterUnit_statement(ctx *parser.Unit_statementContext) {+ if ctx.Data_manipulation_language_statements() == nil {+ l.validate = false}- l.resourceMap[resource.String()] = resource}-// EnterAlter_table_properties is called when production alter_table_properties is entered.-func (l *plsqlChangedResourceExtractListener) EnterAlter_table_properties(ctx *parser.Alter_table_propertiesContext) {- if ctx.RENAME() == nil {- return- }- result := []string{NormalizeIdentifierContext(ctx.Tableview_name().Identifier())}- if ctx.Tableview_name().Id_expression() != nil {- result = append(result, NormalizeIDExpression(ctx.Tableview_name().Id_expression()))- }- if len(result) == 1 {- result = []string{l.currentSchema, result[0]}- }-- resource := base.SchemaResource{- Database: l.currentDatabase,- Schema: result[0],- Table: result[1],+// EnterData_manipulation_language_statements is called when production data_manipulation_language_statements is entered.+func (l *queryValidateListener) EnterData_manipulation_language_statements(ctx *parser.Data_manipulation_language_statementsContext) {+ if ctx.Select_statement() == nil && ctx.Explain_statement() == nil {+ l.validate = false}- l.resourceMap[resource.String()] = resource}func ExtractResourceList(currentDatabase string, currentSchema string, statement string) ([]base.SchemaResource, error) {@@ -190,197 +113,3 @@ func (l *plsqlResourceExtractListener) EnterTableview_name(ctx *parser.Tableview}l.resourceMap[resource.String()] = resource}--// ValidateForEditor validates the given PLSQL for editor.-func ValidateForEditor(tree antlr.Tree) error {- l := &plsqlValidateForEditorListener{- validate: true,- }- antlr.ParseTreeWalkerDefault.Walk(l, tree)- if !l.validate {- return errors.New("only support SELECT sql statement")- }- return nil-}--type plsqlValidateForEditorListener struct {- *parser.BasePlSqlParserListener-- validate bool-}--// EnterSql_script is called when production sql_script is entered.-func (l *plsqlValidateForEditorListener) EnterSql_script(ctx *parser.Sql_scriptContext) {- if len(ctx.AllSql_plus_command()) > 0 {- l.validate = false- }-}--// EnterUnit_statement is called when production unit_statement is entered.-func (l *plsqlValidateForEditorListener) EnterUnit_statement(ctx *parser.Unit_statementContext) {- if ctx.Data_manipulation_language_statements() == nil {- l.validate = false- }-}--// EnterData_manipulation_language_statements is called when production data_manipulation_language_statements is entered.-func (l *plsqlValidateForEditorListener) EnterData_manipulation_language_statements(ctx *parser.Data_manipulation_language_statementsContext) {- if ctx.Select_statement() == nil && ctx.Explain_statement() == nil {- l.validate = false- }-}--// EquivalentType returns true if the given type is equivalent to the given text.-func EquivalentType(tp parser.IDatatypeContext, text string) (bool, error) {- tree, _, err := ParsePLSQL(fmt.Sprintf(`CREATE TABLE t(a %s);`, text))- if err != nil {- return false, err- }-- listener := &typeEquivalentListener{tp: tp, equivalent: false}- antlr.ParseTreeWalkerDefault.Walk(listener, tree)- return listener.equivalent, nil-}--type typeEquivalentListener struct {- *parser.BasePlSqlParserListener-- tp parser.IDatatypeContext- equivalent bool-}--// EnterColumn_definition is called when production column_definition is entered.-func (l *typeEquivalentListener) EnterColumn_definition(ctx *parser.Column_definitionContext) {- if ctx.Datatype() != nil {- l.equivalent = equalDataType(l.tp, ctx.Datatype())- }-}--func equalDataType(lType parser.IDatatypeContext, rType parser.IDatatypeContext) bool {- if lType == nil || rType == nil {- return false- }- lNative := lType.Native_datatype_element()- rNative := rType.Native_datatype_element()-- if lNative != nil && rNative != nil {- switch {- case lNative.BINARY_INTEGER() != nil:- return rNative.BINARY_INTEGER() != nil- case lNative.PLS_INTEGER() != nil:- return rNative.PLS_INTEGER() != nil- case lNative.NATURAL() != nil:- return rNative.NATURAL() != nil- case lNative.BINARY_FLOAT() != nil:- return rNative.BINARY_FLOAT() != nil- case lNative.BINARY_DOUBLE() != nil:- return rNative.BINARY_DOUBLE() != nil- case lNative.NATURALN() != nil:- return rNative.NATURALN() != nil- case lNative.POSITIVE() != nil:- return rNative.POSITIVE() != nil- case lNative.POSITIVEN() != nil:- return rNative.POSITIVEN() != nil- case lNative.SIGNTYPE() != nil:- return rNative.SIGNTYPE() != nil- case lNative.SIMPLE_INTEGER() != nil:- return rNative.SIMPLE_INTEGER() != nil- case lNative.NVARCHAR2() != nil:- return rNative.NVARCHAR2() != nil- case lNative.DEC() != nil:- return rNative.DEC() != nil- case lNative.INTEGER() != nil:- return rNative.INTEGER() != nil- case lNative.INT() != nil:- return rNative.INT() != nil- case lNative.NUMERIC() != nil:- return rNative.NUMERIC() != nil- case lNative.SMALLINT() != nil:- return rNative.SMALLINT() != nil- case lNative.NUMBER() != nil:- return rNative.NUMBER() != nil- case lNative.DECIMAL() != nil:- return rNative.DECIMAL() != nil- case lNative.DOUBLE() != nil:- return rNative.DOUBLE() != nil- case lNative.FLOAT() != nil:- return rNative.FLOAT() != nil- case lNative.REAL() != nil:- return rNative.REAL() != nil- case lNative.NCHAR() != nil:- return rNative.NCHAR() != nil- case lNative.LONG() != nil:- return rNative.LONG() != nil- case lNative.CHAR() != nil:- return rNative.CHAR() != nil- case lNative.CHARACTER() != nil:- return rNative.CHARACTER() != nil- case lNative.VARCHAR2() != nil:- return rNative.VARCHAR2() != nil- case lNative.VARCHAR() != nil:- return rNative.VARCHAR() != nil- case lNative.STRING() != nil:- return rNative.STRING() != nil- case lNative.RAW() != nil:- return rNative.RAW() != nil- case lNative.BOOLEAN() != nil:- return rNative.BOOLEAN() != nil- case lNative.DATE() != nil:- return rNative.DATE() != nil- case lNative.ROWID() != nil:- return rNative.ROWID() != nil- case lNative.UROWID() != nil:- return rNative.UROWID() != nil- case lNative.YEAR() != nil:- return rNative.YEAR() != nil- case lNative.MONTH() != nil:- return rNative.MONTH() != nil- case lNative.DAY() != nil:- return rNative.DAY() != nil- case lNative.HOUR() != nil:- return rNative.HOUR() != nil- case lNative.MINUTE() != nil:- return rNative.MINUTE() != nil- case lNative.SECOND() != nil:- return rNative.SECOND() != nil- case lNative.TIMEZONE_HOUR() != nil:- return rNative.TIMEZONE_HOUR() != nil- case lNative.TIMEZONE_MINUTE() != nil:- return rNative.TIMEZONE_MINUTE() != nil- case lNative.TIMEZONE_REGION() != nil:- return rNative.TIMEZONE_REGION() != nil- case lNative.TIMEZONE_ABBR() != nil:- return rNative.TIMEZONE_ABBR() != nil- case lNative.TIMESTAMP() != nil:- return rNative.TIMESTAMP() != nil- case lNative.TIMESTAMP_UNCONSTRAINED() != nil:- return rNative.TIMESTAMP_UNCONSTRAINED() != nil- case lNative.TIMESTAMP_TZ_UNCONSTRAINED() != nil:- return rNative.TIMESTAMP_TZ_UNCONSTRAINED() != nil- case lNative.TIMESTAMP_LTZ_UNCONSTRAINED() != nil:- return rNative.TIMESTAMP_LTZ_UNCONSTRAINED() != nil- case lNative.YMINTERVAL_UNCONSTRAINED() != nil:- return rNative.YMINTERVAL_UNCONSTRAINED() != nil- case lNative.DSINTERVAL_UNCONSTRAINED() != nil:- return rNative.DSINTERVAL_UNCONSTRAINED() != nil- case lNative.BFILE() != nil:- return rNative.BFILE() != nil- case lNative.BLOB() != nil:- return rNative.BLOB() != nil- case lNative.CLOB() != nil:- return rNative.CLOB() != nil- case lNative.NCLOB() != nil:- return rNative.NCLOB() != nil- case lNative.MLSLABEL() != nil:- return rNative.MLSLABEL() != nil- default:- return false- }- }-- if lNative != nil || rNative != nil {- return false- }-- return lType.GetText() == rType.GetText()-}diff --git a/backend/plugin/parser/plsql/resource_change.go b/backend/plugin/parser/plsql/resource_change.gonew file mode 100644index 0000000000..648f3da4bc--- /dev/null+++ b/backend/plugin/parser/plsql/resource_change.go@@ -0,0 +1,120 @@+package plsql++import (+ "sort"++ "github.com/antlr4-go/antlr/v4"+ parser "github.com/bytebase/plsql-parser"++ "github.com/bytebase/bytebase/backend/plugin/parser/base"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++func init() {+ base.RegisterExtractChangedResourcesFunc(storepb.Engine_ORACLE, extractChangedResources)+ base.RegisterExtractChangedResourcesFunc(storepb.Engine_DM, extractChangedResources)+}++func extractChangedResources(currentDatabase string, currentSchema string, statement string) ([]base.SchemaResource, error) {+ tree, _, err := ParsePLSQL(statement)+ if err != nil {+ return nil, err+ }++ l := &plsqlChangedResourceExtractListener{+ currentDatabase: currentDatabase,+ currentSchema: currentSchema,+ resourceMap: make(map[string]base.SchemaResource),+ }++ var result []base.SchemaResource+ antlr.ParseTreeWalkerDefault.Walk(l, tree)+ for _, resource := range l.resourceMap {+ result = append(result, resource)+ }++ sort.Slice(result, func(i, j int) bool {+ return result[i].String() < result[j].String()+ })++ return result, nil+}++type plsqlChangedResourceExtractListener struct {+ *parser.BasePlSqlParserListener++ currentDatabase string+ currentSchema string+ resourceMap map[string]base.SchemaResource+}++// EnterCreate_table is called when production create_table is entered.+func (l *plsqlChangedResourceExtractListener) EnterCreate_table(ctx *parser.Create_tableContext) {+ resource := base.SchemaResource{+ Database: l.currentDatabase,+ Schema: l.currentSchema,+ Table: NormalizeIdentifierContext(ctx.Table_name().Identifier()),+ }++ if ctx.Schema_name() != nil {+ resource.Schema = NormalizeIdentifierContext(ctx.Schema_name().Identifier())+ }+ l.resourceMap[resource.String()] = resource+}++// EnterDrop_table is called when production drop_table is entered.+func (l *plsqlChangedResourceExtractListener) EnterDrop_table(ctx *parser.Drop_tableContext) {+ result := []string{NormalizeIdentifierContext(ctx.Tableview_name().Identifier())}+ if ctx.Tableview_name().Id_expression() != nil {+ result = append(result, NormalizeIDExpression(ctx.Tableview_name().Id_expression()))+ }+ if len(result) == 1 {+ result = []string{l.currentSchema, result[0]}+ }++ resource := base.SchemaResource{+ Database: l.currentDatabase,+ Schema: result[0],+ Table: result[1],+ }+ l.resourceMap[resource.String()] = resource+}++// EnterAlter_table is called when production alter_table is entered.+func (l *plsqlChangedResourceExtractListener) EnterAlter_table(ctx *parser.Alter_tableContext) {+ result := []string{NormalizeIdentifierContext(ctx.Tableview_name().Identifier())}+ if ctx.Tableview_name().Id_expression() != nil {+ result = append(result, NormalizeIDExpression(ctx.Tableview_name().Id_expression()))+ }+ if len(result) == 1 {+ result = []string{l.currentSchema, result[0]}+ }++ resource := base.SchemaResource{+ Database: l.currentDatabase,+ Schema: result[0],+ Table: result[1],+ }+ l.resourceMap[resource.String()] = resource+}++// EnterAlter_table_properties is called when production alter_table_properties is entered.+func (l *plsqlChangedResourceExtractListener) EnterAlter_table_properties(ctx *parser.Alter_table_propertiesContext) {+ if ctx.RENAME() == nil {+ return+ }+ result := []string{NormalizeIdentifierContext(ctx.Tableview_name().Identifier())}+ if ctx.Tableview_name().Id_expression() != nil {+ result = append(result, NormalizeIDExpression(ctx.Tableview_name().Id_expression()))+ }+ if len(result) == 1 {+ result = []string{l.currentSchema, result[0]}+ }++ resource := base.SchemaResource{+ Database: l.currentDatabase,+ Schema: result[0],+ Table: result[1],+ }+ l.resourceMap[resource.String()] = resource+}diff --git a/backend/plugin/parser/tidb/query.go b/backend/plugin/parser/tidb/query.goindex d69283a604..dd8f60a766 100644--- a/backend/plugin/parser/tidb/query.go+++ b/backend/plugin/parser/tidb/query.go@@ -12,7 +12,7 @@ import ()func init() {- base.RegisterQueryValidator(storepb.Engine_TIDB, ValidateSQLForEditor)+ base.RegisterQueryValidator(storepb.Engine_TIDB, validateQuery)base.RegisterExtractResourceListFunc(storepb.Engine_TIDB, ExtractResourceList)// TODO(d): migrate to mysql parser.base.RegisterExtractDatabaseListFunc(storepb.Engine_MYSQL, ExtractDatabaseList)@@ -21,12 +21,12 @@ func init() {base.RegisterExtractDatabaseListFunc(storepb.Engine_TIDB, ExtractDatabaseList)}-// ValidateSQLForEditor validates the SQL statement for SQL editor.+// validateQuery validates the SQL statement for SQL editor.// We validate the statement by following steps:// 1. Remove all quoted text(quoted identifier, string literal) and comments from the statement.// 2. Use regexp to check if the statement is a normal SELECT statement and EXPLAIN statement.// 3. For CTE, use regexp to check if the statement has UPDATE, DELETE and INSERT statements.-func ValidateSQLForEditor(statement string) (bool, error) {+func validateQuery(statement string) (bool, error) {stmtList, err := ParseTiDB(statement, "", "")if err != nil {return false, err