Skip to content

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

chore: implement get/list instance in gRPC (#4046)

ecmadao05dc6baa3a24
diff --git a/proto/README.md b/proto/README.md
index b59ce35b39..0a3207f8ce 100644
--- a/proto/README.md
+++ b/proto/README.md
@@ -2,3 +2,7 @@
- Install buf: https://docs.buf.build/installation
- Run: buf generate
+
+Note:
+You may have command conflict for the `buf`: https://github.com/ohmyzsh/ohmyzsh/issues/11169
+If so please remove the brew alias in `~/.oh-my-zsh/plugins/brew/brew.plugin.zsh`
diff --git a/server/api/v1/instance_service.go b/server/api/v1/instance_service.go
new file mode 100644
index 0000000000..4385cae593
--- /dev/null
+++ b/server/api/v1/instance_service.go
@@ -0,0 +1,146 @@
+package v1
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/plugin/db"
+ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
+ "github.com/bytebase/bytebase/store"
+)
+
+const instanceNamePrefix = "instances/"
+
+// InstanceService implements the instance service.
+type InstanceService struct {
+ v1pb.UnimplementedInstanceServiceServer
+ store *store.Store
+}
+
+// NewInstanceService creates a new InstanceService.
+func NewInstanceService(store *store.Store) *InstanceService {
+ return &InstanceService{
+ store: store,
+ }
+}
+
+// GetInstance gets an instance.
+func (s *InstanceService) GetInstance(ctx context.Context, request *v1pb.GetInstanceRequest) (*v1pb.Instance, error) {
+ environmentID, instanceID, err := getEnvironmentAndInstanceID(request.Name)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+
+ instance, err := s.store.GetInstanceV2(ctx, environmentID, instanceID)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ if instance == nil {
+ return nil, status.Errorf(codes.InvalidArgument, "instance %q not found", instanceID)
+ }
+ return convertInstance(environmentID, instance), nil
+}
+
+// ListInstances lists all instances.
+func (s *EnvironmentService) ListInstances(ctx context.Context, request *v1pb.ListInstancesRequest) (*v1pb.ListInstancesResponse, error) {
+ environmentID, err := getEnvironmentID(request.Parent)
+ if err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, err.Error())
+ }
+
+ instances, err := s.store.ListInstanceV2(ctx, environmentID, request.ShowDeleted)
+ if err != nil {
+ return nil, status.Errorf(codes.Internal, err.Error())
+ }
+ response := &v1pb.ListInstancesResponse{}
+ for _, instance := range instances {
+ response.Instances = append(response.Instances, convertInstance(environmentID, instance))
+ }
+ return response, nil
+}
+
+func getEnvironmentAndInstanceID(name string) (string, string, error) {
+ // the instance request should be environments/{environment-id}/instances/{instance-id}
+ if !strings.HasPrefix(name, environmentNamePrefix) {
+ return "", "", errors.Errorf("invalid request %q", name)
+ }
+
+ sections := strings.Split(name, "/")
+ if len(sections) != 4 {
+ return "", "", errors.Errorf("invalid request %q", name)
+ }
+
+ if fmt.Sprintf("%s/", sections[2]) != instanceNamePrefix {
+ return "", "", errors.Errorf("invalid request %q", name)
+ }
+
+ if sections[1] == "" || sections[3] == "" {
+ return "", "", errors.Errorf("invalid request %q", name)
+ }
+
+ return sections[1], sections[3], nil
+}
+
+func convertInstance(environmentID string, instance *store.InstanceMessage) *v1pb.Instance {
+ engine := v1pb.Engine_ENGINE_UNSPECIFIED
+ switch instance.Engine {
+ case db.ClickHouse:
+ engine = v1pb.Engine_ENGINE_CLICKHOUSE
+ case db.MySQL:
+ engine = v1pb.Engine_ENGINE_MYSQL
+ case db.Postgres:
+ engine = v1pb.Engine_ENGINE_POSTGRES
+ case db.Snowflake:
+ engine = v1pb.Engine_ENGINE_SNOWFLAKE
+ case db.SQLite:
+ engine = v1pb.Engine_ENGINE_SQLITE
+ case db.TiDB:
+ engine = v1pb.Engine_ENGINE_TIDB
+ case db.MongoDB:
+ engine = v1pb.Engine_ENGINE_MONGODB
+ }
+
+ dataSourceList := []*v1pb.DataSource{}
+ for _, ds := range instance.DataSources {
+ dataSourceType := v1pb.DataSourceType_DATA_SOURCE_UNSPECIFIED
+ switch ds.Type {
+ case api.Admin:
+ dataSourceType = v1pb.DataSourceType_DATA_SOURCE_ADMIN
+ case api.RO:
+ dataSourceType = v1pb.DataSourceType_DATA_SOURCE_RO
+ }
+
+ dataSourceList = append(dataSourceList, &v1pb.DataSource{
+ Title: ds.Title,
+ Type: dataSourceType,
+ Username: ds.Username,
+ SslCa: ds.SslCa,
+ SslCert: ds.SslCert,
+ SslKey: ds.SslKey,
+ Host: ds.Host,
+ Port: ds.Port,
+ Database: ds.Database,
+ })
+ }
+
+ state := v1pb.State_STATE_ACTIVE
+ if instance.Deleted {
+ state = v1pb.State_STATE_DELETED
+ }
+
+ return &v1pb.Instance{
+ Name: fmt.Sprintf("%s%s%s%s", environmentNamePrefix, environmentID, instanceNamePrefix, instance.InstanceID),
+ Title: instance.Title,
+ Engine: engine,
+ ExternalLink: instance.ExternalLink,
+ DataSources: dataSourceList,
+ State: state,
+ }
+}
diff --git a/store/data_source.go b/store/data_source.go
index 2a345cc703..84a68ba63d 100644
--- a/store/data_source.go
+++ b/store/data_source.go
@@ -509,3 +509,70 @@ func (*Store) clearDataSourceImpl(ctx context.Context, tx *Tx, instanceID, datab
}
return nil
}
+
+// DataSourceMessage is the mssage for data source.
+type DataSourceMessage struct {
+ Title string
+ Type api.DataSourceType
+ Username string
+ Password string
+ SslCa string
+ SslCert string
+ SslKey string
+ Host string
+ Port string
+ Database string
+}
+
+func (s *Store) listDataSourceV2(ctx context.Context, tx *Tx, instanceID int) ([]*DataSourceMessage, error) {
+ var dataSourceMessages []*DataSourceMessage
+ rows, err := tx.QueryContext(ctx, `
+ SELECT
+ database_id,
+ name,
+ type,
+ username,
+ password,
+ ssl_key,
+ ssl_cert,
+ ssl_ca,
+ host_override,
+ port_override
+ FROM data_source
+ WHERE instance_id = $1`,
+ instanceID,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var dataSourceMessage DataSourceMessage
+ var databaseID int
+ if err := rows.Scan(
+ &databaseID,
+ &dataSourceMessage.Title,
+ &dataSourceMessage.Type,
+ &dataSourceMessage.Username,
+ &dataSourceMessage.Password,
+ &dataSourceMessage.SslKey,
+ &dataSourceMessage.SslCert,
+ &dataSourceMessage.SslCa,
+ &dataSourceMessage.Host,
+ &dataSourceMessage.Password,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ database, err := s.getDatabaseRaw(ctx, &api.DatabaseFind{
+ ID: &databaseID,
+ })
+ if err != nil {
+ return nil, err
+ }
+ dataSourceMessage.Database = database.Name
+ dataSourceMessages = append(dataSourceMessages, &dataSourceMessage)
+ }
+
+ return dataSourceMessages, nil
+}
diff --git a/store/instance.go b/store/instance.go
index 5ad11a7b58..578794ccdd 100644
--- a/store/instance.go
+++ b/store/instance.go
@@ -759,3 +759,128 @@ func findInstanceQuery(find *api.InstanceFind) (string, []interface{}) {
return strings.Join(where, " AND "), args
}
+
+// InstanceMessage is the mssage for instance.
+type InstanceMessage struct {
+ InstanceID string
+ Title string
+ Engine db.Type
+ ExternalLink string
+ Deleted bool
+ DataSources []*DataSourceMessage
+}
+
+// GetInstanceV2 gets an instance by the resource_id.
+func (s *Store) GetInstanceV2(ctx context.Context, environmentID, resourceID string) (*InstanceMessage, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ var instanceMessage InstanceMessage
+ var rowStatus string
+ var instanceID int
+ if err := tx.QueryRowContext(ctx, `
+ SELECT
+ instance.id AS id,
+ instance.resource_id AS resource_id,
+ instance.name AS name,
+ engine,
+ external_link,
+ instance.row_status AS row_status
+ FROM instance
+ LEFT JOIN environment
+ ON environment.id = instance.environment_id
+ WHERE environment.resource_id = $1 AND instance.resource_id = $2`,
+ environmentID,
+ resourceID,
+ ).Scan(
+ &instanceID,
+ &instanceMessage.InstanceID,
+ &instanceMessage.Title,
+ &instanceMessage.Engine,
+ &instanceMessage.ExternalLink,
+ &rowStatus,
+ ); err != nil {
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ return nil, FormatError(err)
+ }
+ instanceMessage.Deleted = convertRowStatusToDeleted(rowStatus)
+
+ dataSourceList, err := s.listDataSourceV2(ctx, tx, instanceID)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ instanceMessage.DataSources = dataSourceList
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return &instanceMessage, nil
+}
+
+// ListInstanceV2 lists all instance.
+func (s *Store) ListInstanceV2(ctx context.Context, environmentID string, showDeleted bool) ([]*InstanceMessage, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ where, args := []string{"1 = 1"}, []interface{}{environmentID}
+ if !showDeleted {
+ where, args = append(where, fmt.Sprintf("instance.row_status = $%d", len(args)+1)), append(args, api.Normal)
+ }
+
+ var instanceMessages []*InstanceMessage
+ rows, err := tx.QueryContext(ctx, `
+ SELECT
+ instance.id AS id,
+ instance.resource_id AS resource_id,
+ instance.name AS name,
+ engine,
+ external_link,
+ instance.row_status AS row_status
+ FROM instance
+ LEFT JOIN environment
+ ON environment.id = instance.environment_id
+ WHERE environment.resource_id = $1 AND `+strings.Join(where, " AND "),
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var instanceMessage InstanceMessage
+ var rowStatus string
+ var instanceID int
+ if err := rows.Scan(
+ &instanceID,
+ &instanceMessage.InstanceID,
+ &instanceMessage.Title,
+ &instanceMessage.Engine,
+ &instanceMessage.ExternalLink,
+ &rowStatus,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+ instanceMessage.Deleted = convertRowStatusToDeleted(rowStatus)
+ dataSourceList, err := s.listDataSourceV2(ctx, tx, instanceID)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ instanceMessage.DataSources = dataSourceList
+ instanceMessages = append(instanceMessages, &instanceMessage)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return instanceMessages, nil
+}