Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: support data source list in instance for OpenAPI (#3744)
ecmadao20feae65192e
diff --git a/.gitignore b/.gitignoreindex e99537ba34..ce69107ba8 100644--- a/.gitignore+++ b/.gitignore@@ -37,4 +37,4 @@ bytebase-builddist/docs/openapi/swagger.jsondocs/sqlservice/swagger.json-frontend/src/types/sql-review.*.yaml+frontend/src/types/sql-review.*.yaml\ No newline at end of filediff --git a/api/v1/data_source.go b/api/v1/data_source.gonew file mode 100644index 0000000000..b8e80e1727--- /dev/null+++ b/api/v1/data_source.go@@ -0,0 +1,34 @@+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"`++ // HostOverride and PortOverride are only used for read-only data sources for user's read-replica instances.+ HostOverride string `json:"hostOverride"`+ PortOverride string `json:"portOverride"`+}++// 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"`+ HostOverride string `json:"hostOverride"`+ PortOverride string `json:"portOverride"`+}diff --git a/api/v1/instance.go b/api/v1/instance.goindex 649cdf70da..897a6be616 100644--- a/api/v1/instance.go+++ b/api/v1/instance.go@@ -9,7 +9,8 @@ type Instance struct {ID int `json:"id"`// Related fields- Environment string `json:"environment"`+ Environment string `json:"environment"`+ DataSourceList []*DataSource `json:"dataSourceList"`// Domain specific fieldsName string `json:"name"`@@ -19,13 +20,13 @@ type Instance struct {Host string `json:"host"`Port string `json:"port"`Database string `json:"database"`- Username string `json:"username"`}// InstanceCreate is the API message for creating an instance.type InstanceCreate struct {// Related fields- Environment string `json:"environment"`+ Environment string `json:"environment"`+ DataSourceList []*DataSourceCreate `json:"dataSourceList"`// Domain specific fieldsName string `json:"name"`@@ -34,15 +35,13 @@ type InstanceCreate struct {Host string `json:"host"`Port string `json:"port"`Database string `json:"database"`- Username string `json:"username"`- Password string `json:"password"`- SslCa string `json:"sslCa"`- SslCert string `json:"sslCert"`- SslKey string `json:"sslKey"`}// InstancePatch is the API message for patching an instance.type InstancePatch struct {+ // Related fields+ DataSourceList []*DataSourceCreate `json:"dataSourceList"`+// Domain specific fieldsName *string `json:"name"`ExternalLink *string `json:"externalLink"`diff --git a/server/instance.go b/server/instance.goindex 9c16c18270..9fd40975e5 100644--- a/server/instance.go+++ b/server/instance.go@@ -18,6 +18,7 @@ import ("github.com/bytebase/bytebase/common/log""github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/resources/postgres"+ "github.com/bytebase/bytebase/store")// pgConnectionInfo represents the embedded postgres instance connection info.@@ -32,14 +33,32 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {g.POST("/instance", func(c echo.Context) error {ctx := c.Request().Context()- instanceCreate := &api.InstanceCreate{- CreatorID: c.Get(getPrincipalIDContextKey()).(int),- }+ 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, instanceCreate)+ instance, err := s.createInstance(ctx, &store.InstanceCreate{+ CreatorID: c.Get(getPrincipalIDContextKey()).(int),+ EnvironmentID: instanceCreate.EnvironmentID,+ DataSourceList: []*api.DataSourceCreate{+ {+ Name: api.AdminDataSourceName,+ Type: api.Admin,+ Username: instanceCreate.Username,+ Password: instanceCreate.Password,+ SslCa: instanceCreate.SslCa,+ SslCert: instanceCreate.SslCert,+ SslKey: instanceCreate.SslKey,+ },+ },+ Name: instanceCreate.Name,+ Engine: instanceCreate.Engine,+ ExternalLink: instanceCreate.ExternalLink,+ Host: instanceCreate.Host,+ Port: instanceCreate.Port,+ Database: instanceCreate.Database,+ })if err != nil {return err}@@ -99,15 +118,22 @@ 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)}- instancePatch := &api.InstancePatch{- ID: id,- UpdaterID: c.Get(getPrincipalIDContextKey()).(int),- }+ instancePatch := &api.InstancePatch{}if err := jsonapi.UnmarshalPayload(c.Request().Body, instancePatch); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch instance request").SetInternal(err)}- instancePatched, err := s.updateInstance(ctx, instancePatch)+ instancePatched, err := s.updateInstance(ctx, &store.InstancePatch{+ ID: id,+ RowStatus: instancePatch.RowStatus,+ UpdaterID: c.Get(getPrincipalIDContextKey()).(int),+ Name: instancePatch.Name,+ EngineVersion: instancePatch.EngineVersion,+ ExternalLink: instancePatch.ExternalLink,+ Host: instancePatch.Host,+ Port: instancePatch.Port,+ Database: instancePatch.Database,+ })if err != nil {return err}@@ -433,7 +459,7 @@ func (s *Server) disallowBytebaseStore(engine db.Type, host, port string) errorreturn nil}-func (s *Server) createInstance(ctx context.Context, create *api.InstanceCreate) (*api.Instance, error) {+func (s *Server) createInstance(ctx context.Context, create *store.InstanceCreate) (*api.Instance, error) {if err := s.instanceCountGuard(ctx); err != nil {return nil, err}@@ -477,7 +503,7 @@ func (s *Server) createInstance(ctx context.Context, create *api.InstanceCreate)return instance, nil}-func (s *Server) updateInstance(ctx context.Context, patch *api.InstancePatch) (*api.Instance, error) {+func (s *Server) updateInstance(ctx context.Context, patch *store.InstancePatch) (*api.Instance, error) {instance, 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)@@ -503,8 +529,8 @@ func (s *Server) updateInstance(ctx context.Context, patch *api.InstancePatch) (return nil, echo.NewHTTPError(http.StatusBadRequest, "database parameter is only allowed for Postgres")}- var instancePatched *api.Instance- if patch.RowStatus != nil || patch.Name != nil || patch.ExternalLink != nil || patch.Host != nil || patch.Port != nil || patch.Database != nil {+ instancePatched := instance+ 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) {diff --git a/server/openapi_instance.go b/server/openapi_instance.goindex 5435b329fc..31d622090e 100644--- a/server/openapi_instance.go+++ b/server/openapi_instance.go@@ -11,6 +11,7 @@ import ("github.com/bytebase/bytebase/api"openAPIV1 "github.com/bytebase/bytebase/api/v1"+ "github.com/bytebase/bytebase/store")func (s *Server) registerOpenAPIRoutesForInstance(g *echo.Group) {@@ -68,20 +69,24 @@ func (s *Server) createInstanceByOpenAPI(c echo.Context) error {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Should only find one environment with name: %s", instanceCreate.Environment))}- instance, err := s.createInstance(ctx, &api.InstanceCreate{- CreatorID: c.Get(getPrincipalIDContextKey()).(int),- EnvironmentID: envList[0].ID,- Name: instanceCreate.Name,- Engine: instanceCreate.Engine,- ExternalLink: instanceCreate.ExternalLink,- Host: instanceCreate.Host,- Port: instanceCreate.Port,- Database: instanceCreate.Database,- Username: instanceCreate.Username,- Password: instanceCreate.Password,- SslCa: instanceCreate.SslCa,- SslCert: instanceCreate.SslCert,- SslKey: instanceCreate.SslKey,+ dataSourceCreateList, err := convertToAPIDataSouceList(instanceCreate.DataSourceList)+ if err != nil {+ return err+ }+ if len(dataSourceCreateList) == 0 {+ return echo.NewHTTPError(http.StatusBadRequest, "Should specific at least one data source.")+ }++ instance, err := s.createInstance(ctx, &store.InstanceCreate{+ CreatorID: c.Get(getPrincipalIDContextKey()).(int),+ EnvironmentID: envList[0].ID,+ DataSourceList: dataSourceCreateList,+ Name: instanceCreate.Name,+ Engine: instanceCreate.Engine,+ ExternalLink: instanceCreate.ExternalLink,+ Host: instanceCreate.Host,+ Port: instanceCreate.Port,+ Database: instanceCreate.Database,})if err != nil {return err@@ -107,7 +112,7 @@ func (s *Server) updateInstanceByOpenAPI(c echo.Context) error {return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch instance request").SetInternal(err)}- instance, err := s.updateInstance(ctx, &api.InstancePatch{+ patch := &store.InstancePatch{ID: id,UpdaterID: c.Get(getPrincipalIDContextKey()).(int),Name: instancePatch.Name,@@ -115,7 +120,15 @@ func (s *Server) updateInstanceByOpenAPI(c echo.Context) error {Host: instancePatch.Host,Port: instancePatch.Port,Database: instancePatch.Database,- })+ }++ dataSourceCreateList, err := convertToAPIDataSouceList(instancePatch.DataSourceList)+ if err != nil {+ return err+ }+ patch.DataSourceList = dataSourceCreateList++ instance, err := s.updateInstance(ctx, patch)if err != nil {return err}@@ -131,7 +144,7 @@ func (s *Server) deleteInstanceByOpenAPI(c echo.Context) error {}rowStatus := string(api.Archived)- if _, err := s.updateInstance(ctx, &api.InstancePatch{+ if _, err := s.updateInstance(ctx, &store.InstancePatch{ID: id,UpdaterID: c.Get(getPrincipalIDContextKey()).(int),RowStatus: &rowStatus,@@ -161,16 +174,75 @@ func (s *Server) getInstanceByID(c echo.Context) error {}func convertToOpenAPIInstance(instance *api.Instance) *openAPIV1.Instance {+ dataSourceList := []*openAPIV1.DataSource{}+ for _, dataSource := range instance.DataSourceList {+ dataSourceList = append(dataSourceList, &openAPIV1.DataSource{+ ID: dataSource.ID,+ DatabaseID: dataSource.DatabaseID,+ Name: dataSource.Name,+ Type: dataSource.Type,+ Username: dataSource.Username,+ HostOverride: dataSource.HostOverride,+ PortOverride: dataSource.PortOverride,+ })+ }+return &openAPIV1.Instance{- ID: instance.ID,- Environment: instance.Environment.Name,- Name: instance.Name,- Engine: instance.Engine,- EngineVersion: instance.EngineVersion,- ExternalLink: instance.ExternalLink,- Host: instance.Host,- Port: instance.Port,- Database: instance.Database,- Username: instance.Username,+ ID: instance.ID,+ Environment: instance.Environment.Name,+ Name: instance.Name,+ Engine: instance.Engine,+ EngineVersion: instance.EngineVersion,+ ExternalLink: instance.ExternalLink,+ Host: instance.Host,+ Port: instance.Port,+ Database: instance.Database,+ DataSourceList: dataSourceList,}}++func convertToAPIDataSouceList(dataSourceList []*openAPIV1.DataSourceCreate) ([]*api.DataSourceCreate, error) {+ var res []*api.DataSourceCreate++ dataSourceNameMap := map[string]bool{}+ dataSourceTypeMap := map[api.DataSourceType]bool{}+ for _, dataSource := range dataSourceList {+ if dataSourceNameMap[dataSource.Name] {+ return nil, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Duplicate data source name %s. The data source name should be unique", dataSource.Name))+ }+ if dataSourceTypeMap[dataSource.Type] {+ return nil, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Duplicate data source type %s. The data source type should be unique", dataSource.Name))+ }+ dataSourceNameMap[dataSource.Name] = true+ dataSourceTypeMap[dataSource.Type] = true++ switch dataSource.Type {+ case api.Admin:+ res = append(res, &api.DataSourceCreate{+ Name: dataSource.Name,+ Type: api.Admin,+ Username: dataSource.Username,+ Password: dataSource.Password,+ SslCa: dataSource.SslCa,+ SslCert: dataSource.SslCert,+ SslKey: dataSource.SslKey,+ })+ case api.RO:+ res = append(res, &api.DataSourceCreate{+ Name: dataSource.Name,+ Type: api.RO,+ Username: dataSource.Username,+ Password: dataSource.Password,+ SslCa: dataSource.SslCa,+ SslCert: dataSource.SslCert,+ SslKey: dataSource.SslKey,+ HostOverride: dataSource.HostOverride,+ PortOverride: dataSource.PortOverride,+ })+ default:+ return nil, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("The data source type %s is not supported", dataSource.Type))+ }+ }++ return res, nil+}diff --git a/server/runner/schemasync/syncer.go b/server/runner/schemasync/syncer.goindex 48b7b7bf8e..44928e7a90 100644--- a/server/runner/schemasync/syncer.go+++ b/server/runner/schemasync/syncer.go@@ -186,7 +186,7 @@ func (s *Syncer) syncInstanceSchema(ctx context.Context, instance *api.Instance,// 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 {- _, err := s.store.PatchInstance(ctx, &api.InstancePatch{+ _, err := s.store.PatchInstance(ctx, &store.InstancePatch{ID: instance.ID,UpdaterID: api.SystemBotID,EngineVersion: &instanceMeta.Version,diff --git a/store/data_source.go b/store/data_source.goindex f528b4c8e5..d8f1c80b18 100644--- a/store/data_source.go+++ b/store/data_source.go@@ -490,3 +490,11 @@ func (*Store) deleteDataSourceImpl(ctx context.Context, tx *Tx, delete *api.Data}return nil}++// clearDataSourceImpl deletes dataSources by instance id and database id.+func (*Store) clearDataSourceImpl(ctx context.Context, tx *Tx, instanceID, databaseID int) error {+ if _, err := tx.ExecContext(ctx, `DELETE FROM data_source WHERE instance_id = $1 AND database_id = $2`, instanceID, databaseID); err != nil {+ return FormatError(err)+ }+ return nil+}diff --git a/store/instance.go b/store/instance.goindex 5408b076e9..05a5000868 100644--- a/store/instance.go+++ b/store/instance.go@@ -14,6 +14,48 @@ import ("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 {@@ -67,7 +109,7 @@ func (raw *instanceRaw) toInstance() *api.Instance {}// CreateInstance creates an instance of Instance.-func (s *Store) CreateInstance(ctx context.Context, create *api.InstanceCreate) (*api.Instance, error) {+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)@@ -114,7 +156,7 @@ func (s *Store) FindInstance(ctx context.Context, find *api.InstanceFind) ([]*ap}// PatchInstance patches an instance of Instance.-func (s *Store) PatchInstance(ctx context.Context, patch *api.InstancePatch) (*api.Instance, error) {+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)@@ -332,7 +374,7 @@ func (s *Store) composeInstance(ctx context.Context, raw *instanceRaw) (*api.Ins}// createInstanceRaw creates a new instance.-func (s *Store) createInstanceRaw(ctx context.Context, create *api.InstanceCreate) (*instanceRaw, error) {+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)@@ -359,21 +401,22 @@ func (s *Store) createInstanceRaw(ctx context.Context, create *api.InstanceCreatreturn nil, err}- // Create admin data source- adminDataSourceCreate := &api.DataSourceCreate{- CreatorID: create.CreatorID,- InstanceID: instance.ID,- DatabaseID: allDatabase.ID,- Name: api.AdminDataSourceName,- Type: api.Admin,- Username: create.Username,- Password: create.Password,- SslKey: create.SslKey,- SslCert: create.SslCert,- SslCa: create.SslCa,- }- if err := s.createDataSourceRawTx(ctx, tx, adminDataSourceCreate); err != nil {- return nil, err+ for _, dataSource := range create.DataSourceList {+ dataSourceCreate := &api.DataSourceCreate{+ CreatorID: create.CreatorID,+ InstanceID: instance.ID,+ DatabaseID: allDatabase.ID,+ Name: dataSource.Name,+ Type: dataSource.Type,+ Username: dataSource.Username,+ Password: dataSource.Password,+ SslKey: dataSource.SslKey,+ SslCert: dataSource.SslCert,+ SslCa: dataSource.SslCa,+ }+ if err := s.createDataSourceRawTx(ctx, tx, dataSourceCreate); err != nil {+ return nil, err+ }}if err := tx.Commit(); err != nil {@@ -443,7 +486,7 @@ func (s *Store) getInstanceRaw(ctx context.Context, find *api.InstanceFind) (*in// patchInstanceRaw updates an existing instance by ID.// Returns ENOTFOUND if instance does not exist.-func (s *Store) patchInstanceRaw(ctx context.Context, patch *api.InstancePatch) (*instanceRaw, error) {+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)@@ -455,6 +498,49 @@ func (s *Store) patchInstanceRaw(ctx context.Context, patch *api.InstancePatch)return nil, FormatError(err)}+ if patch.DataSourceList != nil {+ dbName := api.AllDatabaseName+ dbFind := &api.DatabaseFind{+ InstanceID: &patch.ID,+ Name: &dbName,+ IncludeAllDatabase: true,+ }+ databaseList, err := s.findDatabaseImpl(ctx, tx, dbFind)+ if err != nil {+ return nil, err+ }+ if len(databaseList) == 0 {+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("cannot find database with filter %+v. ", dbFind)}+ }+ if len(databaseList) > 1 {+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d databases with filter %+v, expect 1. ", len(databaseList), dbFind)}+ }+ database := databaseList[0]++ if err := s.clearDataSourceImpl(ctx, tx, patch.ID, database.ID); 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: database.ID,+ Name: dataSource.Name,+ Type: dataSource.Type,+ Username: dataSource.Username,+ Password: dataSource.Password,+ SslKey: dataSource.SslKey,+ SslCert: dataSource.SslCert,+ SslCa: dataSource.SslCa,+ }+ if err := s.createDataSourceRawTx(ctx, tx, dataSourceCreate); err != nil {+ return nil, err+ }+ }+ }+if err := tx.Commit(); err != nil {return nil, FormatError(err)}@@ -467,7 +553,7 @@ func (s *Store) patchInstanceRaw(ctx context.Context, patch *api.InstancePatch)}// createInstanceImpl creates a new instance.-func createInstanceImpl(ctx context.Context, tx *Tx, create *api.InstanceCreate) (*instanceRaw, error) {+func createInstanceImpl(ctx context.Context, tx *Tx, create *InstanceCreate) (*instanceRaw, error) {// Insert row into database.query := `INSERT INTO instance (@@ -579,7 +665,7 @@ func findInstanceImpl(ctx context.Context, tx *Tx, find *api.InstanceFind) ([]*i}// patchInstanceImpl updates a instance by ID. Returns the new state of the instance after update.-func patchInstanceImpl(ctx context.Context, tx *Tx, patch *api.InstancePatch) (*instanceRaw, error) {+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 {