Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: decouple api/service/store packages for Setting (#1190)
Yilong Li7177a8d14e22
diff --git a/api/setting.go b/api/setting.goindex cbfdcfd782..ff3bbf8ad9 100644--- a/api/setting.go+++ b/api/setting.go@@ -1,7 +1,6 @@package apiimport (- "context""encoding/json")@@ -15,42 +14,6 @@ const (SettingBrandingLogo SettingName = "bb.branding.logo")-// SettingRaw is the store model for an Setting.-// Fields have exactly the same meanings as Setting.-type SettingRaw struct {- ID int-- // Standard fields- CreatorID int- CreatedTs int64- UpdaterID int- UpdatedTs int64-- // Domain specific fields- Name SettingName- Value string- Description string-}--// ToSetting creates an instance of Setting based on the SettingRaw.-// This is intended to be called when we need to compose an Setting relationship.-func (raw *SettingRaw) ToSetting() *Setting {- return &Setting{- ID: raw.ID,-- // Standard fields- CreatorID: raw.CreatorID,- CreatedTs: raw.CreatedTs,- UpdaterID: raw.UpdaterID,- UpdatedTs: raw.UpdatedTs,-- // Domain specific fields- Name: raw.Name,- Value: raw.Value,- Description: raw.Description,- }-}-// Setting is the API message for a setting.type Setting struct {ID int `jsonapi:"primary,setting"`@@ -99,12 +62,3 @@ func (find *SettingFind) String() string {}return string(str)}--// SettingService is the service for settings.-type SettingService interface {- // Creates new setting and returns if not exist, returns the existing one otherwise.- CreateSettingIfNotExist(ctx context.Context, create *SettingCreate) (*SettingRaw, error)- FindSettingList(ctx context.Context, find *SettingFind) ([]*SettingRaw, error)- FindSetting(ctx context.Context, find *SettingFind) (*SettingRaw, error)- PatchSetting(ctx context.Context, patch *SettingPatch) (*SettingRaw, error)-}diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.goindex 137c575959..2a09da5039 100644--- a/bin/server/cmd/root.go+++ b/bin/server/cmd/root.go@@ -310,7 +310,7 @@ func NewMain(activeProfile Profile, logger *zap.Logger) (*Main, error) {}, nil}-func initSetting(ctx context.Context, settingService api.SettingService) (*config, error) {+func initSetting(ctx context.Context, store *store.Store) (*config, error) {result := &config{}{configCreate := &api.SettingCreate{@@ -319,7 +319,7 @@ func initSetting(ctx context.Context, settingService api.SettingService) (*confiValue: common.RandomString(secretLength),Description: "Random string used to sign the JWT auth token.",}- config, err := settingService.CreateSettingIfNotExist(ctx, configCreate)+ config, err := store.CreateSettingIfNotExist(ctx, configCreate)if err != nil {return nil, err}@@ -329,14 +329,14 @@ func initSetting(ctx context.Context, settingService api.SettingService) (*confireturn result, nil}-func initBranding(ctx context.Context, settingService api.SettingService) error {+func initBranding(ctx context.Context, store *store.Store) error {configCreate := &api.SettingCreate{CreatorID: api.SystemBotID,Name: api.SettingBrandingLogo,Value: "",Description: "The branding logo image in base64 string format.",}- _, err := settingService.CreateSettingIfNotExist(ctx, configCreate)+ _, err := store.CreateSettingIfNotExist(ctx, configCreate)if err != nil {return err}@@ -433,29 +433,25 @@ func (m *Main) Run(ctx context.Context) error {if err != nil {return fmt.Errorf("cannot new db: %w", err)}-if err := db.Open(ctx); err != nil {return fmt.Errorf("cannot open db: %w", err)}+ m.db = db++ cacheService := server.NewCacheService(m.l)+ storeInstance := store.New(m.l, db, cacheService)- settingService := store.NewSettingService(m.l, db)- config, err := initSetting(ctx, settingService)+ config, err := initSetting(ctx, storeInstance)if err != nil {return fmt.Errorf("failed to init config: %w", err)}- err = initBranding(ctx, settingService)+ err = initBranding(ctx, storeInstance)if err != nil {return fmt.Errorf("failed to init branding: %w", err)}- m.db = db-- cacheService := server.NewCacheService(m.l)- storeInstance := store.New(m.l, db, cacheService)-s := server.NewServer(m.l, storeInstance, m.lvl, version, host, m.profile.port, frontendHost, frontendPort, m.profile.datastorePort, m.profile.mode, m.profile.dataDir, m.profile.backupRunnerInterval, config.secret, readonly, demo, debug)- s.SettingService = settingServices.InstanceUserService = store.NewInstanceUserService(m.l, db)s.TableService = store.NewTableService(m.l, db)s.ColumnService = store.NewColumnService(m.l, db)diff --git a/server/server.go b/server/server.goindex b58af3dbbb..2e02d19ff1 100644--- a/server/server.go+++ b/server/server.go@@ -37,7 +37,6 @@ type Server struct {ActivityManager *ActivityManager- SettingService api.SettingServiceInstanceUserService api.InstanceUserServiceTableService api.TableServiceColumnService api.ColumnServicediff --git a/server/setting.go b/server/setting.goindex 614fec91e0..9459bb4eba 100644--- a/server/setting.go+++ b/server/setting.go@@ -1,7 +1,6 @@package serverimport (- "context""fmt""net/http"@@ -22,18 +21,10 @@ func (s *Server) registerSettingRoutes(g *echo.Group) {g.GET("/setting", func(c echo.Context) error {ctx := c.Request().Context()find := &api.SettingFind{}- settingRawList, err := s.SettingService.FindSettingList(ctx, find)+ settingList, err := s.store.FindSetting(ctx, find)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch setting list").SetInternal(err)}- var settingList []*api.Setting- for _, raw := range settingRawList {- setting, err := s.composeSettingRelationship(ctx, raw)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to compose setting relationship for ID %d", raw.ID)).SetInternal(err)- }- settingList = append(settingList, setting)- }filteredList := []*api.Setting{}for _, setting := range settingList {@@ -67,7 +58,7 @@ func (s *Server) registerSettingRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, "Malformatted update setting request").SetInternal(err)}- setting, err := s.SettingService.PatchSetting(ctx, settingPatch)+ setting, err := s.store.PatchSetting(ctx, settingPatch)if err != nil {if common.ErrorCode(err) == common.NotFound {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Setting name not found: %s", settingPatch.Name))@@ -76,27 +67,9 @@ func (s *Server) registerSettingRoutes(g *echo.Group) {}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, setting.ToSetting()); err != nil {+ if err := jsonapi.MarshalPayload(c.Response().Writer, setting); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal setting response").SetInternal(err)}return nil})}--func (s *Server) composeSettingRelationship(ctx context.Context, raw *api.SettingRaw) (*api.Setting, error) {- setting := raw.ToSetting()-- creator, err := s.store.GetPrincipalByID(ctx, setting.CreatorID)- if err != nil {- return nil, err- }- setting.Creator = creator-- updater, err := s.store.GetPrincipalByID(ctx, setting.UpdaterID)- if err != nil {- return nil, err- }- setting.Updater = updater-- return setting, nil-}diff --git a/store/setting.go b/store/setting.goindex 09fde60c4a..4edee7b553 100644--- a/store/setting.go+++ b/store/setting.go@@ -8,32 +8,117 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"- "go.uber.org/zap")-var (- _ api.SettingService = (*SettingService)(nil)-)+// settingRaw is the store model for an Setting.+// Fields have exactly the same meanings as Setting.+type settingRaw struct {+ ID int++ // Standard fields+ CreatorID int+ CreatedTs int64+ UpdaterID int+ UpdatedTs int64++ // Domain specific fields+ Name api.SettingName+ Value string+ Description string+}++// toSetting creates an instance of Setting based on the settingRaw.+// This is intended to be called when we need to compose an Setting relationship.+func (raw *settingRaw) toSetting() *api.Setting {+ return &api.Setting{+ ID: raw.ID,++ // Standard fields+ CreatorID: raw.CreatorID,+ CreatedTs: raw.CreatedTs,+ UpdaterID: raw.UpdaterID,+ UpdatedTs: raw.UpdatedTs,++ // Domain specific fields+ Name: raw.Name,+ Value: raw.Value,+ Description: raw.Description,+ }+}++// CreateSettingIfNotExist creates an instance of Setting+func (s *Store) CreateSettingIfNotExist(ctx context.Context, create *api.SettingCreate) (*api.Setting, error) {+ settingRaw, err := s.createSettingRawIfNotExist(ctx, create)+ if err != nil {+ return nil, fmt.Errorf("failed to create Setting with SettingCreate[%+v], error[%w]", create, err)+ }+ setting, err := s.composeSetting(ctx, settingRaw)+ if err != nil {+ return nil, fmt.Errorf("failed to compose Setting with settingRaw[%+v], error[%w]", settingRaw, err)+ }+ return setting, nil+}-// SettingService represents a service for managing setting.-type SettingService struct {- l *zap.Logger- db *DB+// FindSetting finds a list of Setting instances+func (s *Store) FindSetting(ctx context.Context, find *api.SettingFind) ([]*api.Setting, error) {+ settingRawList, err := s.findSettingRaw(ctx, find)+ if err != nil {+ return nil, fmt.Errorf("failed to find Setting list, error[%w]", err)+ }+ var settingList []*api.Setting+ for _, raw := range settingRawList {+ setting, err := s.composeSetting(ctx, raw)+ if err != nil {+ return nil, fmt.Errorf("failed to compose Setting with settingRaw[%+v], error[%w]", raw, err)+ }+ settingList = append(settingList, setting)+ }+ return settingList, nil}-// NewSettingService returns a new instance of SettingService.-func NewSettingService(logger *zap.Logger, db *DB) *SettingService {- return &SettingService{l: logger, db: db}+// PatchSetting patches an instance of Setting+func (s *Store) PatchSetting(ctx context.Context, patch *api.SettingPatch) (*api.Setting, error) {+ settingRaw, err := s.patchSettingRaw(ctx, patch)+ if err != nil {+ return nil, fmt.Errorf("failed to patch Setting with SettingPatch[%+v], error[%w]", patch, err)+ }+ setting, err := s.composeSetting(ctx, settingRaw)+ if err != nil {+ return nil, fmt.Errorf("failed to compose Setting with settingRaw[%+v], error[%w]", settingRaw, err)+ }+ return setting, nil+}++//+// private functions+//++func (s *Store) composeSetting(ctx context.Context, raw *settingRaw) (*api.Setting, error) {+ setting := raw.toSetting()++ creator, err := s.GetPrincipalByID(ctx, setting.CreatorID)+ if err != nil {+ return nil, err+ }+ setting.Creator = creator++ updater, err := s.GetPrincipalByID(ctx, setting.UpdaterID)+ if err != nil {+ return nil, err+ }+ setting.Updater = updater++ return setting, nil}-// CreateSettingIfNotExist creates a new setting only if the named setting does not exist.-func (s *SettingService) CreateSettingIfNotExist(ctx context.Context, create *api.SettingCreate) (*api.SettingRaw, error) {+// createSettingRawIfNotExist creates a new setting only if the named setting does not exist.+func (s *Store) createSettingRawIfNotExist(ctx context.Context, create *api.SettingCreate) (*settingRaw, error) {// We do a find followed by a create if NOT found. Though SQLite supports UPSERT ON CONFLICT DO NOTHING syntax, it doesn't// support RETURNING in such case. So we have to use separate SELECT and INSERT anyway.find := &api.SettingFind{Name: &create.Name,}- setting, err := s.FindSetting(ctx, find)+ setting, err := s.getSettingRaw(ctx, find)if err != nil {return nil, err}@@ -44,7 +129,7 @@ func (s *SettingService) CreateSettingIfNotExist(ctx context.Context, create *ap}defer tx.PTx.Rollback()- setting, err := createSetting(ctx, tx.PTx, create)+ setting, err := createSettingImpl(ctx, tx.PTx, create)if err != nil {return nil, err}@@ -59,31 +144,31 @@ func (s *SettingService) CreateSettingIfNotExist(ctx context.Context, create *apreturn setting, nil}-// FindSettingList retrieves a list of settings based on find.-func (s *SettingService) FindSettingList(ctx context.Context, find *api.SettingFind) ([]*api.SettingRaw, error) {+// findSettingRaw retrieves a list of settings based on find.+func (s *Store) findSettingRaw(ctx context.Context, find *api.SettingFind) ([]*settingRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)}defer tx.PTx.Rollback()- list, err := findSettingList(ctx, tx.PTx, find)+ list, err := findSettingImpl(ctx, tx.PTx, find)if err != nil {return nil, err}return list, nil}-// FindSetting retrieves a single setting based on find.+// getSettingRaw retrieves a single setting based on find.// Returns ECONFLICT if finding more than 1 matching records.-func (s *SettingService) FindSetting(ctx context.Context, find *api.SettingFind) (*api.SettingRaw, error) {+func (s *Store) getSettingRaw(ctx context.Context, find *api.SettingFind) (*settingRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)}defer tx.PTx.Rollback()- list, err := findSettingList(ctx, tx.PTx, find)+ list, err := findSettingImpl(ctx, tx.PTx, find)if err != nil {return nil, err}@@ -96,16 +181,16 @@ func (s *SettingService) FindSetting(ctx context.Context, find *api.SettingFind)return list[0], nil}-// PatchSetting updates an existing setting by name.+// patchSettingRaw updates an existing setting by name.// Returns ENOTFOUND if setting does not exist.-func (s *SettingService) PatchSetting(ctx context.Context, patch *api.SettingPatch) (*api.SettingRaw, error) {+func (s *Store) patchSettingRaw(ctx context.Context, patch *api.SettingPatch) (*settingRaw, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {return nil, FormatError(err)}defer tx.PTx.Rollback()- setting, err := patchSetting(ctx, tx.PTx, patch)+ setting, err := patchSettingImpl(ctx, tx.PTx, patch)if err != nil {return nil, FormatError(err)}@@ -117,8 +202,8 @@ func (s *SettingService) PatchSetting(ctx context.Context, patch *api.SettingPatreturn setting, nil}-// createSetting creates a new setting.-func createSetting(ctx context.Context, tx *sql.Tx, create *api.SettingCreate) (*api.SettingRaw, error) {+// createSettingImpl creates a new setting.+func createSettingImpl(ctx context.Context, tx *sql.Tx, create *api.SettingCreate) (*settingRaw, error) {// Insert row into database.row, err := tx.QueryContext(ctx, `INSERT INTO setting (@@ -144,7 +229,7 @@ func createSetting(ctx context.Context, tx *sql.Tx, create *api.SettingCreate) (defer row.Close()row.Next()- var settingRaw api.SettingRaw+ var settingRaw settingRawif err := row.Scan(&settingRaw.Name,&settingRaw.Value,@@ -156,7 +241,7 @@ func createSetting(ctx context.Context, tx *sql.Tx, create *api.SettingCreate) (return &settingRaw, nil}-func findSettingList(ctx context.Context, tx *sql.Tx, find *api.SettingFind) ([]*api.SettingRaw, error) {+func findSettingImpl(ctx context.Context, tx *sql.Tx, find *api.SettingFind) ([]*settingRaw, error) {// Build WHERE clause.where, args := []string{"1 = 1"}, []interface{}{}if v := find.Name; v != nil {@@ -182,9 +267,9 @@ func findSettingList(ctx context.Context, tx *sql.Tx, find *api.SettingFind) ([]defer rows.Close()// Iterate over result set and deserialize rows into settingRawList.- var settingRawList []*api.SettingRaw+ var settingRawList []*settingRawfor rows.Next() {- var settingRaw api.SettingRaw+ var settingRaw settingRawif err := rows.Scan(&settingRaw.CreatorID,&settingRaw.CreatedTs,@@ -206,8 +291,8 @@ func findSettingList(ctx context.Context, tx *sql.Tx, find *api.SettingFind) ([]return settingRawList, nil}-// patchSetting updates a setting by name. Returns the new state of the setting after update.-func patchSetting(ctx context.Context, tx *sql.Tx, patch *api.SettingPatch) (*api.SettingRaw, error) {+// patchSettingImpl updates a setting by name. Returns the new state of the setting after update.+func patchSettingImpl(ctx context.Context, tx *sql.Tx, patch *api.SettingPatch) (*settingRaw, error) {// Build UPDATE clause.set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}set, args = append(set, "value = $2"), append(args, patch.Value)@@ -229,7 +314,7 @@ func patchSetting(ctx context.Context, tx *sql.Tx, patch *api.SettingPatch) (*apdefer row.Close()if row.Next() {- var settingRaw api.SettingRaw+ var settingRaw settingRawif err := row.Scan(&settingRaw.CreatorID,&settingRaw.CreatedTs,