Skip to content

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

Add backup service backend and UI connector.

spinningbot0f00330c8db5
diff --git a/api/backup.go b/api/backup.go
new file mode 100644
index 0000000000..88f811ada3
--- /dev/null
+++ b/api/backup.go
@@ -0,0 +1,52 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+)
+
+type Backup struct {
+ ID int `jsonapi:"primary,table"`
+
+ // Standard fields
+ CreatorId int
+ Creator *Principal `jsonapi:"attr,creator"`
+ CreatedTs int64 `jsonapi:"attr,createdTs"`
+ UpdaterId int
+ Updater *Principal `jsonapi:"attr,updater"`
+ UpdatedTs int64 `jsonapi:"attr,updatedTs"`
+
+ // Related fields
+ DatabaseId int
+ Database *Database `jsonapi:"relation,database"`
+
+ // 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
+
+ // Related fields
+ DatabaseId *int
+
+ // Domain specific fields
+ Name *string
+}
+
+func (find *BackupFind) String() string {
+ str, err := json.Marshal(*find)
+ if err != nil {
+ return err.Error()
+ }
+ return string(str)
+}
+
+type BackupService interface {
+ FindBackupList(ctx context.Context, find *BackupFind) ([]*Backup, error)
+}
diff --git a/bin/server/cmd/root.go b/bin/server/cmd/root.go
index f997303736..993289e354 100644
--- a/bin/server/cmd/root.go
+++ b/bin/server/cmd/root.go
@@ -278,6 +278,7 @@ func (m *main) Run() error {
server.TableService = store.NewTableService(m.l, db)
server.ColumnService = store.NewColumnService(m.l, db)
server.IndexService = store.NewIndexService(m.l, db)
+ server.BackupService = store.NewBackupService(m.l, db)
server.IssueService = store.NewIssueService(m.l, db, server.CacheService)
server.IssueSubscriberService = store.NewIssueSubscriberService(m.l, db)
server.PipelineService = store.NewPipelineService(m.l, db, server.CacheService)
diff --git a/frontend/src/components/BackupTable.vue b/frontend/src/components/BackupTable.vue
index 7a5f56dddd..d2869f0845 100644
--- a/frontend/src/components/BackupTable.vue
+++ b/frontend/src/components/BackupTable.vue
@@ -14,7 +14,7 @@
{{ backup.path }}
</BBTableCell>
<BBTableCell class="w-4">
- {{ backup.time }}
+ {{ humanizeTs(backup.createdTs) }}
</BBTableCell>
<BBTableCell class="w-4">
{{ backup.creator }}
diff --git a/frontend/src/components/DatabaseBackupPanel.vue b/frontend/src/components/DatabaseBackupPanel.vue
index 918daf94fe..a11c5eb5df 100644
--- a/frontend/src/components/DatabaseBackupPanel.vue
+++ b/frontend/src/components/DatabaseBackupPanel.vue
@@ -48,11 +48,11 @@
</template>
<script lang="ts">
-import { computed, reactive, PropType, ComputedRef } from "vue";
+import { computed, watchEffect, reactive, PropType, ComputedRef } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { v1 as uuidv1 } from "uuid";
-import { Backup } from "../types";
+import { Backup, Database } from "../types";
import BackupTable from "../components/BackupTable.vue";
interface LocalState {
@@ -63,6 +63,10 @@ interface LocalState {
export default {
name: "DatabaseBackupPanel",
props: {
+ database: {
+ required: true,
+ type: Object as PropType<Database>,
+ },
},
components: {
BackupTable,
@@ -76,10 +80,15 @@ export default {
backupPath: "backup.sql",
});
- const backupList = <Backup[]>[
- {id: 1, database: {}, creator: {}, createdTs: 123, name: "777a8cc0-edd1-11eb-af34-7f52646e3685", path: "1.sql",},
- {id: 2, database: {}, creator: {}, createdTs: 123, name: "777a8cc0-edd1-11eb-af34-7f52646e3685", path: "/home/hello/world/1.sql",},
- ];
+ const prepareBackupList = () => {
+ store.dispatch("backup/fetchBackupListByDatabaseId", props.database.id);
+ };
+
+ watchEffect(prepareBackupList);
+
+ const backupList = computed(() => {
+ return store.getters["backup/backupListByDatabaseId"](props.database.id);
+ });
const updateInstance = (field: string, value: string) => {
(state as any)[field] = value;
diff --git a/frontend/src/store/index.ts b/frontend/src/store/index.ts
index 04959b7b5f..8c7a478c09 100644
--- a/frontend/src/store/index.ts
+++ b/frontend/src/store/index.ts
@@ -28,6 +28,7 @@ import sql from "./modules/sql";
import stage from "./modules/stage";
import table from "./modules/table";
import task from "./modules/task";
+import backup from "./modules/backup";
// Following states are persisted in local storage
import uistate from "./modules/uistate";
import vcs from "./modules/vcs";
@@ -61,6 +62,7 @@ export const store: Store<any> = createStore({
sql,
stage,
table,
+ backup,
task,
uistate,
vcs,
diff --git a/frontend/src/store/modules/backup.ts b/frontend/src/store/modules/backup.ts
new file mode 100644
index 0000000000..f7e0db862b
--- /dev/null
+++ b/frontend/src/store/modules/backup.ts
@@ -0,0 +1,82 @@
+import axios from "axios";
+import {
+ Database,
+ DatabaseId,
+ ResourceIdentifier,
+ ResourceObject,
+ Backup,
+ BackupState,
+ unknown,
+} from "../../types";
+
+function convert(
+ backup: ResourceObject,
+ includedList: ResourceObject[],
+ rootGetters: any
+): Backup {
+ const databaseId = (backup.relationships!.database.data as ResourceIdentifier)
+ .id;
+
+ let database: Database = unknown("DATABASE") as Database;
+ for (const item of includedList || []) {
+ if (item.type == "database" && item.id == databaseId) {
+ database = rootGetters["database/convert"](item, includedList);
+ break;
+ }
+ }
+ return {
+ ...(backup.attributes as Omit<Backup, "id" | "database">),
+ id: parseInt(backup.id),
+ database,
+ };
+}
+
+const state: () => BackupState = () => ({
+ backupListByDatabaseId: new Map(),
+});
+
+const getters = {
+ backupListByDatabaseId:
+ (state: BackupState) =>
+ (databaseId: DatabaseId): Backup[] => {
+ return state.backupListByDatabaseId.get(databaseId) || [];
+ },
+};
+
+const actions = {
+ async fetchBackupListByDatabaseId(
+ { commit, rootGetters }: any,
+ databaseId: DatabaseId
+ ) {
+ const data = (await axios.get(`/api/database/${databaseId}/backup`)).data;
+ const backupList = data.data.map((backup: ResourceObject) => {
+ return convert(backup, data.included, rootGetters);
+ });
+
+ commit("setTableListByDatabaseId", { databaseId, backupList });
+ return backupList;
+ },
+};
+
+const mutations = {
+ setTableListByDatabaseId(
+ state: BackupState,
+ {
+ databaseId,
+ backupList,
+ }: {
+ databaseId: DatabaseId;
+ backupList: Backup[];
+ }
+ ) {
+ state.backupListByDatabaseId.set(databaseId, backupList);
+ },
+};
+
+export default {
+ namespaced: true,
+ state,
+ getters,
+ actions,
+ mutations,
+};
diff --git a/frontend/src/types/backup.ts b/frontend/src/types/backup.ts
index 5984f43a47..005c710434 100644
--- a/frontend/src/types/backup.ts
+++ b/frontend/src/types/backup.ts
@@ -12,7 +12,13 @@ export type Backup = {
// Standard fields
creator: Principal;
createdTs: number;
+ updater: Principal;
+ updatedTs: number;
name: string;
+ status: string;
+ type: string;
+ storageBackend: string;
path: string;
+ comment: string;
};
diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.ts
index cca50156c1..51e9512dbe 100644
--- a/frontend/src/types/store.ts
+++ b/frontend/src/types/store.ts
@@ -27,6 +27,7 @@ import { Project } from "./project";
import { Repository } from "./repository";
import { Setting, SettingName } from "./setting";
import { Table } from "./table";
+import { Backup } from "./backup";
import { VCS } from "./vcs";
export interface ActuatorState {
@@ -113,6 +114,10 @@ export interface TableState {
tableListByDatabaseId: Map<DatabaseId, Table[]>;
}
+export interface BackupState {
+ backupListByDatabaseId: Map<DatabaseId, Backup[]>;
+}
+
export interface VCSState {
vcsById: Map<VCSId, VCS>;
}
diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csv
index a15a348b55..d302f9abaf 100644
--- a/server/acl_casbin_policy_dba.csv
+++ b/server/acl_casbin_policy_dba.csv
@@ -29,6 +29,7 @@ p, DBA, /database/{id}, GET
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, /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 3166d07db2..aed2f1a679 100644
--- a/server/acl_casbin_policy_developer.csv
+++ b/server/acl_casbin_policy_developer.csv
@@ -25,6 +25,7 @@ p, DEVELOPER, /database/{id}, GET
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, /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 7425fb4308..574be3d6f7 100644
--- a/server/acl_casbin_policy_owner.csv
+++ b/server/acl_casbin_policy_owner.csv
@@ -33,6 +33,7 @@ p, OWNER, /database/{id}, GET
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, /issue, POST
p, OWNER, /issue, GET
p, OWNER, /issue/{id}, GET
diff --git a/server/database.go b/server/database.go
index 7dab88cde7..64c05b7d9a 100644
--- a/server/database.go
+++ b/server/database.go
@@ -254,6 +254,42 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
}
return nil
})
+
+ g.GET("/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)
+ }
+
+ 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)
+ }
+
+ backupFind := &api.BackupFind{
+ DatabaseId: &id,
+ }
+ backupList, err := s.BackupService.FindBackupList(context.Background(), backupFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to backup list for database id: %d", id)).SetInternal(err)
+ }
+
+ for _, backup := range backupList {
+ backup.Database = database
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, backupList); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal fetch table list response: %v", id)).SetInternal(err)
+ }
+ return nil
+ })
}
func (s *Server) ComposeDatabaseByFind(ctx context.Context, find *api.DatabaseFind) (*api.Database, error) {
diff --git a/server/server.go b/server/server.go
index 66f7d942d2..f8d3f7bb75 100644
--- a/server/server.go
+++ b/server/server.go
@@ -36,6 +36,7 @@ type Server struct {
ColumnService api.ColumnService
IndexService api.IndexService
DataSourceService api.DataSourceService
+ BackupService api.BackupService
IssueService api.IssueService
IssueSubscriberService api.IssueSubscriberService
PipelineService api.PipelineService
diff --git a/store/backup.go b/store/backup.go
new file mode 100644
index 0000000000..feb9e26969
--- /dev/null
+++ b/store/backup.go
@@ -0,0 +1,106 @@
+package store
+
+import (
+ "context"
+ "strings"
+
+ "github.com/bytebase/bytebase/api"
+ "go.uber.org/zap"
+)
+
+var (
+ _ api.BackupService = (*BackupService)(nil)
+)
+
+// BackupService represents a service for managing table.
+type BackupService struct {
+ l *zap.Logger
+ db *DB
+}
+
+// NewBackupService returns a new instance of BackupService.
+func NewBackupService(logger *zap.Logger, db *DB) *BackupService {
+ return &BackupService{l: logger, db: db}
+}
+
+// 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)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := s.findBackupList(ctx, tx, find)
+ if err != nil {
+ return []*api.Backup{}, err
+ }
+
+ return list, 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{}{}
+ if v := find.ID; v != nil {
+ where, args = append(where, "id = ?"), append(args, *v)
+ }
+ if v := find.DatabaseId; v != nil {
+ where, args = append(where, "database_id = ?"), append(args, *v)
+ }
+ if v := find.Name; v != nil {
+ where, args = append(where, "name = ?"), append(args, *v)
+ }
+
+ rows, err := tx.QueryContext(ctx, `
+ SELECT
+ id,
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
+ database_id,
+ name,
+ `+"`status`,"+`
+ `+"`type`,"+`
+ storage_backend,
+ path,
+ comment
+ FROM backup
+ WHERE `+strings.Join(where, " AND "),
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer rows.Close()
+
+ // Iterate over result set and deserialize rows into list.
+ list := make([]*api.Backup, 0)
+ for rows.Next() {
+ var backup api.Backup
+ if err := rows.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)
+ }
+
+ list = append(list, &backup)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return list, nil
+}
diff --git a/store/seed/test/10000__reset.sql b/store/seed/test/10000__reset.sql
index 7f91ac7851..4e3957f0ae 100644
--- a/store/seed/test/10000__reset.sql
+++ b/store/seed/test/10000__reset.sql
@@ -47,6 +47,9 @@ DELETE FROM
DELETE FROM
tbl;
+DELETE FROM
+ backup;
+
DELETE FROM
db;
diff --git a/store/seed/test/10074__backup.sql b/store/seed/test/10074__backup.sql
new file mode 100644
index 0000000000..9d87ba43a5
--- /dev/null
+++ b/store/seed/test/10074__backup.sql
@@ -0,0 +1,30 @@
+
+-- Backup for database 7008 blog
+INSERT INTO
+ backup (
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
+ database_id,
+ name,
+ `status`,
+ `type`,
+ storage_backend,
+ path,
+ `comment`
+ )
+VALUES
+ (
+ 101,
+ 1624558090,
+ 101,
+ 1624558090,
+ 7008,
+ 'blog-backup-1',
+ 'DONE',
+ 'MANUAL',
+ 'LOCAL',
+ '/tmp/blog-backup-1.sql',
+ 'The first backup'
+ );
\ No newline at end of file