Skip to content

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

Implement patch /environment/reorder

天舟9cfcac211566
diff --git a/backend/api/environment.go b/backend/api/environment.go
index 07f69fcaed..04aa45c888 100644
--- a/backend/api/environment.go
+++ b/backend/api/environment.go
@@ -3,7 +3,7 @@ package api
import "context"
type Environment struct {
- ID string `jsonapi:"primary,principal"`
+ ID int `jsonapi:"primary,environment"`
// Standard fields
RowStatus RowStatus `jsonapi:"attr,rowStatus"`
@@ -15,7 +15,7 @@ type Environment struct {
// Domain specific fields
Name string `jsonapi:"attr,name"`
- Order uint `jsonapi:"attr,order"`
+ Order int `jsonapi:"attr,order"`
}
type EnvironmentCreate struct {
@@ -35,14 +35,15 @@ type EnvironmentFind struct {
type EnvironmentPatch struct {
// Standard fields
- ID int
+ ID int `jsonapi:"primary,environmentpatch"`
RowStatus *string `jsonapi:"attr,rowStatus"`
WorkspaceId int
// Value is assigned from the jwt subject field passed by the client.
UpdaterId int
// Domain specific fields
- Name *string `jsonapi:"attr,name"`
+ Name *string `jsonapi:"attr,name"`
+ Order *int `jsonapi:"attr,order"`
}
type EnvironmentDelete struct {
diff --git a/backend/server/environment.go b/backend/server/environment.go
index 44eb2325bf..a2d5c781a2 100644
--- a/backend/server/environment.go
+++ b/backend/server/environment.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"net/http"
+ "reflect"
"strconv"
"github.com/bytebase/bytebase"
@@ -56,7 +57,7 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
g.PATCH("/environment/:id", 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)
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Environment ID is not a number: %s", c.Param("id"))).SetInternal(err)
}
environmentPatch := &api.EnvironmentPatch{
@@ -105,4 +106,39 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
c.Response().WriteHeader(http.StatusOK)
return nil
})
+
+ g.PATCH("/environment/reorder", func(c echo.Context) error {
+ patchList, err := jsonapi.UnmarshalManyPayload(c.Request().Body, reflect.TypeOf(new(api.EnvironmentPatch)))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted environment batch update request").SetInternal(err)
+ }
+
+ for _, item := range patchList {
+ environmentPatch, _ := item.(*api.EnvironmentPatch)
+ environmentPatch.WorkspaceId = api.DEFAULT_WORKPSACE_ID
+ environmentPatch.UpdaterId = c.Get(GetPrincipalIdContextKey()).(int)
+ _, err = s.EnvironmentService.PatchEnvironmentByID(context.Background(), environmentPatch)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Environment ID not found: %d", environmentPatch.ID))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch environment ID: %v", environmentPatch.ID)).SetInternal(err)
+ }
+ }
+
+ wsId := api.DEFAULT_WORKPSACE_ID
+ environmentFind := &api.EnvironmentFind{
+ WorkspaceId: &wsId,
+ }
+ list, err := s.EnvironmentService.FindEnvironmentList(context.Background(), environmentFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch environment list for batch update").SetInternal(err)
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, list); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal environment batch update response").SetInternal(err)
+ }
+ return nil
+ })
}
diff --git a/backend/store/environment.go b/backend/store/environment.go
index 044296c84a..1d40fb3437 100644
--- a/backend/store/environment.go
+++ b/backend/store/environment.go
@@ -32,7 +32,7 @@ func (s *EnvironmentService) CreateEnvironment(ctx context.Context, create *api.
}
defer tx.Rollback()
- environment, err := createEnvironment(ctx, tx, create)
+ environment, err := s.createEnvironment(ctx, tx, create)
if err != nil {
return nil, err
}
@@ -52,7 +52,7 @@ func (s *EnvironmentService) FindEnvironmentList(ctx context.Context, find *api.
}
defer tx.Rollback()
- list, err := findEnvironmentList(ctx, tx, find)
+ list, err := s.findEnvironmentList(ctx, tx, find)
if err != nil {
return []*api.Environment{}, err
}
@@ -69,7 +69,7 @@ func (s *EnvironmentService) PatchEnvironmentByID(ctx context.Context, patch *ap
}
defer tx.Rollback()
- environment, err := patchEnvironment(ctx, tx, patch)
+ environment, err := s.patchEnvironment(ctx, tx, patch)
if err != nil {
return nil, FormatError(err)
}
@@ -90,7 +90,7 @@ func (s *EnvironmentService) DeleteEnvironmentByID(ctx context.Context, delete *
}
defer tx.Rollback()
- err = deleteEnvironment(ctx, tx, delete)
+ err = s.deleteEnvironment(ctx, tx, delete)
if err != nil {
return FormatError(err)
}
@@ -103,7 +103,7 @@ func (s *EnvironmentService) DeleteEnvironmentByID(ctx context.Context, delete *
}
// createEnvironment creates a new environment.
-func createEnvironment(ctx context.Context, tx *Tx, create *api.EnvironmentCreate) (*api.Environment, error) {
+func (s *EnvironmentService) createEnvironment(ctx context.Context, tx *Tx, create *api.EnvironmentCreate) (*api.Environment, error) {
// The order is the MAX(order) + 1
row1, err1 := tx.QueryContext(ctx, `
SELECT `+"`order`"+`
@@ -171,7 +171,7 @@ func createEnvironment(ctx context.Context, tx *Tx, create *api.EnvironmentCreat
return &environment, nil
}
-func findEnvironmentList(ctx context.Context, tx *Tx, find *api.EnvironmentFind) (_ []*api.Environment, err error) {
+func (s *EnvironmentService) findEnvironmentList(ctx context.Context, tx *Tx, find *api.EnvironmentFind) (_ []*api.Environment, err error) {
// Build WHERE clause.
where, args := []string{"1 = 1"}, []interface{}{}
if v := find.WorkspaceId; v != nil {
@@ -226,7 +226,7 @@ func findEnvironmentList(ctx context.Context, tx *Tx, find *api.EnvironmentFind)
}
// patchEnvironment updates a environment by ID. Returns the new state of the environment after update.
-func patchEnvironment(ctx context.Context, tx *Tx, patch *api.EnvironmentPatch) (*api.Environment, error) {
+func (s *EnvironmentService) patchEnvironment(ctx context.Context, tx *Tx, patch *api.EnvironmentPatch) (*api.Environment, error) {
// Build UPDATE clause.
set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterId}
if v := patch.RowStatus; v != nil {
@@ -235,6 +235,9 @@ func patchEnvironment(ctx context.Context, tx *Tx, patch *api.EnvironmentPatch)
if v := patch.Name; v != nil {
set, args = append(set, "name = ?"), append(args, *v)
}
+ if v := patch.Order; v != nil {
+ set, args = append(set, "`order` = ?"), append(args, *v)
+ }
args = append(args, patch.ID)
@@ -267,7 +270,6 @@ func patchEnvironment(ctx context.Context, tx *Tx, patch *api.EnvironmentPatch)
); err != nil {
return nil, FormatError(err)
}
-
return &environment, nil
}
@@ -275,7 +277,7 @@ func patchEnvironment(ctx context.Context, tx *Tx, patch *api.EnvironmentPatch)
}
// deleteEnvironment permanently deletes a environment by ID.
-func deleteEnvironment(ctx context.Context, tx *Tx, delete *api.EnvironmentDelete) error {
+func (s *EnvironmentService) deleteEnvironment(ctx context.Context, tx *Tx, delete *api.EnvironmentDelete) error {
// Remove row from database.
result, err := tx.ExecContext(ctx, `DELETE FROM environment WHERE id = ?`, delete.ID)
if err != nil {
diff --git a/backend/store/migration/0001_init_schema.down.sql b/backend/store/migration/0001_init_schema.down.sql
index b03cbafdf5..a8271b9c0c 100644
--- a/backend/store/migration/0001_init_schema.down.sql
+++ b/backend/store/migration/0001_init_schema.down.sql
@@ -1,4 +1,4 @@
-DROP TABLE IF EXISTS environment;
+DROP TABLE environment;
DROP TABLE member;
diff --git a/backend/store/migration/0001_init_schema.up.sql b/backend/store/migration/0001_init_schema.up.sql
index ddecf9468e..8a1b5eb5c9 100644
--- a/backend/store/migration/0001_init_schema.up.sql
+++ b/backend/store/migration/0001_init_schema.up.sql
@@ -149,8 +149,7 @@ CREATE TABLE environment (
updater_id INTEGER NOT NULL REFERENCES principal (id),
updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
name TEXT NOT NULL UNIQUE,
- `order` INTEGER NOT NULL,
- UNIQUE(workspace_id, `order`)
+ `order` INTEGER NOT NULL
);
INSERT INTO
diff --git a/backend/store/seed/0030_environment.sql b/backend/store/seed/0030_environment.sql
index 96fd386fe6..beb23c2fe7 100644
--- a/backend/store/seed/0030_environment.sql
+++ b/backend/store/seed/0030_environment.sql
@@ -8,7 +8,7 @@ INSERT INTO
`order`
)
VALUES
- ('NORMAL', 1, 1001, 1001, 'Sandbox A', 1);
+ ('NORMAL', 1, 1001, 1001, 'Sandbox A', 0);
INSERT INTO
environment (
@@ -20,7 +20,7 @@ INSERT INTO
`order`
)
VALUES
- ('NORMAL', 1, 1001, 1001, 'Integration', 2);
+ ('NORMAL', 1, 1001, 1001, 'Integration', 1);
INSERT INTO
environment (
@@ -32,7 +32,7 @@ INSERT INTO
`order`
)
VALUES
- ('NORMAL', 1, 1001, 1001, 'Staging', 3);
+ ('NORMAL', 1, 1001, 1001, 'Staging', 2);
INSERT INTO
environment (
@@ -44,7 +44,7 @@ INSERT INTO
`order`
)
VALUES
- ('NORMAL', 1, 1001, 1001, 'Prod', 4);
+ ('NORMAL', 1, 1001, 1001, 'Prod', 3);
INSERT INTO
environment (
@@ -56,4 +56,4 @@ INSERT INTO
`order`
)
VALUES
- ('ARCHIVED', 1, 1001, 1001, 'Archived Env 1', 5);
\ No newline at end of file
+ ('ARCHIVED', 1, 1001, 1001, 'Archived Env 1', 4);
\ No newline at end of file
diff --git a/frontend/src/miragejs/models/index.js b/frontend/src/miragejs/models/index.js
index b99ebb536b..8df6b4f39f 100644
--- a/frontend/src/miragejs/models/index.js
+++ b/frontend/src/miragejs/models/index.js
@@ -161,8 +161,6 @@ export default {
dataSourceMemberCreate: Model,
// Misc
- batchUpdate: Model,
-
signupInfo: Model,
loginInfo: Model,
diff --git a/frontend/src/miragejs/routes/environment.js b/frontend/src/miragejs/routes/environment.js
index 33f913bbbc..0a527a356c 100644
--- a/frontend/src/miragejs/routes/environment.js
+++ b/frontend/src/miragejs/routes/environment.js
@@ -72,32 +72,36 @@ export default function configureEnvironment(route) {
return createdEnvironment;
});
- route.patch("/environment/batch", function (schema, request) {
- const attrs = this.normalizedRequestAttrs("batch-update");
- for (let i = 0; i < attrs.idList.length; i++) {
- const env = schema.environments.find(attrs.idList[i]);
+ route.patch("/environment/reorder", function (schema, request) {
+ const list = JSON.parse(request.requestBody).data;
+ let updaterId;
+ let updated = false;
+ for (let i = 0; i < list.length; i++) {
+ const env = schema.environments.find(list[i].id);
if (env) {
+ updaterId = list[i].attributes.updaterId;
const oneUpdate = {
- updaterId: attrs.updaterId,
+ updaterId: list[i].attributes.updaterId,
+ order: list[i].attributes.order,
};
- for (let j = 0; j < attrs.fieldMaskList.length; j++) {
- oneUpdate[attrs.fieldMaskList[j]] = attrs.rowValueList[i][j];
- }
env.update(oneUpdate);
+ updated = true;
}
}
- const ts = Date.now();
- const messageTemplate = {
- containerId: WORKSPACE_ID,
- createdTs: ts,
- updatedTs: ts,
- type: "bb.message.environment.reorder",
- status: "DELIVERED",
- creatorId: attrs.updaterId,
- workspaceId: WORKSPACE_ID,
- };
- postMessageToOwnerAndDBA(schema, attrs.updaterId, messageTemplate);
+ if (updated) {
+ const ts = Date.now();
+ const messageTemplate = {
+ containerId: WORKSPACE_ID,
+ createdTs: ts,
+ updatedTs: ts,
+ type: "bb.message.environment.reorder",
+ status: "DELIVERED",
+ creatorId: updaterId,
+ workspaceId: WORKSPACE_ID,
+ };
+ postMessageToOwnerAndDBA(schema, updaterId, messageTemplate);
+ }
return schema.environments.where((environment) => {
return environment.workspaceId == WORKSPACE_ID;
diff --git a/frontend/src/store/modules/environment.ts b/frontend/src/store/modules/environment.ts
index bb312a9b08..d0d08d0982 100644
--- a/frontend/src/store/modules/environment.ts
+++ b/frontend/src/store/modules/environment.ts
@@ -8,7 +8,6 @@ import {
unknown,
RowStatus,
EnvironmentPatch,
- BatchUpdate,
PrincipalId,
empty,
EMPTY_ID,
@@ -111,18 +110,20 @@ const actions = {
orderedEnvironmentList: Environment[];
}
) {
- const batchUpdate: BatchUpdate = {
- updaterId,
- idList: orderedEnvironmentList.map((item) => item.id),
- fieldMaskList: ["order"],
- rowValueList: orderedEnvironmentList.map((_, index) => [index]),
- };
- const environmentList = (
- await axios.patch(`/api/environment/batch`, {
- data: {
- attributes: batchUpdate,
- type: "batchupdate",
+ const list: any[] = [];
+ orderedEnvironmentList.forEach((item, index) => {
+ list.push({
+ id: item.id,
+ type: "environmentpatch",
+ attributes: {
+ updaterId,
+ order: index,
},
+ });
+ });
+ const environmentList = (
+ await axios.patch(`/api/environment/reorder`, {
+ data: list,
})
).data.data.map((env: ResourceObject) => {
return convert(env, rootGetters);
diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.ts
index d240faadac..d2128838b8 100644
--- a/frontend/src/types/common.ts
+++ b/frontend/src/types/common.ts
@@ -21,13 +21,6 @@ export const DEFAULT_PROJECT_ID = "1";
export const ALL_DATABASE_NAME = "*";
-export type BatchUpdate = {
- updaterId: PrincipalId;
- idList: string[];
- fieldMaskList: string[];
- rowValueList: any[][];
-};
-
// RowStatus
export type RowStatus = "NORMAL" | "ARCHIVED" | "PENDING_DELETE";
diff --git a/frontend/src/types/environment.ts b/frontend/src/types/environment.ts
index 026a2cc4e7..bedf9e5528 100644
--- a/frontend/src/types/environment.ts
+++ b/frontend/src/types/environment.ts
@@ -33,4 +33,5 @@ export type EnvironmentPatch = {
// Domain specific fields
name?: string;
+ order?: number;
};