Skip to content

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

Implement database and dataSource endpoint

天舟f56b93ed4e48
diff --git a/backend/api/dataSource.go b/backend/api/dataSource.go
new file mode 100644
index 0000000000..d1e3524c7b
--- /dev/null
+++ b/backend/api/dataSource.go
@@ -0,0 +1,88 @@
+package api
+
+import "context"
+
+type DataSourceType string
+
+const (
+ Admin DataSourceType = "ADMIN"
+ RW DataSourceType = "RW"
+ RO DataSourceType = "RO"
+)
+
+func (e DataSourceType) String() string {
+ switch e {
+ case Admin:
+ return "ADMIN"
+ case RW:
+ return "RW"
+ case RO:
+ return "RO"
+ }
+ return ""
+}
+
+type DataSource struct {
+ ID int `jsonapi:"primary,data-source"`
+
+ // Related fields
+ Instance *ResourceObject `jsonapi:"relation,instance"`
+ Database *ResourceObject `jsonapi:"relation,database"`
+
+ // Standard fields
+ WorkspaceId int
+ CreatorId int `jsonapi:"attr,creatorId"`
+ CreatedTs int64 `jsonapi:"attr,createdTs"`
+ UpdaterId int `jsonapi:"attr,updaterId"`
+ UpdatedTs int64 `jsonapi:"attr,updatedTs"`
+
+ // Domain specific fields
+ Name string `jsonapi:"attr,name"`
+ Type DataSourceType `jsonapi:"attr,type"`
+ Username string `jsonapi:"attr,username"`
+ Password string `jsonapi:"attr,password"`
+}
+
+type DataSourceCreate struct {
+ // Related fields
+ InstanceId int
+ DatabaseId int
+
+ // Standard fields
+ WorkspaceId int
+ // Value is assigned from the jwt subject field passed by the client.
+ CreatorId int
+
+ // Domain specific fields
+ Name string `jsonapi:"attr,name"`
+ Type DataSourceType `jsonapi:"attr,type"`
+ Username string `jsonapi:"attr,username"`
+ Password string `jsonapi:"attr,password"`
+}
+
+type DataSourceFind struct {
+ // Standard fields
+ WorkspaceId *int
+ InstanceId *int
+ DatabaseId *int
+ Type *DataSourceType
+}
+
+type DataSourcePatch struct {
+ // Standard fields
+ ID int `jsonapi:"primary,data-source-patch"`
+ WorkspaceId int
+ // Value is assigned from the jwt subject field passed by the client.
+ UpdaterId int
+
+ // Domain specific fields
+ Username *string `jsonapi:"attr,username"`
+ Password *string `jsonapi:"attr,password"`
+}
+
+type DataSourceService interface {
+ CreateDataSource(ctx context.Context, create *DataSourceCreate) (*DataSource, error)
+ FindDataSourceList(ctx context.Context, find *DataSourceFind) ([]*DataSource, error)
+ FindDataSource(ctx context.Context, find *DataSourceFind) (*DataSource, error)
+ PatchDataSource(ctx context.Context, patch *DataSourcePatch) (*DataSource, error)
+}
diff --git a/backend/api/database.go b/backend/api/database.go
new file mode 100644
index 0000000000..fb46042b42
--- /dev/null
+++ b/backend/api/database.go
@@ -0,0 +1,87 @@
+package api
+
+import "context"
+
+type SyncStatus string
+
+const (
+ OK SyncStatus = "OK"
+ Drifted SyncStatus = "DRIFTED"
+ NotFound SyncStatus = "NOT_FOUND"
+)
+
+func (e SyncStatus) String() string {
+ switch e {
+ case OK:
+ return "OK"
+ case Drifted:
+ return "DRIFTED"
+ case NotFound:
+ return "NOT_FOUND"
+ }
+ return ""
+}
+
+type Database struct {
+ ID int `jsonapi:"primary,database"`
+
+ // Related fields
+ Project *Project `jsonapi:"relation,project"`
+ ProjectId int
+ Instance *Instance `jsonapi:"relation,instance"`
+ InstanceId int
+ DataSourceList []*DataSource `jsonapi:"relation,dataSource"`
+
+ // Standard fields
+ WorkspaceId int
+ CreatorId int `jsonapi:"attr,creatorId"`
+ CreatedTs int64 `jsonapi:"attr,createdTs"`
+ UpdaterId int `jsonapi:"attr,updaterId"`
+ UpdatedTs int64 `jsonapi:"attr,updatedTs"`
+
+ // Domain specific fields
+ Name string `jsonapi:"attr,name"`
+ SyncStatus SyncStatus `jsonapi:"attr,syncStatus"`
+ LastSuccessfulSyncTs int64 `jsonapi:"attr,lastSuccessfulSyncTs"`
+ Fingerprint string `jsonapi:"attr,fingerprint"`
+}
+
+type DatabaseCreate struct {
+ // Related fields
+ ProjectId int
+ InstanceId int
+
+ // Standard fields
+ WorkspaceId int
+ // Value is assigned from the jwt subject field passed by the client.
+ CreatorId int
+
+ // Domain specific fields
+ Name string `jsonapi:"attr,name"`
+ IssueId string `jsonapi:"attr,issueId"`
+}
+
+type DatabaseFind struct {
+ // Standard fields
+ ID *int
+ WorkspaceId *int
+ InstanceId *int
+}
+
+type DatabasePatch struct {
+ // Related fields
+ ProjectId *int `jsonapi:"attr,project"`
+
+ // Standard fields
+ ID int `jsonapi:"primary,database-patch"`
+ WorkspaceId int
+ // Value is assigned from the jwt subject field passed by the client.
+ UpdaterId int
+}
+
+type DatabaseService interface {
+ CreateDatabase(ctx context.Context, create *DatabaseCreate) (*Database, error)
+ FindDatabaseList(ctx context.Context, find *DatabaseFind) ([]*Database, error)
+ FindDatabase(ctx context.Context, find *DatabaseFind) (*Database, error)
+ PatchDatabaseByID(ctx context.Context, patch *DatabasePatch) (*Database, error)
+}
diff --git a/backend/api/environment.go b/backend/api/environment.go
index 0e1c212840..eb37e47e39 100644
--- a/backend/api/environment.go
+++ b/backend/api/environment.go
@@ -30,6 +30,7 @@ type EnvironmentCreate struct {
type EnvironmentFind struct {
// Standard fields
+ ID *int
WorkspaceId *int
}
@@ -56,6 +57,7 @@ type EnvironmentDelete struct {
type EnvironmentService interface {
CreateEnvironment(ctx context.Context, create *EnvironmentCreate) (*Environment, error)
FindEnvironmentList(ctx context.Context, find *EnvironmentFind) ([]*Environment, error)
+ FindEnvironment(ctx context.Context, find *EnvironmentFind) (*Environment, error)
PatchEnvironmentByID(ctx context.Context, patch *EnvironmentPatch) (*Environment, error)
DeleteEnvironmentByID(ctx context.Context, delete *EnvironmentDelete) error
}
diff --git a/backend/api/instance.go b/backend/api/instance.go
index f008d8b690..34b1b06604 100644
--- a/backend/api/instance.go
+++ b/backend/api/instance.go
@@ -3,10 +3,12 @@ package api
import "context"
type Instance struct {
- ID string `jsonapi:"primary,instance"`
+ ID int `jsonapi:"primary,instance"`
// Related fields
- Environment *ResourceObject `jsonapi:"relation,environment"`
+ EnvironmentId int
+ Environment *Environment `jsonapi:"relation,environment"`
+ DataSourceList []*DataSource `jsonapi:"relation,dataSource"`
// Standard fields
RowStatus RowStatus `jsonapi:"attr,rowStatus"`
@@ -21,8 +23,8 @@ type Instance struct {
ExternalLink string `jsonapi:"attr,externalLink"`
Host string `jsonapi:"attr,host"`
Port string `jsonapi:"attr,port"`
- Username string `jsonapi:"attr,username"`
- Password string `jsonapi:"attr,password"`
+ // Username string `jsonapi:"attr,username"`
+ // Password string `jsonapi:"attr,password"`
}
type InstanceCreate struct {
@@ -51,7 +53,7 @@ type InstanceFind struct {
type InstancePatch struct {
// Standard fields
- ID int `jsonapi:"primary,instance-patch"`
+ ID int `jsonapi:"primary,instancePatch"`
RowStatus *string `jsonapi:"attr,rowStatus"`
WorkspaceId int
// Value is assigned from the jwt subject field passed by the client.
diff --git a/backend/api/project.go b/backend/api/project.go
index 6f20157360..e5db91a3dc 100644
--- a/backend/api/project.go
+++ b/backend/api/project.go
@@ -6,7 +6,7 @@ type Project struct {
ID int `jsonapi:"primary,project"`
// Related fields
- ProjectMemberList []*ProjectMember `jsonapi:"relation,environment"`
+ ProjectMemberList []*ProjectMember `jsonapi:"relation,project-member-list"`
// Standard fields
RowStatus RowStatus `jsonapi:"attr,rowStatus"`
diff --git a/backend/cmd/echo/main.go b/backend/cmd/echo/main.go
index 97d3e7262b..4473d54d08 100644
--- a/backend/cmd/echo/main.go
+++ b/backend/cmd/echo/main.go
@@ -41,10 +41,12 @@ func (m *Main) Run() error {
server := server.NewServer(m.l)
server.PrincipalService = store.NewPrincipalService(m.l, db)
server.MemberService = store.NewMemberService(m.l, db)
- server.EnvironmentService = store.NewEnvironmentService(m.l, db)
- server.InstanceService = store.NewInstanceService(m.l, db)
server.ProjectService = store.NewProjectService(m.l, db)
server.ProjectMemberService = store.NewProjectMemberService(m.l, db)
+ server.EnvironmentService = store.NewEnvironmentService(m.l, db)
+ server.InstanceService = store.NewInstanceService(m.l, db)
+ server.DatabaseService = store.NewDatabaseService(m.l, db)
+ server.DataSourceService = store.NewDataSourceService(m.l, db)
m.server = server
if err := server.Run(); err != nil {
diff --git a/backend/server/acl_casbin_policy_dba.csv b/backend/server/acl_casbin_policy_dba.csv
index 7a88fa574c..f5d56627d4 100644
--- a/backend/server/acl_casbin_policy_dba.csv
+++ b/backend/server/acl_casbin_policy_dba.csv
@@ -2,6 +2,13 @@ p, DBA, /principal, GET
p, DBA, /principal/{id}, GET
p, DBA, /principal/{id}, PATCH_SELF
p, DBA, /member, GET
+p, DBA, /project, POST
+p, DBA, /project, GET
+p, DBA, /project/{id}, GET
+p, DBA, /project/{id}, PATCH
+p, DBA, /project/{projectId}/member, POST
+p, DBA, /project/{projectId}/member/{memberId}, PATCH
+p, DBA, /project/{projectId}/member/{memberId}, DELETE
p, DBA, /environment, POST
p, DBA, /environment, GET
p, DBA, /environment/{id}, PATCH
@@ -10,10 +17,7 @@ p, DBA, /instance, POST
p, DBA, /instance, GET
p, DBA, /instance/{id}, GET
p, DBA, /instance/{id}, PATCH
-p, DBA, /project, POST
-p, DBA, /project, GET
-p, DBA, /project/{id}, GET
-p, DBA, /project/{id}, PATCH
-p, DBA, /project/{projectId}/member, POST
-p, DBA, /project/{projectId}/member/{memberId}, PATCH
-p, DBA, /project/{projectId}/member/{memberId}, DELETE
\ No newline at end of file
+p, DBA, /database, POST
+p, DBA, /database, GET
+p, DBA, /database/{id}, GET
+p, DBA, /database/{id}, PATCH
\ No newline at end of file
diff --git a/backend/server/acl_casbin_policy_developer.csv b/backend/server/acl_casbin_policy_developer.csv
index bfb0149fa6..8bdda2019a 100644
--- a/backend/server/acl_casbin_policy_developer.csv
+++ b/backend/server/acl_casbin_policy_developer.csv
@@ -2,13 +2,17 @@ p, DEVELOPER, /principal, GET
p, DEVELOPER, /principal/{id}, GET
p, DEVELOPER, /principal/{id}, PATCH_SELF
p, DEVELOPER, /member, GET
-p, DEVELOPER, /environment, GET
-p, DEVELOPER, /instance, GET
-p, DEVELOPER, /instance/{id}, GET
p, DEVELOPER, /project, POST
p, DEVELOPER, /project, GET
p, DEVELOPER, /project/{id}, GET
p, DEVELOPER, /project/{id}, PATCH
p, DEVELOPER, /project/{projectId}/member, POST
p, DEVELOPER, /project/{projectId}/member/{memberId}, PATCH
-p, DEVELOPER, /project/{projectId}/member/{memberId}, DELETE
\ No newline at end of file
+p, DEVELOPER, /project/{projectId}/member/{memberId}, DELETE
+p, DEVELOPER, /environment, GET
+p, DEVELOPER, /instance, GET
+p, DEVELOPER, /instance/{id}, GET
+p, DEVELOPER, /database, POST
+p, DEVELOPER, /database, GET
+p, DEVELOPER, /database/{id}, GET
+p, DEVELOPER, /database/{id}, PATCH
diff --git a/backend/server/acl_casbin_policy_owner.csv b/backend/server/acl_casbin_policy_owner.csv
index a080cdc036..35e77536c6 100644
--- a/backend/server/acl_casbin_policy_owner.csv
+++ b/backend/server/acl_casbin_policy_owner.csv
@@ -7,6 +7,13 @@ p, OWNER, /member, POST
p, OWNER, /member, GET
p, OWNER, /member/{id}, PATCH
p, OWNER, /member/{id}, DELETE
+p, OWNER, /project, POST
+p, OWNER, /project, GET
+p, OWNER, /project/{id}, GET
+p, OWNER, /project/{id}, PATCH
+p, OWNER, /project/{projectId}/member, POST
+p, OWNER, /project/{projectId}/member/{memberId}, PATCH
+p, OWNER, /project/{projectId}/member/{memberId}, DELETE
p, OWNER, /environment, POST
p, OWNER, /environment, GET
p, OWNER, /environment/{id}, PATCH
@@ -15,10 +22,7 @@ p, OWNER, /instance, POST
p, OWNER, /instance, GET
p, OWNER, /instance/{id}, GET
p, OWNER, /instance/{id}, PATCH
-p, OWNER, /project, POST
-p, OWNER, /project, GET
-p, OWNER, /project/{id}, GET
-p, OWNER, /project/{id}, PATCH
-p, OWNER, /project/{projectId}/member, POST
-p, OWNER, /project/{projectId}/member/{memberId}, PATCH
-p, OWNER, /project/{projectId}/member/{memberId}, DELETE
\ No newline at end of file
+p, OWNER, /database, POST
+p, OWNER, /database, GET
+p, OWNER, /database/{id}, GET
+p, OWNER, /database/{id}, PATCH
diff --git a/backend/server/database.go b/backend/server/database.go
new file mode 100644
index 0000000000..72855284be
--- /dev/null
+++ b/backend/server/database.go
@@ -0,0 +1,170 @@
+package server
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "strconv"
+
+ "github.com/bytebase/bytebase"
+ "github.com/bytebase/bytebase/api"
+ "github.com/google/jsonapi"
+ "github.com/labstack/echo/v4"
+)
+
+func (s *Server) registerDatabaseRoutes(g *echo.Group) {
+ g.POST("/database", func(c echo.Context) error {
+ databaseCreate := &api.DatabaseCreate{WorkspaceId: api.DEFAULT_WORKPSACE_ID}
+ if err := jsonapi.UnmarshalPayload(c.Request().Body, databaseCreate); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted create database request").SetInternal(err)
+ }
+
+ databaseCreate.CreatorId = c.Get(GetPrincipalIdContextKey()).(int)
+
+ database, err := s.DatabaseService.CreateDatabase(context.Background(), databaseCreate)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ECONFLICT {
+ return echo.NewHTTPError(http.StatusConflict, fmt.Sprintf("Database name already exists: %s", databaseCreate.Name))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create database").SetInternal(err)
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, database); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal create database response").SetInternal(err)
+ }
+ return nil
+ })
+
+ g.GET("/database", func(c echo.Context) error {
+ wsId := api.DEFAULT_WORKPSACE_ID
+ databaseFind := &api.DatabaseFind{
+ WorkspaceId: &wsId,
+ }
+ if instanceIdStr := c.QueryParam("instance"); instanceIdStr != "" {
+ instanceId, err := strconv.Atoi(instanceIdStr)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Query parameter instance is not a number: %s", instanceIdStr)).SetInternal(err)
+ }
+ databaseFind.InstanceId = &instanceId
+ }
+ list, err := s.DatabaseService.FindDatabaseList(context.Background(), databaseFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch database list").SetInternal(err)
+ }
+
+ for _, database := range list {
+ projectFind := &api.ProjectFind{
+ ID: &database.ProjectId,
+ }
+ database.Project, err = s.ProjectService.FindProject(context.Background(), projectFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project for database: %v", database.Name)).SetInternal(err)
+ }
+
+ instanceFind := &api.InstanceFind{
+ ID: &database.InstanceId,
+ }
+ database.Instance, err = s.InstanceService.FindInstance(context.Background(), instanceFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance for database: %v", database.Name)).SetInternal(err)
+ }
+
+ environmentFind := &api.EnvironmentFind{
+ ID: &database.Instance.EnvironmentId,
+ }
+ database.Instance.Environment, err = s.EnvironmentService.FindEnvironment(context.Background(), environmentFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch environment for database: %v", database.Name)).SetInternal(err)
+ }
+
+ database.DataSourceList = []*api.DataSource{}
+ }
+
+ 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 database list response").SetInternal(err)
+ }
+ return nil
+ })
+
+ g.GET("/database/: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)
+ }
+
+ databaseFind := &api.DatabaseFind{
+ ID: &id,
+ }
+ database, err := s.DatabaseService.FindDatabase(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)
+ }
+
+ projectFind := &api.ProjectFind{
+ ID: &database.ProjectId,
+ }
+ database.Project, err = s.ProjectService.FindProject(context.Background(), projectFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project for database: %v", database.Name)).SetInternal(err)
+ }
+
+ instanceFind := &api.InstanceFind{
+ ID: &database.InstanceId,
+ }
+ database.Instance, err = s.InstanceService.FindInstance(context.Background(), instanceFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance for database: %v", database.Name)).SetInternal(err)
+ }
+
+ environmentFind := &api.EnvironmentFind{
+ ID: &database.Instance.EnvironmentId,
+ }
+ database.Instance.Environment, err = s.EnvironmentService.FindEnvironment(context.Background(), environmentFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch environment for database: %v", database.Name)).SetInternal(err)
+ }
+
+ database.DataSourceList = []*api.DataSource{}
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, database); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal project ID response: %v", id)).SetInternal(err)
+ }
+ return nil
+ })
+
+ g.PATCH("/database/:id", func(c echo.Context) error {
+ id, err := strconv.Atoi(c.Param("id"))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Database ID is not a number: %s", c.Param("id"))).SetInternal(err)
+ }
+
+ databasePatch := &api.DatabasePatch{
+ ID: id,
+ WorkspaceId: api.DEFAULT_WORKPSACE_ID,
+ UpdaterId: c.Get(GetPrincipalIdContextKey()).(int),
+ }
+ if err := jsonapi.UnmarshalPayload(c.Request().Body, databasePatch); err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch database request").SetInternal(err)
+ }
+
+ database, err := s.DatabaseService.PatchDatabaseByID(context.Background(), databasePatch)
+ 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 patch database ID: %v", id)).SetInternal(err)
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, database); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal database ID response: %v", id)).SetInternal(err)
+ }
+ return nil
+ })
+}
diff --git a/backend/server/instance.go b/backend/server/instance.go
index ae8a759645..d0dcde5461 100644
--- a/backend/server/instance.go
+++ b/backend/server/instance.go
@@ -46,6 +46,16 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch instance list").SetInternal(err)
}
+ for _, instance := range list {
+ environmentFind := &api.EnvironmentFind{
+ ID: &instance.EnvironmentId,
+ }
+ instance.Environment, err = s.EnvironmentService.FindEnvironment(context.Background(), environmentFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch environment for instance: %v", instance.Name)).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 instance list response").SetInternal(err)
@@ -70,6 +80,22 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance ID: %v", id)).SetInternal(err)
}
+ environmentFind := &api.EnvironmentFind{
+ ID: &instance.EnvironmentId,
+ }
+ instance.Environment, err = s.EnvironmentService.FindEnvironment(context.Background(), environmentFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch environment for instance: %v", instance.Name)).SetInternal(err)
+ }
+
+ dataSourceFind := &api.DataSourceFind{
+ InstanceId: &instance.ID,
+ }
+ instance.DataSourceList, err = s.DataSourceService.FindDataSourceList(context.Background(), dataSourceFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch data source for instance: %v", instance.Name)).SetInternal(err)
+ }
+
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, instance); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal instance ID response: %v", id)).SetInternal(err)
@@ -92,12 +118,64 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch instance request").SetInternal(err)
}
- instance, err := s.InstanceService.PatchInstanceByID(context.Background(), instancePatch)
- if err != nil {
- if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
+ var instance *api.Instance
+ if instancePatch.RowStatus != nil || instancePatch.Name != nil || instancePatch.ExternalLink != nil || instancePatch.Host != nil || instancePatch.Port != nil {
+ instance, err = s.InstanceService.PatchInstanceByID(context.Background(), instancePatch)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch instance ID: %v", id)).SetInternal(err)
+ }
+ } else if instancePatch.Username != nil || instancePatch.Password != nil {
+ instanceFind := &api.InstanceFind{
+ ID: &id,
}
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch instance ID: %v", id)).SetInternal(err)
+ instance, err = s.InstanceService.FindInstance(context.Background(), instanceFind)
+ if err != nil {
+ if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance ID not found: %d", id))
+ }
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch instance ID: %v", id)).SetInternal(err)
+ }
+
+ dataSourceType := api.Admin
+ dataSourceFind := &api.DataSourceFind{
+ InstanceId: &instance.ID,
+ Type: &dataSourceType,
+ }
+ adminDataSource, err := s.DataSourceService.FindDataSource(context.Background(), dataSourceFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch data source for instance: %v", instance.Name)).SetInternal(err)
+ }
+
+ dataSourcePatch := &api.DataSourcePatch{
+ ID: adminDataSource.ID,
+ WorkspaceId: api.DEFAULT_WORKPSACE_ID,
+ UpdaterId: c.Get(GetPrincipalIdContextKey()).(int),
+ Username: instancePatch.Username,
+ Password: instancePatch.Password,
+ }
+ _, err = s.DataSourceService.PatchDataSource(context.Background(), dataSourcePatch)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch data source for instance: %v", instance.Name)).SetInternal(err)
+ }
+ }
+
+ environmentFind := &api.EnvironmentFind{
+ ID: &instance.EnvironmentId,
+ }
+ instance.Environment, err = s.EnvironmentService.FindEnvironment(context.Background(), environmentFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch environment for instance: %v", instance.Name)).SetInternal(err)
+ }
+
+ dataSourceFind := &api.DataSourceFind{
+ InstanceId: &instance.ID,
+ }
+ instance.DataSourceList, err = s.DataSourceService.FindDataSourceList(context.Background(), dataSourceFind)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch data source for instance: %v", instance.Name)).SetInternal(err)
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
diff --git a/backend/server/server.go b/backend/server/server.go
index 1a9184ed87..d5ea2bed10 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -21,10 +21,12 @@ type Server struct {
PrincipalService api.PrincipalService
MemberService api.MemberService
- EnvironmentService api.EnvironmentService
- InstanceService api.InstanceService
ProjectService api.ProjectService
ProjectMemberService api.ProjectMemberService
+ EnvironmentService api.EnvironmentService
+ InstanceService api.InstanceService
+ DatabaseService api.DatabaseService
+ DataSourceService api.DataSourceService
e *echo.Echo
}
@@ -109,10 +111,11 @@ func NewServer(logger *bytebase.Logger) *Server {
s.registerAuthRoutes(g)
s.registerPrincipalRoutes(g)
s.registerMemberRoutes(g)
- s.registerEnvironmentRoutes(g)
- s.registerInstanceRoutes(g)
s.registerProjectRoutes(g)
s.registerProjectMemberRoutes(g)
+ s.registerEnvironmentRoutes(g)
+ s.registerInstanceRoutes(g)
+ s.registerDatabaseRoutes(g)
return s
}
diff --git a/backend/store/dataSource.go b/backend/store/dataSource.go
new file mode 100644
index 0000000000..f8db8781f1
--- /dev/null
+++ b/backend/store/dataSource.go
@@ -0,0 +1,285 @@
+package store
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/bytebase/bytebase"
+ "github.com/bytebase/bytebase/api"
+)
+
+var (
+ _ api.DataSourceService = (*DataSourceService)(nil)
+)
+
+// DataSourceService represents a service for managing dataSource.
+type DataSourceService struct {
+ l *bytebase.Logger
+ db *DB
+}
+
+// NewDataSourceService returns a new instance of DataSourceService.
+func NewDataSourceService(logger *bytebase.Logger, db *DB) *DataSourceService {
+ return &DataSourceService{l: logger, db: db}
+}
+
+// CreateDataSource creates a new dataSource.
+func (s *DataSourceService) CreateDataSource(ctx context.Context, create *api.DataSourceCreate) (*api.DataSource, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ dataSource, err := s.createDataSource(ctx, tx, create)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return dataSource, nil
+}
+
+// FindDataSourceList retrieves a list of data sources based on find.
+func (s *DataSourceService) FindDataSourceList(ctx context.Context, find *api.DataSourceFind) ([]*api.DataSource, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := s.findDataSourceList(ctx, tx, find)
+ if err != nil {
+ return []*api.DataSource{}, err
+ }
+
+ return list, nil
+}
+
+// FindDataSource retrieves a single dataSource based on find.
+// Returns ENOTFOUND if no matching record.
+// Returns the first matching one and prints a warning if finding more than 1 matching records.
+func (s *DataSourceService) FindDataSource(ctx context.Context, find *api.DataSourceFind) (*api.DataSource, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := s.findDataSourceList(ctx, tx, find)
+ if err != nil {
+ return nil, err
+ } else if len(list) == 0 {
+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("data source not found: %v", find)}
+ } else if len(list) > 1 {
+ s.l.Logf(bytebase.WARN, "found mulitple data sources: %d, expect 1", len(list))
+ }
+ return list[0], nil
+}
+
+// PatchDataSource updates an existing dataSource by ID.
+// Returns ENOTFOUND if dataSource does not exist.
+func (s *DataSourceService) PatchDataSource(ctx context.Context, patch *api.DataSourcePatch) (*api.DataSource, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ dataSource, err := s.patchDataSource(ctx, tx, patch)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return dataSource, nil
+}
+
+// createDataSource creates a new dataSource.
+func (s *DataSourceService) createDataSource(ctx context.Context, tx *Tx, create *api.DataSourceCreate) (*api.DataSource, error) {
+ // Insert row into dataSource.
+ row, err := tx.QueryContext(ctx, `
+ INSERT INTO data_source (
+ workspace_id,
+ creator_id,
+ updater_id,
+ instance_id,
+ database_id,
+ name,
+ type,
+ username,
+ password
+ )
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ RETURNING id, workspace_id, creator_id, created_ts, updater_id, updated_ts, instance_id, database_id, name, type, username, password
+ `,
+ create.WorkspaceId,
+ create.CreatorId,
+ create.CreatorId,
+ create.InstanceId,
+ create.DatabaseId,
+ create.Name,
+ create.Type,
+ create.Username,
+ create.Password,
+ )
+
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ row.Next()
+ var dataSource api.DataSource
+ dataSource.Instance = &api.ResourceObject{}
+ dataSource.Database = &api.ResourceObject{}
+ if err := row.Scan(
+ &dataSource.ID,
+ &dataSource.WorkspaceId,
+ &dataSource.CreatorId,
+ &dataSource.CreatedTs,
+ &dataSource.UpdaterId,
+ &dataSource.UpdatedTs,
+ &dataSource.Instance.ID,
+ &dataSource.Database.ID,
+ &dataSource.Name,
+ &dataSource.Type,
+ &dataSource.Username,
+ &dataSource.Password,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return &dataSource, nil
+}
+
+func (s *DataSourceService) findDataSourceList(ctx context.Context, tx *Tx, find *api.DataSourceFind) (_ []*api.DataSource, err error) {
+ // Build WHERE clause.
+ where, args := []string{"1 = 1"}, []interface{}{}
+ if v := find.WorkspaceId; v != nil {
+ where, args = append(where, "workspace_id = ?"), append(args, *v)
+ }
+ if v := find.InstanceId; v != nil {
+ where, args = append(where, "instance_id = ?"), append(args, *v)
+ }
+ if v := find.DatabaseId; v != nil {
+ where, args = append(where, "`database_id` = ?"), append(args, *v)
+ }
+ if v := find.Type; v != nil {
+ where, args = append(where, "`type` = ?"), append(args, api.DataSourceType(*v))
+ }
+
+ rows, err := tx.QueryContext(ctx, `
+ SELECT
+ id,
+ workspace_id,
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
+ instance_id,
+ database_id,
+ name,
+ type,
+ username,
+ password
+ FROM data_source
+ 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.DataSource, 0)
+ for rows.Next() {
+ var dataSource api.DataSource
+ dataSource.Instance = &api.ResourceObject{}
+ dataSource.Database = &api.ResourceObject{}
+ if err := rows.Scan(
+ &dataSource.ID,
+ &dataSource.WorkspaceId,
+ &dataSource.CreatorId,
+ &dataSource.CreatedTs,
+ &dataSource.UpdaterId,
+ &dataSource.UpdatedTs,
+ &dataSource.Instance.ID,
+ &dataSource.Database.ID,
+ &dataSource.Name,
+ &dataSource.Type,
+ &dataSource.Username,
+ &dataSource.Password,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ list = append(list, &dataSource)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return list, nil
+}
+
+// patchDataSource updates a dataSource by ID. Returns the new state of the dataSource after update.
+func (s *DataSourceService) patchDataSource(ctx context.Context, tx *Tx, patch *api.DataSourcePatch) (*api.DataSource, error) {
+ // Build UPDATE clause.
+ set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterId}
+ if v := patch.Username; v != nil {
+ set, args = append(set, "username = ?"), append(args, *v)
+ }
+ if v := patch.Password; v != nil {
+ set, args = append(set, "password = ?"), append(args, *v)
+ }
+
+ args = append(args, patch.ID)
+
+ // Execute update query with RETURNING.
+ row, err := tx.QueryContext(ctx, `
+ UPDATE data_source
+ SET `+strings.Join(set, ", ")+`
+ WHERE id = ?
+ RETURNING id, workspace_id, creator_id, created_ts, updater_id, updated_ts, instance_id, database_id, name, type, username, password
+ `,
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ if row.Next() {
+ var dataSource api.DataSource
+ dataSource.Instance = &api.ResourceObject{}
+ dataSource.Database = &api.ResourceObject{}
+ if err := row.Scan(
+ &dataSource.ID,
+ &dataSource.WorkspaceId,
+ &dataSource.CreatorId,
+ &dataSource.CreatedTs,
+ &dataSource.UpdaterId,
+ &dataSource.UpdatedTs,
+ &dataSource.Instance.ID,
+ &dataSource.Database.ID,
+ &dataSource.Name,
+ &dataSource.Type,
+ &dataSource.Username,
+ &dataSource.Password,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+ return &dataSource, nil
+ }
+
+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("dataSource ID not found: %d", patch.ID)}
+}
diff --git a/backend/store/database.go b/backend/store/database.go
new file mode 100644
index 0000000000..22f052d3cb
--- /dev/null
+++ b/backend/store/database.go
@@ -0,0 +1,268 @@
+package store
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/bytebase/bytebase"
+ "github.com/bytebase/bytebase/api"
+)
+
+var (
+ _ api.DatabaseService = (*DatabaseService)(nil)
+)
+
+// DatabaseService represents a service for managing database.
+type DatabaseService struct {
+ l *bytebase.Logger
+ db *DB
+}
+
+// NewDatabaseService returns a new instance of DatabaseService.
+func NewDatabaseService(logger *bytebase.Logger, db *DB) *DatabaseService {
+ return &DatabaseService{l: logger, db: db}
+}
+
+// CreateDatabase creates a new database.
+func (s *DatabaseService) CreateDatabase(ctx context.Context, create *api.DatabaseCreate) (*api.Database, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ database, err := s.createDatabase(ctx, tx, create)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return database, nil
+}
+
+// FindDatabaseList retrieves a list of databases based on find.
+func (s *DatabaseService) FindDatabaseList(ctx context.Context, find *api.DatabaseFind) ([]*api.Database, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := s.findDatabaseList(ctx, tx, find)
+ if err != nil {
+ return []*api.Database{}, err
+ }
+
+ return list, nil
+}
+
+// FindDatabase retrieves a single database based on find.
+// Returns ENOTFOUND if no matching record.
+// Returns the first matching one and prints a warning if finding more than 1 matching records.
+func (s *DatabaseService) FindDatabase(ctx context.Context, find *api.DatabaseFind) (*api.Database, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := s.findDatabaseList(ctx, tx, find)
+ if err != nil {
+ return nil, err
+ } else if len(list) == 0 {
+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("project not found: %v", find)}
+ } else if len(list) > 1 {
+ s.l.Logf(bytebase.WARN, "found mulitple projects: %d, expect 1", len(list))
+ }
+ return list[0], nil
+}
+
+// PatchDatabaseByID updates an existing database by ID.
+// Returns ENOTFOUND if database does not exist.
+func (s *DatabaseService) PatchDatabaseByID(ctx context.Context, patch *api.DatabasePatch) (*api.Database, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ database, err := s.patchDatabase(ctx, tx, patch)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return database, nil
+}
+
+// createDatabase creates a new database.
+func (s *DatabaseService) createDatabase(ctx context.Context, tx *Tx, create *api.DatabaseCreate) (*api.Database, error) {
+ // Insert row into database.
+ row, err := tx.QueryContext(ctx, `
+ INSERT INTO db (
+ workspace_id,
+ creator_id,
+ updater_id,
+ instance_id,
+ project_id,
+ name,
+ sync_status,
+ last_successful_sync_ts,
+ fingerprint
+ )
+ VALUES (?, ?, ?, ?, ?, ?, 'NOT_FOUND', 0, '')
+ RETURNING id, workspace_id, creator_id, created_ts, updater_id, updated_ts, instance_id, project_id, name, sync_status, last_successful_sync, fingerprint
+ `,
+ create.WorkspaceId,
+ create.CreatorId,
+ create.CreatorId,
+ create.InstanceId,
+ create.ProjectId,
+ create.Name,
+ )
+
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ row.Next()
+ var database api.Database
+ if err := row.Scan(
+ &database.ID,
+ &database.WorkspaceId,
+ &database.CreatorId,
+ &database.CreatedTs,
+ &database.UpdaterId,
+ &database.UpdatedTs,
+ &database.InstanceId,
+ &database.ProjectId,
+ &database.Name,
+ &database.SyncStatus,
+ &database.LastSuccessfulSyncTs,
+ &database.Fingerprint,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return &database, nil
+}
+
+func (s *DatabaseService) findDatabaseList(ctx context.Context, tx *Tx, find *api.DatabaseFind) (_ []*api.Database, err error) {
+ // Build WHERE clause.
+ where, args := []string{"1 = 1"}, []interface{}{}
+ if v := find.WorkspaceId; v != nil {
+ where, args = append(where, "workspace_id = ?"), append(args, *v)
+ }
+
+ if v := find.InstanceId; v != nil {
+ where, args = append(where, "instance_id = ?"), append(args, *v)
+ }
+
+ rows, err := tx.QueryContext(ctx, `
+ SELECT
+ id,
+ workspace_id,
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
+ instance_id,
+ project_id,
+ name,
+ sync_status,
+ last_successful_sync_ts,
+ fingerprint
+ FROM db
+ 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.Database, 0)
+ for rows.Next() {
+ var database api.Database
+ if err := rows.Scan(
+ &database.ID,
+ &database.WorkspaceId,
+ &database.CreatorId,
+ &database.CreatedTs,
+ &database.UpdaterId,
+ &database.UpdatedTs,
+ &database.InstanceId,
+ &database.ProjectId,
+ &database.Name,
+ &database.SyncStatus,
+ &database.LastSuccessfulSyncTs,
+ &database.Fingerprint,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ list = append(list, &database)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return list, nil
+}
+
+// patchDatabase updates a database by ID. Returns the new state of the database after update.
+func (s *DatabaseService) patchDatabase(ctx context.Context, tx *Tx, patch *api.DatabasePatch) (*api.Database, error) {
+ // Build UPDATE clause.
+ set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterId}
+ if v := patch.ProjectId; v != nil {
+ set, args = append(set, "name = ?"), append(args, *v)
+ }
+
+ args = append(args, patch.ID)
+
+ // Execute update query with RETURNING.
+ row, err := tx.QueryContext(ctx, `
+ UPDATE db
+ SET `+strings.Join(set, ", ")+`
+ WHERE id = ?
+ RETURNING id, workspace_id, creator_id, created_ts, updater_id, updated_ts, instance_id, project_id, name, sync_status, last_successful_sync, fingerprint
+ `,
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ if row.Next() {
+ var database api.Database
+ if err := row.Scan(
+ &database.ID,
+ &database.WorkspaceId,
+ &database.CreatorId,
+ &database.CreatedTs,
+ &database.UpdaterId,
+ &database.UpdatedTs,
+ &database.InstanceId,
+ &database.ProjectId,
+ &database.Name,
+ &database.SyncStatus,
+ &database.LastSuccessfulSyncTs,
+ &database.Fingerprint,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+ return &database, nil
+ }
+
+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("database ID not found: %d", patch.ID)}
+}
diff --git a/backend/store/environment.go b/backend/store/environment.go
index 8dd0b6d12a..36cf408cc4 100644
--- a/backend/store/environment.go
+++ b/backend/store/environment.go
@@ -60,6 +60,27 @@ func (s *EnvironmentService) FindEnvironmentList(ctx context.Context, find *api.
return list, nil
}
+// FindEnvironment retrieves a single environment based on find.
+// Returns ENOTFOUND if no matching record.
+// Returns the first matching one and prints a warning if finding more than 1 matching records.
+func (s *EnvironmentService) FindEnvironment(ctx context.Context, find *api.EnvironmentFind) (*api.Environment, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := s.findEnvironmentList(ctx, tx, find)
+ if err != nil {
+ return nil, err
+ } else if len(list) == 0 {
+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("enviornment not found: %v", find)}
+ } else if len(list) > 1 {
+ s.l.Logf(bytebase.WARN, "found mulitple environments: %d, expect 1", len(list))
+ }
+ return list[0], nil
+}
+
// PatchEnvironmentByID updates an existing environment by ID.
// Returns ENOTFOUND if environment does not exist.
func (s *EnvironmentService) PatchEnvironmentByID(ctx context.Context, patch *api.EnvironmentPatch) (*api.Environment, error) {
@@ -173,6 +194,9 @@ func (s *EnvironmentService) createEnvironment(ctx context.Context, tx *Tx, crea
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.ID; v != nil {
+ where, args = append(where, "id = ?"), append(args, *v)
+ }
if v := find.WorkspaceId; v != nil {
where, args = append(where, "workspace_id = ?"), append(args, *v)
}
diff --git a/backend/store/instance.go b/backend/store/instance.go
index da73641c8a..4813687f12 100644
--- a/backend/store/instance.go
+++ b/backend/store/instance.go
@@ -136,7 +136,6 @@ func createInstance(ctx context.Context, tx *Tx, create *api.InstanceCreate) (*a
row.Next()
var instance api.Instance
- instance.Environment = &api.ResourceObject{}
if err := row.Scan(
&instance.ID,
&instance.RowStatus,
@@ -145,7 +144,7 @@ func createInstance(ctx context.Context, tx *Tx, create *api.InstanceCreate) (*a
&instance.UpdaterId,
&instance.UpdatedTs,
&instance.WorkspaceId,
- &instance.Environment.ID,
+ &instance.EnvironmentId,
&instance.Name,
&instance.ExternalLink,
&instance.Host,
@@ -194,7 +193,6 @@ func findInstanceList(ctx context.Context, tx *Tx, find *api.InstanceFind) (_ []
list := make([]*api.Instance, 0)
for rows.Next() {
var instance api.Instance
- instance.Environment = &api.ResourceObject{}
if err := rows.Scan(
&instance.ID,
&instance.RowStatus,
@@ -203,7 +201,7 @@ func findInstanceList(ctx context.Context, tx *Tx, find *api.InstanceFind) (_ []
&instance.UpdaterId,
&instance.UpdatedTs,
&instance.WorkspaceId,
- &instance.Environment.ID,
+ &instance.EnvironmentId,
&instance.Name,
&instance.ExternalLink,
&instance.Host,
@@ -259,7 +257,6 @@ func patchInstance(ctx context.Context, tx *Tx, patch *api.InstancePatch) (*api.
if row.Next() {
var instance api.Instance
- instance.Environment = &api.ResourceObject{}
if err := row.Scan(
&instance.ID,
&instance.RowStatus,
@@ -268,7 +265,7 @@ func patchInstance(ctx context.Context, tx *Tx, patch *api.InstancePatch) (*api.
&instance.UpdaterId,
&instance.UpdatedTs,
&instance.WorkspaceId,
- &instance.Environment.ID,
+ &instance.EnvironmentId,
&instance.Name,
&instance.ExternalLink,
&instance.Host,
diff --git a/backend/store/migration/0001_init_schema.down.sql b/backend/store/migration/0001_init_schema.down.sql
index 8c94495b93..1c8948d1a5 100644
--- a/backend/store/migration/0001_init_schema.down.sql
+++ b/backend/store/migration/0001_init_schema.down.sql
@@ -1,3 +1,7 @@
+DROP TABLE IF EXISTS data_source;
+
+DROP TABLE db;
+
DROP TABLE instance;
DROP TABLE environment;
diff --git a/backend/store/migration/0001_init_schema.up.sql b/backend/store/migration/0001_init_schema.up.sql
index 27e998c4a5..98fe1e792c 100644
--- a/backend/store/migration/0001_init_schema.up.sql
+++ b/backend/store/migration/0001_init_schema.up.sql
@@ -299,4 +299,83 @@ SET
WHERE
rowid = old.rowid;
+END;
+
+-- db table stores the databases for a particular instance
+-- data is sycned periodically from the instance
+CREATE TABLE db (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ row_status TEXT NOT NULL CHECK (
+ row_status IN ('NORMAL', 'ARCHIVED', 'PENDING_DELETE')
+ ) DEFAULT 'NORMAL',
+ creator_id INTEGER NOT NULL REFERENCES principal (id),
+ created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
+ updater_id INTEGER NOT NULL REFERENCES principal (id),
+ updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
+ workspace_id INTEGER NOT NULL REFERENCES workspace (id),
+ instance_id INTEGER NOT NULL REFERENCES instance (id),
+ project_id INTEGER NOT NULL REFERENCES project (id),
+ name TEXT NOT NULL,
+ sync_status TEXT NOT NULL CHECK (
+ sync_status IN ('OK', 'DRIFTED', 'NOT_FOUND')
+ ),
+ last_successful_sync_ts BIGINT NOT NULL,
+ fingerprint TEXT NOT NULL,
+ UNIQUE(instance_id, name)
+);
+
+INSERT INTO
+ sqlite_sequence (name, seq)
+VALUES
+ ('db', 1000);
+
+CREATE TRIGGER IF NOT EXISTS `trigger_update_db_modification_time`
+AFTER
+UPDATE
+ ON `db` FOR EACH ROW BEGIN
+UPDATE
+ `db`
+SET
+ updated_ts = (strftime('%s', 'now'))
+WHERE
+ rowid = old.rowid;
+
+END;
+
+-- data_source table stores the data source for a particular database
+CREATE TABLE data_source (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ row_status TEXT NOT NULL CHECK (
+ row_status IN ('NORMAL', 'ARCHIVED', 'PENDING_DELETE')
+ ) DEFAULT 'NORMAL',
+ creator_id INTEGER NOT NULL REFERENCES principal (id),
+ created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
+ updater_id INTEGER NOT NULL REFERENCES principal (id),
+ updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
+ workspace_id INTEGER NOT NULL REFERENCES workspace (id),
+ instance_id INTEGER NOT NULL REFERENCES instance (id),
+ database_id INTEGER NOT NULL REFERENCES db (id),
+ name TEXT NOT NULL,
+ `type` TEXT NOT NULL CHECK (TYPE IN ('ADMIN', 'RW', 'RO')),
+ username TEXT NOT NULL,
+ `password` TEXT NOT NULL,
+ UNIQUE(instance_id, name)
+);
+
+INSERT INTO
+ sqlite_sequence (name, seq)
+VALUES
+ ('data_source', 1000);
+
+CREATE TRIGGER IF NOT EXISTS `trigger_update_data_source_modification_time`
+AFTER
+UPDATE
+ ON `data_source` FOR EACH ROW BEGIN
+UPDATE
+ `data_source`
+SET
+ updated_ts = (strftime('%s', 'now'))
+WHERE
+ rowid = old.rowid;
+
END;
\ No newline at end of file
diff --git a/backend/store/seed/0070_database.sql b/backend/store/seed/0070_database.sql
new file mode 100644
index 0000000000..6a9c18104d
--- /dev/null
+++ b/backend/store/seed/0070_database.sql
@@ -0,0 +1,134 @@
+INSERT INTO
+ db (
+ id,
+ creator_id,
+ updater_id,
+ workspace_id,
+ instance_id,
+ project_id,
+ name,
+ sync_status,
+ last_successful_sync_ts,
+ fingerprint
+ )
+VALUES
+ (
+ 7001,
+ 1001,
+ 1001,
+ 1,
+ 6001,
+ 1,
+ '*',
+ 'OK',
+ 0,
+ ''
+ );
+
+INSERT INTO
+ db (
+ id,
+ creator_id,
+ updater_id,
+ workspace_id,
+ instance_id,
+ project_id,
+ name,
+ sync_status,
+ last_successful_sync_ts,
+ fingerprint
+ )
+VALUES
+ (
+ 7002,
+ 1001,
+ 1001,
+ 1,
+ 6002,
+ 1,
+ '*',
+ 'OK',
+ 0,
+ ''
+ );
+
+INSERT INTO
+ db (
+ id,
+ creator_id,
+ updater_id,
+ workspace_id,
+ instance_id,
+ project_id,
+ name,
+ sync_status,
+ last_successful_sync_ts,
+ fingerprint
+ )
+VALUES
+ (
+ 7003,
+ 1001,
+ 1001,
+ 1,
+ 6003,
+ 1,
+ '*',
+ 'OK',
+ 0,
+ ''
+ );
+
+INSERT INTO
+ db (
+ id,
+ creator_id,
+ updater_id,
+ workspace_id,
+ instance_id,
+ project_id,
+ name,
+ sync_status,
+ last_successful_sync_ts,
+ fingerprint
+ )
+VALUES
+ (
+ 7004,
+ 1001,
+ 1001,
+ 1,
+ 6004,
+ 1,
+ '*',
+ 'OK',
+ 0,
+ ''
+ );
+
+INSERT INTO
+ db (
+ id,
+ creator_id,
+ updater_id,
+ workspace_id,
+ instance_id,
+ project_id,
+ name,
+ sync_status,
+ last_successful_sync_ts,
+ fingerprint
+ )
+VALUES
+ (
+ 7005,
+ 1001,
+ 1001,
+ 1,
+ 6005,
+ 1,
+ '*',
+ 'OK',
+ 0,
+ ''
+ );
\ No newline at end of file
diff --git a/backend/store/seed/0080_data_source.sql b/backend/store/seed/0080_data_source.sql
new file mode 100644
index 0000000000..1b3ee7e253
--- /dev/null
+++ b/backend/store/seed/0080_data_source.sql
@@ -0,0 +1,134 @@
+INSERT INTO
+ data_source (
+ id,
+ creator_id,
+ updater_id,
+ workspace_id,
+ instance_id,
+ database_id,
+ name,
+ TYPE,
+ username,
+ PASSWORD
+ )
+VALUES
+ (
+ 8001,
+ 1,
+ 1,
+ 1,
+ 6001,
+ 7001,
+ 'Admin data source',
+ 'ADMIN',
+ 'admin1',
+ 'adminpwd1'
+ );
+
+INSERT INTO
+ data_source (
+ id,
+ creator_id,
+ updater_id,
+ workspace_id,
+ instance_id,
+ database_id,
+ name,
+ TYPE,
+ username,
+ PASSWORD
+ )
+VALUES
+ (
+ 8002,
+ 1,
+ 1,
+ 1,
+ 6002,
+ 7002,
+ 'Admin data source',
+ 'ADMIN',
+ 'admin2',
+ 'adminpwd2'
+ );
+
+INSERT INTO
+ data_source (
+ id,
+ creator_id,
+ updater_id,
+ workspace_id,
+ instance_id,
+ database_id,
+ name,
+ TYPE,
+ username,
+ PASSWORD
+ )
+VALUES
+ (
+ 8003,
+ 1,
+ 1,
+ 1,
+ 6003,
+ 7003,
+ 'Admin data source',
+ 'ADMIN',
+ 'admin3',
+ 'adminpwd3'
+ );
+
+INSERT INTO
+ data_source (
+ id,
+ creator_id,
+ updater_id,
+ workspace_id,
+ instance_id,
+ database_id,
+ name,
+ TYPE,
+ username,
+ PASSWORD
+ )
+VALUES
+ (
+ 8004,
+ 1,
+ 1,
+ 1,
+ 6004,
+ 7004,
+ 'Admin data source',
+ 'ADMIN',
+ 'admin4',
+ 'adminpwd4'
+ );
+
+INSERT INTO
+ data_source (
+ id,
+ creator_id,
+ updater_id,
+ workspace_id,
+ instance_id,
+ database_id,
+ name,
+ TYPE,
+ username,
+ PASSWORD
+ )
+VALUES
+ (
+ 8005,
+ 1,
+ 1,
+ 1,
+ 6005,
+ 7005,
+ 'Admin data source',
+ 'ADMIN',
+ 'admin5',
+ 'adminpwd5'
+ );
\ No newline at end of file
diff --git a/frontend/src/components/InstanceForm.vue b/frontend/src/components/InstanceForm.vue
index 6420c94101..f7e41b3279 100644
--- a/frontend/src/components/InstanceForm.vue
+++ b/frontend/src/components/InstanceForm.vue
@@ -276,7 +276,6 @@ import { instanceSlug, isDBAOrOwner } from "../utils";
import {
Instance,
InstanceCreate,
- DataSourceCreate,
UNKNOWN_ID,
Principal,
InstancePatch,
diff --git a/frontend/src/components/InstanceTable.vue b/frontend/src/components/InstanceTable.vue
index 77ffde818e..64566f3564 100644
--- a/frontend/src/components/InstanceTable.vue
+++ b/frontend/src/components/InstanceTable.vue
@@ -104,6 +104,8 @@ export default {
const clickInstance = function (section: number, row: number) {
const instance = props.instanceList[row];
+ console.log("aaa", instance);
+ console.log("slug", instanceSlug(instance));
router.push(`/instance/${instanceSlug(instance)}`);
};
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
index 63114ea2d5..c47a8a6d7b 100644
--- a/frontend/src/main.ts
+++ b/frontend/src/main.ts
@@ -99,9 +99,10 @@ axios.interceptors.request.use((request) => {
!request.url!.startsWith("/api/auth/signup") &&
!request.url!.startsWith("/api/principal") &&
!request.url!.startsWith("/api/member") &&
+ !request.url!.startsWith("/api/project") &&
!request.url!.startsWith("/api/environment") &&
!request.url!.startsWith("/api/instance") &&
- !request.url!.startsWith("/api/project"))
+ !request.url!.startsWith("/api/database"))
) {
request.url = request.url!.replace("/api", "/mock");
}
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index db05bceb38..cdd2426d9d 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -691,6 +691,7 @@ router.beforeEach((to, from, next) => {
name: "error.404",
replace: false,
});
+ throw error;
});
return;
}
@@ -710,6 +711,7 @@ router.beforeEach((to, from, next) => {
name: "error.404",
replace: false,
});
+ throw error;
});
return;
}
@@ -743,6 +745,7 @@ router.beforeEach((to, from, next) => {
name: "error.404",
replace: false,
});
+ throw error;
});
}
})
@@ -751,6 +754,7 @@ router.beforeEach((to, from, next) => {
name: "error.404",
replace: false,
});
+ throw error;
});
return;
}
@@ -766,6 +770,7 @@ router.beforeEach((to, from, next) => {
name: "error.404",
replace: false,
});
+ throw error;
});
return;
}
@@ -781,6 +786,7 @@ router.beforeEach((to, from, next) => {
name: "error.404",
replace: false,
});
+ throw error;
});
return;
}
diff --git a/frontend/src/store/modules/instance.ts b/frontend/src/store/modules/instance.ts
index a1b4a882bd..827ecc3a9b 100644
--- a/frontend/src/store/modules/instance.ts
+++ b/frontend/src/store/modules/instance.ts
@@ -187,7 +187,7 @@ const actions = {
const data = (
await axios.patch(`/api/instance/${instanceId}?include=dataSource`, {
data: {
- type: "instancepatch",
+ type: "instancePatch",
attributes: instancePatch,
},
})