Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Implement adding backup in backup service backend.
spinningbote2f55cce9550
diff --git a/api/backup.go b/api/backup.goindex 88f811ada3..722ca7155a 100644--- a/api/backup.go+++ b/api/backup.go@@ -29,6 +29,23 @@ type Backup struct {Comment string `jsonapi:"attr,comment"`}+type BackupCreate struct {+ // Standard fields+ // Value is assigned from the jwt subject field passed by the client.+ CreatorId int++ // Related fields+ DatabaseId int `jsonapi:"attr,databaseId"`++ // Domain specific fields+ Name string `jsonapi:"attr,name"`+ Status string `jsonapi:"attr,status"`+ Type string `jsonapi:"attr,type"`+ StorageBackend string `jsonapi:"attr,storageBackend"`+ Path string `jsonapi:"attr,path"`+ Comment string `jsonapi:"attr,comment"`+}+type BackupFind struct {ID *int@@ -47,6 +64,19 @@ func (find *BackupFind) String() string {return string(str)}+type BackupPatch struct {+ ID int++ // Standard fields+ // Value is assigned from the jwt subject field passed by the client.+ UpdaterId int++ // Domain specific fields+ Status string+}+type BackupService interface {+ CreateBackup(ctx context.Context, create *BackupCreate) (*Backup, error)FindBackupList(ctx context.Context, find *BackupFind) ([]*Backup, error)+ PatchBackup(ctx context.Context, patch *BackupPatch) (*Backup, error)}diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csvindex d302f9abaf..608565dc43 100644--- a/server/acl_casbin_policy_dba.csv+++ b/server/acl_casbin_policy_dba.csv@@ -30,6 +30,7 @@ p, DBA, /database/{id}, PATCHp, DBA, /database/{id}/table, GETp, DBA, /database/{id}/table/{tableName}, GETp, DBA, /database/{id}/backup, GET+p, DBA, /database/{id}/backup, POSTp, DBA, /issue, POSTp, DBA, /issue, GETp, DBA, /issue/{id}, GETdiff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csvindex aed2f1a679..0fb266a6a9 100644--- a/server/acl_casbin_policy_developer.csv+++ b/server/acl_casbin_policy_developer.csv@@ -26,6 +26,7 @@ p, DEVELOPER, /database/{id}, PATCHp, DEVELOPER, /database/{id}/table, GETp, DEVELOPER, /database/{id}/table/{tableName}, GETp, DEVELOPER, /database/{id}/backup, GET+p, DEVELOPER, /database/{id}/backup, POSTp, DEVELOPER, /issue, POSTp, DEVELOPER, /issue, GETp, DEVELOPER, /issue/{id}, GETdiff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csvindex 574be3d6f7..05f3db5752 100644--- a/server/acl_casbin_policy_owner.csv+++ b/server/acl_casbin_policy_owner.csv@@ -34,6 +34,7 @@ p, OWNER, /database/{id}, PATCHp, OWNER, /database/{id}/table, GETp, OWNER, /database/{id}/table/{tableName}, GETp, OWNER, /database/{id}/backup, GET+p, OWNER, /database/{id}/backup, POSTp, OWNER, /issue, POSTp, OWNER, /issue, GETp, OWNER, /issue/{id}, GETdiff --git a/server/database.go b/server/database.goindex 64c05b7d9a..0cfe03acdc 100644--- a/server/database.go+++ b/server/database.go@@ -255,6 +255,45 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {return nil})+ g.POST("/database/:id/backup", func(c echo.Context) error {+ id, err := strconv.Atoi(c.Param("id"))+ if err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)+ }++ backupCreate := &api.BackupCreate{}+ if err := jsonapi.UnmarshalPayload(c.Request().Body, backupCreate); err != nil {+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create database request").SetInternal(err)+ }+ backupCreate.CreatorId = c.Get(GetPrincipalIdContextKey()).(int)++ databaseFind := &api.DatabaseFind{+ ID: &id,+ }+ database, err := s.ComposeDatabaseByFind(context.Background(), databaseFind)+ if err != nil {+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database ID not found: %d", id))+ }+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch database ID: %v", id)).SetInternal(err)+ }++ backup, err := s.BackupService.CreateBackup(context.Background(), backupCreate)+ if err != nil {+ if bytebase.ErrorCode(err) == bytebase.ECONFLICT {+ return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Backup name already exists: %s", backupCreate.Name))+ }+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create backup").SetInternal(err)+ }+ backup.Database = database++ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)+ if err := jsonapi.MarshalPayload(c.Response().Writer, backup); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal create backup response").SetInternal(err)+ }+ return nil+ })+g.GET("/database/:id/backup", func(c echo.Context) error {id, err := strconv.Atoi(c.Param("id"))if err != nil {diff --git a/store/backup.go b/store/backup.goindex feb9e26969..a307939cab 100644--- a/store/backup.go+++ b/store/backup.go@@ -2,8 +2,10 @@ package storeimport ("context"+ "fmt""strings"+ "github.com/bytebase/bytebase""github.com/bytebase/bytebase/api""go.uber.org/zap")@@ -12,7 +14,7 @@ var (_ api.BackupService = (*BackupService)(nil))-// BackupService represents a service for managing table.+// BackupService represents a service for managing backup.type BackupService struct {l *zap.Loggerdb *DB@@ -23,6 +25,26 @@ func NewBackupService(logger *zap.Logger, db *DB) *BackupService {return &BackupService{l: logger, db: db}}+// CreateBackup creates a new backup.+func (s *BackupService) CreateBackup(ctx context.Context, create *api.BackupCreate) (*api.Backup, error) {+ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, FormatError(err)+ }+ defer tx.Rollback()++ backup, err := s.createBackup(ctx, tx, create)+ if err != nil {+ return nil, err+ }++ if err := tx.Commit(); err != nil {+ return nil, FormatError(err)+ }++ return backup, nil+}+// FindBackupList retrieves a list of backups based on find.func (s *BackupService) FindBackupList(ctx context.Context, find *api.BackupFind) ([]*api.Backup, error) {tx, err := s.db.BeginTx(ctx, nil)@@ -39,6 +61,83 @@ func (s *BackupService) FindBackupList(ctx context.Context, find *api.BackupFindreturn list, nil}+// PatchBackup updates an existing backup by ID.+// Returns ENOTFOUND if backup does not exist.+func (s *BackupService) PatchBackup(ctx context.Context, patch *api.BackupPatch) (*api.Backup, error) {+ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, FormatError(err)+ }+ defer tx.Rollback()++ backup, err := s.patchBackup(ctx, tx, patch)+ if err != nil {+ return nil, FormatError(err)+ }++ if err := tx.Commit(); err != nil {+ return nil, FormatError(err)+ }++ return backup, nil+}++// createBackup creates a new backup.+func (s *BackupService) createBackup(ctx context.Context, tx *Tx, create *api.BackupCreate) (*api.Backup, error) {+ // Insert row into backup.+ row, err := tx.QueryContext(ctx, `+ INSERT INTO backup (+ creator_id,+ updater_id,+ database_id,+ name,+ `+"`status`,"+`+ `+"`type`,"+`+ storage_backend,+ path,+ comment+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, name, `+"`status`,"+` `+"`type`, storage_backend, path, comment"+`+ `,+ create.CreatorId,+ create.CreatorId,+ create.DatabaseId,+ create.Name,+ create.Status,+ create.Type,+ create.StorageBackend,+ create.Path,+ create.Comment,+ )++ if err != nil {+ return nil, FormatError(err)+ }+ defer row.Close()++ row.Next()+ var backup api.Backup+ if err := row.Scan(+ &backup.ID,+ &backup.CreatorId,+ &backup.CreatedTs,+ &backup.UpdaterId,+ &backup.UpdatedTs,+ &backup.DatabaseId,+ &backup.Name,+ &backup.Status,+ &backup.Type,+ &backup.StorageBackend,+ &backup.Path,+ &backup.Comment,+ ); err != nil {+ return nil, FormatError(err)+ }++ return &backup, nil+}+func (s *BackupService) findBackupList(ctx context.Context, tx *Tx, find *api.BackupFind) (_ []*api.Backup, err error) {// Build WHERE clause.where, args := []string{"1 = 1"}, []interface{}{}@@ -104,3 +203,49 @@ func (s *BackupService) findBackupList(ctx context.Context, tx *Tx, find *api.Bareturn list, nil}++// patchBackup updates a backup by ID. Returns the new state of the backup after update.+func (s *BackupService) patchBackup(ctx context.Context, tx *Tx, patch *api.BackupPatch) (*api.Backup, error) {+ // Build UPDATE clause.+ set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterId}+ set, args = append(set, "status = ?"), append(args, patch.Status)++ args = append(args, patch.ID)++ // Execute update query with RETURNING.+ row, err := tx.QueryContext(ctx, `+ UPDATE backup+ SET `+strings.Join(set, ", ")+`+ WHERE id = ?+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, name, `+"`status`,"+` `+"`type`, storage_backend, path, comment"+`+ `,+ args...,+ )+ if err != nil {+ return nil, FormatError(err)+ }+ defer row.Close()++ if row.Next() {+ var backup api.Backup+ if err := row.Scan(+ &backup.ID,+ &backup.CreatorId,+ &backup.CreatedTs,+ &backup.UpdaterId,+ &backup.UpdatedTs,+ &backup.DatabaseId,+ &backup.Name,+ &backup.Status,+ &backup.Type,+ &backup.StorageBackend,+ &backup.Path,+ &backup.Comment,+ ); err != nil {+ return nil, FormatError(err)+ }+ return &backup, nil+ }++ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("backup ID not found: %d", patch.ID)}+}diff --git a/store/sqlite.go b/store/sqlite.goindex 5a9a4c237e..1c0f6c6671 100644--- a/store/sqlite.go+++ b/store/sqlite.go@@ -343,6 +343,8 @@ func FormatError(err error) error {return bytebase.Errorf(bytebase.ECONFLICT, "database name already exists")case "UNIQUE constraint failed: data_source.instance_id, data_source.name":return bytebase.Errorf(bytebase.ECONFLICT, "data source name already exists")+ case "UNIQUE constraint failed: backup.database_id, backup.name":+ return bytebase.Errorf(bytebase.ECONFLICT, "backup name already exists")case "UNIQUE constraint failed: bookmark.creator_id, bookmark.link":return bytebase.Errorf(bytebase.ECONFLICT, "bookmark already exists")case "UNIQUE constraint failed: repo.project_id":