Skip to content

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

chore: azure pr comment (#11492)

ecmadao7ecf7936303e
diff --git a/backend/api/gitops/webhook.go b/backend/api/gitops/webhook.go
index f26e2c7e81..2f4534fe89 100644
--- a/backend/api/gitops/webhook.go
+++ b/backend/api/gitops/webhook.go
@@ -149,15 +149,13 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {
if err != nil {
return c.String(http.StatusOK, fmt.Sprintf("failed to create issue from pull request %s, error %v", prInfo.url, err))
}
- if vcsProvider.Type == storepb.VCSType_GITHUB || vcsProvider.Type == storepb.VCSType_GITLAB || vcsProvider.Type == storepb.VCSType_BITBUCKET {
- comment := getPullRequestComment(setting.ExternalUrl, issue.Name)
- pullRequestID := getPullRequestID(prInfo.url)
- if err := vcs.Get(
- vcsProvider.Type,
- vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken},
- ).CreatePullRequestComment(ctx, vcsConnector.Payload.ExternalId, pullRequestID, comment); err != nil {
- return c.String(http.StatusOK, fmt.Sprintf("failed to create pull request comment, error %v", err))
- }
+ comment := getPullRequestComment(setting.ExternalUrl, issue.Name)
+ pullRequestID := getPullRequestID(prInfo.url)
+ if err := vcs.Get(
+ vcsProvider.Type,
+ vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken},
+ ).CreatePullRequestComment(ctx, vcsConnector.Payload.ExternalId, pullRequestID, comment); err != nil {
+ return c.String(http.StatusOK, fmt.Sprintf("failed to create pull request comment, error %v", err))
}
return nil
})
diff --git a/backend/api/v1/vcs_provider_service.go b/backend/api/v1/vcs_provider_service.go
index fae7c9aa0c..10b827228d 100644
--- a/backend/api/v1/vcs_provider_service.go
+++ b/backend/api/v1/vcs_provider_service.go
@@ -11,6 +11,7 @@ import (
"google.golang.org/protobuf/types/known/emptypb"
"github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/component/config"
"github.com/bytebase/bytebase/backend/plugin/vcs"
"github.com/bytebase/bytebase/backend/store"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
@@ -20,12 +21,13 @@ import (
// VCSProviderService represents a service for managing vcs provider.
type VCSProviderService struct {
v1pb.UnimplementedVCSProviderServiceServer
- store *store.Store
+ store *store.Store
+ profile *config.Profile
}
// NewVCSProviderService returns a new instance of VCSProviderService.
-func NewVCSProviderService(store *store.Store) *VCSProviderService {
- return &VCSProviderService{store: store}
+func NewVCSProviderService(store *store.Store, profile *config.Profile) *VCSProviderService {
+ return &VCSProviderService{store: store, profile: profile}
}
// GetVCSProvider get a single vcs provider.
@@ -64,6 +66,16 @@ func (s *VCSProviderService) CreateVCSProvider(ctx context.Context, request *v1p
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, err.Error())
}
+ // TODO(ed): add test and remove this
+ if s.profile.Mode != common.ReleaseModeDev {
+ if _, err := vcs.Get(
+ vcsProvider.Type,
+ vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken},
+ ).FetchRepositoryList(ctx, false); err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, "failed to fetch repositories, please check if the token has right permissions: %v", err)
+ }
+ }
+
principalID, ok := ctx.Value(common.PrincipalIDContextKey).(int)
if !ok {
return nil, status.Errorf(codes.Internal, "principal ID not found")
@@ -98,6 +110,16 @@ func (s *VCSProviderService) UpdateVCSProvider(ctx context.Context, request *v1p
return nil, status.Errorf(codes.InvalidArgument, "secret should not be empty")
}
update.AccessToken = &request.VcsProvider.AccessToken
+ // TODO(ed): add test and remove this
+ if s.profile.Mode != common.ReleaseModeDev {
+ vcsProvider.AccessToken = request.VcsProvider.AccessToken
+ if _, err := vcs.Get(
+ vcsProvider.Type,
+ vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken},
+ ).FetchRepositoryList(ctx, false); err != nil {
+ return nil, status.Errorf(codes.InvalidArgument, "failed to fetch repositories, please check if the token has right permissions: %v", err)
+ }
+ }
}
}
@@ -135,7 +157,7 @@ func (s *VCSProviderService) SearchVCSProviderRepositories(ctx context.Context,
apiExternalProjectList, err := vcs.Get(
vcsProvider.Type,
vcs.ProviderConfig{InstanceURL: vcsProvider.InstanceURL, AuthToken: vcsProvider.AccessToken},
- ).FetchAllRepositoryList(ctx)
+ ).FetchRepositoryList(ctx, true)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to fetch external project list: %v", err)
}
diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.go
index e915f3c79a..7c2413df33 100644
--- a/backend/plugin/vcs/azure/azure.go
+++ b/backend/plugin/vcs/azure/azure.go
@@ -119,7 +119,7 @@ func (p *Provider) getChangesByCommit(ctx context.Context, externalRepositoryID,
return &result, nil
}
-// FetchAllRepositoryList fetches all projects where the authenticated use has permissions, which is required
+// FetchRepositoryList fetches all projects where the authenticated use has permissions, which is required
// to create webhook in the repository.
//
// NOTE: Azure DevOps does not support listing all projects cross all organizations API yet, thus we need
@@ -128,7 +128,7 @@ func (p *Provider) getChangesByCommit(ctx context.Context, externalRepositoryID,
// The request included in this function requires the following scopes:
// vso.profile, vso.project.
// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/repositories/list?view=azure-devops-rest-7.0&tabs=HTTP
-func (p *Provider) FetchAllRepositoryList(ctx context.Context) ([]*vcs.Repository, error) {
+func (p *Provider) FetchRepositoryList(ctx context.Context, listAll bool) ([]*vcs.Repository, error) {
publicAlias, err := p.getAuthenticatedProfilePublicAlias(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to get authenticated profile public alias")
@@ -187,6 +187,9 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context) ([]*vcs.Repositor
}(); err != nil {
return nil, errors.Wrapf(err, "failed to list repositories under the organization %s", organization)
}
+ if !listAll {
+ break
+ }
}
// Sort result by FullPath.
@@ -369,8 +372,51 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, repositoryID, lastMe
return files, nil
}
+type Comment struct {
+ Content string `json:"content"`
+ CommentType string `json:"commentType"`
+}
+
+type PullRequestThread struct {
+ Comments []*Comment `json:"comments"`
+ Status string `json:"status"`
+}
+
// CreatePullRequestComment creates a pull request comment.
-func (*Provider) CreatePullRequestComment(_ context.Context, _, _, _ string) error {
+// We will create a thread in Azure pull request instead of a comment.
+//
+// Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-request-threads/create?view=azure-devops-rest-7.1&tabs=HTTP
+func (p *Provider) CreatePullRequestComment(ctx context.Context, repositoryID, pullRequestID, comment string) error {
+ thread := &PullRequestThread{
+ Status: "active",
+ Comments: []*Comment{
+ {
+ Content: comment,
+ CommentType: "text",
+ },
+ },
+ }
+ commentCreatePayload, err := json.Marshal(thread)
+ if err != nil {
+ return errors.Wrap(err, "failed to marshal request body for creating pull request comment")
+ }
+
+ apiURL, err := getRepositoryAPIURL(repositoryID)
+ if err != nil {
+ return err
+ }
+
+ values := &url.Values{}
+ values.Set("api-version", "7.0")
+ url := fmt.Sprintf("%s/pullRequests/%s/threads?%s", apiURL, pullRequestID, values.Encode())
+ code, body, err := internal.Post(ctx, url, p.getAuthorization(), commentCreatePayload)
+ if err != nil {
+ return errors.Wrapf(err, "POST %s", url)
+ }
+ if code != http.StatusOK {
+ return errors.Errorf("failed to create thread, code: %v, body: %s", code, string(body))
+ }
+
return nil
}
diff --git a/backend/plugin/vcs/bitbucket/bitbucket.go b/backend/plugin/vcs/bitbucket/bitbucket.go
index d51ea04c5a..95b7626741 100644
--- a/backend/plugin/vcs/bitbucket/bitbucket.go
+++ b/backend/plugin/vcs/bitbucket/bitbucket.go
@@ -133,11 +133,11 @@ type RepositoryPermission struct {
Repository Repository `json:"repository"`
}
-// FetchAllRepositoryList fetches all repositories where the authenticated user
+// FetchRepositoryList fetches all repositories where the authenticated user
// has admin permissions, which is required to create webhook in the repository.
//
// Docs: https://developer.atlassian.com/cloud/bitbucket/rest/api-group-repositories/#api-user-permissions-repositories-get
-func (p *Provider) FetchAllRepositoryList(ctx context.Context) ([]*vcs.Repository, error) {
+func (p *Provider) FetchRepositoryList(ctx context.Context, listAll bool) ([]*vcs.Repository, error) {
var bbcRepos []*Repository
params := url.Values{}
params.Add("q", `permission="admin"`)
@@ -151,6 +151,9 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context) ([]*vcs.Repositor
return nil, errors.Wrap(err, "fetch paginated list")
}
bbcRepos = append(bbcRepos, repos...)
+ if !listAll {
+ break
+ }
}
var repos []*vcs.Repository
diff --git a/backend/plugin/vcs/github/github.go b/backend/plugin/vcs/github/github.go
index 3d8b9e0347..cdad12c890 100644
--- a/backend/plugin/vcs/github/github.go
+++ b/backend/plugin/vcs/github/github.go
@@ -143,7 +143,7 @@ type CommitsDiff struct {
Files []PullRequestFile `json:"files"`
}
-// FetchAllRepositoryList fetches all repositories where the authenticated user
+// FetchRepositoryList fetches all repositories where the authenticated user
// has admin permissions, which is required to create webhook in the repository.
//
// NOTE: GitHub API does not provide a native filter for admin permissions, thus
@@ -151,7 +151,7 @@ type CommitsDiff struct {
// the `permissions.admin` field.
//
// Docs: https://docs.github.com/en/rest/repos/repos#list-repositories-for-the-authenticated-user
-func (p *Provider) FetchAllRepositoryList(ctx context.Context) ([]*vcs.Repository, error) {
+func (p *Provider) FetchRepositoryList(ctx context.Context, listAll bool) ([]*vcs.Repository, error) {
var githubRepos []Repository
page := 1
for {
@@ -161,7 +161,7 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context) ([]*vcs.Repositor
}
githubRepos = append(githubRepos, repos...)
- if !hasNextPage {
+ if !hasNextPage || !listAll {
break
}
page++
diff --git a/backend/plugin/vcs/gitlab/gitlab.go b/backend/plugin/vcs/gitlab/gitlab.go
index e31091ce5b..a8f7688b32 100644
--- a/backend/plugin/vcs/gitlab/gitlab.go
+++ b/backend/plugin/vcs/gitlab/gitlab.go
@@ -164,11 +164,11 @@ func (*Provider) APIURL(instanceURL string) string {
return fmt.Sprintf("%s/%s", instanceURL, apiPath)
}
-// FetchAllRepositoryList fetches all repositories where the authenticated user
+// FetchRepositoryList fetches all repositories where the authenticated user
// has a maintainer role, which is required to create webhook in the project.
//
// Docs: https://docs.gitlab.com/ee/api/projects.html#list-all-projects
-func (p *Provider) FetchAllRepositoryList(ctx context.Context) ([]*vcs.Repository, error) {
+func (p *Provider) FetchRepositoryList(ctx context.Context, listAll bool) ([]*vcs.Repository, error) {
var gitlabRepos []gitLabRepository
page := 1
for {
@@ -178,7 +178,7 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context) ([]*vcs.Repositor
}
gitlabRepos = append(gitlabRepos, repos...)
- if !hasNextPage {
+ if !hasNextPage || !listAll {
break
}
page++
diff --git a/backend/plugin/vcs/vcs.go b/backend/plugin/vcs/vcs.go
index 37fc29a4ef..93e060af5f 100644
--- a/backend/plugin/vcs/vcs.go
+++ b/backend/plugin/vcs/vcs.go
@@ -73,8 +73,8 @@ type Provider interface {
// Returns the API URL for a given VCS instance URL
APIURL(instanceURL string) string
- // Fetch all repository within a given user's scope
- FetchAllRepositoryList(ctx context.Context) ([]*Repository, error)
+ // Fetch repositories within a given user's scope
+ FetchRepositoryList(ctx context.Context, listAll bool) ([]*Repository, error)
// Reads the file content
ReadFileContent(ctx context.Context, repositoryID, filePath string, refInfo RefInfo) (string, error)
diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.go
index 31862621e8..7399c6a300 100644
--- a/backend/server/grpc_routes.go
+++ b/backend/server/grpc_routes.go
@@ -75,7 +75,7 @@ func configureGrpcRouters(
v1pb.RegisterSettingServiceServer(grpcServer, apiv1.NewSettingService(stores, profile, licenseService, stateCfg))
v1pb.RegisterAnomalyServiceServer(grpcServer, apiv1.NewAnomalyService(stores))
v1pb.RegisterSQLServiceServer(grpcServer, apiv1.NewSQLService(stores, schemaSyncer, dbFactory, activityManager, licenseService, profile, iamManager))
- v1pb.RegisterVCSProviderServiceServer(grpcServer, apiv1.NewVCSProviderService(stores))
+ v1pb.RegisterVCSProviderServiceServer(grpcServer, apiv1.NewVCSProviderService(stores, profile))
v1pb.RegisterRiskServiceServer(grpcServer, apiv1.NewRiskService(stores, licenseService))
issueService := apiv1.NewIssueService(stores, activityManager, relayRunner, stateCfg, licenseService, profile, iamManager, metricReporter)
v1pb.RegisterIssueServiceServer(grpcServer, issueService)
diff --git a/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue b/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
index 8e68bdb50d..fb4e78ef90 100644
--- a/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
+++ b/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
@@ -84,6 +84,7 @@ import { Status } from "nice-grpc-web";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import ExprEditor from "@/components/ExprEditor";
+import { DatabaseGroupSelect } from "@/components/v2/Select";
import type { ConditionGroupExpr } from "@/plugins/cel";
import { emptySimpleExpr, wrapAsGroup } from "@/plugins/cel";
import { useDBGroupStore, useSubscriptionV1Store } from "@/store";
@@ -109,7 +110,6 @@ import type {
import { convertCELStringToExpr } from "@/utils/databaseGroup/cel";
import { getErrorCode } from "@/utils/grpcweb";
import { EnvironmentSelect, ProjectSelect, ResourceIdField } from "../v2";
-import DatabaseGroupSelect from "./DatabaseGroupSelect.vue";
import MatchedDatabaseView from "./MatchedDatabaseView.vue";
import MatchedTableView from "./MatchedTableView.vue";
import type { ResourceType } from "./utils";
diff --git a/frontend/src/components/DatabaseGroup/DatabaseGroupSelect.vue b/frontend/src/components/DatabaseGroup/DatabaseGroupSelect.vue
deleted file mode 100644
index bde2c6165a..0000000000
--- a/frontend/src/components/DatabaseGroup/DatabaseGroupSelect.vue
+++ /dev/null
@@ -1,79 +0,0 @@
-<template>
- <NSelect
- :value="state.selectedDatabaseGroup"
- :options="dbGroupOptions"
- :disabled="disabled"
- :placeholder="'Select Database Group'"
- @update:value="$emit('update:selected', $event)"
- />
-</template>
-
-<script lang="ts" setup>
-import { head } from "lodash-es";
-import type { SelectOption } from "naive-ui";
-import { computed, reactive, watch } from "vue";
-import { useDBGroupStore } from "@/store";
-import type { DatabaseGroup } from "@/types/proto/v1/project_service";
-
-interface LocalState {
- selectedDatabaseGroup?: string;
-}
-
-const props = defineProps<{
- project: string;
- selected?: string;
- environment?: string;
- disabled?: boolean;
-}>();
-
-const emit = defineEmits<{
- (event: "update:selected", name: string | undefined): void;
-}>();
-
-const state = reactive<LocalState>({
- selectedDatabaseGroup: undefined,
-});
-
-const dbGroupStore = useDBGroupStore();
-
-const dbGroupList = computed(() => {
- return dbGroupStore
- .getDBGroupListByProjectName(props.project)
- .filter((dbGroup) =>
- props.environment ? dbGroup.environment.uid === props.environment : true
- );
-});
-const dbGroupOptions = computed(() => {
- return dbGroupList.value.map<SelectOption>((dbGroup) => ({
- value: dbGroup.name,
- label: dbGroup.databaseGroupName,
- }));
-});
-
-const invalidateSelectionIfNeeded = () => {
- if (
- state.selectedDatabaseGroup &&
- !dbGroupList.value.find(
- (item: DatabaseGroup) => item.name == state.selectedDatabaseGroup
- )
- ) {
- state.selectedDatabaseGroup = undefined;
- emit("update:selected", undefined);
- }
-};
-
-watch(
- [() => props.project, () => props.selected, () => props.environment],
- () => {
- invalidateSelectionIfNeeded();
- state.selectedDatabaseGroup = dbGroupList.value.find(
- (item) => item.name === props.selected
- )?.name;
- if (!state.selectedDatabaseGroup) {
- state.selectedDatabaseGroup = head(dbGroupList.value)?.name;
- }
- emit("update:selected", state.selectedDatabaseGroup);
- },
- { immediate: true, deep: true }
-);
-</script>
diff --git a/frontend/src/components/RepositoryForm.vue b/frontend/src/components/RepositoryForm.vue
index bc90d0c991..e2c3f0c9c9 100644
--- a/frontend/src/components/RepositoryForm.vue
+++ b/frontend/src/components/RepositoryForm.vue
@@ -56,10 +56,12 @@
</div>
<!-- TODO(ed): i18n -->
<DatabaseGroupSelect
- v-model:value="repositoryConfig.databaseGroup"
+ v-model:selected="repositoryConfig.databaseGroup"
class="mt-2"
style="width: 100%"
:project="project.name"
+ :clearable="true"
+ :select-first-as-default="false"
/>
</div>
<div>
diff --git a/frontend/src/components/RepositoryPanel.vue b/frontend/src/components/RepositoryPanel.vue
index 301839c3a2..33fd91f1f8 100644
--- a/frontend/src/components/RepositoryPanel.vue
+++ b/frontend/src/components/RepositoryPanel.vue
@@ -48,13 +48,18 @@
@confirm="deleteConnector"
/>
<div v-if="allowEdit" class="ml-3 flex items-center space-x-3">
- <NButton @click.prevent="$emit('cancel')">
- {{ $t("common.cancel") }}
+ <NButton
+ v-if="allowUpdate"
+ @click.prevent="discardChanges"
+ :disabled="state.processing"
+ >
+ {{ $t("common.discard-changes") }}
</NButton>
<NButton
type="primary"
:disabled="!allowUpdate"
@click.prevent="doUpdate"
+ :loading="state.processing"
>
{{ $t("common.update") }}
</NButton>
@@ -95,25 +100,25 @@ const emit = defineEmits<{
const vcsV1Store = useVCSProviderStore();
const vcsConnectorStore = useVCSConnectorStore();
+const initConfig = computed(
+ (): RepositoryConfig => ({
+ resourceId: getVCSConnectorId(props.vcsConnector.name).vcsConnectorId,
+ baseDirectory: props.vcsConnector.baseDirectory,
+ branch: props.vcsConnector.branch,
+ databaseGroup: props.vcsConnector.databaseGroup,
+ })
+);
+
const state = reactive<LocalState>({
- repositoryConfig: {
- resourceId: "",
- baseDirectory: "",
- branch: "",
- databaseGroup: "",
- },
+ repositoryConfig: initConfig.value,
processing: false,
});
watch(
() => props.vcsConnector,
- (cur) => {
- state.repositoryConfig = {
- resourceId: getVCSConnectorId(props.vcsConnector.name).vcsConnectorId,
- baseDirectory: cur.baseDirectory,
- branch: cur.branch,
- databaseGroup: cur.databaseGroup,
- };
+ () => {
+ state.repositoryConfig = initConfig.value;
+ state.processing = false;
},
{ deep: true, immediate: true }
);
@@ -146,7 +151,6 @@ const repositoryInfo = computed((): VCSRepository => {
const allowUpdate = computed(() => {
return (
- !state.processing &&
!isEmpty(state.repositoryConfig.branch) &&
(props.vcsConnector.branch !== state.repositoryConfig.branch ||
props.vcsConnector.baseDirectory !==
@@ -169,6 +173,11 @@ const deleteConnector = async () => {
}
};
+const discardChanges = () => {
+ state.repositoryConfig = initConfig.value;
+ state.processing = false;
+};
+
const doUpdate = async () => {
if (state.processing) {
return;
diff --git a/frontend/src/components/VCS/VCSProviderBasicInfoPanel.vue b/frontend/src/components/VCS/VCSProviderBasicInfoPanel.vue
index baeb00e161..790b59535e 100644
--- a/frontend/src/components/VCS/VCSProviderBasicInfoPanel.vue
+++ b/frontend/src/components/VCS/VCSProviderBasicInfoPanel.vue
@@ -164,7 +164,7 @@
</ul>
<BBTextField
class="mt-2 w-full"
- :required="true"
+ :required="create"
:placeholder="accessTokenPlaceholder"
:value="config.accessToken"
@update:value="changeAccessToken($event)"
diff --git a/frontend/src/components/v2/Select/DatabaseGroupSelect.vue b/frontend/src/components/v2/Select/DatabaseGroupSelect.vue
index cd6d08a395..28dafbbeba 100644
--- a/frontend/src/components/v2/Select/DatabaseGroupSelect.vue
+++ b/frontend/src/components/v2/Select/DatabaseGroupSelect.vue
@@ -1,99 +1,88 @@
<template>
<NSelect
- :value="value ?? null"
- :options="options"
- :placeholder="placeholder ?? $t('database-group.select')"
- :virtual-scroll="true"
- :filter="filterByName"
- :filterable="true"
- class="bb-databaseGroup-select"
- style="width: 12rem"
- v-bind="$attrs"
- :render-label="renderLabel"
- @update:value="$emit('update:value', $event)"
+ :value="state.selectedDatabaseGroup"
+ :options="dbGroupOptions"
+ :disabled="disabled"
+ :clearable="clearable"
+ :placeholder="'Select Database Group'"
+ @update:value="$emit('update:selected', $event)"
/>
</template>
<script lang="ts" setup>
-import type { SelectOption, SelectRenderLabel } from "naive-ui";
-import { NSelect } from "naive-ui";
-import { computed, h, watch } from "vue";
-import { useSlots } from "vue";
+import { head } from "lodash-es";
+import type { SelectOption } from "naive-ui";
+import { computed, reactive, watch } from "vue";
import { useDBGroupStore } from "@/store";
-import type { ComposedDatabaseGroup } from "@/types";
+import type { DatabaseGroup } from "@/types/proto/v1/project_service";
-interface DatabaseGroupSelectOption extends SelectOption {
- value: string;
- databaseGroup: ComposedDatabaseGroup;
+interface LocalState {
+ selectedDatabaseGroup?: string;
}
-const slots = useSlots();
const props = withDefaults(
defineProps<{
- value?: string;
project: string;
- placeholder?: string;
+ selected?: string;
+ environment?: string;
+ disabled?: boolean;
+ clearable?: boolean;
+ selectFirstAsDefault?: boolean;
}>(),
{
- value: undefined,
- project: undefined,
- placeholder: undefined,
+ clearable: false,
+ selectFirstAsDefault: true,
}
);
-defineEmits<{
- (event: "update:value", value: string | undefined): void;
+const emit = defineEmits<{
+ (event: "update:selected", name: string | undefined): void;
}>();
-const dbGroupStore = useDBGroupStore();
-
-const databaseGroupList = computed(() => {
- return dbGroupStore.getDBGroupListByProjectName(props.project);
+const state = reactive<LocalState>({
+ selectedDatabaseGroup: undefined,
});
-watch(
- () => props.project,
- async (project) =>
- await dbGroupStore.getOrFetchDBGroupListByProjectName(project),
- { immediate: true }
-);
-
-const filterByName = (pattern: string, option: SelectOption) => {
- const { databaseGroup } = option as DatabaseGroupSelectOption;
- return databaseGroup.databaseGroupName
- .toLowerCase()
- .includes(pattern.toLowerCase());
-};
+const dbGroupStore = useDBGroupStore();
-const options = computed(() => {
- return databaseGroupList.value.map<DatabaseGroupSelectOption>(
- (databaseGroup) => {
- return {
- databaseGroup,
- value: databaseGroup.name,
- label: databaseGroup.databaseGroupName,
- };
- }
- );
+const dbGroupList = computed(() => {
+ return dbGroupStore
+ .getDBGroupListByProjectName(props.project)
+ .filter((dbGroup) =>
+ props.environment ? dbGroup.environment.uid === props.environment : true
+ );
+});
+const dbGroupOptions = computed(() => {
+ return dbGroupList.value.map<SelectOption>((dbGroup) => ({
+ value: dbGroup.name,
+ label: dbGroup.databaseGroupName,
+ }));
});
-const renderLabel: SelectRenderLabel = (option) => {
- const { databaseGroup } = option as DatabaseGroupSelectOption;
- if (!databaseGroup) {
- return;
- }
-
- if (slots.default) {
- return slots.default({ databaseGroup });
+const invalidateSelectionIfNeeded = () => {
+ if (
+ state.selectedDatabaseGroup &&
+ !dbGroupList.value.find(
+ (item: DatabaseGroup) => item.name == state.selectedDatabaseGroup
+ )
+ ) {
+ state.selectedDatabaseGroup = undefined;
+ emit("update:selected", undefined);
}
-
- const children = [h("div", {}, [databaseGroup.databaseGroupName])];
- return h(
- "div",
- {
- class: "w-full flex flex-row justify-start items-center truncate",
- },
- children
- );
};
+
+watch(
+ [() => props.project, () => props.selected, () => props.environment],
+ () => {
+ invalidateSelectionIfNeeded();
+ state.selectedDatabaseGroup = dbGroupList.value.find(
+ (item) => item.name === props.selected
+ )?.name;
+ if (!state.selectedDatabaseGroup && props.selectFirstAsDefault) {
+ state.selectedDatabaseGroup = head(dbGroupList.value)?.name;
+ }
+ emit("update:selected", state.selectedDatabaseGroup);
+ },
+ { immediate: true, deep: true }
+);
</script>
diff --git a/frontend/src/views/SettingWorkspaceVCSDetail.vue b/frontend/src/views/SettingWorkspaceVCSDetail.vue
index 8a9d623733..62f1e7b522 100644
--- a/frontend/src/views/SettingWorkspaceVCSDetail.vue
+++ b/frontend/src/views/SettingWorkspaceVCSDetail.vue
@@ -24,13 +24,18 @@
</div>
</template>
<div class="space-x-3">
- <NButton v-if="allowUpdate" @click.prevent="cancel">
- {{ $t("common.cancel") }}
+ <NButton
+ v-if="allowUpdate"
+ @click.prevent="cancel"
+ :disabled="state.loading"
+ >
+ {{ $t("common.discard-changes") }}
</NButton>
<NButton
type="primary"
:disabled="!allowUpdate"
@click.prevent="doUpdate"
+ :loading="state.loading"
>
{{ $t("common.update") }}
</NButton>
@@ -67,6 +72,7 @@ import { hasWorkspacePermissionV2 } from "@/utils";
interface LocalState {
config: VCSConfig;
+ loading: boolean;
}
const props = defineProps<{
@@ -99,6 +105,7 @@ const resetState = () => {
const state = reactive<LocalState>({
config: initState.value,
+ loading: false,
});
const hasUpdateVCSPermission = computed(() => {
@@ -142,10 +149,12 @@ const allowUpdate = computed(() => {
);
});
-const doUpdate = () => {
+const doUpdate = async () => {
if (!vcs.value) {
return;
}
+ state.loading = true;
+
const vcsPatch: Partial<VCSProvider> = {
name: vcs.value.name,
};
@@ -156,7 +165,8 @@ const doUpdate = () => {
vcsPatch.accessToken = state.config.accessToken;
}
- vcsV1Store.updateVCS(vcsPatch).then((updatedVCS: VCSProvider | undefined) => {
+ try {
+ const updatedVCS = await vcsV1Store.updateVCS(vcsPatch);
if (!updatedVCS) {
return;
}
@@ -166,19 +176,24 @@ const doUpdate = () => {
style: "SUCCESS",
title: `Successfully updated '${updatedVCS.title}'`,
});
- });
+ } finally {
+ state.loading = false;
+ }
};
const cancel = () => {
resetState();
};
-const deleteVCS = () => {
+const deleteVCS = async () => {
if (!vcs.value) {
return;
}
- const title = vcs.value.title;
- vcsV1Store.deleteVCS(vcs.value.name).then(() => {
+ state.loading = true;
+
+ try {
+ const title = vcs.value.title;
+ await vcsV1Store.deleteVCS(vcs.value.name);
pushNotification({
module: "bytebase",
style: "SUCCESS",
@@ -187,6 +202,8 @@ const deleteVCS = () => {
router.push({
name: WORKSPACE_ROUTE_GITOPS,
});
- });
+ } finally {
+ state.loading = false;
+ }
};
</script>