Skip to content

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

test(schema system): add integration test for schema system (#1380)

rebeliced1c2f591368a
diff --git a/plugin/advisor/mysql/parser.go b/plugin/advisor/mysql/parser.go
index 633c6e4365..a6ff6b21fd 100644
--- a/plugin/advisor/mysql/parser.go
+++ b/plugin/advisor/mysql/parser.go
@@ -1,6 +1,7 @@
package mysql
import (
+ "github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/plugin/advisor"
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tidb/parser/ast"
@@ -25,6 +26,7 @@ func parseStatement(statement string, charset string, collation string) ([]ast.S
return nil, []advisor.Advice{
{
Status: advisor.Error,
+ Code: common.DbStatementSyntaxError,
Title: advisor.SyntaxErrorTitle,
Content: err.Error(),
},
diff --git a/tests/schema_system_test.go b/tests/schema_system_test.go
new file mode 100644
index 0000000000..6c4110b3c7
--- /dev/null
+++ b/tests/schema_system_test.go
@@ -0,0 +1,326 @@
+//go:build mysql
+// +build mysql
+
+package tests
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strconv"
+ "testing"
+
+ "github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/common"
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/db"
+ "github.com/bytebase/bytebase/resources/mysql"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSchemaSystem(t *testing.T) {
+ type test struct {
+ statement string
+ result []api.TaskCheckResult
+ }
+
+ var (
+ databaseName = "testSchemaSystem"
+ schemaReviewAccessErr = fmt.Sprintf(`http response error code %d body "{\"message\":\"%s\"}\n"`, http.StatusForbidden, api.FeatureSchemaReviewPolicy.AccessErrorMessage())
+ statements = []string{
+ "CREATE TABLE user(" +
+ "id INT PRIMARY KEY," +
+ "name VARCHAR(255) NOT NULL," +
+ "room_id INT NOT NULL," +
+ "creator_id INT NOT NULL," +
+ "created_ts TIMESTAMP NOT NULL," +
+ "updater_id INT NOT NULL," +
+ "updated_ts TIMESTAMP NOT NULL," +
+ "INDEX idx_user_name(name)," +
+ "UNIQUE KEY uk_user_id_name(id, name)," +
+ "FOREIGN KEY fk_user_room_id_room_id(room_id) REFERENCES room(id)" +
+ ") ENGINE = INNODB",
+ "CREATE TABLE userTable(" +
+ "id INT," +
+ "name VARCHAR(255)," +
+ "roomId INT," +
+ "INDEX idx1(name)," +
+ "UNIQUE KEY uk1(id, name)," +
+ "FOREIGN KEY fk1(roomId) REFERENCES room(id)" +
+ ") ENGINE = CSV",
+ }
+ tests = []test{
+ {
+ statement: statements[0],
+ result: []api.TaskCheckResult{
+ {
+ Status: api.TaskCheckStatusSuccess,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ statement: "CREATE TABLE user(id);",
+ result: []api.TaskCheckResult{
+ {
+ Status: api.TaskCheckStatusError,
+ Code: common.DbStatementSyntaxError,
+ Title: advisor.SyntaxErrorTitle,
+ Content: "line 1 column 21 near \");\" ",
+ },
+ },
+ },
+ {
+ statement: statements[1],
+ result: []api.TaskCheckResult{
+ {
+ Status: api.TaskCheckStatusError,
+ Code: common.NotInnoDBEngine,
+ Title: "InnoDB engine is not used",
+ Content: fmt.Sprintf("%q doesn't use InnoDB engine", statements[1]),
+ },
+ {
+ Status: api.TaskCheckStatusWarn,
+ Code: common.NamingTableConventionMismatch,
+ Title: "Mismatch table naming convention",
+ Content: "`userTable` mismatches table naming convention, naming format should be \"^[a-z]+(_[a-z]+)?$\"",
+ },
+ {
+ Status: api.TaskCheckStatusWarn,
+ Code: common.NamingColumnConventionMismatch,
+ Title: "Mismatch column naming convention",
+ Content: "`userTable`.`roomId` mismatches column naming convention, naming format should be \"^[a-z]+(_[a-z]+)?$\"",
+ },
+ {
+ Status: api.TaskCheckStatusWarn,
+ Code: common.NamingIndexConventionMismatch,
+ Title: "Mismatch index naming convention",
+ Content: "Index in table `userTable` mismatches the naming convention, expect \"^idx_userTable_name$\" but found `idx1`",
+ },
+ {
+ Status: api.TaskCheckStatusWarn,
+ Code: common.NamingUKConventionMismatch,
+ Title: "Mismatch unique key naming convention",
+ Content: "Unique key in table `userTable` mismatches the naming convention, expect \"^uk_userTable_id_name$\" but found `uk1`",
+ },
+ {
+ Status: api.TaskCheckStatusWarn,
+ Code: common.NamingFKConventionMismatch,
+ Title: "Mismatch foreign key naming convention",
+ Content: "Foreign key in table `userTable` mismatches the naming convention, expect \"^fk_userTable_roomId_room_id$\" but found `fk1`",
+ },
+ {
+ Status: api.TaskCheckStatusError,
+ Code: common.TableNoPK,
+ Title: "Require PRIMARY KEY",
+ Content: "Table `userTable` requires PRIMARY KEY",
+ },
+ {
+ Status: api.TaskCheckStatusWarn,
+ Code: common.NoRequiredColumn,
+ Title: "Require columns",
+ Content: "Table `userTable` requires columns: created_ts, creator_id, updated_ts, updater_id",
+ },
+ {
+ Status: api.TaskCheckStatusWarn,
+ Code: common.ColumnCanNull,
+ Title: "Column can have NULL value",
+ Content: "`userTable`.`id` can have NULL value",
+ },
+ {
+ Status: api.TaskCheckStatusWarn,
+ Code: common.ColumnCanNull,
+ Title: "Column can have NULL value",
+ Content: "`userTable`.`name` can have NULL value",
+ },
+ {
+ Status: api.TaskCheckStatusWarn,
+ Code: common.ColumnCanNull,
+ Title: "Column can have NULL value",
+ Content: "`userTable`.`roomId` can have NULL value",
+ },
+ },
+ },
+ {
+ statement: "DELETE FROM t",
+ result: []api.TaskCheckResult{
+ {
+ Status: api.TaskCheckStatusError,
+ Code: common.StatementNoWhere,
+ Title: "Require WHERE clause",
+ Content: "\"DELETE FROM t\" requires WHERE clause",
+ },
+ },
+ },
+ {
+ statement: "DELETE FROM t WHERE a like `%abc`",
+ result: []api.TaskCheckResult{
+ {
+ Status: api.TaskCheckStatusError,
+ Code: common.StatementLeadingWildcardLike,
+ Title: "No leading wildcard LIKE",
+ Content: "\"DELETE FROM t WHERE a like `%abc`\" uses leading wildcard LIKE",
+ },
+ },
+ },
+ {
+ // TODO(rebelice): most advisors cannot get the SQL text with sub-queries, fix it
+ statement: "INSERT INTO t_copy SELECT * FROM t",
+ result: []api.TaskCheckResult{
+ {
+ Status: api.TaskCheckStatusError,
+ Code: common.StatementSelectAll,
+ Title: "No SELECT all",
+ Content: "\"\" uses SELECT all",
+ },
+ {
+ Status: api.TaskCheckStatusError,
+ Code: common.StatementNoWhere,
+ Title: "Require WHERE clause",
+ Content: "\"\" requires WHERE clause",
+ },
+ },
+ },
+ {
+ statement: "DELETE FROM t WHERE a = (SELECT max(id) FROM user WHERE name = 'bytebase')",
+ result: []api.TaskCheckResult{
+ {
+ Status: api.TaskCheckStatusSuccess,
+ Code: common.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ }
+ )
+
+ t.Parallel()
+ a := require.New(t)
+ ctx := context.Background()
+ ctl := &controller{}
+ dataDir := t.TempDir()
+ port := getTestPort(t.Name()) + 3
+ err := ctl.StartServer(ctx, dataDir, getTestPort(t.Name()))
+ a.NoError(err)
+ defer ctl.Close(ctx)
+ err = ctl.Login()
+ a.NoError(err)
+
+ // Create a MySQL instance.
+ _, stopInstance := mysql.SetupTestInstance(t, port)
+ defer stopInstance()
+
+ mysqlDB, err := sql.Open("mysql", fmt.Sprintf("root@tcp(127.0.0.1:%d)/mysql", port))
+ a.NoError(err)
+ defer mysqlDB.Close()
+
+ _, err = mysqlDB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %v", databaseName))
+ a.NoError(err)
+
+ _, err = mysqlDB.Exec("DROP USER IF EXISTS bytebase")
+ a.NoError(err)
+ _, err = mysqlDB.Exec("CREATE USER 'bytebase' IDENTIFIED WITH mysql_native_password BY 'bytebase'")
+ a.NoError(err)
+
+ _, err = mysqlDB.Exec("GRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, DELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, SELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE, REPLICATION CLIENT, REPLICATION SLAVE, LOCK TABLES, RELOAD ON *.* to bytebase")
+ a.NoError(err)
+
+ // Create a project.
+ project, err := ctl.createProject(api.ProjectCreate{
+ Name: "Test Schema System Project",
+ Key: "TestSchemaSystem",
+ })
+ a.NoError(err)
+
+ environments, err := ctl.getEnvironments()
+ a.NoError(err)
+ prodEnvironment, err := findEnvironment(environments, "Prod")
+ a.NoError(err)
+
+ policyPayload, err := prodTemplateSchemaReviewPolicy()
+ a.NoError(err)
+
+ err = ctl.upsertPolicy(api.PolicyUpsert{
+ EnvironmentID: prodEnvironment.ID,
+ Type: api.PolicyTypeSchemaReview,
+ Payload: &policyPayload,
+ })
+ a.EqualError(err, schemaReviewAccessErr)
+
+ err = ctl.setLicense()
+ a.NoError(err)
+
+ err = ctl.upsertPolicy(api.PolicyUpsert{
+ EnvironmentID: prodEnvironment.ID,
+ Type: api.PolicyTypeSchemaReview,
+ Payload: &policyPayload,
+ })
+ a.NoError(err)
+
+ instance, err := ctl.addInstance(api.InstanceCreate{
+ EnvironmentID: prodEnvironment.ID,
+ Name: "mysqlInstance",
+ Engine: db.MySQL,
+ Host: "127.0.0.1",
+ Port: strconv.Itoa(port),
+ Username: "bytebase",
+ Password: "bytebase",
+ })
+ a.NoError(err)
+
+ databases, err := ctl.getDatabases(api.DatabaseFind{
+ ProjectID: &project.ID,
+ })
+ a.NoError(err)
+ a.Nil(databases)
+ databases, err = ctl.getDatabases(api.DatabaseFind{
+ InstanceID: &instance.ID,
+ })
+ a.NoError(err)
+ a.Nil(databases)
+
+ err = ctl.createDatabase(project, instance, databaseName, nil)
+ a.NoError(err)
+
+ databases, err = ctl.getDatabases(api.DatabaseFind{
+ ProjectID: &project.ID,
+ })
+ a.NoError(err)
+ a.Equal(1, len(databases))
+
+ database := databases[0]
+ a.Equal(database.Instance.ID, instance.ID)
+
+ for _, t := range tests {
+ createContext, err := json.Marshal(&api.UpdateSchemaContext{
+ MigrationType: db.Migrate,
+ DetailList: []*api.UpdateSchemaDetail{
+ {
+ DatabaseID: database.ID,
+ Statement: t.statement,
+ },
+ },
+ })
+ a.NoError(err)
+
+ issue, err := ctl.createIssue(api.IssueCreate{
+ ProjectID: project.ID,
+ Name: fmt.Sprintf("update schema for database %q", databaseName),
+ Type: api.IssueDatabaseSchemaUpdate,
+ Description: fmt.Sprintf("This updates the schema of database %q", databaseName),
+ AssigneeID: project.Creator.ID,
+ CreateContext: string(createContext),
+ })
+ a.NoError(err)
+
+ result, err := ctl.getSchemaReviewResult(issue.ID)
+ a.NoError(err)
+
+ a.Equal(t.result, result)
+ }
+}
diff --git a/tests/tests.go b/tests/tests.go
index 0a05c64c6b..208aa7ac79 100644
--- a/tests/tests.go
+++ b/tests/tests.go
@@ -124,6 +124,7 @@ func getTestPort(testName string) int {
"TestTenantVCSDatabaseNameTemplate",
"TestBootWithExternalPg",
"TestSheetVCS",
+ "TestSchemaSystem",
}
port := 1234
for _, name := range tests {
@@ -1226,3 +1227,201 @@ func (ctl *controller) createDataSource(dataSourceCreate api.DataSourceCreate) e
}
return nil
}
+
+// upsertPolicy upserts the policy.
+func (ctl *controller) upsertPolicy(policyUpsert api.PolicyUpsert) error {
+ buf := new(bytes.Buffer)
+ if err := jsonapi.MarshalPayload(buf, &policyUpsert); err != nil {
+ return fmt.Errorf("failed to marshal policyUpsert, error: %w", err)
+ }
+
+ body, err := ctl.patch(fmt.Sprintf("/policy/environment/%d?type=%s", policyUpsert.EnvironmentID, policyUpsert.Type), buf)
+ if err != nil {
+ return err
+ }
+
+ policy := new(api.Policy)
+ if err = jsonapi.UnmarshalPayload(body, policy); err != nil {
+ return fmt.Errorf("fail to unmarshal policy response, error: %w", err)
+ }
+ return nil
+}
+
+// schemaReviewTaskCheckRunFinished will return schema review task check result for next task.
+// If the schema review task check is not done, return nil, false, nil.
+func (ctl *controller) schemaReviewTaskCheckRunFinished(issue *api.Issue) ([]api.TaskCheckResult, bool, error) {
+ var result []api.TaskCheckResult
+ for _, stage := range issue.Pipeline.StageList {
+ for _, task := range stage.TaskList {
+ if task.Status == api.TaskPendingApproval {
+ for _, taskCheck := range task.TaskCheckRunList {
+ if taskCheck.Type == api.TaskCheckDatabaseStatementAdvise {
+ switch taskCheck.Status {
+ case api.TaskCheckRunRunning:
+ return nil, false, nil
+ case api.TaskCheckRunDone:
+ checkResult := &api.TaskCheckRunResultPayload{}
+ if err := json.Unmarshal([]byte(taskCheck.Result), checkResult); err != nil {
+ return nil, false, err
+ }
+ result = append(result, checkResult.ResultList...)
+ }
+ }
+ }
+ return result, true, nil
+ }
+ }
+ }
+ return nil, true, nil
+}
+
+// getSchemaReviewResult will wait for next task schema review task check to finish and return the task check result.
+func (ctl *controller) getSchemaReviewResult(id int) ([]api.TaskCheckResult, error) {
+ ticker := time.NewTicker(100 * time.Millisecond)
+ defer ticker.Stop()
+
+ for range ticker.C {
+ issue, err := ctl.getIssue(id)
+ if err != nil {
+ return nil, err
+ }
+
+ status, err := getAggregatedTaskStatus(issue)
+ if err != nil {
+ return nil, err
+ }
+
+ if status != api.TaskPendingApproval {
+ return nil, fmt.Errorf("the status of issue %v is not pending approval", id)
+ }
+
+ result, yes, err := ctl.schemaReviewTaskCheckRunFinished(issue)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get schema review result for issue %v: %w", id, err)
+ }
+ if yes {
+ return result, nil
+ }
+ }
+ return nil, nil
+}
+
+// setDefaultSchemaReviewRulePayload sets the default payload for this rule.
+func setDefaultSchemaReviewRulePayload(ruleTp api.SchemaReviewRuleType) (string, error) {
+ var payload []byte
+ var err error
+ switch ruleTp {
+ case api.SchemaRuleMySQLEngine:
+ case api.SchemaRuleStatementNoSelectAll:
+ case api.SchemaRuleStatementRequireWhere:
+ case api.SchemaRuleStatementNoLeadingWildcardLike:
+ case api.SchemaRuleTableRequirePK:
+ case api.SchemaRuleColumnNotNull:
+ case api.SchemaRuleTableNaming:
+ fallthrough
+ case api.SchemaRuleColumnNaming:
+ payload, err = json.Marshal(api.NamingRulePayload{
+ Format: "^[a-z]+(_[a-z]+)?$",
+ })
+ case api.SchemaRuleIDXNaming:
+ payload, err = json.Marshal(api.NamingRulePayload{
+ Format: "^idx_{{table}}_{{column_list}}$",
+ })
+ case api.SchemaRuleUKNaming:
+ payload, err = json.Marshal(api.NamingRulePayload{
+ Format: "^uk_{{table}}_{{column_list}}$",
+ })
+ case api.SchemaRuleFKNaming:
+ payload, err = json.Marshal(api.NamingRulePayload{
+ Format: "^fk_{{referencing_table}}_{{referencing_column}}_{{referenced_table}}_{{referenced_column}}$",
+ })
+ case api.SchemaRuleRequiredColumn:
+ payload, err = json.Marshal(api.RequiredColumnRulePayload{
+ ColumnList: []string{
+ "id",
+ "created_ts",
+ "updated_ts",
+ "creator_id",
+ "updater_id",
+ },
+ })
+ default:
+ return "", fmt.Errorf("Unknow schema review type for default payload: %s", ruleTp)
+ }
+
+ if err != nil {
+ return "", err
+ }
+ return string(payload), nil
+}
+
+// prodTemplateSchemaReviewPolicy returns the default schema review policy.
+func prodTemplateSchemaReviewPolicy() (string, error) {
+ policy := api.SchemaReviewPolicy{
+ Name: "Prod",
+ RuleList: []*api.SchemaReviewRule{
+ {
+ Type: api.SchemaRuleMySQLEngine,
+ Level: api.SchemaRuleLevelError,
+ },
+ {
+ Type: api.SchemaRuleTableNaming,
+ Level: api.SchemaRuleLevelWarning,
+ },
+ {
+ Type: api.SchemaRuleColumnNaming,
+ Level: api.SchemaRuleLevelWarning,
+ },
+ {
+ Type: api.SchemaRuleIDXNaming,
+ Level: api.SchemaRuleLevelWarning,
+ },
+ {
+ Type: api.SchemaRuleUKNaming,
+ Level: api.SchemaRuleLevelWarning,
+ },
+ {
+ Type: api.SchemaRuleFKNaming,
+ Level: api.SchemaRuleLevelWarning,
+ },
+ {
+ Type: api.SchemaRuleStatementNoSelectAll,
+ Level: api.SchemaRuleLevelError,
+ },
+ {
+ Type: api.SchemaRuleStatementRequireWhere,
+ Level: api.SchemaRuleLevelError,
+ },
+ {
+ Type: api.SchemaRuleStatementNoLeadingWildcardLike,
+ Level: api.SchemaRuleLevelError,
+ },
+ {
+ Type: api.SchemaRuleTableRequirePK,
+ Level: api.SchemaRuleLevelError,
+ },
+ {
+ Type: api.SchemaRuleRequiredColumn,
+ Level: api.SchemaRuleLevelWarning,
+ },
+ {
+ Type: api.SchemaRuleColumnNotNull,
+ Level: api.SchemaRuleLevelWarning,
+ },
+ },
+ }
+
+ for _, rule := range policy.RuleList {
+ payload, err := setDefaultSchemaReviewRulePayload(rule.Type)
+ if err != nil {
+ return "", err
+ }
+ rule.Payload = payload
+ }
+
+ s, err := json.Marshal(policy)
+ if err != nil {
+ return "", err
+ }
+ return string(s), nil
+}