Skip to content

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

chore: migrate to instance v1 store (#4355)

Danny Xu59e8d969aebb
diff --git a/api/instance.go b/api/instance.go
index 4fc3af8fc8..59cdcdbd18 100644
--- a/api/instance.go
+++ b/api/instance.go
@@ -33,10 +33,6 @@ type Instance struct {
// InstanceCreate is the API message for creating an instance.
type InstanceCreate struct {
- // Standard fields
- // Value is assigned from the jwt subject field passed by the client.
- CreatorID int
-
// Related fields
EnvironmentID int `jsonapi:"attr,environmentId"`
@@ -65,14 +61,6 @@ type InstanceFind struct {
// Standard fields
RowStatus *RowStatus
-
- // Related fields
- EnvironmentID *int
-
- // Domain specific fields
- Name *string
- Host *string
- Port *string
}
func (find *InstanceFind) String() string {
diff --git a/api/v1/auth.go b/api/v1/auth.go
deleted file mode 100644
index 2668ad1833..0000000000
--- a/api/v1/auth.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package v1
-
-// Login is the API message for logins.
-type Login struct {
- // Domain specific fields
- Email string `json:"email"`
- Password string `json:"password"`
-}
-
-// LoginResponse is the API message for user login response.
-type LoginResponse struct {
- ID int `json:"id"`
- Name string `json:"name"`
- Email string `json:"email"`
- Token string `json:"token"`
-}
diff --git a/api/v1/data_source.go b/api/v1/data_source.go
deleted file mode 100644
index edb8b7e0d7..0000000000
--- a/api/v1/data_source.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package v1
-
-import "github.com/bytebase/bytebase/api"
-
-// DataSource is the API message for a data source.
-type DataSource struct {
- ID int `json:"id"`
-
- // Related fields
- DatabaseID int `json:"databaseId"`
-
- // Domain specific fields
- Name string `json:"name"`
- Type api.DataSourceType `json:"type"`
- Username string `json:"username"`
-
- Host string `json:"host"`
- Port string `json:"port"`
- Database string `json:"database"`
-}
-
-// DataSourceCreate is the API message for creating a data source.
-type DataSourceCreate struct {
- // Domain specific fields
- Name string `json:"name"`
- Type api.DataSourceType `json:"type"`
- Username string `json:"username"`
- Password string `json:"password"`
- SslCa string `json:"sslCa"`
- SslCert string `json:"sslCert"`
- SslKey string `json:"sslKey"`
- Host string `json:"host"`
- Port string `json:"port"`
- Database string `json:"database"`
-}
diff --git a/api/v1/environment.go b/api/v1/environment.go
deleted file mode 100644
index e4f3c920a5..0000000000
--- a/api/v1/environment.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package v1
-
-import (
- "github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/plugin/advisor"
-)
-
-// Environment is the API message for an environment.
-type Environment struct {
- ID int `json:"id"`
-
- // Related fields
- EnvironmentTierPolicy *api.EnvironmentTierPolicy `json:"environmentTierPolicy,omitempty"`
- PipelineApprovalPolicy *api.PipelineApprovalPolicy `json:"pipelineApprovalPolicy,omitempty"`
- BackupPlanPolicy *api.BackupPlanPolicy `json:"backupPlanPolicy,omitempty"`
- SQLReviewPolicy *advisor.SQLReviewPolicy `json:"sqlReviewPolicy,omitempty"`
-
- // Domain specific fields
- Name string `json:"name"`
- Order int `json:"order"`
-}
-
-// EnvironmentUpsert is the API message for upsert an environment.
-type EnvironmentUpsert struct {
- // Related fields
- EnvironmentTierPolicy *api.EnvironmentTierPolicy `json:"environmentTierPolicy"`
- PipelineApprovalPolicy *api.PipelineApprovalPolicy `json:"pipelineApprovalPolicy"`
- BackupPlanPolicy *api.BackupPlanPolicy `json:"backupPlanPolicy"`
- SQLReviewPolicy *advisor.SQLReviewPolicy `json:"sqlReviewPolicy"`
-
- // Domain specific fields
- Name *string `json:"name"`
- Order *int `json:"order"`
-}
diff --git a/api/v1/instance.go b/api/v1/instance.go
index ac041c90ab..2914795a26 100644
--- a/api/v1/instance.go
+++ b/api/v1/instance.go
@@ -1,55 +1,5 @@
package v1
-import (
- "github.com/bytebase/bytebase/plugin/db"
-)
-
-// Instance is the API message for an instance.
-type Instance struct {
- ID int `json:"id"`
-
- // Related fields
- Environment string `json:"environment"`
- DataSourceList []*DataSource `json:"dataSourceList"`
-
- // Domain specific fields
- Name string `json:"name"`
- Engine db.Type `json:"engine"`
- EngineVersion string `json:"engineVersion"`
- ExternalLink string `json:"externalLink"`
- Host string `json:"host"`
- Port string `json:"port"`
- Database string `json:"database"`
-}
-
-// InstanceCreate is the API message for creating an instance.
-type InstanceCreate struct {
- // Related fields
- Environment string `json:"environment"`
- DataSourceList []*DataSourceCreate `json:"dataSourceList"`
-
- // Domain specific fields
- Name string `json:"name"`
- Engine db.Type `json:"engine"`
- ExternalLink string `json:"externalLink"`
- Host string `json:"host"`
- Port string `json:"port"`
- Database string `json:"database"`
-}
-
-// InstancePatch is the API message for patching an instance.
-type InstancePatch struct {
- // Related fields
- DataSourceList []*DataSourceCreate `json:"dataSourceList"`
-
- // Domain specific fields
- Name *string `json:"name"`
- ExternalLink *string `json:"externalLink"`
- Host *string `json:"host"`
- Port *string `json:"port"`
- Database *string `json:"database"`
-}
-
// InstanceDatabasePatch is the API message for patching an instance database.
type InstanceDatabasePatch struct {
// Project is the project resource ID.
diff --git a/server/api/v1/instance_service.go b/server/api/v1/instance_service.go
index 224c391e57..e24bf00387 100644
--- a/server/api/v1/instance_service.go
+++ b/server/api/v1/instance_service.go
@@ -141,7 +141,7 @@ func (s *InstanceService) UpdateInstance(ctx context.Context, request *v1pb.Upda
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, err.Error())
}
- patch.DataSources = datasourceList
+ patch.DataSources = &datasourceList
}
}
@@ -165,12 +165,11 @@ func (s *InstanceService) DeleteInstance(ctx context.Context, request *v1pb.Dele
return nil, status.Errorf(codes.InvalidArgument, "instance %q has been deleted", request.Name)
}
- rowStatus := api.Archived
if _, err := s.store.UpdateInstanceV2(ctx, &store.UpdateInstanceMessage{
UpdaterID: ctx.Value(common.PrincipalIDContextKey).(int),
EnvironmentID: instance.EnvironmentID,
ResourceID: instance.ResourceID,
- RowStatus: &rowStatus,
+ Delete: &deletePatch,
}); err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
@@ -188,12 +187,11 @@ func (s *InstanceService) UndeleteInstance(ctx context.Context, request *v1pb.Un
return nil, status.Errorf(codes.InvalidArgument, "instance %q is active", request.Name)
}
- rowStatus := api.Normal
ins, err := s.store.UpdateInstanceV2(ctx, &store.UpdateInstanceMessage{
UpdaterID: ctx.Value(common.PrincipalIDContextKey).(int),
EnvironmentID: instance.EnvironmentID,
ResourceID: instance.ResourceID,
- RowStatus: &rowStatus,
+ Delete: &undeletePatch,
})
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
diff --git a/server/environment.go b/server/environment.go
index 4f94e888ef..e86769740a 100644
--- a/server/environment.go
+++ b/server/environment.go
@@ -195,14 +195,14 @@ func (s *Server) updateEnvironment(ctx context.Context, patch *store.Environment
return nil, echo.NewHTTPError(http.StatusBadRequest, "Invalid environment name, please visit https://www.bytebase.com/docs/vcs-integration/name-and-organize-schema-files#file-path-template?source=console to get more detail.").SetInternal(err)
}
}
+ environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{UID: &patch.ID})
+ if err != nil {
+ return nil, err
+ }
// Ensure the environment has no instance before it's archived.
if v := patch.RowStatus; v != nil && *v == string(api.Archived) {
- normalStatus := api.Normal
- instances, err := s.store.FindInstance(ctx, &api.InstanceFind{
- EnvironmentID: &patch.ID,
- RowStatus: &normalStatus,
- })
+ instances, err := s.store.ListInstancesV2(ctx, &store.FindInstanceMessage{EnvironmentID: &environment.ResourceID, ShowDeleted: false})
if err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError, errors.Errorf("failed to find instances in the environment %d", patch.ID)).SetInternal(err)
}
diff --git a/server/instance.go b/server/instance.go
index fde655178a..2629abaf57 100644
--- a/server/instance.go
+++ b/server/instance.go
@@ -9,6 +9,7 @@ import (
"strings"
"github.com/google/jsonapi"
+ "github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
"go.uber.org/zap"
@@ -33,45 +34,81 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
g.POST("/instance", func(c echo.Context) error {
ctx := c.Request().Context()
+ if err := s.instanceCountGuard(ctx); err != nil {
+ return err
+ }
+
instanceCreate := &api.InstanceCreate{}
if err := jsonapi.UnmarshalPayload(c.Request().Body, instanceCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformed create instance request").SetInternal(err)
}
- instance, err := s.createInstance(ctx, &store.InstanceCreate{
- CreatorID: c.Get(getPrincipalIDContextKey()).(int),
- EnvironmentID: instanceCreate.EnvironmentID,
- DataSourceList: []*api.DataSourceCreate{
+ if err := s.disallowBytebaseStore(instanceCreate.Engine, instanceCreate.Host, instanceCreate.Port); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
+ }
+ if instanceCreate.Engine != db.Postgres && instanceCreate.Engine != db.MongoDB && instanceCreate.Database != "" {
+ return echo.NewHTTPError(http.StatusBadRequest, "database parameter is only allowed for Postgres and MongoDB")
+ }
+ environment, err := s.store.GetEnvironmentByID(ctx, instanceCreate.EnvironmentID)
+ if err != nil {
+ return err
+ }
+ if environment == nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("environment %v not found", instanceCreate.EnvironmentID))
+ }
+ creator := c.Get(getPrincipalIDContextKey()).(int)
+ instance, err := s.store.CreateInstanceV2(ctx, environment.ResourceID, &store.InstanceMessage{
+ ResourceID: fmt.Sprintf("instance-%s", uuid.New().String()[:8]),
+ Title: instanceCreate.Name,
+ Engine: instanceCreate.Engine,
+ ExternalLink: instanceCreate.ExternalLink,
+ DataSources: []*store.DataSourceMessage{
{
- Name: api.AdminDataSourceName,
- Type: api.Admin,
- Username: instanceCreate.Username,
- Password: instanceCreate.Password,
- SslCa: instanceCreate.SslCa,
- SslCert: instanceCreate.SslCert,
- SslKey: instanceCreate.SslKey,
- Host: instanceCreate.Host,
- Port: instanceCreate.Port,
- Options: api.DataSourceOptions{
- SRV: instanceCreate.SRV,
- AuthenticationDatabase: instanceCreate.AuthenticationDatabase,
- },
- Database: instanceCreate.Database,
+ Title: api.AdminDataSourceName,
+ Type: api.Admin,
+ Username: instanceCreate.Username,
+ Password: instanceCreate.Password,
+ SslCa: instanceCreate.SslCa,
+ SslCert: instanceCreate.SslCert,
+ SslKey: instanceCreate.SslKey,
+ Host: instanceCreate.Host,
+ Port: instanceCreate.Port,
+ Database: instanceCreate.Database,
+ SRV: instanceCreate.SRV,
+ AuthenticationDatabase: instanceCreate.AuthenticationDatabase,
},
},
- Name: instanceCreate.Name,
- Engine: instanceCreate.Engine,
- ExternalLink: instanceCreate.ExternalLink,
- Host: instanceCreate.Host,
- Port: instanceCreate.Port,
- Database: instanceCreate.Database,
- })
+ }, creator)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create instance").SetInternal(err)
+ }
+ composedInstance, err := s.store.GetInstanceByID(ctx, instance.UID)
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.
+ driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)
+ if err == nil {
+ defer driver.Close(ctx)
+ if err := driver.SetupMigrationIfNeeded(ctx); err != nil {
+ log.Warn("Failed to setup migration schema on instance creation",
+ zap.String("instance", instance.ResourceID),
+ zap.String("engine", string(instance.Engine)),
+ zap.Error(err))
+ }
+ if _, err := s.SchemaSyncer.SyncInstance(ctx, instance); err != nil {
+ log.Warn("Failed to sync instance",
+ zap.String("instance", instance.ResourceID),
+ zap.Error(err))
+ }
+ // Sync all databases in the instance asynchronously.
+ s.stateCfg.InstanceDatabaseSyncChan <- composedInstance
+ }
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, instance); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, composedInstance); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal create instance response").SetInternal(err)
}
return nil
@@ -124,26 +161,66 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("instanceID"))).SetInternal(err)
}
+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &id})
+ if err != nil {
+ return err
+ }
+ if instance == nil {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("instance %v not found", id))
+ }
- instancePatch := &api.InstancePatch{}
- if err := jsonapi.UnmarshalPayload(c.Request().Body, instancePatch); err != nil {
+ patch := &api.InstancePatch{}
+ if err := jsonapi.UnmarshalPayload(c.Request().Body, patch); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch instance request").SetInternal(err)
}
- instancePatched, err := s.updateInstance(ctx, &store.InstancePatch{
- ID: id,
- RowStatus: instancePatch.RowStatus,
+ var deletes *bool
+ if patch.RowStatus != nil {
+ if *patch.RowStatus == string(api.Normal) {
+ if err := s.instanceCountGuard(ctx); err != nil {
+ return err
+ }
+ f := false
+ deletes = &f
+ } else if *patch.RowStatus == string(api.Archived) {
+ databases, err := s.store.ListDatabases(ctx, &store.FindDatabaseMessage{InstanceID: &instance.ResourceID})
+ if err != nil {
+ return err
+ }
+ var databaseNameList []string
+ for _, database := range databases {
+ if database.ProjectID != api.DefaultProjectID {
+ databaseNameList = append(databaseNameList, database.DatabaseName)
+ }
+ }
+ if len(databaseNameList) > 0 {
+ return echo.NewHTTPError(http.StatusBadRequest,
+ fmt.Sprintf("You should transfer these databases to the default project before deleting the instance: %s.", strings.Join(databaseNameList, ", ")))
+ }
+ f := true
+ deletes = &f
+ }
+ }
+
+ updateMessage := &store.UpdateInstanceMessage{
+ Title: patch.Name,
+ ExternalLink: patch.ExternalLink,
+ Delete: deletes,
UpdaterID: c.Get(getPrincipalIDContextKey()).(int),
- Name: instancePatch.Name,
- EngineVersion: instancePatch.EngineVersion,
- ExternalLink: instancePatch.ExternalLink,
- })
+ EnvironmentID: instance.EnvironmentID,
+ ResourceID: instance.ResourceID,
+ }
+ if _, err := s.store.UpdateInstanceV2(ctx, updateMessage); err != nil {
+ return err
+ }
+
+ composedInstance, err := s.store.GetInstanceByID(ctx, instance.UID)
if err != nil {
return err
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, instancePatched); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, composedInstance); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal instance ID response: %v", id)).SetInternal(err)
}
return nil
@@ -462,165 +539,3 @@ func (s *Server) disallowBytebaseStore(engine db.Type, host, port string) error
}
return nil
}
-
-func (s *Server) createInstance(ctx context.Context, create *store.InstanceCreate) (*api.Instance, error) {
- if err := s.instanceCountGuard(ctx); err != nil {
- return nil, err
- }
- if err := s.validateDataSourceList(create.DataSourceList); err != nil {
- return nil, err
- }
-
- if err := s.disallowBytebaseStore(create.Engine, create.Host, create.Port); err != nil {
- return nil, echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
- }
- if create.Engine != db.Postgres && create.Engine != db.MongoDB && create.Database != "" {
- return nil, echo.NewHTTPError(http.StatusBadRequest, "database parameter is only allowed for Postgres and MongoDB")
- }
-
- composedInstance, err := s.store.CreateInstance(ctx, create)
- if err != nil {
- if common.ErrorCode(err) == common.Conflict {
- return nil, echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Instance name already exists: %s", create.Name))
- }
- return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to create instance").SetInternal(err)
- }
- instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &composedInstance.ID})
- if err != nil {
- return nil, 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.
- driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)
- if err == nil {
- defer driver.Close(ctx)
- if err := driver.SetupMigrationIfNeeded(ctx); err != nil {
- log.Warn("Failed to setup migration schema on instance creation",
- zap.String("instance", instance.ResourceID),
- zap.String("engine", string(instance.Engine)),
- zap.Error(err))
- }
- if _, err := s.SchemaSyncer.SyncInstance(ctx, instance); err != nil {
- log.Warn("Failed to sync instance",
- zap.String("instance", instance.ResourceID),
- zap.Error(err))
- }
- // Sync all databases in the instance asynchronously.
- s.stateCfg.InstanceDatabaseSyncChan <- composedInstance
- }
-
- return composedInstance, nil
-}
-
-func (s *Server) updateInstance(ctx context.Context, patch *store.InstancePatch) (*api.Instance, error) {
- if v := patch.DataSourceList; v != nil {
- if err := s.validateDataSourceList(v); err != nil {
- return nil, err
- }
- }
-
- composedInstance, err := s.store.GetInstanceByID(ctx, patch.ID)
- if err != nil {
- return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get instance ID: %v", patch.ID)).SetInternal(err)
- }
- if composedInstance == nil {
- return nil, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", patch.ID))
- }
-
- host, port, database := composedInstance.Host, composedInstance.Port, composedInstance.Database
- if patch.Host != nil {
- host = *patch.Host
- }
- if patch.Port != nil {
- port = *patch.Port
- }
- if patch.Database != nil {
- database = *patch.Database
- }
- if err := s.disallowBytebaseStore(composedInstance.Engine, host, port); err != nil {
- return nil, echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
- }
- if composedInstance.Engine != db.Postgres && composedInstance.Engine != db.MongoDB && database != "" {
- return nil, echo.NewHTTPError(http.StatusBadRequest, "database parameter is only allowed for Postgres and MongoDB")
- }
-
- instancePatched := composedInstance
- if patch.RowStatus != nil || patch.Name != nil || patch.ExternalLink != nil || patch.Host != nil || patch.Port != nil || patch.Database != nil || patch.DataSourceList != 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.
- if patch.RowStatus != nil && *patch.RowStatus == string(api.Normal) {
- if err := s.instanceCountGuard(ctx); err != nil {
- return nil, err
- }
- }
- // Ensure all databases belong to this instance are under the default project before instance is archived.
- if v := patch.RowStatus; v != nil && *v == string(api.Archived) {
- databases, err := s.store.ListDatabases(ctx, &store.FindDatabaseMessage{InstanceID: &composedInstance.ResourceID})
- if err != nil {
- return nil, echo.NewHTTPError(http.StatusInternalServerError,
- errors.Errorf("failed to list databases in the instance %d", patch.ID)).SetInternal(err)
- }
- var databaseNameList []string
- for _, database := range databases {
- if database.ProjectID != api.DefaultProjectID {
- databaseNameList = append(databaseNameList, database.DatabaseName)
- }
- }
- if len(databaseNameList) > 0 {
- return nil, echo.NewHTTPError(http.StatusBadRequest,
- fmt.Sprintf("You should transfer these databases to the default project before deleting the instance: %s.", strings.Join(databaseNameList, ", ")))
- }
- }
- instancePatched, err = s.store.PatchInstance(ctx, patch)
- if err != nil {
- if common.ErrorCode(err) == common.NotFound {
- return nil, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", patch.ID))
- }
- return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch instance ID: %v", patch.ID)).SetInternal(err)
- }
- }
-
- // Try immediately setup the migration schema, sync the engine version and schema after updating any connection related info.
- if patch.Host != nil || patch.Port != nil || patch.Database != nil {
- instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &instancePatched.ID})
- if err != nil {
- return nil, err
- }
- db, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)
- if err == nil {
- defer db.Close(ctx)
- if err := db.SetupMigrationIfNeeded(ctx); err != nil {
- log.Warn("Failed to setup migration schema on instance update",
- zap.String("instance_name", instancePatched.Name),
- zap.String("engine", string(instancePatched.Engine)),
- zap.Error(err))
- }
- if _, err := s.SchemaSyncer.SyncInstance(ctx, instance); err != nil {
- log.Warn("Failed to sync instance",
- zap.Int("instance_id", instancePatched.ID),
- zap.Error(err))
- }
- // Sync all databases in the instance asynchronously.
- s.stateCfg.InstanceDatabaseSyncChan <- instancePatched
- }
- }
-
- return instancePatched, nil
-}
-
-func (*Server) validateDataSourceList(dataSourceList []*api.DataSourceCreate) error {
- dataSourceMap := map[api.DataSourceType]bool{}
- for _, dataSource := range dataSourceList {
- if dataSourceMap[dataSource.Type] {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Duplicate data source type %s", dataSource.Type))
- }
- dataSourceMap[dataSource.Type] = true
- }
- if !dataSourceMap[api.Admin] {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Missing required data source type %s", api.Admin))
- }
-
- return nil
-}
diff --git a/server/openapi_instance.go b/server/openapi_instance.go
index 66fa339ca1..df49ecfed3 100644
--- a/server/openapi_instance.go
+++ b/server/openapi_instance.go
@@ -7,7 +7,6 @@ import (
"github.com/labstack/echo/v4"
- "github.com/bytebase/bytebase/api"
openAPIV1 "github.com/bytebase/bytebase/api/v1"
"github.com/bytebase/bytebase/store"
)
@@ -26,17 +25,23 @@ func (s *Server) updateInstanceDatabase(c echo.Context) error {
return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch instance database request").SetInternal(err)
}
- instances, err := s.store.FindInstance(ctx, &api.InstanceFind{Name: &instanceName})
+ instances, err := s.store.ListInstancesV2(ctx, &store.FindInstanceMessage{})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find instance").SetInternal(err)
}
- if len(instances) != 1 {
- return echo.NewHTTPError(http.StatusBadRequest, "Found %v instances with name %q but expecting one", len(instances), instanceName)
+ var instance *store.InstanceMessage
+ for _, ins := range instances {
+ if ins.Title == instanceName {
+ instance = ins
+ break
+ }
+ }
+ if instance == nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Failed to find instance")
}
- instance := instances[0]
database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{
- EnvironmentID: &instance.Environment.ResourceID,
+ EnvironmentID: &instance.EnvironmentID,
InstanceID: &instance.ResourceID,
DatabaseName: &databaseName,
})
diff --git a/server/runner/schemasync/syncer.go b/server/runner/schemasync/syncer.go
index e6001d0e78..b0fa833a2c 100644
--- a/server/runner/schemasync/syncer.go
+++ b/server/runner/schemasync/syncer.go
@@ -175,17 +175,15 @@ func (s *Syncer) SyncInstance(ctx context.Context, instance *store.InstanceMessa
return nil, err
}
- // 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 instanceMeta.Version != instance.EngineVersion {
- if _, err := s.store.PatchInstance(ctx, &store.InstancePatch{
- ID: instance.UID,
+ if _, err := s.store.UpdateInstanceV2(ctx, &store.UpdateInstanceMessage{
UpdaterID: api.SystemBotID,
+ EnvironmentID: instance.EnvironmentID,
+ ResourceID: instance.ResourceID,
EngineVersion: &instanceMeta.Version,
}); err != nil {
return nil, err
}
- instance.EngineVersion = instanceMeta.Version
}
var instanceUsers []*store.InstanceUserMessage
diff --git a/store/cache.go b/store/cache.go
index 1c179d3543..699414a552 100644
--- a/store/cache.go
+++ b/store/cache.go
@@ -15,8 +15,6 @@ type cacheNamespace string
const (
// projectMemberCacheNamespace is the cache type of project members.
projectMemberCacheNamespace cacheNamespace = "pm"
- // instanceCacheNamespace is the cache type of instances.
- instanceCacheNamespace cacheNamespace = "i"
// pipelineCacheNamespace is the cache type of pipelines.
pipelineCacheNamespace cacheNamespace = "pl"
// issueCacheNamespace is the cache type of issues.
diff --git a/store/data_source.go b/store/data_source.go
index e640825395..3c2a7a029e 100644
--- a/store/data_source.go
+++ b/store/data_source.go
@@ -83,20 +83,6 @@ func (s *Store) GetDataSource(ctx context.Context, find *api.DataSourceFind) (*a
return composeDataSource(dataSourceRaw), nil
}
-// findDataSource finds a list of DataSource instances.
-func (s *Store) findDataSource(ctx context.Context, find *api.DataSourceFind) ([]*api.DataSource, error) {
- dataSourceRawList, err := s.findDataSourceRaw(ctx, find)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to find DataSource list with DataSourceFind[%+v]", find)
- }
-
- var dataSourceList []*api.DataSource
- for _, raw := range dataSourceRawList {
- dataSourceList = append(dataSourceList, composeDataSource(raw))
- }
- return dataSourceList, nil
-}
-
// PatchDataSource patches an instance of DataSource.
func (s *Store) PatchDataSource(ctx context.Context, instance *InstanceMessage, patch *api.DataSourcePatch) (*api.DataSource, error) {
dataSourceRaw, err := s.patchDataSourceRaw(ctx, patch)
@@ -131,21 +117,7 @@ func (s *Store) DeleteDataSource(ctx context.Context, instance *InstanceMessage,
return nil
}
-//
-// private functions
-//
-
-// createDataSourceRawTx creates an instance of DataSource.
-// This uses an existing transaction object.
-func (s *Store) createDataSourceRawTx(ctx context.Context, tx *Tx, create *api.DataSourceCreate) error {
- if _, err := s.createDataSourceImpl(ctx, tx, create); err != nil {
- return errors.Wrapf(err, "failed to create data source with DataSourceCreate[%+v]", create)
- }
- // Invalidate the cache.
- s.cache.DeleteCache(dataSourceCacheNamespace, create.InstanceID)
- return nil
-}
-
+// private functions.
func composeDataSource(raw *dataSourceRaw) *api.DataSource {
return raw.toDataSource()
}
@@ -172,38 +144,6 @@ func (s *Store) createDataSourceRaw(ctx context.Context, create *api.DataSourceC
return dataSource, nil
}
-// findDataSourceRaw retrieves a list of data sources based on find.
-func (s *Store) findDataSourceRaw(ctx context.Context, find *api.DataSourceFind) ([]*dataSourceRaw, error) {
- findCopy := *find
- findCopy.InstanceID = nil
- isListDataSource := find.InstanceID != nil && findCopy == api.DataSourceFind{}
- var cacheList []*dataSourceRaw
- has, err := s.cache.FindCache(dataSourceCacheNamespace, *find.InstanceID, &cacheList)
- if err != nil {
- return nil, err
- }
- if has && isListDataSource {
- return cacheList, nil
- }
-
- tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- list, err := s.findDataSourceImpl(ctx, tx, find)
- if err != nil {
- return nil, err
- }
- if isListDataSource {
- if err := s.cache.UpsertCache(dataSourceCacheNamespace, *find.InstanceID, list); err != nil {
- return nil, err
- }
- }
- return list, nil
-}
-
// getDataSourceRaw retrieves a single dataSource based on find.
// Returns ECONFLICT if finding more than 1 matching records.
func (s *Store) getDataSourceRaw(ctx context.Context, find *api.DataSourceFind) (*dataSourceRaw, error) {
@@ -484,6 +424,9 @@ type DataSourceMessage struct {
// Flatten data source options.
SRV bool
AuthenticationDatabase string
+ // (deprecated) Output only.
+ UID int
+ DatabaseID int
}
// UpdateDataSourceMessage is the message for the data source.
@@ -511,6 +454,8 @@ func (*Store) listDataSourceV2(ctx context.Context, tx *Tx, instanceID string) (
var dataSourceMessages []*DataSourceMessage
rows, err := tx.QueryContext(ctx, `
SELECT
+ data_source.id,
+ data_source.database_id,
data_source.name,
data_source.type,
data_source.username,
@@ -535,6 +480,8 @@ func (*Store) listDataSourceV2(ctx context.Context, tx *Tx, instanceID string) (
for rows.Next() {
var dataSourceMessage DataSourceMessage
if err := rows.Scan(
+ &dataSourceMessage.UID,
+ &dataSourceMessage.DatabaseID,
&dataSourceMessage.Title,
&dataSourceMessage.Type,
&dataSourceMessage.Username,
diff --git a/store/instance.go b/store/instance.go
index 8b0fa04522..59f1300dd1 100644
--- a/store/instance.go
+++ b/store/instance.go
@@ -6,592 +6,131 @@ import (
"fmt"
"strings"
- "github.com/google/uuid"
"github.com/pkg/errors"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/plugin/db"
)
-// InstanceCreate is the API message to create the instance.
-// TODO(ed): This is an temporary struct to compatible with OpenAPI and JSONAPI. Find way to move it into the API package.
-type InstanceCreate struct {
- // Standard fields
- // Value is assigned from the jwt subject field passed by the client.
- CreatorID int
-
- // Related fields
- EnvironmentID int
- DataSourceList []*api.DataSourceCreate
-
- // Domain specific fields
- Name string
- Engine db.Type
- ExternalLink string
- Host string
- Port string
- Database string
-}
-
-// InstancePatch is the API message for patching an instance.
-// TODO(ed): This is an temporary struct to compatible with OpenAPI and JSONAPI. Find way to move it into the API package.
-type InstancePatch struct {
- ID int
-
- // Standard fields
- RowStatus *string
- // Value is assigned from the jwt subject field passed by the client.
- UpdaterID int
-
- // Related fields
- DataSourceList []*api.DataSourceCreate
-
- // Domain specific fields
- Name *string
- EngineVersion *string
- ExternalLink *string
- Host *string
- Port *string
- Database *string
-}
-
-// instanceRaw is the store model for an Instance.
-// Fields have exactly the same meanings as Instance.
-type instanceRaw struct {
- ID int
- ResourceID string
-
- // 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
- Database 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() *api.Instance {
- return &api.Instance{
- ID: raw.ID,
- ResourceID: raw.ResourceID,
- RowStatus: raw.RowStatus,
-
- // 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,
- Database: raw.Database,
- }
-}
-
-// CreateInstance creates an instance of Instance.
-func (s *Store) CreateInstance(ctx context.Context, create *InstanceCreate) (*api.Instance, error) {
- instanceRaw, err := s.createInstanceRaw(ctx, create)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to create Instance with InstanceCreate[%+v]", create)
- }
- instance, err := s.composeInstance(ctx, instanceRaw)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to compose Instance with instanceRaw[%+v]", instanceRaw)
- }
- 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)
+ instance, err := s.GetInstanceV2(ctx, &FindInstanceMessage{UID: &id})
if err != nil {
return nil, errors.Wrapf(err, "failed to get Instance with ID %d", id)
}
- if instanceRaw == nil {
+ if instance == nil {
return nil, nil
}
- instance, err := s.composeInstance(ctx, instanceRaw)
+ composedInstance, err := s.composeInstance(ctx, instance)
if err != nil {
- return nil, errors.Wrapf(err, "failed to compose Instance with instanceRaw[%+v]", instanceRaw)
+ return nil, errors.Wrapf(err, "failed to compose Instance with instance[%+v]", instance)
}
- return instance, nil
+ return composedInstance, nil
}
// 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, errors.Wrapf(err, "failed to find Instance list with InstanceFind[%+v]", find)
- }
- var instanceList []*api.Instance
- for _, raw := range instanceRawList {
- instance, err := s.composeInstance(ctx, raw)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to compose Instance with instanceRaw[%+v]", raw)
- }
- instanceList = append(instanceList, instance)
- }
- return instanceList, nil
-}
-
-// PatchInstance patches an instance of Instance.
-func (s *Store) PatchInstance(ctx context.Context, patch *InstancePatch) (*api.Instance, error) {
- instanceRaw, err := s.patchInstanceRaw(ctx, patch)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to patch Instance with InstancePatch[%+v]", patch)
- }
- instance, err := s.composeInstance(ctx, instanceRaw)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to compose Instance with instanceRaw[%+v]", instanceRaw)
- }
- s.instanceCache.Delete(getInstanceCacheKey(instance.Environment.ResourceID, instanceRaw.ResourceID))
- s.instanceIDCache.Delete(instance.ID)
- return instance, nil
-}
-
-// private function.
-func (s *Store) composeInstance(ctx context.Context, raw *instanceRaw) (*api.Instance, error) {
- instance := raw.toInstance()
-
- env, err := s.GetEnvironmentByID(ctx, instance.EnvironmentID)
- if err != nil {
- return nil, err
- }
- instance.Environment = env
-
- dataSourceList, err := s.findDataSource(ctx, &api.DataSourceFind{
- InstanceID: &instance.ID,
- })
+ v2Find := &FindInstanceMessage{ShowDeleted: true}
+ instances, err := s.ListInstancesV2(ctx, v2Find)
if err != nil {
return nil, err
}
- instance.DataSourceList = dataSourceList
- return instance, nil
-}
-// createInstanceRaw creates a new instance.
-func (s *Store) createInstanceRaw(ctx context.Context, create *InstanceCreate) (*instanceRaw, error) {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- instance, err := createInstanceImpl(ctx, tx, create)
- if err != nil {
- return nil, err
- }
-
- // Create * database
- allDatabaseUID, err := s.createDatabaseDefaultImpl(ctx, tx, instance.ID, &DatabaseMessage{DatabaseName: api.AllDatabaseName})
- if err != nil {
- return nil, err
- }
-
- for _, dataSource := range create.DataSourceList {
- dataSourceCreate := &api.DataSourceCreate{
- CreatorID: create.CreatorID,
- InstanceID: instance.ID,
- DatabaseID: allDatabaseUID,
- Name: dataSource.Name,
- Type: dataSource.Type,
- Username: dataSource.Username,
- Password: dataSource.Password,
- SslKey: dataSource.SslKey,
- SslCert: dataSource.SslCert,
- SslCa: dataSource.SslCa,
- Host: dataSource.Host,
- Port: dataSource.Port,
- Options: dataSource.Options,
- Database: dataSource.Database,
+ var composedInstances []*api.Instance
+ for _, instance := range instances {
+ composedInstance, err := s.composeInstance(ctx, instance)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to compose Instance with instance[%+v]", instance)
}
- if err := s.createDataSourceRawTx(ctx, tx, dataSourceCreate); err != nil {
- return nil, err
+ if find.RowStatus != nil && composedInstance.RowStatus != *find.RowStatus {
+ continue
}
+ composedInstances = append(composedInstances, composedInstance)
}
-
- if err := tx.Commit(); err != nil {
- return nil, FormatError(err)
- }
-
- if err := s.cache.UpsertCache(instanceCacheNamespace, instance.ID, instance); err != nil {
- return nil, err
- }
-
- return instance, nil
-}
-
-// 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, &sql.TxOptions{ReadOnly: true})
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- list, err := findInstanceImpl(ctx, tx, find)
- if err != nil {
- return nil, err
- }
-
- return list, nil
+ return composedInstances, nil
}
-// getInstanceRaw retrieves a single instance based on find.
-// Returns ECONFLICT if finding more than 1 matching records.
-func (s *Store) getInstanceRaw(ctx context.Context, find *api.InstanceFind) (*instanceRaw, error) {
- if find.ID != nil {
- instanceRaw := &instanceRaw{}
- has, err := s.cache.FindCache(instanceCacheNamespace, *find.ID, instanceRaw)
- if err != nil {
- return nil, err
- }
- if has {
- return instanceRaw, nil
- }
+// private function.
+func (s *Store) composeInstance(ctx context.Context, instance *InstanceMessage) (*api.Instance, error) {
+ composedInstance := &api.Instance{
+ ID: instance.UID,
+ ResourceID: instance.ResourceID,
+ RowStatus: api.Normal,
+ Name: instance.Title,
+ Engine: instance.Engine,
+ EngineVersion: instance.EngineVersion,
+ ExternalLink: instance.ExternalLink,
}
-
- tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
- if err != nil {
- return nil, FormatError(err)
+ if instance.Deleted {
+ composedInstance.RowStatus = api.Archived
}
- defer tx.Rollback()
- list, err := findInstanceImpl(ctx, tx, find)
+ environment, err := s.GetEnvironmentV2(ctx, &FindEnvironmentMessage{ResourceID: &instance.EnvironmentID})
if err != nil {
return nil, err
}
-
- if len(list) == 0 {
- return nil, nil
- } else if len(list) > 1 {
- return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d instances with filter %+v, expect 1", len(list), find)}
- }
-
- instance := list[0]
- if err := s.cache.UpsertCache(instanceCacheNamespace, instance.ID, instance); err != nil {
- return nil, err
- }
- return instance, nil
-}
-
-// patchInstanceRaw updates an existing instance by ID.
-// Returns ENOTFOUND if instance does not exist.
-func (s *Store) patchInstanceRaw(ctx context.Context, patch *InstancePatch) (*instanceRaw, error) {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- instance, err := patchInstanceImpl(ctx, tx, patch)
+ composedInstance.EnvironmentID = environment.UID
+ composedEnvironment, err := s.GetEnvironmentByID(ctx, environment.UID)
if err != nil {
- return nil, FormatError(err)
- }
-
- if patch.DataSourceList != nil {
- allDatabaseName := api.AllDatabaseName
- databaseList, err := s.listDatabaseImplV2(ctx, tx, &FindDatabaseMessage{
- InstanceID: &instance.ResourceID,
- DatabaseName: &allDatabaseName,
- IncludeAllDatabase: true,
- })
- if err != nil {
- return nil, err
- }
- if len(databaseList) == 0 {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("data source database not found for instance %q", instance.ResourceID)}
- }
- if len(databaseList) > 1 {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("found %d data source databases for instance %q", len(databaseList), instance.ResourceID)}
- }
- allDatabase := databaseList[0]
-
- if err := s.clearDataSourceImpl(ctx, tx, patch.ID, allDatabase.UID); err != nil {
- return nil, err
- }
- s.cache.DeleteCache(dataSourceCacheNamespace, patch.ID)
-
- for _, dataSource := range patch.DataSourceList {
- dataSourceCreate := &api.DataSourceCreate{
- CreatorID: patch.UpdaterID,
- InstanceID: instance.ID,
- DatabaseID: allDatabase.UID,
- Name: dataSource.Name,
- Type: dataSource.Type,
- Username: dataSource.Username,
- Password: dataSource.Password,
- SslKey: dataSource.SslKey,
- SslCert: dataSource.SslCert,
- SslCa: dataSource.SslCa,
- Host: dataSource.Host,
- Port: dataSource.Port,
- Options: dataSource.Options,
- Database: dataSource.Database,
- }
- if err := s.createDataSourceRawTx(ctx, tx, dataSourceCreate); err != nil {
- return nil, err
- }
- }
- }
-
- if err := tx.Commit(); err != nil {
- return nil, FormatError(err)
- }
-
- if err := s.cache.UpsertCache(instanceCacheNamespace, instance.ID, instance); err != nil {
return nil, err
}
-
- return instance, nil
-}
-
-// createInstanceImpl creates a new instance.
-func createInstanceImpl(ctx context.Context, tx *Tx, create *InstanceCreate) (*instanceRaw, error) {
- // TODO(d): allow users to set resource_id.
- resourceID := fmt.Sprintf("instance-%s", uuid.New().String()[:8])
- // Insert row into database.
- query := `
- INSERT INTO instance (
- creator_id,
- updater_id,
- environment_id,
- name,
- engine,
- external_link,
- host,
- port,
- database,
- resource_id
- )
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
- RETURNING id, resource_id, row_status, creator_id, created_ts, updater_id, updated_ts, environment_id, name, engine, engine_version, external_link, host, port, database
- `
- var instanceRaw instanceRaw
- if err := tx.QueryRowContext(ctx, query,
- create.CreatorID,
- create.CreatorID,
- create.EnvironmentID,
- create.Name,
- create.Engine,
- create.ExternalLink,
- create.Host,
- create.Port,
- create.Database,
- resourceID,
- ).Scan(
- &instanceRaw.ID,
- &instanceRaw.ResourceID,
- &instanceRaw.RowStatus,
- &instanceRaw.CreatorID,
- &instanceRaw.CreatedTs,
- &instanceRaw.UpdaterID,
- &instanceRaw.UpdatedTs,
- &instanceRaw.EnvironmentID,
- &instanceRaw.Name,
- &instanceRaw.Engine,
- &instanceRaw.EngineVersion,
- &instanceRaw.ExternalLink,
- &instanceRaw.Host,
- &instanceRaw.Port,
- &instanceRaw.Database,
- ); err != nil {
- if err == sql.ErrNoRows {
- return nil, common.FormatDBErrorEmptyRowWithQuery(query)
- }
- return nil, FormatError(err)
- }
- return &instanceRaw, nil
-}
-
-func findInstanceImpl(ctx context.Context, tx *Tx, find *api.InstanceFind) ([]*instanceRaw, error) {
- where, args := findInstanceQuery(find)
-
- rows, err := tx.QueryContext(ctx, `
- SELECT
- id,
- resource_id,
- row_status,
- creator_id,
- created_ts,
- updater_id,
- updated_ts,
- environment_id,
- name,
- engine,
- engine_version,
- external_link,
- host,
- port,
- database
- FROM instance
- WHERE `+where,
- args...,
- )
- if err != nil {
- return nil, FormatError(err)
- }
- defer rows.Close()
-
- // Iterate over result set and deserialize rows into instanceRawList.
- var instanceRawList []*instanceRaw
- for rows.Next() {
- var instanceRaw instanceRaw
- if err := rows.Scan(
- &instanceRaw.ID,
- &instanceRaw.ResourceID,
- &instanceRaw.RowStatus,
- &instanceRaw.CreatorID,
- &instanceRaw.CreatedTs,
- &instanceRaw.UpdaterID,
- &instanceRaw.UpdatedTs,
- &instanceRaw.EnvironmentID,
- &instanceRaw.Name,
- &instanceRaw.Engine,
- &instanceRaw.EngineVersion,
- &instanceRaw.ExternalLink,
- &instanceRaw.Host,
- &instanceRaw.Port,
- &instanceRaw.Database,
- ); err != nil {
- return nil, FormatError(err)
- }
- instanceRawList = append(instanceRawList, &instanceRaw)
- }
- if err := rows.Err(); err != nil {
- return nil, FormatError(err)
- }
-
- return instanceRawList, nil
-}
-
-// patchInstanceImpl updates an instance by ID. Returns the new state of the instance after update.
-func patchInstanceImpl(ctx context.Context, tx *Tx, patch *InstancePatch) (*instanceRaw, error) {
- // Build UPDATE clause.
- set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}
- if v := patch.RowStatus; v != nil {
- set, args = append(set, fmt.Sprintf("row_status = $%d", len(args)+1)), append(args, api.RowStatus(*v))
- }
- if v := patch.Name; v != nil {
- set, args = append(set, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.EngineVersion; v != nil {
- set, args = append(set, fmt.Sprintf("engine_version = $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.ExternalLink; v != nil {
- set, args = append(set, fmt.Sprintf("external_link = $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.Host; v != nil {
- set, args = append(set, fmt.Sprintf("host = $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.Port; v != nil {
- set, args = append(set, fmt.Sprintf("port = $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.Database; v != nil {
- set, args = append(set, fmt.Sprintf("database = $%d", len(args)+1)), append(args, *v)
- }
-
- args = append(args, patch.ID)
-
- var instanceRaw instanceRaw
- // Execute update query with RETURNING.
- if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
- UPDATE instance
- SET `+strings.Join(set, ", ")+`
- WHERE id = $%d
- RETURNING id, resource_id, row_status, creator_id, created_ts, updater_id, updated_ts, environment_id, name, engine, engine_version, external_link, host, port, database
- `, len(args)),
- args...,
- ).Scan(
- &instanceRaw.ID,
- &instanceRaw.ResourceID,
- &instanceRaw.RowStatus,
- &instanceRaw.CreatorID,
- &instanceRaw.CreatedTs,
- &instanceRaw.UpdaterID,
- &instanceRaw.UpdatedTs,
- &instanceRaw.EnvironmentID,
- &instanceRaw.Name,
- &instanceRaw.Engine,
- &instanceRaw.EngineVersion,
- &instanceRaw.ExternalLink,
- &instanceRaw.Host,
- &instanceRaw.Port,
- &instanceRaw.Database,
- ); err != nil {
- if err == sql.ErrNoRows {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("instance ID not found: %d", patch.ID)}
+ composedInstance.Environment = composedEnvironment
+
+ for _, ds := range instance.DataSources {
+ composedInstance.DataSourceList = append(composedInstance.DataSourceList, &api.DataSource{
+ ID: ds.UID,
+ InstanceID: instance.UID,
+ DatabaseID: ds.DatabaseID,
+ Name: ds.Title,
+ Type: ds.Type,
+ Username: ds.Username,
+ Password: ds.Password,
+ SslCa: ds.SslCa,
+ SslCert: ds.SslCert,
+ SslKey: ds.SslKey,
+ Host: ds.Host,
+ Port: ds.Port,
+ Options: api.DataSourceOptions{SRV: ds.SRV, AuthenticationDatabase: ds.AuthenticationDatabase},
+ Database: ds.Database,
+ })
+ if ds.Type == api.Admin {
+ composedInstance.Host = ds.Host
+ composedInstance.Port = ds.Port
}
- return nil, FormatError(err)
}
- return &instanceRaw, nil
-}
-func findInstanceQuery(find *api.InstanceFind) (string, []interface{}) {
- // Build WHERE clause.
- where, args := []string{"TRUE"}, []interface{}{}
- if v := find.ID; v != nil {
- where, args = append(where, fmt.Sprintf("id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.RowStatus; v != nil {
- where, args = append(where, fmt.Sprintf("row_status = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.EnvironmentID; v != nil {
- where, args = append(where, fmt.Sprintf("environment_id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.Host; v != nil {
- where, args = append(where, fmt.Sprintf("host = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.Port; v != nil {
- where, args = append(where, fmt.Sprintf("port = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.Name; v != nil {
- where, args = append(where, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)
- }
-
- return strings.Join(where, " AND "), args
+ return composedInstance, nil
}
// InstanceMessage is the mssage for instance.
type InstanceMessage struct {
+ ResourceID string
+ Title string
+ Engine db.Type
+ ExternalLink string
+ DataSources []*DataSourceMessage
+ // Output only.
EnvironmentID string
UID int
- ResourceID string
- Title string
- Engine db.Type
- EngineVersion string
- ExternalLink string
Deleted bool
- DataSources []*DataSourceMessage
+ EngineVersion string
}
// UpdateInstanceMessage is the mssage for updating an instance.
type UpdateInstanceMessage struct {
+ Title *string
+ ExternalLink *string
+ Delete *bool
+ DataSources *[]*DataSourceMessage
+ EngineVersion *string
+
+ // Output only.
UpdaterID int
EnvironmentID string
ResourceID string
-
- Title *string
- ExternalLink *string
- RowStatus *api.RowStatus
- DataSources []*DataSourceMessage
}
// FindInstanceMessage is the message for finding instances.
@@ -669,6 +208,10 @@ func (s *Store) ListInstancesV2(ctx context.Context, find *FindInstanceMessage)
// CreateInstanceV2 creates the instance.
func (s *Store) CreateInstanceV2(ctx context.Context, environmentID string, instanceCreate *InstanceMessage, creatorID int) (*InstanceMessage, error) {
+ if err := validateDataSourceList(instanceCreate.DataSources); err != nil {
+ return nil, err
+ }
+
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
@@ -726,6 +269,11 @@ func (s *Store) CreateInstanceV2(ctx context.Context, environmentID string, inst
}
}
+ dataSources, err := s.listDataSourceV2(ctx, tx, instanceCreate.ResourceID)
+ if err != nil {
+ return nil, err
+ }
+
if err := tx.Commit(); err != nil {
return nil, FormatError(err)
}
@@ -737,7 +285,7 @@ func (s *Store) CreateInstanceV2(ctx context.Context, environmentID string, inst
Title: instanceCreate.Title,
Engine: instanceCreate.Engine,
ExternalLink: instanceCreate.ExternalLink,
- DataSources: instanceCreate.DataSources,
+ DataSources: dataSources,
}
s.instanceCache.Store(getInstanceCacheKey(instance.EnvironmentID, instance.ResourceID), instance)
s.instanceIDCache.Store(instance.UID, instance)
@@ -746,6 +294,12 @@ func (s *Store) CreateInstanceV2(ctx context.Context, environmentID string, inst
// UpdateInstanceV2 updates an instance.
func (s *Store) UpdateInstanceV2(ctx context.Context, patch *UpdateInstanceMessage) (*InstanceMessage, error) {
+ if patch.DataSources != nil {
+ if err := validateDataSourceList(*patch.DataSources); err != nil {
+ return nil, err
+ }
+ }
+
set, args := []string{"updater_id = $1"}, []interface{}{fmt.Sprintf("%d", patch.UpdaterID)}
if v := patch.Title; v != nil {
set, args = append(set, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)
@@ -753,8 +307,15 @@ func (s *Store) UpdateInstanceV2(ctx context.Context, patch *UpdateInstanceMessa
if v := patch.ExternalLink; v != nil {
set, args = append(set, fmt.Sprintf("external_link = $%d", len(args)+1)), append(args, *v)
}
- if v := patch.RowStatus; v != nil {
- set, args = append(set, fmt.Sprintf("row_status = $%d", len(args)+1)), append(args, *v)
+ if v := patch.EngineVersion; v != nil {
+ set, args = append(set, fmt.Sprintf("engine_version = $%d", len(args)+1)), append(args, *v)
+ }
+ if v := patch.Delete; v != nil {
+ rowStatus := api.Normal
+ if *patch.Delete {
+ rowStatus = api.Archived
+ }
+ set, args = append(set, fmt.Sprintf(`"row_status" = $%d`, len(args)+1)), append(args, rowStatus)
}
tx, err := s.db.BeginTx(ctx, nil)
@@ -822,7 +383,7 @@ func (s *Store) UpdateInstanceV2(ctx context.Context, patch *UpdateInstanceMessa
return nil, err
}
- for _, ds := range patch.DataSources {
+ for _, ds := range *patch.DataSources {
if err := s.addDataSourceToInstanceImplV2(ctx, tx, instance.UID, allDatabase.UID, patch.UpdaterID, ds); err != nil {
return nil, err
}
@@ -950,3 +511,17 @@ func (s *Store) FindInstanceWithDatabaseBackupEnabled(ctx context.Context) ([]*I
}
return instances, nil
}
+
+func validateDataSourceList(dataSources []*DataSourceMessage) error {
+ dataSourceMap := map[api.DataSourceType]bool{}
+ for _, dataSource := range dataSources {
+ if dataSourceMap[dataSource.Type] {
+ return status.Errorf(codes.InvalidArgument, "duplicate data source type %s", dataSource.Type)
+ }
+ dataSourceMap[dataSource.Type] = true
+ }
+ if !dataSourceMap[api.Admin] {
+ return status.Errorf(codes.InvalidArgument, "missing required data source type %s", api.Admin)
+ }
+ return nil
+}