Skip to content

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

Implement adding backup in backup service backend.

spinningbote2f55cce9550
diff --git a/api/backup.go b/api/backup.go
index 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.csv
index 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}, PATCH
p, DBA, /database/{id}/table, GET
p, DBA, /database/{id}/table/{tableName}, GET
p, DBA, /database/{id}/backup, GET
+p, DBA, /database/{id}/backup, POST
p, DBA, /issue, POST
p, DBA, /issue, GET
p, DBA, /issue/{id}, GET
diff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csv
index 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}, PATCH
p, DEVELOPER, /database/{id}/table, GET
p, DEVELOPER, /database/{id}/table/{tableName}, GET
p, DEVELOPER, /database/{id}/backup, GET
+p, DEVELOPER, /database/{id}/backup, POST
p, DEVELOPER, /issue, POST
p, DEVELOPER, /issue, GET
p, DEVELOPER, /issue/{id}, GET
diff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csv
index 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}, PATCH
p, OWNER, /database/{id}/table, GET
p, OWNER, /database/{id}/table/{tableName}, GET
p, OWNER, /database/{id}/backup, GET
+p, OWNER, /database/{id}/backup, POST
p, OWNER, /issue, POST
p, OWNER, /issue, GET
p, OWNER, /issue/{id}, GET
diff --git a/server/database.go b/server/database.go
index 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.go
index feb9e26969..a307939cab 100644
--- a/store/backup.go
+++ b/store/backup.go
@@ -2,8 +2,10 @@ package store
import (
"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.Logger
db *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.BackupFind
return 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.Ba
return 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.go
index 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":