Skip to content

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

refactor: decouple api/service/store packages for Instance (#1089)

Yilong Li7581bdc97eb2
diff --git a/api/instance.go b/api/instance.go
index 828361f9b6..f8b3610780 100644
--- a/api/instance.go
+++ b/api/instance.go
@@ -1,62 +1,11 @@
package api
import (
- "context"
"encoding/json"
"github.com/bytebase/bytebase/plugin/db"
)
-// InstanceRaw is the store model for an Instance.
-// Fields have exactly the same meanings as Instance.
-type InstanceRaw struct {
- ID int
-
- // Standard fields
- RowStatus RowStatus
- CreatorID int
- CreatedTs int64
- UpdaterID int
- UpdatedTs int64
-
- // Related fields
- EnvironmentID int
-
- // Domain specific fields
- Name string
- Engine db.Type
- EngineVersion string
- ExternalLink string
- Host string
- Port string
-}
-
-// ToInstance creates an instance of Instance based on the InstanceRaw.
-// This is intended to be called when we need to compose an Instance relationship.
-func (raw *InstanceRaw) ToInstance() *Instance {
- return &Instance{
- ID: raw.ID,
-
- // Standard fields
- RowStatus: raw.RowStatus,
- CreatorID: raw.CreatorID,
- CreatedTs: raw.CreatedTs,
- UpdaterID: raw.UpdaterID,
- UpdatedTs: raw.UpdatedTs,
-
- // Related fields
- EnvironmentID: raw.EnvironmentID,
-
- // Domain specific fields
- Name: raw.Name,
- Engine: raw.Engine,
- EngineVersion: raw.EngineVersion,
- ExternalLink: raw.ExternalLink,
- Host: raw.Host,
- Port: raw.Port,
- }
-}
-
// Instance is the API message for an instance.
type Instance struct {
ID int `jsonapi:"primary,instance"`
@@ -213,13 +162,3 @@ type MigrationHistory struct {
IssueID string `jsonapi:"attr,issueId"`
Payload string `jsonapi:"attr,payload"`
}
-
-// InstanceService is the service for instances.
-type InstanceService interface {
- // CreateInstance should also create the * database and the admin data source.
- CreateInstance(ctx context.Context, create *InstanceCreate) (*InstanceRaw, error)
- FindInstanceList(ctx context.Context, find *InstanceFind) ([]*InstanceRaw, error)
- FindInstance(ctx context.Context, find *InstanceFind) (*InstanceRaw, error)
- CountInstance(ctx context.Context, find *InstanceFind) (int, error)
- PatchInstance(ctx context.Context, patch *InstancePatch) (*InstanceRaw, error)
-}
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.go
index db5c7a3494..47dd82941e 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -457,7 +457,6 @@ func (m *Main) Run(ctx context.Context) error {
s.DatabaseService = store.NewDatabaseService(m.l, db, cacheService, storeInstance)
// TODO(dragonly): remove this hack
storeInstance.DatabaseService = s.DatabaseService
- s.InstanceService = store.NewInstanceService(m.l, db, cacheService, s.DatabaseService, storeInstance)
s.InstanceUserService = store.NewInstanceUserService(m.l, db)
s.TableService = store.NewTableService(m.l, db)
s.ColumnService = store.NewColumnService(m.l, db)
diff --git a/server/anomaly_scanner.go b/server/anomaly_scanner.go
index d3b9a0d461..19647acec0 100644
--- a/server/anomaly_scanner.go
+++ b/server/anomaly_scanner.go
@@ -80,22 +80,16 @@ func (s *AnomalyScanner) Run(ctx context.Context, wg *sync.WaitGroup) {
instanceFind := &api.InstanceFind{
RowStatus: &rowStatus,
}
- instanceRawList, err := s.server.InstanceService.FindInstanceList(ctx, instanceFind)
+ instanceList, err := s.server.store.FindInstance(ctx, instanceFind)
if err != nil {
s.l.Error("Failed to retrieve instance list", zap.Error(err))
return
}
- for _, instanceRaw := range instanceRawList {
- instance, err := s.server.composeInstanceRelationship(ctx, instanceRaw)
- if err != nil {
- s.l.Error(fmt.Sprintf("Failed to compose instance relationship, ID %v, name %q.", instanceRaw.ID, instanceRaw.Name), zap.Error(err))
- continue
- }
-
+ for _, instance := range instanceList {
foundEnv := false
for _, env := range envList {
- if env.ID == instanceRaw.EnvironmentID {
+ if env.ID == instance.EnvironmentID {
if env.RowStatus == api.Normal {
instance.Environment = env
}
@@ -109,11 +103,11 @@ func (s *AnomalyScanner) Run(ctx context.Context, wg *sync.WaitGroup) {
}
mu.Lock()
- if _, ok := runningTasks[instanceRaw.ID]; ok {
+ if _, ok := runningTasks[instance.ID]; ok {
mu.Unlock()
continue
}
- runningTasks[instanceRaw.ID] = true
+ runningTasks[instance.ID] = true
mu.Unlock()
// Do NOT use go-routine otherwise would cause "database locked" in underlying SQLite
diff --git a/server/database.go b/server/database.go
index 03b29c5077..cdd7c25124 100644
--- a/server/database.go
+++ b/server/database.go
@@ -25,15 +25,15 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
}
databaseCreate.CreatorID = c.Get(getPrincipalIDContextKey()).(int)
- instanceRaw, err := s.InstanceService.FindInstance(ctx, &api.InstanceFind{ID: &databaseCreate.InstanceID})
+ instance, err := s.store.GetInstanceByID(ctx, databaseCreate.InstanceID)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find instance").SetInternal(err)
}
- if instanceRaw == nil {
+ if instance == nil {
err := fmt.Errorf("Instance ID not found %v", databaseCreate.InstanceID)
return echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
}
- databaseCreate.EnvironmentID = instanceRaw.EnvironmentID
+ databaseCreate.EnvironmentID = instance.EnvironmentID
project, err := s.composeProjectByID(ctx, databaseCreate.ProjectID)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find project").SetInternal(err)
@@ -48,7 +48,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
// Pre-validate database labels.
if databaseCreate.Labels != nil && *databaseCreate.Labels != "" {
// TODO(dragonly): compose Instance
- if err := s.setDatabaseLabels(ctx, *databaseCreate.Labels, &api.Database{Name: databaseCreate.Name, Instance: instanceRaw.ToInstance()} /* dummy database */, project, databaseCreate.CreatorID, true /* validateOnly */); err != nil {
+ if err := s.setDatabaseLabels(ctx, *databaseCreate.Labels, &api.Database{Name: databaseCreate.Name, Instance: instance} /* dummy database */, project, databaseCreate.CreatorID, true /* validateOnly */); err != nil {
return err
}
}
@@ -989,7 +989,7 @@ func (s *Server) composeDatabaseRelationship(ctx context.Context, raw *api.Datab
}
db.Project = project
- instance, err := s.composeInstanceByID(ctx, db.InstanceID)
+ instance, err := s.store.GetInstanceByID(ctx, db.InstanceID)
if err != nil {
return nil, err
}
diff --git a/server/instance.go b/server/instance.go
index ed16e8f16f..dd48c2cf2c 100644
--- a/server/instance.go
+++ b/server/instance.go
@@ -31,7 +31,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
}
- instanceRaw, err := s.InstanceService.CreateInstance(ctx, instanceCreate)
+ instance, err := s.store.CreateInstance(ctx, instanceCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Instance name already exists: %s", instanceCreate.Name))
@@ -39,11 +39,6 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create instance").SetInternal(err)
}
- instance, err := s.composeInstanceRelationship(ctx, instanceRaw)
- if err != nil {
- return err
- }
-
// Try creating the "bytebase" db in the added instance if needed.
// Since we allow user to add new instance upfront even providing the incorrect username/password,
// thus it's OK if it fails. Frontend will surface relevant info suggesting the "bytebase" db hasn't created yet.
@@ -74,20 +69,11 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
rowStatus := api.RowStatus(rowStatusStr)
instanceFind.RowStatus = &rowStatus
}
- instanceRawList, err := s.InstanceService.FindInstanceList(ctx, instanceFind)
+ instanceList, err := s.store.FindInstance(ctx, instanceFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch instance list").SetInternal(err)
}
- var instanceList []*api.Instance
- for _, instanceRaw := range instanceRawList {
- instance, err := s.composeInstanceRelationship(ctx, instanceRaw)
- if err != nil {
- return err
- }
- instanceList = append(instanceList, instance)
- }
-
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, instanceList); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal instance list response").SetInternal(err)
@@ -102,7 +88,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceID"))).SetInternal(err)
}
- instance, err := s.composeInstanceByID(ctx, id)
+ instance, err := s.store.GetInstanceByID(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
@@ -131,7 +117,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
if err := jsonapi.UnmarshalPayload(c.Request().Body, instancePatch); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch instance request").SetInternal(err)
}
- instance, err := s.composeInstanceByID(ctx, id)
+ instance, err := s.store.GetInstanceByID(ctx, id)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get instance ID: %v", id)).SetInternal(err)
}
@@ -149,7 +135,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
}
- var instancePatchedRaw *api.InstanceRaw
+ var instancePatched *api.Instance
if instancePatch.RowStatus != nil || instancePatch.Name != nil || instancePatch.ExternalLink != nil || instancePatch.Host != nil || instancePatch.Port != nil {
// Users can switch instance status from ARCHIVED to NORMAL.
// So we need to check the current instance count with NORMAL status for quota limitation.
@@ -158,7 +144,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return err
}
}
- instancePatchedRaw, err = s.InstanceService.PatchInstance(ctx, instancePatch)
+ instancePatched, err = s.store.PatchInstance(ctx, instancePatch)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
@@ -167,11 +153,6 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
}
}
- instancePatched, err := s.composeInstanceRelationship(ctx, instancePatchedRaw)
- if err != nil {
- return err
- }
-
// Try immediately setup the migration schema, sync the engine version and schema after updating any connection related info.
if instancePatch.Host != nil || instancePatch.Port != nil {
db, err := getAdminDatabaseDriver(ctx, instancePatched, "", s.l)
@@ -179,8 +160,8 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
defer db.Close(ctx)
if err := db.SetupMigrationIfNeeded(ctx); err != nil {
s.l.Warn("Failed to setup migration schema on instance update",
- zap.String("instance_name", instancePatchedRaw.Name),
- zap.String("engine", string(instancePatchedRaw.Engine)),
+ zap.String("instance_name", instancePatched.Name),
+ zap.String("engine", string(instancePatched.Engine)),
zap.Error(err))
}
s.syncEngineVersionAndSchema(ctx, instancePatched)
@@ -223,7 +204,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceID"))).SetInternal(err)
}
- instance, err := s.composeInstanceByID(ctx, id)
+ instance, err := s.store.GetInstanceByID(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
@@ -256,7 +237,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceID"))).SetInternal(err)
}
- instance, err := s.composeInstanceByID(ctx, id)
+ instance, err := s.store.GetInstanceByID(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
@@ -301,7 +282,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("History ID is not a number: %s", c.Param("historyID"))).SetInternal(err)
}
- instance, err := s.composeInstanceByID(ctx, id)
+ instance, err := s.store.GetInstanceByID(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
@@ -359,7 +340,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceID"))).SetInternal(err)
}
- instance, err := s.composeInstanceByID(ctx, id)
+ instance, err := s.store.GetInstanceByID(ctx, id)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
@@ -428,77 +409,6 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
})
}
-func (s *Server) composeInstanceByID(ctx context.Context, id int) (*api.Instance, error) {
- instanceFind := &api.InstanceFind{
- ID: &id,
- }
- instanceRaw, err := s.InstanceService.FindInstance(ctx, instanceFind)
- if err != nil {
- return nil, err
- }
- if instanceRaw == nil {
- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("instance not found with ID %v", id)}
- }
-
- instance, err := s.composeInstanceRelationship(ctx, instanceRaw)
- if err != nil {
- return nil, err
- }
-
- return instance, nil
-}
-
-func (s *Server) composeInstanceRelationship(ctx context.Context, raw *api.InstanceRaw) (*api.Instance, error) {
- instance := raw.ToInstance()
-
- creator, err := s.store.GetPrincipalByID(ctx, instance.CreatorID)
- if err != nil {
- return nil, err
- }
- instance.Creator = creator
-
- updater, err := s.store.GetPrincipalByID(ctx, instance.UpdaterID)
- if err != nil {
- return nil, err
- }
- instance.Updater = updater
-
- env, err := s.store.GetEnvironmentByID(ctx, instance.EnvironmentID)
- if err != nil {
- return nil, err
- }
- instance.Environment = env
-
- rowStatus := api.Normal
- anomalyList, err := s.store.FindAnomaly(ctx, &api.AnomalyFind{
- RowStatus: &rowStatus,
- InstanceID: &instance.ID,
- InstanceOnly: true,
- })
- if err != nil {
- return nil, err
- }
- instance.AnomalyList = anomalyList
-
- dataSourceList, err := s.store.FindDataSource(ctx, &api.DataSourceFind{
- InstanceID: &instance.ID,
- })
- if err != nil {
- return nil, err
- }
- instance.DataSourceList = dataSourceList
- for _, dataSource := range instance.DataSourceList {
- if dataSource.Creator, err = s.store.GetPrincipalByID(ctx, dataSource.CreatorID); err != nil {
- return nil, err
- }
- if dataSource.Updater, err = s.store.GetPrincipalByID(ctx, dataSource.UpdaterID); err != nil {
- return nil, err
- }
- }
-
- return instance, nil
-}
-
func (s *Server) findInstanceAdminPasswordByID(ctx context.Context, instanceID int) (string, error) {
dataSourceFind := &api.DataSourceFind{
InstanceID: &instanceID,
@@ -519,7 +429,7 @@ func (s *Server) findInstanceAdminPasswordByID(ctx context.Context, instanceID i
// We only count instances with NORMAL status since users cannot make any operations for ARCHIVED one.
func (s *Server) instanceCountGuard(ctx context.Context) error {
status := api.Normal
- count, err := s.InstanceService.CountInstance(ctx, &api.InstanceFind{
+ count, err := s.store.CountInstance(ctx, &api.InstanceFind{
RowStatus: &status,
})
diff --git a/server/issue.go b/server/issue.go
index 73284deeb4..e39b0355f9 100644
--- a/server/issue.go
+++ b/server/issue.go
@@ -555,7 +555,7 @@ func (s *Server) createPipelineFromIssue(ctx context.Context, issueCreate *api.I
}
// Find instance.
- instance, err := s.composeInstanceByID(ctx, m.InstanceID)
+ instance, err := s.store.GetInstanceByID(ctx, m.InstanceID)
if err != nil {
return nil, err
}
diff --git a/server/schema_syncer.go b/server/schema_syncer.go
index 1d6a0ce3f0..cfe9e24f86 100644
--- a/server/schema_syncer.go
+++ b/server/schema_syncer.go
@@ -57,29 +57,21 @@ func (s *SchemaSyncer) Run(ctx context.Context, wg *sync.WaitGroup) {
instanceFind := &api.InstanceFind{
RowStatus: &rowStatus,
}
- instanceRawList, err := s.server.InstanceService.FindInstanceList(ctx, instanceFind)
+ instanceList, err := s.server.store.FindInstance(ctx, instanceFind)
if err != nil {
s.l.Error("Failed to retrieve instances", zap.Error(err))
return
}
- for _, instanceRaw := range instanceRawList {
+ for _, instance := range instanceList {
mu.Lock()
- if _, ok := runningTasks[instanceRaw.ID]; ok {
+ if _, ok := runningTasks[instance.ID]; ok {
mu.Unlock()
continue
}
- runningTasks[instanceRaw.ID] = true
+ runningTasks[instance.ID] = true
mu.Unlock()
- instance, err := s.server.composeInstanceRelationship(ctx, instanceRaw)
- if err != nil {
- s.l.Error("Failed to sync instance",
- zap.Int("id", instance.ID),
- zap.String("name", instance.Name),
- zap.String("error", err.Error()))
- continue
- }
go func(instance *api.Instance) {
s.l.Debug("Sync instance schema", zap.String("instance", instance.Name))
defer func() {
diff --git a/server/server.go b/server/server.go
index e644daa4ae..bfea0d9fa6 100644
--- a/server/server.go
+++ b/server/server.go
@@ -40,7 +40,6 @@ type Server struct {
ProjectService api.ProjectService
ProjectMemberService api.ProjectMemberService
ProjectWebhookService api.ProjectWebhookService
- InstanceService api.InstanceService
InstanceUserService api.InstanceUserService
DatabaseService api.DatabaseService
TableService api.TableService
diff --git a/server/sql.go b/server/sql.go
index 38468c09ff..8558d38117 100644
--- a/server/sql.go
+++ b/server/sql.go
@@ -84,7 +84,7 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted sql sync schema request").SetInternal(err)
}
- instance, err := s.composeInstanceByID(ctx, sync.InstanceID)
+ instance, err := s.store.GetInstanceByID(ctx, sync.InstanceID)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", sync.InstanceID))
@@ -121,7 +121,7 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted sql execute request, only support SELECT sql statement")
}
- instance, err := s.composeInstanceByID(ctx, exec.InstanceID)
+ instance, err := s.store.GetInstanceByID(ctx, exec.InstanceID)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", exec.InstanceID))
@@ -240,7 +240,7 @@ func (s *Server) syncEngineVersionAndSchema(ctx context.Context, instance *api.I
// Underlying version may change due to upgrade, however it's a rare event, so we only update if it actually differs
// to avoid changing the updated_ts
if version != instance.EngineVersion {
- _, err := s.InstanceService.PatchInstance(ctx, &api.InstancePatch{
+ _, err := s.store.PatchInstance(ctx, &api.InstancePatch{
ID: instance.ID,
UpdaterID: api.SystemBotID,
EngineVersion: &version,
diff --git a/server/task.go b/server/task.go
index f6e828a125..693e63c7cb 100644
--- a/server/task.go
+++ b/server/task.go
@@ -458,7 +458,7 @@ func (s *Server) composeTaskRelationship(ctx context.Context, raw *api.TaskRaw)
taskCheckRun.Updater = updater
}
- instance, err := s.composeInstanceByID(ctx, task.InstanceID)
+ instance, err := s.store.GetInstanceByID(ctx, task.InstanceID)
if err != nil {
return nil, err
}
@@ -519,10 +519,11 @@ func (s *Server) composeTaskRelationshipValidateOnly(ctx context.Context, task *
}
}
- task.Instance, err = s.composeInstanceByID(ctx, task.InstanceID)
+ instance, err := s.store.GetInstanceByID(ctx, task.InstanceID)
if err != nil {
return err
}
+ task.Instance = instance
if task.DatabaseID != nil {
databaseFind := &api.DatabaseFind{
@@ -657,8 +658,7 @@ func (s *Server) changeTaskStatusWithPatch(ctx context.Context, task *api.Task,
// If create database or schema update task completes, we sync the corresponding instance schema immediately.
if (taskPatched.Type == api.TaskDatabaseCreate || taskPatched.Type == api.TaskDatabaseSchemaUpdate) &&
taskPatched.Status == api.TaskDone {
- // TODO(dragonly): remove this composition
- instance, err := s.composeInstanceByID(ctx, task.InstanceID)
+ instance, err := s.store.GetInstanceByID(ctx, task.InstanceID)
if err != nil {
return nil, fmt.Errorf("failed to sync instance schema after completing task: %w", err)
}
diff --git a/server/task_check_executor_migration_schema.go b/server/task_check_executor_migration_schema.go
index 2243488eeb..ccb93e0265 100644
--- a/server/task_check_executor_migration_schema.go
+++ b/server/task_check_executor_migration_schema.go
@@ -41,7 +41,7 @@ func (exec *TaskCheckMigrationSchemaExecutor) Run(ctx context.Context, server *S
}, nil
}
- instance, err := server.composeInstanceByID(ctx, task.InstanceID)
+ instance, err := server.store.GetInstanceByID(ctx, task.InstanceID)
if err != nil {
return []api.TaskCheckResult{}, err
}
diff --git a/server/task_scheduler.go b/server/task_scheduler.go
index 3a96a961a5..4e63b1fdfc 100644
--- a/server/task_scheduler.go
+++ b/server/task_scheduler.go
@@ -271,10 +271,7 @@ func (s *TaskScheduler) ScheduleIfNeeded(ctx context.Context, task *api.Task) (*
return task, nil
}
- instanceFind := &api.InstanceFind{
- ID: &task.InstanceID,
- }
- instance, err := s.server.InstanceService.FindInstance(ctx, instanceFind)
+ instance, err := s.server.store.GetInstanceByID(ctx, task.InstanceID)
if err != nil {
return nil, err
}
diff --git a/store/instance.go b/store/instance.go
index 3d9145b89c..ae719bc936 100644
--- a/store/instance.go
+++ b/store/instance.go
@@ -8,38 +8,214 @@ import (
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
- "go.uber.org/zap"
+ "github.com/bytebase/bytebase/plugin/db"
)
-var (
- _ api.InstanceService = (*InstanceService)(nil)
-)
+// instanceRaw is the store model for an Instance.
+// Fields have exactly the same meanings as Instance.
+type instanceRaw struct {
+ ID int
+
+ // Standard fields
+ RowStatus api.RowStatus
+ CreatorID int
+ CreatedTs int64
+ UpdaterID int
+ UpdatedTs int64
+
+ // Related fields
+ EnvironmentID int
+
+ // Domain specific fields
+ Name string
+ Engine db.Type
+ EngineVersion string
+ ExternalLink string
+ Host string
+ Port string
+}
-// InstanceService represents a service for managing instance.
-type InstanceService struct {
- l *zap.Logger
- db *DB
+// toInstance creates an instance of Instance based on the instanceRaw.
+// This is intended to be called when we need to compose an Instance relationship.
+func (raw *instanceRaw) toInstance() *api.Instance {
+ return &api.Instance{
+ ID: raw.ID,
+
+ // Standard fields
+ RowStatus: raw.RowStatus,
+ CreatorID: raw.CreatorID,
+ CreatedTs: raw.CreatedTs,
+ UpdaterID: raw.UpdaterID,
+ UpdatedTs: raw.UpdatedTs,
+
+ // Related fields
+ EnvironmentID: raw.EnvironmentID,
+
+ // Domain specific fields
+ Name: raw.Name,
+ Engine: raw.Engine,
+ EngineVersion: raw.EngineVersion,
+ ExternalLink: raw.ExternalLink,
+ Host: raw.Host,
+ Port: raw.Port,
+ }
+}
- cache api.CacheService
+// CreateInstance creates an instance of Instance
+func (s *Store) CreateInstance(ctx context.Context, create *api.InstanceCreate) (*api.Instance, error) {
+ instanceRaw, err := s.createInstanceRaw(ctx, create)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to create Instance with InstanceCreate[%+v], error[%w]", create, err)
+ }
+ instance, err := s.composeInstance(ctx, instanceRaw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose Instance with instanceRaw[%+v], error[%w]", instanceRaw, err)
+ }
+ return instance, nil
+}
+
+// GetInstanceByID gets an instance of Instance
+func (s *Store) GetInstanceByID(ctx context.Context, id int) (*api.Instance, error) {
+ find := &api.InstanceFind{ID: &id}
+ instanceRaw, err := s.getInstanceRaw(ctx, find)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to get Instance with ID[%d], error[%w]", id, err)
+ }
+ if instanceRaw == nil {
+ return nil, nil
+ }
+ instance, err := s.composeInstance(ctx, instanceRaw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose Instance with instanceRaw[%+v], error[%w]", instanceRaw, err)
+ }
+ return instance, nil
+}
- databaseService api.DatabaseService
- store *Store
+// FindInstance finds a list of Instance instances
+func (s *Store) FindInstance(ctx context.Context, find *api.InstanceFind) ([]*api.Instance, error) {
+ instanceRawList, err := s.findInstanceRaw(ctx, find)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to find Instance list, error[%w]", err)
+ }
+ var instanceList []*api.Instance
+ for _, raw := range instanceRawList {
+ instance, err := s.composeInstance(ctx, raw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose Instance with instanceRaw[%+v], error[%w]", raw, err)
+ }
+ instanceList = append(instanceList, instance)
+ }
+ return instanceList, nil
}
-// NewInstanceService returns a new instance of InstanceService.
-func NewInstanceService(logger *zap.Logger, db *DB, cache api.CacheService, databaseService api.DatabaseService, store *Store) *InstanceService {
- return &InstanceService{l: logger, db: db, cache: cache, databaseService: databaseService, store: store}
+// PatchInstance patches an instance of Instance
+func (s *Store) PatchInstance(ctx context.Context, patch *api.InstancePatch) (*api.Instance, error) {
+ instanceRaw, err := s.patchInstanceRaw(ctx, patch)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to patch Instance with InstancePatch[%+v], error[%w]", patch, err)
+ }
+ instance, err := s.composeInstance(ctx, instanceRaw)
+ if err != nil {
+ return nil, fmt.Errorf("Failed to compose Instance with instanceRaw[%+v], error[%w]", instanceRaw, err)
+ }
+ return instance, nil
}
-// CreateInstance creates a new instance.
-func (s *InstanceService) CreateInstance(ctx context.Context, create *api.InstanceCreate) (*api.InstanceRaw, error) {
+// CountInstance counts the number of instances.
+func (s *Store) CountInstance(ctx context.Context, find *api.InstanceFind) (int, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return 0, FormatError(err)
+ }
+ defer tx.PTx.Rollback()
+
+ where, args := findInstanceQuery(find)
+
+ row, err := tx.PTx.QueryContext(ctx, `
+ SELECT COUNT(*)
+ FROM instance
+ WHERE `+where,
+ args...,
+ )
+ if err != nil {
+ return 0, FormatError(err)
+ }
+ defer row.Close()
+
+ count := 0
+ if row.Next() {
+ if err := row.Scan(&count); err != nil {
+ return 0, FormatError(err)
+ }
+ }
+
+ return count, nil
+}
+
+//
+// private function
+//
+
+func (s *Store) composeInstance(ctx context.Context, raw *instanceRaw) (*api.Instance, error) {
+ instance := raw.toInstance()
+
+ creator, err := s.GetPrincipalByID(ctx, instance.CreatorID)
+ if err != nil {
+ return nil, err
+ }
+ instance.Creator = creator
+
+ updater, err := s.GetPrincipalByID(ctx, instance.UpdaterID)
+ if err != nil {
+ return nil, err
+ }
+ instance.Updater = updater
+
+ env, err := s.GetEnvironmentByID(ctx, instance.EnvironmentID)
+ if err != nil {
+ return nil, err
+ }
+ instance.Environment = env
+
+ rowStatus := api.Normal
+ anomalyList, err := s.FindAnomaly(ctx, &api.AnomalyFind{
+ RowStatus: &rowStatus,
+ InstanceID: &instance.ID,
+ InstanceOnly: true,
+ })
+ if err != nil {
+ return nil, err
+ }
+ instance.AnomalyList = anomalyList
+
+ dataSourceList, err := s.FindDataSource(ctx, &api.DataSourceFind{
+ InstanceID: &instance.ID,
+ })
+ if err != nil {
+ return nil, err
+ }
+ instance.DataSourceList = dataSourceList
+ for _, dataSource := range instance.DataSourceList {
+ if dataSource.Creator, err = s.GetPrincipalByID(ctx, dataSource.CreatorID); err != nil {
+ return nil, err
+ }
+ if dataSource.Updater, err = s.GetPrincipalByID(ctx, dataSource.UpdaterID); err != nil {
+ return nil, err
+ }
+ }
+
+ return instance, nil
+}
+
+// createInstanceRaw creates a new instance.
+func (s *Store) createInstanceRaw(ctx context.Context, create *api.InstanceCreate) (*instanceRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.PTx.Rollback()
- instance, err := createInstance(ctx, tx.PTx, create)
+ instance, err := createInstanceImpl(ctx, tx.PTx, create)
if err != nil {
return nil, err
}
@@ -54,7 +230,7 @@ func (s *InstanceService) CreateInstance(ctx context.Context, create *api.Instan
CharacterSet: api.DefaultCharactorSetName,
Collation: api.DefaultCollationName,
}
- allDatabase, err := s.databaseService.CreateDatabaseTx(ctx, tx.PTx, databaseCreate)
+ allDatabase, err := s.DatabaseService.CreateDatabaseTx(ctx, tx.PTx, databaseCreate)
if err != nil {
return nil, err
}
@@ -69,7 +245,7 @@ func (s *InstanceService) CreateInstance(ctx context.Context, create *api.Instan
Username: create.Username,
Password: create.Password,
}
- if err := s.store.createDataSourceRawTx(ctx, tx.PTx, adminDataSourceCreate); err != nil {
+ if err := s.createDataSourceRawTx(ctx, tx.PTx, adminDataSourceCreate); err != nil {
return nil, err
}
@@ -84,15 +260,15 @@ func (s *InstanceService) CreateInstance(ctx context.Context, create *api.Instan
return instance, nil
}
-// FindInstanceList retrieves a list of instances based on find.
-func (s *InstanceService) FindInstanceList(ctx context.Context, find *api.InstanceFind) ([]*api.InstanceRaw, error) {
+// findInstanceRaw retrieves a list of instances based on find.
+func (s *Store) findInstanceRaw(ctx context.Context, find *api.InstanceFind) ([]*instanceRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.PTx.Rollback()
- list, err := findInstanceList(ctx, tx.PTx, find)
+ list, err := findInstanceImpl(ctx, tx.PTx, find)
if err != nil {
return nil, err
}
@@ -100,42 +276,11 @@ func (s *InstanceService) FindInstanceList(ctx context.Context, find *api.Instan
return list, nil
}
-// CountInstance counts the number of instances.
-func (s *InstanceService) CountInstance(ctx context.Context, find *api.InstanceFind) (int, error) {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return 0, FormatError(err)
- }
- defer tx.PTx.Rollback()
-
- where, args := findInstanceQuery(find)
-
- row, err := tx.PTx.QueryContext(ctx, `
- SELECT COUNT(*)
- FROM instance
- WHERE `+where,
- args...,
- )
- if err != nil {
- return 0, FormatError(err)
- }
- defer row.Close()
-
- count := 0
- if row.Next() {
- if err := row.Scan(&count); err != nil {
- return 0, FormatError(err)
- }
- }
-
- return count, nil
-}
-
-// FindInstance retrieves a single instance based on find.
+// getInstanceRaw retrieves a single instance based on find.
// Returns ECONFLICT if finding more than 1 matching records.
-func (s *InstanceService) FindInstance(ctx context.Context, find *api.InstanceFind) (*api.InstanceRaw, error) {
+func (s *Store) getInstanceRaw(ctx context.Context, find *api.InstanceFind) (*instanceRaw, error) {
if find.ID != nil {
- instanceRaw := &api.InstanceRaw{}
+ instanceRaw := &instanceRaw{}
has, err := s.cache.FindCache(api.InstanceCache, *find.ID, instanceRaw)
if err != nil {
return nil, err
@@ -151,7 +296,7 @@ func (s *InstanceService) FindInstance(ctx context.Context, find *api.InstanceFi
}
defer tx.PTx.Rollback()
- list, err := findInstanceList(ctx, tx.PTx, find)
+ list, err := findInstanceImpl(ctx, tx.PTx, find)
if err != nil {
return nil, err
}
@@ -169,16 +314,16 @@ func (s *InstanceService) FindInstance(ctx context.Context, find *api.InstanceFi
return instance, nil
}
-// PatchInstance updates an existing instance by ID.
+// patchInstanceRaw updates an existing instance by ID.
// Returns ENOTFOUND if instance does not exist.
-func (s *InstanceService) PatchInstance(ctx context.Context, patch *api.InstancePatch) (*api.InstanceRaw, error) {
+func (s *Store) patchInstanceRaw(ctx context.Context, patch *api.InstancePatch) (*instanceRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.PTx.Rollback()
- instance, err := patchInstance(ctx, tx.PTx, patch)
+ instance, err := patchInstanceImpl(ctx, tx.PTx, patch)
if err != nil {
return nil, FormatError(err)
}
@@ -194,8 +339,8 @@ func (s *InstanceService) PatchInstance(ctx context.Context, patch *api.Instance
return instance, nil
}
-// createInstance creates a new instance.
-func createInstance(ctx context.Context, tx *sql.Tx, create *api.InstanceCreate) (*api.InstanceRaw, error) {
+// createInstanceImpl creates a new instance.
+func createInstanceImpl(ctx context.Context, tx *sql.Tx, create *api.InstanceCreate) (*instanceRaw, error) {
// Insert row into database.
row, err := tx.QueryContext(ctx, `
INSERT INTO instance (
@@ -227,7 +372,7 @@ func createInstance(ctx context.Context, tx *sql.Tx, create *api.InstanceCreate)
defer row.Close()
row.Next()
- var instanceRaw api.InstanceRaw
+ var instanceRaw instanceRaw
if err := row.Scan(
&instanceRaw.ID,
&instanceRaw.RowStatus,
@@ -249,7 +394,7 @@ func createInstance(ctx context.Context, tx *sql.Tx, create *api.InstanceCreate)
return &instanceRaw, nil
}
-func findInstanceList(ctx context.Context, tx *sql.Tx, find *api.InstanceFind) ([]*api.InstanceRaw, error) {
+func findInstanceImpl(ctx context.Context, tx *sql.Tx, find *api.InstanceFind) ([]*instanceRaw, error) {
where, args := findInstanceQuery(find)
rows, err := tx.QueryContext(ctx, `
@@ -277,9 +422,9 @@ func findInstanceList(ctx context.Context, tx *sql.Tx, find *api.InstanceFind) (
defer rows.Close()
// Iterate over result set and deserialize rows into instanceRawList.
- var instanceRawList []*api.InstanceRaw
+ var instanceRawList []*instanceRaw
for rows.Next() {
- var instanceRaw api.InstanceRaw
+ var instanceRaw instanceRaw
if err := rows.Scan(
&instanceRaw.ID,
&instanceRaw.RowStatus,
@@ -307,8 +452,8 @@ func findInstanceList(ctx context.Context, tx *sql.Tx, find *api.InstanceFind) (
return instanceRawList, nil
}
-// patchInstance updates a instance by ID. Returns the new state of the instance after update.
-func patchInstance(ctx context.Context, tx *sql.Tx, patch *api.InstancePatch) (*api.InstanceRaw, error) {
+// patchInstanceImpl updates a instance by ID. Returns the new state of the instance after update.
+func patchInstanceImpl(ctx context.Context, tx *sql.Tx, patch *api.InstancePatch) (*instanceRaw, error) {
// Build UPDATE clause.
set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}
if v := patch.RowStatus; v != nil {
@@ -347,7 +492,7 @@ func patchInstance(ctx context.Context, tx *sql.Tx, patch *api.InstancePatch) (*
defer row.Close()
if row.Next() {
- var instanceRaw api.InstanceRaw
+ var instanceRaw instanceRaw
if err := row.Scan(
&instanceRaw.ID,
&instanceRaw.RowStatus,