Skip to content

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

chore: implement CRUD for environment OpenAPI (#3430)

ecmadaocdd49f847a46
diff --git a/api/environment.go b/api/environment.go
index 8ec31a3b5f..ce991b1faa 100644
--- a/api/environment.go
+++ b/api/environment.go
@@ -33,7 +33,8 @@ type EnvironmentCreate struct {
CreatorID int
// Domain specific fields
- Name string `jsonapi:"attr,name"`
+ Name string `jsonapi:"attr,name"`
+ Order *int `jsonapi:"attr,order"`
}
// EnvironmentFind is the API message for finding environments.
diff --git a/api/v1/environment.go b/api/v1/environment.go
new file mode 100644
index 0000000000..c2d8ec18f1
--- /dev/null
+++ b/api/v1/environment.go
@@ -0,0 +1,24 @@
+package v1
+
+// Environment is the API message for an environment.
+type Environment struct {
+ ID int `json:"id"`
+
+ // Domain specific fields
+ Name string `json:"name"`
+ Order int `json:"order"`
+}
+
+// EnvironmentPatch is the API message for patching an environment.
+type EnvironmentPatch struct {
+ // Domain specific fields
+ Name *string `json:"name"`
+ Order *int `json:"order"`
+}
+
+// EnvironmentCreate is the API message for creating an environment.
+type EnvironmentCreate struct {
+ // Domain specific fields
+ Name string `json:"name"`
+ Order *int `json:"order"`
+}
diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csv
index efe3afd812..6390b9abea 100644
--- a/server/acl_casbin_policy_dba.csv
+++ b/server/acl_casbin_policy_dba.csv
@@ -26,7 +26,9 @@ p, DBA, /project/{projectID}/webhook/{webhookID}, DELETE
p, DBA, /project/{projectID}/webhook/{webhookID}/test, GET
p, DBA, /environment, POST
p, DBA, /environment, GET
+p, DBA, /environment/{environmentID}, GET
p, DBA, /environment/{environmentID}, PATCH
+p, DBA, /environment/{environmentID}, DELETE
p, DBA, /environment/{environmentID}/backup-setting, PATCH
p, DBA, /policy, GET
p, DBA, /policy/environment/{environmentID}, GET
diff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csv
index d3b3d9a096..015b455b8c 100644
--- a/server/acl_casbin_policy_developer.csv
+++ b/server/acl_casbin_policy_developer.csv
@@ -25,6 +25,7 @@ p, DEVELOPER, /project/{projectID}/webhook/{webhookID}, PATCH
p, DEVELOPER, /project/{projectID}/webhook/{webhookID}, DELETE
p, DEVELOPER, /project/{projectID}/webhook/{webhookID}/test, GET
p, DEVELOPER, /environment, GET
+p, DEVELOPER, /environment/{environmentID}, GET
p, DEVELOPER, /policy, GET
p, DEVELOPER, /policy/environment/{environmentID}, GET
p, DEVELOPER, /instance, GET
diff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csv
index b5ea2ccaa7..e402b22beb 100644
--- a/server/acl_casbin_policy_owner.csv
+++ b/server/acl_casbin_policy_owner.csv
@@ -29,7 +29,9 @@ p, OWNER, /project/{projectID}/webhook/{webhookID}, DELETE
p, OWNER, /project/{projectID}/webhook/{webhookID}/test, GET
p, OWNER, /environment, POST
p, OWNER, /environment, GET
+p, OWNER, /environment/{environmentID}, GET
p, OWNER, /environment/{environmentID}, PATCH
+p, OWNER, /environment/{environmentID}, DELETE
p, OWNER, /environment/{environmentID}/backup-setting, PATCH
p, OWNER, /policy, GET
p, OWNER, /policy/environment/{environmentID}, GET
diff --git a/server/environment.go b/server/environment.go
index be04514f50..a57237f3a7 100644
--- a/server/environment.go
+++ b/server/environment.go
@@ -1,6 +1,7 @@
package server
import (
+ "context"
"fmt"
"net/http"
"reflect"
@@ -23,17 +24,9 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
}
envCreate.CreatorID = c.Get(getPrincipalIDContextKey()).(int)
-
- if err := api.IsValidEnvironmentName(envCreate.Name); err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Invalid environment name, please visit https://www.bytebase.com/docs/vcs-integration/name-and-organize-schema-files#file-path-template?source=console to get more detail.").SetInternal(err)
- }
-
- env, err := s.store.CreateEnvironment(ctx, envCreate)
+ env, err := s.createEnvironment(ctx, envCreate)
if err != nil {
- if common.ErrorCode(err) == common.Conflict {
- return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Environment name already exists: %s", envCreate.Name))
- }
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create environment").SetInternal(err)
+ return err
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
@@ -77,33 +70,9 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch environment request").SetInternal(err)
}
- if v := envPatch.Name; v != nil {
- if err := api.IsValidEnvironmentName(*v); err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Invalid environment name, please visit https://www.bytebase.com/docs/vcs-integration/name-and-organize-schema-files#file-path-template?source=console to get more detail.").SetInternal(err)
- }
- }
-
- // Ensure the environment has no instance before it's archived.
- if v := envPatch.RowStatus; v != nil && *v == string(api.Archived) {
- normalStatus := api.Normal
- instances, err := s.store.FindInstance(ctx, &api.InstanceFind{
- EnvironmentID: &id,
- RowStatus: &normalStatus,
- })
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, errors.Errorf("failed to find instances in the environment %d", id)).SetInternal(err)
- }
- if len(instances) > 0 {
- return echo.NewHTTPError(http.StatusBadRequest, "You should archive all instances under the environment before archiving the environment.")
- }
- }
-
- env, err := s.store.PatchEnvironment(ctx, envPatch)
+ env, err := s.updateEnvironment(ctx, envPatch)
if err != nil {
- if common.ErrorCode(err) == common.NotFound {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Environment ID not found: %d", id))
- }
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch environment ID: %v", id)).SetInternal(err)
+ return err
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
@@ -173,3 +142,52 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {
return nil
})
}
+
+func (s *Server) createEnvironment(ctx context.Context, create *api.EnvironmentCreate) (*api.Environment, error) {
+ if err := api.IsValidEnvironmentName(create.Name); err != nil {
+ return nil, echo.NewHTTPError(http.StatusBadRequest, "Invalid environment name, please visit https://www.bytebase.com/docs/vcs-integration/name-and-organize-schema-files#file-path-template?source=console to get more detail.").SetInternal(err)
+ }
+
+ env, err := s.store.CreateEnvironment(ctx, create)
+ if err != nil {
+ if common.ErrorCode(err) == common.Conflict {
+ return nil, echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Environment name already exists: %s", create.Name))
+ }
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to create environment").SetInternal(err)
+ }
+
+ return env, nil
+}
+
+func (s *Server) updateEnvironment(ctx context.Context, patch *api.EnvironmentPatch) (*api.Environment, error) {
+ if v := patch.Name; v != nil {
+ if err := api.IsValidEnvironmentName(*v); err != nil {
+ return nil, echo.NewHTTPError(http.StatusBadRequest, "Invalid environment name, please visit https://www.bytebase.com/docs/vcs-integration/name-and-organize-schema-files#file-path-template?source=console to get more detail.").SetInternal(err)
+ }
+ }
+
+ // Ensure the environment has no instance before it's archived.
+ if v := patch.RowStatus; v != nil && *v == string(api.Archived) {
+ normalStatus := api.Normal
+ instances, err := s.store.FindInstance(ctx, &api.InstanceFind{
+ EnvironmentID: &patch.ID,
+ RowStatus: &normalStatus,
+ })
+ if err != nil {
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, errors.Errorf("failed to find instances in the environment %d", patch.ID)).SetInternal(err)
+ }
+ if len(instances) > 0 {
+ return nil, echo.NewHTTPError(http.StatusBadRequest, "You should archive all instances under the environment before archiving the environment.")
+ }
+ }
+
+ env, err := s.store.PatchEnvironment(ctx, patch)
+ if err != nil {
+ if common.ErrorCode(err) == common.NotFound {
+ return nil, echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Environment ID not found: %d", patch.ID))
+ }
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch environment ID: %v", patch.ID)).SetInternal(err)
+ }
+
+ return env, nil
+}
diff --git a/server/openapi_environment.go b/server/openapi_environment.go
new file mode 100644
index 0000000000..e4dd556f3d
--- /dev/null
+++ b/server/openapi_environment.go
@@ -0,0 +1,151 @@
+package server
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/labstack/echo/v4"
+
+ "github.com/bytebase/bytebase/api"
+ openAPIV1 "github.com/bytebase/bytebase/api/v1"
+ "github.com/bytebase/bytebase/common"
+)
+
+func (s *Server) registerOpenAPIRoutesForEnvironment(g *echo.Group) {
+ g.GET("/environment", s.listEnvironment)
+ g.POST("/environment", s.createEnvironmentByOpenAPI)
+ g.GET("/environment/:environmentID", s.getEnvironmentByID)
+ g.PATCH("/environment/:environmentID", s.updateEnvironmentByOpenAPI)
+ g.DELETE("/environment/:environmentID", s.deleteEnvironmentByOpenAPI)
+}
+
+func (s *Server) listEnvironment(c echo.Context) error {
+ ctx := c.Request().Context()
+ rowStatus := api.Normal
+ envList, err := s.store.FindEnvironment(ctx, &api.EnvironmentFind{
+ RowStatus: &rowStatus,
+ })
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch environment list").SetInternal(err)
+ }
+
+ var response []*openAPIV1.Environment
+ for _, env := range envList {
+ response = append(response, convertToOpenAPIEnvironment(env))
+ }
+
+ return c.JSON(http.StatusOK, response)
+}
+
+func (s *Server) createEnvironmentByOpenAPI(c echo.Context) error {
+ ctx := c.Request().Context()
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Failed to read request body").SetInternal(err)
+ }
+
+ envCreate := &openAPIV1.EnvironmentCreate{}
+ if err := json.Unmarshal(body, envCreate); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformed create environment request").SetInternal(err)
+ }
+
+ env, err := s.createEnvironment(ctx, &api.EnvironmentCreate{
+ CreatorID: c.Get(getPrincipalIDContextKey()).(int),
+ Name: envCreate.Name,
+ Order: envCreate.Order,
+ })
+ if err != nil {
+ return err
+ }
+
+ return c.JSON(http.StatusOK, convertToOpenAPIEnvironment(env))
+}
+
+func (s *Server) getEnvironmentByID(c echo.Context) error {
+ ctx := c.Request().Context()
+ id, err := strconv.Atoi(c.Param("environmentID"))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Environment ID is not a number: %s", c.Param("environmentID"))).SetInternal(err)
+ }
+
+ env, err := s.store.GetEnvironmentByID(ctx, id)
+ if err != nil {
+ if common.ErrorCode(err) == common.NotFound {
+ return echo.NewHTTPError(http.StatusNotFound, "Cannot found environment").SetInternal(err)
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find environment").SetInternal(err)
+ }
+
+ return c.JSON(http.StatusOK, convertToOpenAPIEnvironment(env))
+}
+
+func (s *Server) updateEnvironmentByOpenAPI(c echo.Context) error {
+ ctx := c.Request().Context()
+ id, err := strconv.Atoi(c.Param("environmentID"))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Environment ID is not a number: %s", c.Param("environmentID"))).SetInternal(err)
+ }
+
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Failed to read request body").SetInternal(err)
+ }
+
+ envPatch := &openAPIV1.EnvironmentPatch{}
+ if err := json.Unmarshal(body, envPatch); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch environment request").SetInternal(err)
+ }
+
+ env, err := s.updateEnvironment(ctx, &api.EnvironmentPatch{
+ ID: id,
+ UpdaterID: c.Get(getPrincipalIDContextKey()).(int),
+ Name: envPatch.Name,
+ Order: envPatch.Order,
+ })
+ if err != nil {
+ return err
+ }
+
+ return c.JSON(http.StatusOK, convertToOpenAPIEnvironment(env))
+}
+
+func (s *Server) deleteEnvironmentByOpenAPI(c echo.Context) error {
+ ctx := c.Request().Context()
+ id, err := strconv.Atoi(c.Param("environmentID"))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Environment ID is not a number: %s", c.Param("environmentID"))).SetInternal(err)
+ }
+
+ env, err := s.store.GetEnvironmentByID(ctx, id)
+ if err != nil {
+ if common.ErrorCode(err) == common.NotFound {
+ return echo.NewHTTPError(http.StatusNotFound, "Cannot found environment").SetInternal(err)
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find environment").SetInternal(err)
+ }
+
+ rowStatus := string(api.Archived)
+ name := fmt.Sprintf("archived_%s_%d", env.Name, time.Now().Unix())
+ if _, err := s.updateEnvironment(ctx, &api.EnvironmentPatch{
+ ID: id,
+ UpdaterID: c.Get(getPrincipalIDContextKey()).(int),
+ RowStatus: &rowStatus,
+ Name: &name,
+ }); err != nil {
+ return err
+ }
+
+ return c.String(http.StatusOK, "ok")
+}
+
+func convertToOpenAPIEnvironment(env *api.Environment) *openAPIV1.Environment {
+ return &openAPIV1.Environment{
+ ID: env.ID,
+ Name: env.Name,
+ Order: env.Order,
+ }
+}
diff --git a/server/openapi_instance.go b/server/openapi_instance.go
index 2b5ed32dea..236b60c13c 100644
--- a/server/openapi_instance.go
+++ b/server/openapi_instance.go
@@ -18,17 +18,15 @@ func (s *Server) registerOpenAPIRoutesForInstance(g *echo.Group) {
g.GET("/instance", s.listInstance)
g.GET("/instance/:instanceID", s.getInstanceByID)
g.PATCH("/instance/:instanceID", s.updateInstanceByOpenAPI)
- g.DELETE("/instance/:instanceID", s.archiveInstanceByOpenAPI)
+ g.DELETE("/instance/:instanceID", s.deleteInstanceByOpenAPI)
}
func (s *Server) listInstance(c echo.Context) error {
ctx := c.Request().Context()
- instanceFind := &api.InstanceFind{}
- if rowStatusStr := c.QueryParam("rowstatus"); rowStatusStr != "" {
- rowStatus := api.RowStatus(rowStatusStr)
- instanceFind.RowStatus = &rowStatus
- }
- instanceList, err := s.store.FindInstance(ctx, instanceFind)
+ rowStatus := api.Normal
+ instanceList, err := s.store.FindInstance(ctx, &api.InstanceFind{
+ RowStatus: &rowStatus,
+ })
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch instance list").SetInternal(err)
}
@@ -118,7 +116,7 @@ func (s *Server) updateInstanceByOpenAPI(c echo.Context) error {
return c.JSON(http.StatusOK, convertToOpenAPIInstance(instance))
}
-func (s *Server) archiveInstanceByOpenAPI(c echo.Context) error {
+func (s *Server) deleteInstanceByOpenAPI(c echo.Context) error {
ctx := c.Request().Context()
id, err := strconv.Atoi(c.Param("instanceID"))
if err != nil {
diff --git a/server/server.go b/server/server.go
index 0311b44897..cde495c82b 100644
--- a/server/server.go
+++ b/server/server.go
@@ -420,6 +420,7 @@ func (s *Server) registerOpenAPIRoutes(e *echo.Echo, ce *casbin.Enforcer, prof P
s.registerOpenAPIRoutesForSQL(openAPIGroup)
s.registerOpenAPIRoutesForAuth(openAPIGroup)
s.registerOpenAPIRoutesForInstance(openAPIGroup)
+ s.registerOpenAPIRoutesForEnvironment(openAPIGroup)
openAPIGroup.GET("/healthz", func(c echo.Context) error {
return c.JSON(http.StatusOK, map[string]string{
diff --git a/store/environment.go b/store/environment.go
index 98f4fcea63..446861874e 100644
--- a/store/environment.go
+++ b/store/environment.go
@@ -250,17 +250,22 @@ func (s *Store) patchEnvironmentRaw(ctx context.Context, patch *api.EnvironmentP
// createEnvironmentImpl creates a new environment.
func (Store) createEnvironmentImpl(ctx context.Context, tx *Tx, create *api.EnvironmentCreate) (*environmentRaw, error) {
var order int
- // The order is the MAX(order) + 1
- if err := tx.QueryRowContext(ctx, `
+
+ if create.Order != nil {
+ order = *create.Order
+ } else {
+ // The order is the MAX(order) + 1
+ if err := tx.QueryRowContext(ctx, `
SELECT "order"
FROM environment
ORDER BY "order" DESC
LIMIT 1
`).Scan(&order); err != nil {
- if err == sql.ErrNoRows {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("no environment record found")}
+ if err == sql.ErrNoRows {
+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("no environment record found")}
+ }
+ return nil, FormatError(err)
}
- return nil, FormatError(err)
}
// Insert row into database.