Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: revert PR/5904 (#5910)
Danny Xu854108cc5bbb
diff --git a/backend/legacyapi/project.go b/backend/legacyapi/project.goindex 8b4d8e3f3e..76c1497fa2 100644--- a/backend/legacyapi/project.go+++ b/backend/legacyapi/project.go@@ -74,6 +74,9 @@ type Project struct {ResourceID string `jsonapi:"attr,resourceId"`RowStatus RowStatus `jsonapi:"attr,rowStatus"`+ // Related fields+ ProjectMemberList []*ProjectMember `jsonapi:"relation,projectMember"`+// Domain specific fieldsName string `jsonapi:"attr,name"`Key string `jsonapi:"attr,key"`diff --git a/backend/legacyapi/project_member.go b/backend/legacyapi/project_member.goindex 11170fa7ce..6d63219b1c 100644--- a/backend/legacyapi/project_member.go+++ b/backend/legacyapi/project_member.go@@ -4,6 +4,30 @@ import ("github.com/bytebase/bytebase/backend/common")+// ProjectMember is the API message for project members.+type ProjectMember struct {+ ID string `jsonapi:"primary,projectMember"`++ // Related fields+ // Just returns ProjectID otherwise would cause circular dependency.+ ProjectID int `jsonapi:"attr,projectId"`++ // Domain specific fields+ Role string `jsonapi:"attr,role"`+ Principal *Principal `jsonapi:"relation,principal"`+}++// ProjectMemberCreate is the API message for creating a project member.+type ProjectMemberCreate struct {+ Role common.ProjectRole `jsonapi:"attr,role"`+ PrincipalID int `jsonapi:"attr,principalId"`+}++// ProjectMemberPatch is the API message for patching a project member.+type ProjectMemberPatch struct {+ Role *string `jsonapi:"attr,role"`+}+// ProjectPermissionType is the type of a project permission.type ProjectPermissionType stringdiff --git a/backend/plugin/db/clickhouse/migrate.go b/backend/plugin/db/clickhouse/migrate.gonew file mode 100644index 0000000000..4cd4323362--- /dev/null+++ b/backend/plugin/db/clickhouse/migrate.go@@ -0,0 +1,63 @@+package clickhouse++import (+ "context"+ "fmt"++ "github.com/bytebase/bytebase/backend/plugin/db"+ "github.com/bytebase/bytebase/backend/plugin/db/util"+)++// FindMigrationHistoryList finds the migration history.+func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {+ baseQuery := `+ SELECT+ id,+ created_by,+ created_ts,+ updated_by,+ updated_ts,+ release_version,+ namespace,+ sequence,+ source,+ type,+ status,+ version,+ description,+ statement,+ ` + "`schema`," + `+ schema_prev,+ execution_duration_ns,+ issue_id,+ payload+ FROM bytebase.migration_history `+ paramNames, params := []string{}, []any{}+ if v := find.ID; v != nil {+ paramNames, params = append(paramNames, "id"), append(params, *v)+ }+ if v := find.Database; v != nil {+ paramNames, params = append(paramNames, "namespace"), append(params, *v)+ }+ if v := find.Version; v != nil {+ // TODO(d): support semantic versioning.+ storedVersion, err := util.ToStoredVersion(false, *v, "")+ if err != nil {+ return nil, err+ }+ paramNames, params = append(paramNames, "version"), append(params, storedVersion)+ }+ if v := find.Source; v != nil {+ paramNames, params = append(paramNames, "source"), append(params, *v)+ }+ var query = baseQuery ++ db.FormatParamNameInNumberedPosition(paramNames) ++ `ORDER BY id DESC`+ if v := find.Limit; v != nil {+ query += fmt.Sprintf(" LIMIT %d", *v)+ }+ if v := find.Offset; v != nil {+ query += fmt.Sprintf(" OFFSET %d", *v)+ }+ return util.FindMigrationHistoryList(ctx, query, params, driver.db)+}diff --git a/backend/plugin/db/mysql/migrate.go b/backend/plugin/db/mysql/migrate.gonew file mode 100644index 0000000000..8c4f5c2074--- /dev/null+++ b/backend/plugin/db/mysql/migrate.go@@ -0,0 +1,63 @@+package mysql++import (+ "context"+ "fmt"++ "github.com/bytebase/bytebase/backend/plugin/db"+ "github.com/bytebase/bytebase/backend/plugin/db/util"+)++// FindMigrationHistoryList finds the migration history.+func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {+ baseQuery := `+ SELECT+ id,+ created_by,+ created_ts,+ updated_by,+ updated_ts,+ release_version,+ namespace,+ sequence,+ source,+ type,+ status,+ version,+ description,+ statement,+ ` + "`schema`," + `+ schema_prev,+ execution_duration_ns,+ issue_id,+ payload+ FROM bytebase.migration_history `+ paramNames, params := []string{}, []any{}+ if v := find.ID; v != nil {+ paramNames, params = append(paramNames, "id"), append(params, *v)+ }+ if v := find.Database; v != nil {+ paramNames, params = append(paramNames, "namespace"), append(params, *v)+ }+ if v := find.Version; v != nil {+ // TODO(d): support semantic versioning.+ storedVersion, err := util.ToStoredVersion(false, *v, "")+ if err != nil {+ return nil, err+ }+ paramNames, params = append(paramNames, "version"), append(params, storedVersion)+ }+ if v := find.Source; v != nil {+ paramNames, params = append(paramNames, "source"), append(params, *v)+ }+ var query = baseQuery ++ db.FormatParamNameInQuestionMark(paramNames) ++ `ORDER BY id DESC`+ if v := find.Limit; v != nil {+ query += fmt.Sprintf(" LIMIT %d", *v)+ }+ if v := find.Offset; v != nil {+ query += fmt.Sprintf(" OFFSET %d", *v)+ }+ return util.FindMigrationHistoryList(ctx, query, params, driver.db)+}diff --git a/backend/server/server.go b/backend/server/server.goindex 981f7cac89..b9206aaa9a 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -29,6 +29,7 @@ import ("github.com/pkg/errors"scas "github.com/qiangmzsx/string-adapter/v2"echoSwagger "github.com/swaggo/echo-swagger"+ "go.uber.org/multierr""go.uber.org/zap""google.golang.org/grpc""google.golang.org/grpc/codes"@@ -78,11 +79,13 @@ import (storepb "github.com/bytebase/bytebase/proto/generated-go/store"// Register clickhouse driver.+ "github.com/bytebase/bytebase/backend/plugin/db/clickhouse"+ "github.com/bytebase/bytebase/backend/plugin/db/util"// Register mysql driver.-+ "github.com/bytebase/bytebase/backend/plugin/db/mysql"// Register postgres driver.-+ "github.com/bytebase/bytebase/backend/plugin/db/pg"// Register snowflake driver._ "github.com/bytebase/bytebase/backend/plugin/db/snowflake"// Register sqlite driver.@@ -646,6 +649,9 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {p := prometheus.NewPrometheus("api", nil)p.Use(e)+ // TODO: remove this on May 2023+ go s.backfillInstanceChangeHistory(ctx)+serverStarted = truereturn s, nil}@@ -1166,3 +1172,180 @@ Click "Approve" button to apply the schema update.`,return nil}++func (s *Server) backfillInstanceChangeHistory(ctx context.Context) {+ err := func() error {+ migratedInstanceList, err := s.store.ListInstanceHavingInstanceChangeHistory(ctx)+ if err != nil {+ return err+ }+ instanceMigrated := make(map[int]bool)+ for _, id := range migratedInstanceList {+ instanceMigrated[id] = true+ }++ instanceList, err := s.store.ListInstancesV2(ctx, &store.FindInstanceMessage{})+ if err != nil {+ return err+ }++ issueList, err := s.store.ListIssueV2(ctx, &store.FindIssueMessage{})+ if err != nil {+ return err+ }+ hasIssueID := make(map[int]bool)+ for _, issue := range issueList {+ hasIssueID[issue.UID] = true+ }++ principalList, err := s.store.GetPrincipalList(ctx)+ if err != nil {+ return err+ }+ nameToPrincipal := make(map[string]*api.Principal)+ for _, principal := range principalList {+ nameToPrincipal[principal.Name] = principal+ }++ var errList error+ for _, instance := range instanceList {+ err := func(instance *store.InstanceMessage) error {+ limit := 10+ offset := 0++ if !(instance.Engine == db.MySQL || instance.Engine == db.Postgres || instance.Engine == db.ClickHouse) {+ return nil+ }+ if instanceMigrated[instance.UID] {+ return nil+ }++ databaseList, err := s.store.ListDatabases(ctx, &store.FindDatabaseMessage{InstanceID: &instance.ResourceID, ShowDeleted: true})+ if err != nil {+ return err+ }+ nameToDatabase := make(map[string]*store.DatabaseMessage)+ for i, db := range databaseList {+ nameToDatabase[db.DatabaseName] = databaseList[i]+ }++ driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "bytebase")+ if err != nil {+ return err+ }+ defer driver.Close(ctx)++ for {+ var history []*db.MigrationHistory+ if instance.Engine == db.MySQL {+ myDriver := driver.(*mysql.Driver)+ history, err = myDriver.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{+ InstanceID: &instance.UID,+ Limit: &limit,+ Offset: &offset,+ })+ if err != nil {+ return err+ }+ } else if instance.Engine == db.Postgres {+ pgDriver := driver.(*pg.Driver)+ history, err = pgDriver.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{+ InstanceID: &instance.UID,+ Limit: &limit,+ Offset: &offset,+ })+ if err != nil {+ return err+ }+ } else if instance.Engine == db.ClickHouse {+ cDriver := driver.(*clickhouse.Driver)+ history, err = cDriver.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{+ InstanceID: &instance.UID,+ Limit: &limit,+ Offset: &offset,+ })+ if err != nil {+ return err+ }+ }+ if len(history) == 0 {+ break+ }+ offset += limit++ var creates []*store.InstanceChangeHistoryMessage+ for _, h := range history {+ var databaseID *int+ if database, ok := nameToDatabase[h.Namespace]; ok {+ databaseID = &database.UID+ }++ var issueID *int+ if id, err := strconv.Atoi(h.IssueID); err != nil {+ errList = multierr.Append(errList, err)+ } else if hasIssueID[id] {+ // Has FK constraint on issue_id.+ // Set to id if issue exists.+ issueID = &id+ }++ creatorID := api.SystemBotID+ updaterID := api.SystemBotID+ if principal, ok := nameToPrincipal[h.Creator]; ok {+ creatorID = principal.ID+ }+ if principal, ok := nameToPrincipal[h.Updater]; ok {+ updaterID = principal.ID+ }++ storedVersion, err := util.ToStoredVersion(h.UseSemanticVersion, h.Version, h.SemanticVersionSuffix)+ if err != nil {+ return err+ }++ changeHistory := store.InstanceChangeHistoryMessage{+ CreatorID: creatorID,+ CreatedTs: h.CreatedTs,+ UpdaterID: updaterID,+ UpdatedTs: h.UpdatedTs,+ InstanceID: &instance.UID,+ DatabaseID: databaseID,+ IssueID: issueID,+ ReleaseVersion: h.ReleaseVersion,+ Sequence: int64(h.Sequence),+ Source: h.Source,+ Type: h.Type,+ Status: h.Status,+ Version: storedVersion,+ Description: h.Description,+ Statement: h.Statement,+ Schema: h.Schema,+ SchemaPrev: h.SchemaPrev,+ ExecutionDurationNs: h.ExecutionDurationNs,+ Payload: h.Payload,+ }++ creates = append(creates, &changeHistory)+ }++ if _, err := s.store.CreateInstanceChangeHistory(ctx, creates...); err != nil {+ return err+ }+ }+ return nil+ }(instance)+ if err != nil {+ // New instances may not have the "bytebase" database.+ if strings.Contains(err.Error(), "database \"bytebase\" does not exist") {+ return nil+ }+ errList = multierr.Append(errList, err)+ }+ }+ return errList+ }()++ if err != nil {+ log.Warn("failed to backfill migration history", zap.Error(err))+ }+}diff --git a/backend/store/instance_change_history.go b/backend/store/instance_change_history.goindex 4796a99caf..664358f09e 100644--- a/backend/store/instance_change_history.go+++ b/backend/store/instance_change_history.go@@ -510,3 +510,32 @@ func (s *Store) CreatePendingInstanceChangeHistory(ctx context.Context, prevSchereturn list[0].ID, nil}++// ListInstanceHavingInstanceChangeHistory finds the instance id lists that have instance change history.+func (s *Store) ListInstanceHavingInstanceChangeHistory(ctx context.Context) ([]int, error) {+ query := `+ SELECT DISTINCT+ instance_id+ FROM instance_change_history+ WHERE instance_id IS NOT NULL+ `+ rows, err := s.db.db.QueryContext(ctx, query)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var list []int+ for rows.Next() {+ var id int+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ list = append(list, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }++ return list, nil+}diff --git a/backend/store/project.go b/backend/store/project.goindex cfc2dbb2e2..63911ee9a0 100644--- a/backend/store/project.go+++ b/backend/store/project.go@@ -21,7 +21,7 @@ func (s *Store) GetProjectByID(ctx context.Context, id int) (*api.Project, errorif project == nil {return nil, nil}- composedProject, err := composeProject(project)+ composedProject, err := s.composeProject(ctx, project)if err != nil {return nil, errors.Wrapf(err, "failed to compose Project with projectRaw[%+v]", project)}@@ -37,7 +37,7 @@ func (s *Store) FindProject(ctx context.Context, find *api.ProjectFind) ([]*api.}var composedProjects []*api.Projectfor _, project := range projects {- composedProject, err := composeProject(project)+ composedProject, err := s.composeProject(ctx, project)if err != nil {return nil, errors.Wrapf(err, "failed to compose Project with projectRaw[%+v]", project)}@@ -83,14 +83,14 @@ func (s *Store) PatchProject(ctx context.Context, patch *api.ProjectPatch) (*apiif err != nil {return nil, errors.Wrapf(err, "failed to patch Project with ProjectPatch %#v", patch)}- composedProject, err := composeProject(project)+ composedProject, err := s.composeProject(ctx, project)if err != nil {return nil, errors.Wrapf(err, "failed to compose Project with projectRaw[%+v]", project)}return composedProject, nil}-func composeProject(project *ProjectMessage) (*api.Project, error) {+func (s *Store) composeProject(ctx context.Context, project *ProjectMessage) (*api.Project, error) {composedProject := &api.Project{ID: project.UID,ResourceID: project.ResourceID,@@ -106,6 +106,26 @@ func composeProject(project *ProjectMessage) (*api.Project, error) {if project.Deleted {composedProject.RowStatus = api.Archived}++ policy, err := s.GetProjectPolicy(ctx, &GetProjectPolicyMessage{ProjectID: &project.ResourceID})+ if err != nil {+ return nil, err+ }+ for _, binding := range policy.Bindings {+ for _, member := range binding.Members {+ principal, err := s.GetPrincipalByID(ctx, member.ID)+ if err != nil {+ return nil, err+ }++ composedProject.ProjectMemberList = append(composedProject.ProjectMemberList, &api.ProjectMember{+ ID: fmt.Sprintf("projects/%s/roles/%s/principals/%d", project.ResourceID, binding.Role, principal.ID),+ ProjectID: project.UID,+ Role: string(binding.Role),+ Principal: principal,+ })+ }+ }return composedProject, nil}