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: move create tenant database schema generation from task creation to task execution (#3540)
Danny Xu28d867cf26d1
diff --git a/api/task.go b/api/task.goindex 8028dc51c5..10ab85dd29 100644--- a/api/task.go+++ b/api/task.go@@ -87,13 +87,12 @@ type TaskDatabasePITRCutoverPayload struct{}// TaskDatabaseCreatePayload is the task payload for creating databases.type TaskDatabaseCreatePayload struct {// The project owning the database.- ProjectID int `json:"projectId,omitempty"`- DatabaseName string `json:"databaseName,omitempty"`- Statement string `json:"statement,omitempty"`- CharacterSet string `json:"character,omitempty"`- Collation string `json:"collation,omitempty"`- Labels string `json:"labels,omitempty"`- SchemaVersion string `json:"schemaVersion,omitempty"`+ ProjectID int `json:"projectId,omitempty"`+ DatabaseName string `json:"databaseName,omitempty"`+ Statement string `json:"statement,omitempty"`+ CharacterSet string `json:"character,omitempty"`+ Collation string `json:"collation,omitempty"`+ Labels string `json:"labels,omitempty"`}// TaskDatabaseSchemaBaselinePayload is the task payload for database schema baseline.diff --git a/server/database.go b/server/database.goindex 43872c3f39..e9e851375b 100644--- a/server/database.go+++ b/server/database.go@@ -834,6 +834,9 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {}func (s *Server) setDatabaseLabels(ctx context.Context, labelsJSON string, database *api.Database, project *api.Project, updaterID int, validateOnly bool) error {+ if labelsJSON == "" {+ return nil+ }// NOTE: this is a partially filled DatabaseLabelvar labels []*api.DatabaseLabelif err := json.Unmarshal([]byte(labelsJSON), &labels); err != nil {diff --git a/server/issue.go b/server/issue.goindex 1231180163..c802dc83a6 100644--- a/server/issue.go+++ b/server/issue.go@@ -1080,24 +1080,14 @@ func (s *Server) createDatabaseCreateTaskList(ctx context.Context, c api.CreateD}}- var schemaVersion, schema string// We will use schema from existing tenant databases for creating a database in a tenant mode project if possible.if project.TenantMode == api.TenantModeTenant {if !s.feature(api.FeatureMultiTenancy) {return nil, echo.NewHTTPError(http.StatusForbidden, api.FeatureMultiTenancy.AccessErrorMessage())}- baseDatabaseName, err := api.GetBaseDatabaseName(c.DatabaseName, project.DBNameTemplate, c.Labels)- if err != nil {+ if _, err := api.GetBaseDatabaseName(c.DatabaseName, project.DBNameTemplate, c.Labels); err != nil {return nil, errors.Wrapf(err, "api.GetBaseDatabaseName(%q, %q, %q) failed", c.DatabaseName, project.DBNameTemplate, c.Labels)}- sv, s, err := s.getSchemaFromPeerTenantDatabase(ctx, &instance, &project, project.ID, baseDatabaseName)- if err != nil {- return nil, err- }- schemaVersion, schema = sv, s- }- if schemaVersion == "" {- schemaVersion = common.DefaultMigrationVersion()}// Get admin data source username.@@ -1105,14 +1095,23 @@ func (s *Server) createDatabaseCreateTaskList(ctx context.Context, c api.CreateDif adminDataSource == nil {return nil, common.Errorf(common.Internal, "admin data source not found for instance %d", instance.ID)}+ // Snowflake needs to use upper case of DatabaseName.+ databaseName := c.DatabaseName+ if instance.Engine == db.Snowflake {+ databaseName = strings.ToUpper(databaseName)+ }+ statement, err := getCreateDatabaseStatement(instance.Engine, c, databaseName, adminDataSource.Username)+ if err != nil {+ return nil, err+ }payload := api.TaskDatabaseCreatePayload{- ProjectID: project.ID,- CharacterSet: c.CharacterSet,- Collation: c.Collation,- Labels: c.Labels,- SchemaVersion: schemaVersion,+ ProjectID: project.ID,+ CharacterSet: c.CharacterSet,+ Collation: c.Collation,+ Labels: c.Labels,+ DatabaseName: databaseName,+ Statement: statement,}- payload.DatabaseName, payload.Statement = getDatabaseNameAndStatement(instance.Engine, c, adminDataSource.Username, schema)bytes, err := json.Marshal(payload)if err != nil {return nil, errors.Wrap(err, "failed to create database creation task, unable to marshal payload")@@ -1298,70 +1297,6 @@ func checkCharacterSetCollationOwner(dbType db.Type, characterSet, collation, owreturn nil}-func getDatabaseNameAndStatement(dbType db.Type, createDatabaseContext api.CreateDatabaseContext, adminDatasourceUser, schema string) (string, string) {- databaseName := createDatabaseContext.DatabaseName- // Snowflake needs to use upper case of DatabaseName.- if dbType == db.Snowflake {- databaseName = strings.ToUpper(databaseName)- }-- var stmt string- switch dbType {- case db.MySQL, db.TiDB:- stmt = fmt.Sprintf("CREATE DATABASE `%s` CHARACTER SET %s COLLATE %s;", databaseName, createDatabaseContext.CharacterSet, createDatabaseContext.Collation)- if schema != "" {- stmt = fmt.Sprintf("%s\nUSE `%s`;\n%s", stmt, databaseName, schema)- }- case db.Postgres:- // On Cloud RDS, the data source role isn't the actual superuser with sudo privilege.- // We need to grant the database owner role to the data source admin so that Bytebase can have permission for the database using the data source admin.- if adminDatasourceUser != "" && createDatabaseContext.Owner != adminDatasourceUser {- stmt = fmt.Sprintf("GRANT \"%s\" TO \"%s\";\n", createDatabaseContext.Owner, adminDatasourceUser)- }- if createDatabaseContext.Collation == "" {- stmt = fmt.Sprintf("%sCREATE DATABASE \"%s\" ENCODING %q;", stmt, databaseName, createDatabaseContext.CharacterSet)- } else {- stmt = fmt.Sprintf("%sCREATE DATABASE \"%s\" ENCODING %q LC_COLLATE %q;", stmt, databaseName, createDatabaseContext.CharacterSet, createDatabaseContext.Collation)- }- // Set the database owner.- // We didn't use CREATE DATABASE WITH OWNER because RDS requires the current role to be a member of the database owner.- // However, people can still use ALTER DATABASE to change the owner afterwards.- // Error string below:- // query: CREATE DATABASE h1 WITH OWNER hello;- // ERROR: must be member of role "hello"- //- // For tenant project, the schema for the newly created database will belong to the same owner.- // TODO(d): alter schema "public" owner to the database owner.- stmt = fmt.Sprintf("%s\nALTER DATABASE \"%s\" OWNER TO %s;\n", stmt, databaseName, createDatabaseContext.Owner)- if schema != "" {- stmt = fmt.Sprintf("%s\n\\connect \"%s\";\n%s", stmt, databaseName, schema)- }- case db.ClickHouse:- clusterPart := ""- if createDatabaseContext.Cluster != "" {- clusterPart = fmt.Sprintf(" ON CLUSTER `%s`", createDatabaseContext.Cluster)- }- stmt = fmt.Sprintf("CREATE DATABASE `%s`%s;", databaseName, clusterPart)- if schema != "" {- stmt = fmt.Sprintf("%s\nUSE `%s`;\n%s", stmt, databaseName, schema)- }- case db.Snowflake:- databaseName = strings.ToUpper(databaseName)- stmt = fmt.Sprintf("CREATE DATABASE %s;", databaseName)- if schema != "" {- stmt = fmt.Sprintf("%s\nUSE DATABASE %s;\n%s", stmt, databaseName, schema)- }- case db.SQLite:- // This is a fake CREATE DATABASE and USE statement since a single SQLite file represents a database. Engine driver will recognize it and establish a connection to create the sqlite file representing the database.- stmt = fmt.Sprintf("CREATE DATABASE '%s';", databaseName)- if schema != "" {- stmt = fmt.Sprintf("%s\nUSE `%s`;\n%s", stmt, databaseName, schema)- }- }-- return databaseName, stmt-}-func (s *Server) changeIssueStatus(ctx context.Context, issue *api.Issue, newStatus api.IssueStatus, updaterID int, comment string) (*api.Issue, error) {var pipelineStatus api.PipelineStatusswitch newStatus {diff --git a/server/task.go b/server/task.goindex 2026d8c4dd..ff5ee9eef0 100644--- a/server/task.go+++ b/server/task.go@@ -333,9 +333,6 @@ func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.T}oldStatement = payload.Statementpayload.Statement = *taskPatch.Statement- // We should update the schema version if we've updated the SQL, otherwise we will- // get migration history version conflict if the previous task has been attempted.- payload.SchemaVersion = common.DefaultMigrationVersion()bytes, err := json.Marshal(payload)if err != nil {return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct updated task payload").SetInternal(err)diff --git a/server/task_executor_database_create.go b/server/task_executor_database_create.goindex 10080cc273..2a254a918b 100644--- a/server/task_executor_database_create.go+++ b/server/task_executor_database_create.go@@ -13,6 +13,7 @@ import ("go.uber.org/zap""github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/common/log""github.com/bytebase/bytebase/plugin/db")@@ -57,9 +58,42 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Ser}defer driver.Close(ctx)+ project, err := server.store.GetProjectByID(ctx, payload.ProjectID)+ if err != nil {+ return true, nil, errors.Errorf("failed to find project with ID %d", payload.ProjectID)+ }+ if project == nil {+ return true, nil, errors.Errorf("project not found with ID %d", payload.ProjectID)+ }++ var schemaVersion string+ // We will use schema from existing tenant databases for creating a database in a tenant mode project if possible.+ if project.TenantMode == api.TenantModeTenant {+ baseDatabaseName, err := api.GetBaseDatabaseName(payload.DatabaseName, project.DBNameTemplate, payload.Labels)+ if err != nil {+ return true, nil, errors.Wrapf(err, "api.GetBaseDatabaseName(%q, %q, %q) failed", payload.DatabaseName, project.DBNameTemplate, payload.Labels)+ }+ sv, schema, err := server.getSchemaFromPeerTenantDatabase(ctx, instance, project, project.ID, baseDatabaseName)+ if err != nil {+ return true, nil, err+ }+ schemaVersion = sv+ connectionStmt, err := getConnectionStatement(instance.Engine, payload.DatabaseName)+ if err != nil {+ return true, nil, err+ }+ if !strings.Contains(payload.Statement, connectionStmt) {+ statement = fmt.Sprintf("%s\n%s\n%s", statement, connectionStmt, schema)+ }+ }+ if schemaVersion == "" {+ schemaVersion = common.DefaultMigrationVersion()+ }+log.Debug("Start creating database...",zap.String("instance", instance.Name),zap.String("database", payload.DatabaseName),+ zap.String("schemaVersion", schemaVersion),zap.String("statement", statement),)@@ -67,7 +101,7 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Ser// TODO(d): support semantic versioning.mi := &db.MigrationInfo{ReleaseVersion: server.profile.Version,- Version: payload.SchemaVersion,+ Version: schemaVersion,Namespace: payload.DatabaseName,Database: payload.DatabaseName,Environment: instance.Environment.Name,@@ -88,7 +122,6 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Ser} else {mi.Creator = creator.Name}-issue, err := server.store.GetIssueByPipelineID(ctx, task.PipelineID)if err != nil {// If somehow we unable to find the issue, we just emit the error since it's not@@ -135,7 +168,7 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *SerCollation: payload.Collation,LastSuccessfulSyncTs: time.Now().Unix(),Labels: &payload.Labels,- SchemaVersion: payload.SchemaVersion,+ SchemaVersion: schemaVersion,}createdDatabase, err := server.store.CreateDatabase(ctx, databaseCreate)if err != nil {@@ -151,6 +184,10 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Ser}database = updatedDatabase}+ // Set database labels, except bb.environment is immutable and must match instance environment.+ if err := server.setDatabaseLabels(ctx, payload.Labels, database, project, database.CreatorID, false); err != nil {+ return true, nil, errors.Errorf("failed to record database labels after creating database %v", database.ID)+ }// After the task related database entry created successfully,// we need to update task's database_id with the newly created database immediately.@@ -161,31 +198,74 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *SerID: task.ID,UpdaterID: api.SystemBotID,DatabaseID: &database.ID,+ Statement: &statement,}_, err = server.store.PatchTask(ctx, taskDatabaseIDPatch)if err != nil {return true, nil, err}- if payload.Labels != "" {- project, err := server.store.GetProjectByID(ctx, payload.ProjectID)- if err != nil {- return true, nil, errors.Errorf("failed to find project with ID %d", payload.ProjectID)- }- if project == nil {- return true, nil, errors.Errorf("project not found with ID %d", payload.ProjectID)- }-- // Set database labels, except bb.environment is immutable and must match instance environment.- err = server.setDatabaseLabels(ctx, payload.Labels, database, project, database.CreatorID, false)- if err != nil {- return true, nil, errors.Errorf("failed to record database labels after creating database %v", database.ID)- }- }-return true, &api.TaskRunResultPayload{Detail: fmt.Sprintf("Created database %q", payload.DatabaseName),MigrationID: migrationID,Version: mi.Version,}, nil}++func getCreateDatabaseStatement(dbType db.Type, createDatabaseContext api.CreateDatabaseContext, databaseName, adminDatasourceUser string) (string, error) {+ var stmt string+ switch dbType {+ case db.MySQL, db.TiDB:+ return fmt.Sprintf("CREATE DATABASE `%s` CHARACTER SET %s COLLATE %s;", databaseName, createDatabaseContext.CharacterSet, createDatabaseContext.Collation), nil+ case db.Postgres:+ // On Cloud RDS, the data source role isn't the actual superuser with sudo privilege.+ // We need to grant the database owner role to the data source admin so that Bytebase can have permission for the database using the data source admin.+ if adminDatasourceUser != "" && createDatabaseContext.Owner != adminDatasourceUser {+ stmt = fmt.Sprintf("GRANT \"%s\" TO \"%s\";\n", createDatabaseContext.Owner, adminDatasourceUser)+ }+ if createDatabaseContext.Collation == "" {+ stmt = fmt.Sprintf("%sCREATE DATABASE \"%s\" ENCODING %q;", stmt, databaseName, createDatabaseContext.CharacterSet)+ } else {+ stmt = fmt.Sprintf("%sCREATE DATABASE \"%s\" ENCODING %q LC_COLLATE %q;", stmt, databaseName, createDatabaseContext.CharacterSet, createDatabaseContext.Collation)+ }+ // Set the database owner.+ // We didn't use CREATE DATABASE WITH OWNER because RDS requires the current role to be a member of the database owner.+ // However, people can still use ALTER DATABASE to change the owner afterwards.+ // Error string below:+ // query: CREATE DATABASE h1 WITH OWNER hello;+ // ERROR: must be member of role "hello"+ //+ // For tenant project, the schema for the newly created database will belong to the same owner.+ // TODO(d): alter schema "public" owner to the database owner.+ return fmt.Sprintf("%s\nALTER DATABASE \"%s\" OWNER TO %s;", stmt, databaseName, createDatabaseContext.Owner), nil+ case db.ClickHouse:+ clusterPart := ""+ if createDatabaseContext.Cluster != "" {+ clusterPart = fmt.Sprintf(" ON CLUSTER `%s`", createDatabaseContext.Cluster)+ }+ return fmt.Sprintf("CREATE DATABASE `%s`%s;", databaseName, clusterPart), nil+ case db.Snowflake:+ return fmt.Sprintf("CREATE DATABASE %s;", databaseName), nil+ case db.SQLite:+ // This is a fake CREATE DATABASE and USE statement since a single SQLite file represents a database. Engine driver will recognize it and establish a connection to create the sqlite file representing the database.+ return fmt.Sprintf("CREATE DATABASE '%s';", databaseName), nil+ }+ return "", errors.Errorf("unsupported database type %s", dbType)+}++func getConnectionStatement(dbType db.Type, databaseName string) (string, error) {+ switch dbType {+ case db.MySQL, db.TiDB:+ return fmt.Sprintf("USE `%s`;\n", databaseName), nil+ case db.Postgres:+ return fmt.Sprintf("\\connect \"%s\";\n", databaseName), nil+ case db.ClickHouse:+ return fmt.Sprintf("USE `%s`;\n", databaseName), nil+ case db.Snowflake:+ return fmt.Sprintf("USE DATABASE %s;\n", databaseName), nil+ case db.SQLite:+ return fmt.Sprintf("USE `%s`;\n", databaseName), nil+ }++ return "", errors.Errorf("unsupported database type %s", dbType)+}diff --git a/tests/tests.go b/tests/tests.goindex 0098a69653..2a2ea414e8 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -1297,6 +1297,8 @@ func (ctl *controller) createDatabase(project *api.Project, instance *api.Instanif err != nil {return errors.Wrapf(err, "failed to patch issue status %v to done", issue.ID)}+ // Add a second sleep to avoid schema version conflict.+ time.Sleep(time.Second)return nil}