Skip to content

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

feat(api): implement instance gRPC service (#4226)

h3n4l6c2ce64dc8e2
diff --git a/proto/generated-go/v1/instance_service.pb.go b/proto/generated-go/v1/instance_service.pb.go
index 5ecb8d12e7..60c196993e 100644
--- a/proto/generated-go/v1/instance_service.pb.go
+++ b/proto/generated-go/v1/instance_service.pb.go
@@ -1194,7 +1194,7 @@ var file_v1_instance_service_proto_rawDesc = []byte{
0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75,
0x65, 0x73, 0x74, 0x1a, 0x15, 0x2e, 0x62, 0x79, 0x74, 0x65, 0x62, 0x61, 0x73, 0x65, 0x2e, 0x76,
0x31, 0x2e, 0x49, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x22, 0x45, 0x82, 0xd3, 0xe4, 0x93,
- 0x02, 0x3f, 0x3a, 0x01, 0x2a, 0x22, 0x3a, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x69, 0x6e, 0x73, 0x74,
+ 0x02, 0x3f, 0x3a, 0x01, 0x2a, 0x32, 0x3a, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x69, 0x6e, 0x73, 0x74,
0x61, 0x6e, 0x63, 0x65, 0x3d, 0x65, 0x6e, 0x76, 0x69, 0x72, 0x6f, 0x6e, 0x6d, 0x65, 0x6e, 0x74,
0x73, 0x2f, 0x2a, 0x2f, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x73, 0x2f, 0x2a, 0x7d,
0x3a, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x53, 0x6f, 0x75, 0x72, 0x63,
diff --git a/proto/generated-go/v1/instance_service.pb.gw.go b/proto/generated-go/v1/instance_service.pb.gw.go
index c355ac1481..f160234183 100644
--- a/proto/generated-go/v1/instance_service.pb.gw.go
+++ b/proto/generated-go/v1/instance_service.pb.gw.go
@@ -869,7 +869,7 @@ func RegisterInstanceServiceHandlerServer(ctx context.Context, mux *runtime.Serv
})
- mux.Handle("POST", pattern_InstanceService_UpdateDataSource_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ mux.Handle("PATCH", pattern_InstanceService_UpdateDataSource_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
@@ -1111,7 +1111,7 @@ func RegisterInstanceServiceHandlerClient(ctx context.Context, mux *runtime.Serv
})
- mux.Handle("POST", pattern_InstanceService_UpdateDataSource_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
+ mux.Handle("PATCH", pattern_InstanceService_UpdateDataSource_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
diff --git a/proto/v1/instance_service.proto b/proto/v1/instance_service.proto
index 2b7e874ffe..cd258ee8b4 100644
--- a/proto/v1/instance_service.proto
+++ b/proto/v1/instance_service.proto
@@ -73,7 +73,7 @@ service InstanceService {
rpc UpdateDataSource(UpdateDataSourceRequest) returns (Instance) {
option (google.api.http) = {
- post: "/v1/{instance=environments/*/instances/*}:updateDataSource"
+ patch: "/v1/{instance=environments/*/instances/*}:updateDataSource"
body: "*"
};
}
diff --git a/server/api/auth/auth.go b/server/api/auth/auth.go
index dd73fcc668..949c914e28 100644
--- a/server/api/auth/auth.go
+++ b/server/api/auth/auth.go
@@ -81,11 +81,11 @@ func New(store *store.Store, secret string, licenseService enterpriseAPI.License
func (in *APIAuthInterceptor) AuthenticationInterceptor(ctx context.Context, request interface{}, serverInfo *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
- return nil, status.Error(codes.Unauthenticated, "failed to parse metadata from incoming context")
+ return nil, status.Errorf(codes.Unauthenticated, "failed to parse metadata from incoming context")
}
accessTokenStr, refreshTokenStr, err := getTokenFromMetadata(md)
if err != nil {
- return nil, status.Error(codes.Unauthenticated, err.Error())
+ return nil, status.Errorf(codes.Unauthenticated, err.Error())
}
principalID, err := in.authenticate(ctx, accessTokenStr, refreshTokenStr)
diff --git a/server/api/v1/instance_service.go b/server/api/v1/instance_service.go
index b2e15bc4e2..3fc062b063 100644
--- a/server/api/v1/instance_service.go
+++ b/server/api/v1/instance_service.go
@@ -43,7 +43,6 @@ func (s *InstanceService) GetInstance(ctx context.Context, request *v1pb.GetInst
instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{
EnvironmentID: &environmentID,
ResourceID: &instanceID,
- ShowDeleted: true,
})
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
@@ -134,7 +133,6 @@ func (s *InstanceService) UpdateInstance(ctx context.Context, request *v1pb.Upda
instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{
EnvironmentID: &environmentID,
ResourceID: &instanceID,
- ShowDeleted: true,
})
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
@@ -186,7 +184,6 @@ func (s *InstanceService) DeleteInstance(ctx context.Context, request *v1pb.Dele
instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{
EnvironmentID: &environmentID,
ResourceID: &instanceID,
- ShowDeleted: true,
})
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
@@ -221,7 +218,6 @@ func (s *InstanceService) UndeleteInstance(ctx context.Context, request *v1pb.Un
instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{
EnvironmentID: &environmentID,
ResourceID: &instanceID,
- ShowDeleted: true,
})
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
@@ -248,18 +244,181 @@ func (s *InstanceService) UndeleteInstance(ctx context.Context, request *v1pb.Un
}
// AddDataSource adds a data source to an instance.
-func (*InstanceService) AddDataSource(_ context.Context, _ *v1pb.AddDataSourceRequest) (*v1pb.Instance, error) {
- return nil, status.Errorf(codes.Unimplemented, "method AddDataSource not implemented")
+func (s *InstanceService) AddDataSource(ctx context.Context, request *v1pb.AddDataSourceRequest) (*v1pb.Instance, error) {
+ if request.DataSources == nil {
+ return nil, status.Errorf(codes.InvalidArgument, "data sources is required")
+ }
+ // We only support add RO type datasouce to instance now, see more details in instance_service.proto.
+ if request.DataSources.Type != v1pb.DataSourceType_READ_ONLY {
+ return nil, status.Errorf(codes.InvalidArgument, "only support add read-only data source")
+ }
+
+ dataSource, err := convertToDataSourceMessage(request.DataSources)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, "failed to convert data source")
+ }
+
+ environmentID, instanceID, err := getEnvironmentInstanceID(request.Instance)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{
+ EnvironmentID: &environmentID,
+ ResourceID: &instanceID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if instance == nil {
+ return nil, status.Errorf(codes.NotFound, "instance %q not found", request.Instance)
+ }
+ if instance.Deleted {
+ return nil, status.Errorf(codes.InvalidArgument, "instance %q has been deleted", request.Instance)
+ }
+
+ principalID := ctx.Value(common.PrincipalIDContextKey).(int)
+
+ if err := s.store.AddDataSourceToInstanceV2(ctx, instance.UID, principalID, instance.EnvironmentID, instance.ResourceID, dataSource); err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+
+ instance, err = s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{
+ UID: &instance.UID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+
+ return convertToInstance(instance), nil
}
// RemoveDataSource removes a data source to an instance.
-func (*InstanceService) RemoveDataSource(_ context.Context, _ *v1pb.RemoveDataSourceRequest) (*v1pb.Instance, error) {
- return nil, status.Errorf(codes.Unimplemented, "method RemoveDataSource not implemented")
+func (s *InstanceService) RemoveDataSource(ctx context.Context, request *v1pb.RemoveDataSourceRequest) (*v1pb.Instance, error) {
+ if request.DataSources == nil {
+ return nil, status.Errorf(codes.InvalidArgument, "data sources is required")
+ }
+ // We only support remove RO type datasource to instance now, see more details in instance_service.proto.
+ if request.DataSources.Type != v1pb.DataSourceType_READ_ONLY {
+ return nil, status.Errorf(codes.InvalidArgument, "only support remove read-only data source")
+ }
+
+ dataSource, err := convertToDataSourceMessage(request.DataSources)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, "failed to convert data source")
+ }
+
+ environmentID, instanceID, err := getEnvironmentInstanceID(request.Instance)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{
+ EnvironmentID: &environmentID,
+ ResourceID: &instanceID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if instance == nil {
+ return nil, status.Errorf(codes.NotFound, "instance %q not found", request.Instance)
+ }
+ if instance.Deleted {
+ return nil, status.Errorf(codes.InvalidArgument, "instance %q has been deleted", request.Instance)
+ }
+
+ if err := s.store.RemoveDataSourceV2(ctx, instance.UID, instance.EnvironmentID, instance.ResourceID, dataSource.Type); err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+
+ instance, err = s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{
+ EnvironmentID: &environmentID,
+ ResourceID: &instanceID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+
+ instance, err = s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{
+ UID: &instance.UID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+
+ return convertToInstance(instance), nil
}
// UpdateDataSource updates a data source of an instance.
-func (*InstanceService) UpdateDataSource(_ context.Context, _ *v1pb.UpdateDataSourceRequest) (*v1pb.Instance, error) {
- return nil, status.Errorf(codes.Unimplemented, "method UpdateDataSource not implemented")
+func (s *InstanceService) UpdateDataSource(ctx context.Context, request *v1pb.UpdateDataSourceRequest) (*v1pb.Instance, error) {
+ if request.DataSources == nil {
+ return nil, status.Errorf(codes.InvalidArgument, "datasource is required")
+ }
+ tp, err := convertDataSourceTp(request.DataSources.Type)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+
+ environmentID, instanceID, err := getEnvironmentInstanceID(request.Instance)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+
+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{
+ EnvironmentID: &environmentID,
+ ResourceID: &instanceID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if instance == nil {
+ return nil, status.Errorf(codes.NotFound, "instance %q not found", request.Instance)
+ }
+ if instance.Deleted {
+ return nil, status.Errorf(codes.InvalidArgument, "instance %q has been deleted", request.Instance)
+ }
+
+ patch := &store.UpdateDataSourceMessage{
+ UpdaterID: ctx.Value(common.PrincipalIDContextKey).(int),
+ InstanceUID: instance.UID,
+ Type: tp,
+ EnvironmentID: instance.EnvironmentID,
+ InstanceID: instance.ResourceID,
+ }
+
+ for _, path := range request.UpdateMask.Paths {
+ switch path {
+ case "username":
+ patch.Username = &request.DataSources.Username
+ case "password":
+ patch.Password = &request.DataSources.Password
+ case "ssl_ca":
+ patch.SslCa = &request.DataSources.SslCa
+ case "ssl_cert":
+ patch.SslCert = &request.DataSources.SslCert
+ case "ssl_key":
+ patch.SslKey = &request.DataSources.SslKey
+ case "host":
+ patch.Host = &request.DataSources.Host
+ case "port":
+ patch.Port = &request.DataSources.Port
+ case "srv":
+ patch.SRV = &request.DataSources.Srv
+ case "authentication_database":
+ patch.AuthenticationDatabase = &request.DataSources.AuthenticationDatabase
+ }
+ }
+
+ if err := s.store.UpdateDataSourceV2(ctx, patch); err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+
+ instance, err = s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{
+ UID: &instance.UID,
+ })
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+
+ return convertToInstance(instance), nil
}
func convertToInstance(instance *store.InstanceMessage) *v1pb.Instance {
@@ -356,28 +515,47 @@ func convertToInstanceMessage(instanceID string, instance *v1pb.Instance) (*stor
func convertToDataSourceMessageList(dataSources []*v1pb.DataSource) ([]*store.DataSourceMessage, error) {
datasourceList := []*store.DataSourceMessage{}
for _, ds := range dataSources {
- var dsType api.DataSourceType
- switch ds.Type {
- case v1pb.DataSourceType_READ_ONLY:
- dsType = api.RO
- case v1pb.DataSourceType_ADMIN:
- dsType = api.Admin
- default:
- return nil, errors.Errorf("invalid data source type %v", ds.Type)
+ dataSource, err := convertToDataSourceMessage(ds)
+ if err != nil {
+ return nil, err
}
- datasourceList = append(datasourceList, &store.DataSourceMessage{
- Title: ds.Title,
- Type: dsType,
- Username: ds.Username,
- Password: ds.Password,
- SslCa: ds.SslCa,
- SslCert: ds.SslCert,
- SslKey: ds.SslKey,
- Host: ds.Host,
- Port: ds.Port,
- Database: ds.Database,
- })
+ datasourceList = append(datasourceList, dataSource)
}
return datasourceList, nil
}
+
+func convertToDataSourceMessage(dataSource *v1pb.DataSource) (*store.DataSourceMessage, error) {
+ dsType, err := convertDataSourceTp(dataSource.Type)
+ if err != nil {
+ return nil, err
+ }
+
+ return &store.DataSourceMessage{
+ Title: dataSource.Title,
+ Type: dsType,
+ Username: dataSource.Username,
+ Password: dataSource.Password,
+ SslCa: dataSource.SslCa,
+ SslCert: dataSource.SslCert,
+ SslKey: dataSource.SslKey,
+ Host: dataSource.Host,
+ Port: dataSource.Port,
+ Database: dataSource.Database,
+ SRV: dataSource.Srv,
+ AuthenticationDatabase: dataSource.AuthenticationDatabase,
+ }, nil
+}
+
+func convertDataSourceTp(tp v1pb.DataSourceType) (api.DataSourceType, error) {
+ var dsType api.DataSourceType
+ switch tp {
+ case v1pb.DataSourceType_READ_ONLY:
+ dsType = api.RO
+ case v1pb.DataSourceType_ADMIN:
+ dsType = api.Admin
+ default:
+ return "", errors.Errorf("invalid data source type %v", tp)
+ }
+ return dsType, nil
+}
diff --git a/store/data_source.go b/store/data_source.go
index bd22a828da..5db4857f9e 100644
--- a/store/data_source.go
+++ b/store/data_source.go
@@ -469,7 +469,7 @@ func (*Store) clearDataSourceImpl(ctx context.Context, tx *Tx, instanceID, datab
return nil
}
-// DataSourceMessage is the mssage for data source.
+// DataSourceMessage is the message for data source.
type DataSourceMessage struct {
Title string
Type api.DataSourceType
@@ -486,6 +486,27 @@ type DataSourceMessage struct {
AuthenticationDatabase string
}
+// UpdateDataSourceMessage is the message for the data source.
+type UpdateDataSourceMessage struct {
+ UpdaterID int
+ InstanceUID int
+ EnvironmentID string
+ InstanceID string
+
+ Type api.DataSourceType
+
+ Username *string
+ Password *string
+ SslCa *string
+ SslCert *string
+ SslKey *string
+ Host *string
+ Port *string
+ // Flatten data source options.
+ SRV *bool
+ AuthenticationDatabase *string
+}
+
func (*Store) listDataSourceV2(ctx context.Context, tx *Tx, instanceID string) ([]*DataSourceMessage, error) {
var dataSourceMessages []*DataSourceMessage
rows, err := tx.QueryContext(ctx, `
@@ -536,3 +557,166 @@ func (*Store) listDataSourceV2(ctx context.Context, tx *Tx, instanceID string) (
return dataSourceMessages, nil
}
+
+// AddDataSourceToInstanceV2 adds a RO data source to an instance and return the instance where the data source is added.
+func (s *Store) AddDataSourceToInstanceV2(ctx context.Context, instanceUID, creatorID int, environmentID, instanceID string, dataSource *DataSourceMessage) error {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return errors.New("Failed to begin transaction")
+ }
+ defer tx.Rollback()
+
+ if err := s.addDataSourceToInstanceImplV2(ctx, tx, instanceUID, creatorID, dataSource); err != nil {
+ return err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return errors.New("Failed to commit transaction")
+ }
+
+ s.instanceCache.Delete(getInstanceCacheKey(environmentID, instanceID))
+ s.instanceIDCache.Delete(instanceUID)
+ return nil
+}
+
+// RemoveDataSourceV2 removes a RO data source from an instance.
+func (s *Store) RemoveDataSourceV2(ctx context.Context, instanceUID int, environmentID, instanceID string, dataSourceTp api.DataSourceType) error {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return errors.New("Failed to begin transaction")
+ }
+ defer tx.Rollback()
+
+ result, err := tx.ExecContext(ctx, `
+ DELETE FROM data_source WHERE data_source.instance_id = $1 AND data_source.type = $2;
+ `, instanceUID, dataSourceTp)
+ if err != nil {
+ return FormatError(err)
+ }
+
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return errors.Wrapf(err, "failed to get rows affected")
+ }
+ if rowsAffected != 1 {
+ return errors.Errorf("remove %d type data_sources for instance uid %d, but expected 1", rowsAffected, instanceUID)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return errors.Wrap(err, "failed to commit transaction")
+ }
+
+ s.instanceCache.Delete(getInstanceCacheKey(environmentID, instanceID))
+ s.instanceIDCache.Delete(instanceUID)
+ return nil
+}
+
+// UpdateDataSourceV2 updates a data source and returns the instance.
+func (s *Store) UpdateDataSourceV2(ctx context.Context, patch *UpdateDataSourceMessage) error {
+ set, args := []string{"updater_id = $1"}, []interface{}{fmt.Sprintf("%d", patch.UpdaterID)}
+
+ if v := patch.Username; v != nil {
+ set, args = append(set, fmt.Sprintf("username = $%d", len(args)+1)), append(args, *v)
+ }
+ if v := patch.Password; v != nil {
+ set, args = append(set, fmt.Sprintf("password = $%d", len(args)+1)), append(args, *v)
+ }
+ if v := patch.SslKey; v != nil {
+ set, args = append(set, fmt.Sprintf("ssl_key = $%d", len(args)+1)), append(args, *v)
+ }
+ if v := patch.SslCert; v != nil {
+ set, args = append(set, fmt.Sprintf("ssl_cert = $%d", len(args)+1)), append(args, *v)
+ }
+ if v := patch.SslCa; v != nil {
+ set, args = append(set, fmt.Sprintf("ssl_ca = $%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)
+ }
+
+ // Use jsonb_build_object to build the jsonb object to update some fields in jsonb instead of whole column.
+ var optionSet []string
+ if v := patch.SRV; v != nil {
+ optionSet, args = append(optionSet, fmt.Sprintf("jsonb_build_object('srv', to_jsonb($%d::BOOLEAN))", len(args)+1)), append(args, *v)
+ }
+ if v := patch.AuthenticationDatabase; v != nil {
+ optionSet, args = append(optionSet, fmt.Sprintf("jsonb_build_object('authenticationDatabase', to_jsonb($%d::TEXT))", len(args)+1)), append(args, *v)
+ }
+ if len(optionSet) != 0 {
+ set = append(set, fmt.Sprintf(`options = options || %s`, strings.Join(optionSet, "||")))
+ }
+
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return errors.New("Failed to begin transaction")
+ }
+ defer tx.Rollback()
+
+ // Only update the data source if the
+ query := `UPDATE data_source SET ` + strings.Join(set, ", ") +
+ ` WHERE instance_id = ` + fmt.Sprintf("%d", patch.InstanceUID) +
+ ` AND type = ` + fmt.Sprintf(`'%s'`, patch.Type)
+ result, err := tx.ExecContext(ctx, query, args...)
+ if err != nil {
+ return FormatError(err)
+ }
+
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return errors.Wrapf(err, "failed to get rows affected")
+ }
+ if rowsAffected != 1 {
+ return errors.Errorf("update %v data source records from instance %v, but expected one", rowsAffected, patch.InstanceUID)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return errors.Wrap(err, "failed to commit transaction")
+ }
+
+ s.instanceCache.Delete(getInstanceCacheKey(patch.EnvironmentID, patch.InstanceID))
+ s.instanceIDCache.Delete(patch.InstanceUID)
+ return nil
+}
+
+func (*Store) addDataSourceToInstanceImplV2(ctx context.Context, tx *Tx, instanceUID, creatorID int, dataSource *DataSourceMessage) error {
+ // We flatten the data source fields in DataSourceMessage, so we need to compose them in store layer before INSERT.
+ dataSourceOptions := api.DataSourceOptions{
+ SRV: dataSource.SRV,
+ AuthenticationDatabase: dataSource.AuthenticationDatabase,
+ }
+
+ if _, err := tx.QueryContext(ctx, `
+ INSERT INTO data_source (
+ creator_id,
+ updater_id,
+ instance_id,
+ database_id,
+ name,
+ type,
+ username,
+ password,
+ ssl_key,
+ ssl_cert,
+ ssl_ca,
+ host,
+ port,
+ options,
+ database
+ )
+ SELECT $1, $2, $3, data_source.database_id, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14
+ FROM
+ data_source JOIN db ON data_source.database_id = db.id
+ WHERE data_source.instance_id = $15 AND db.name = $16;
+ `, creatorID, creatorID, instanceUID, dataSource.Title,
+ dataSource.Type, dataSource.Username, dataSource.Password, dataSource.SslKey,
+ dataSource.SslCert, dataSource.SslCa, dataSource.Host, dataSource.Port,
+ dataSourceOptions, dataSource.Database, instanceUID, api.AllDatabaseName,
+ ); err != nil {
+ return FormatError(err)
+ }
+
+ return nil
+}
diff --git a/store/instance.go b/store/instance.go
index d012e09b6d..1f929295da 100644
--- a/store/instance.go
+++ b/store/instance.go
@@ -732,17 +732,10 @@ func (s *Store) GetInstanceV2(ctx context.Context, find *FindInstanceMessage) (*
}
defer tx.Rollback()
- instances, err := s.listInstanceImplV2(ctx, tx, find)
+ instance, err := s.findInstanceImplV2(ctx, tx, find)
if err != nil {
- return nil, err
- }
- if len(instances) == 0 {
- return nil, nil
- }
- if len(instances) > 1 {
- return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d instances with filter %#v, expect 1", len(instances), find)}
+ return nil, errors.Wrapf(err, "failed to find instance")
}
- instance := instances[0]
if err := tx.Commit(); err != nil {
return nil, FormatError(err)
@@ -825,28 +818,8 @@ func (s *Store) CreateInstanceV2(ctx context.Context, environmentID string, inst
return nil, FormatError(err)
}
- allDatabaseUID, err := s.createDatabaseDefaultImpl(ctx, tx, instanceID, &DatabaseMessage{DatabaseName: api.AllDatabaseName})
- if err != nil {
- return nil, err
- }
-
for _, ds := range instanceCreate.DataSources {
- dataSourceCreate := &api.DataSourceCreate{
- CreatorID: creatorID,
- InstanceID: instanceID,
- DatabaseID: allDatabaseUID,
- Name: ds.Title,
- Type: ds.Type,
- Username: ds.Username,
- Password: ds.Password,
- SslKey: ds.SslKey,
- SslCert: ds.SslCert,
- SslCa: ds.SslCa,
- Host: ds.Host,
- Port: ds.Port,
- Database: ds.Database,
- }
- if err := s.createDataSourceRawTx(ctx, tx, dataSourceCreate); err != nil {
+ if err := s.addDataSourceToInstanceImplV2(ctx, tx, instanceID, creatorID, ds); err != nil {
return nil, err
}
}
@@ -955,26 +928,7 @@ func (s *Store) UpdateInstanceV2(ctx context.Context, patch *UpdateInstanceMessa
}
for _, ds := range patch.DataSources {
- dataSourceCreate := &api.DataSourceCreate{
- CreatorID: patch.UpdaterID,
- InstanceID: instance.UID,
- DatabaseID: allDatabase.UID,
- Name: ds.Title,
- Type: ds.Type,
- Username: ds.Username,
- Password: ds.Password,
- SslKey: ds.SslKey,
- SslCert: ds.SslCert,
- SslCa: ds.SslCa,
- Host: ds.Host,
- Port: ds.Port,
- Database: ds.Database,
- Options: api.DataSourceOptions{
- SRV: ds.SRV,
- AuthenticationDatabase: ds.AuthenticationDatabase,
- },
- }
- if err := s.createDataSourceRawTx(ctx, tx, dataSourceCreate); err != nil {
+ if err := s.addDataSourceToInstanceImplV2(ctx, tx, instance.UID, patch.UpdaterID, ds); err != nil {
return nil, err
}
}
@@ -995,6 +949,21 @@ func (s *Store) UpdateInstanceV2(ctx context.Context, patch *UpdateInstanceMessa
return instance, nil
}
+// findInstacnceImplV2 finds an instance by instance uid.
+func (s *Store) findInstanceImplV2(ctx context.Context, tx *Tx, findInstance *FindInstanceMessage) (*InstanceMessage, error) {
+ instances, err := s.listInstanceImplV2(ctx, tx, findInstance)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to list instances with find instance message %+v", findInstance)
+ }
+ if len(instances) == 0 {
+ return nil, errors.Wrapf(err, "cannot to get instance with find instance message %+v", findInstance)
+ }
+ if len(instances) > 1 {
+ return nil, errors.Wrapf(err, "find %d instances with find instance message %+v, expected 1", len(instances), findInstance)
+ }
+ return instances[0], nil
+}
+
func (s *Store) listInstanceImplV2(ctx context.Context, tx *Tx, find *FindInstanceMessage) ([]*InstanceMessage, error) {
where, args := []string{"1 = 1"}, []interface{}{}
if v := find.EnvironmentID; v != nil {