Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: tenancy UI (#358)
Liu Jiba7e74b2fdcf
diff --git a/frontend/src/assets/css/tailwind.css b/frontend/src/assets/css/tailwind.cssindex 0643213ae6..a848d040cd 100644--- a/frontend/src/assets/css/tailwind.css+++ b/frontend/src/assets/css/tailwind.css@@ -201,3 +201,31 @@.tooltip-wrapper:hover .tooltip {@apply visible z-50;}++.fade-enter-active,+.fade-leave-active,+.fade-fast-enter-active,+.fade-fast-leave-active,+.fade-slow-enter-active,+.fade-slow-leave-active {+ @apply transition-opacity ease-in-out duration-300;+}++.fade-fast-enter-active,+.fade-fast-leave-active {+ @apply duration-100;+}++.fade-slow-enter-active,+.fade-slow-leave-active {+ @apply duration-500;+}++.fade-enter-from,+.fade-leave-to,+.fade-fast-enter-from,+.fade-fast-leave-to,+.fade-slow-enter-from,+.fade-slow-leave-to {+ @apply opacity-0;+}diff --git a/frontend/src/bbkit/BBTable/BBTable.vue b/frontend/src/bbkit/BBTable/BBTable.vueindex e382edef8e..5da2d400dd 100644--- a/frontend/src/bbkit/BBTable/BBTable.vue+++ b/frontend/src/bbkit/BBTable/BBTable.vue@@ -4,18 +4,16 @@:class="borderVisibility"><thead v-if="showHeader && !sectionDataSource" class="bg-gray-50">- <tr>+ <template v-if="customHeader">+ <!-- different implements for legacy compatibility -->+ <slot name="header" />+ </template>+ <tr v-else><thv-for="(column, index) in columnList":key="index"scope="col"- class="- py-2- text-left text-xs- font-medium- text-gray-500- tracking-wider- "+ class="py-2 text-left text-xs font-medium text-gray-500 tracking-wider":class="index == 0 ? 'pl-4' : 'pl-2'">{{ column.title }}@@ -29,16 +27,7 @@<thv-if="!compactSection || sectionDataSource.length > 1":colspan="columnList.length"- class="- text-left- pl-4- pt-4- pb-2- py-text-base- leading-6- font-medium- text-gray-900- "+ class="text-left pl-4 pt-4 pb-2 py-text-base leading-6 font-medium text-gray-900"><template v-if="section.link"><router-link :to="section.link" class="normal-link">@@ -102,16 +91,16 @@</template><script lang="ts">-import { computed, PropType } from "vue";+import { computed, defineComponent, PropType } from "vue";import { BBTableColumn, BBTableSectionDataSource } from "../types";-export default {+export default defineComponent({name: "BBTable",components: {},props: {columnList: {- required: true,- type: Object as PropType<BBTableColumn[]>,+ type: Array as PropType<BBTableColumn[]>,+ default: () => [],},dataSource: {default: () => [],@@ -119,6 +108,7 @@ export default {},sectionDataSource: {type: Array as PropType<BBTableSectionDataSource<any>[]>,+ default: undefined,},// Only applicable to sectionDataSource. If true, when there is only one// section, it won't render the extra section header. In another words, it will@@ -131,6 +121,10 @@ export default {default: true,type: Boolean,},+ customHeader: {+ default: false,+ type: Boolean,+ },rowClickable: {default: true,type: Boolean,@@ -175,5 +169,5 @@ export default {});return { borderVisibility };},-};+});</script>diff --git a/frontend/src/bbkit/BBTable/BBTableHeaderCell.vue b/frontend/src/bbkit/BBTable/BBTableHeaderCell.vueindex 734668953a..53a5427be8 100644--- a/frontend/src/bbkit/BBTable/BBTableHeaderCell.vue+++ b/frontend/src/bbkit/BBTable/BBTableHeaderCell.vue@@ -15,8 +15,8 @@ export default defineComponent({name: "BBTableHeaderCell",props: {title: {- required: true,type: String,+ default: "",},leftPadding: {type: Number,diff --git a/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue b/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vueindex e031eae786..10417cf66d 100644--- a/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue+++ b/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue@@ -1,34 +1,55 @@<template>- <div class="mx-4 space-y-4 w-160">+ <div class="mx-4 space-y-4 max-w-min overflow-x-hidden"><VCSTipsInfo :project="state.project" />- <template v-if="projectId">- <template v-if="false && isTenantProject">- <!-- tenant mode project, disabled for now -->- <ProjectTenantView />- </template>- <template v-else>- <!-- standard mode project, single/multiple databases ui -->- <ProjectStandardView- :state="state"- :project="state.project"- :database-list="databaseList"- :environment-list="environmentList"- @select-database="selectDatabase"- />- </template>- </template>- <template v-else>- <!-- a simple table now -->- <DatabaseTable- mode="ALL_SHORT"- :bordered="true"- :custom-click="true"- :database-list="databaseList"- @select-database="selectDatabase"- />- <!-- but also another view for tenant mode databases later -->- </template>+ <div class="overflow-x-auto">+ <div class="mx-1" :class="wrapperClass">+ <template v-if="projectId">+ <template v-if="isTenantProject">+ <!-- tenant mode project -->+ <ProjectTenantView+ :state="state"+ :database-list="databaseList"+ :environment-list="environmentList"+ :project="state.project"+ @dismiss="cancel"+ />+ </template>+ <template v-else>+ <!-- standard mode project, single/multiple databases ui -->+ <ProjectStandardView+ :state="state"+ :project="state.project"+ :database-list="databaseList"+ :environment-list="environmentList"+ @select-database="selectDatabase"+ />+ </template>+ </template>+ <template v-else>+ <NTabs v-model:value="state.tab" type="line">+ <NTabPane :tab="$t('project.mode.standard')" name="standard">+ <!-- a simple table -->+ <DatabaseTable+ mode="ALL_SHORT"+ :bordered="true"+ :custom-click="true"+ :database-list="standardProjectDatabaseList"+ @select-database="selectDatabase"+ />+ </NTabPane>+ <NTabPane :tab="$t('project.mode.tenant')" name="tenant">+ <CommonTenantView+ :state="state"+ :database-list="databaseList"+ :environment-list="environmentList"+ @dismiss="cancel"+ />+ </NTabPane>+ </NTabs>+ </template>+ </div>+ </div><!-- Create button group --><div class="pt-4 border-t border-block-border flex justify-end">@@ -47,6 +68,15 @@>{{ $t("common.next") }}</button>++ <button+ v-if="isTenantProject || (!projectId && state.tab === 'tenant')"+ class="btn-primary ml-3 inline-flex justify-center py-2 px-4"+ :disabled="!allowGenerateTenant"+ @click.prevent="generateTenant"+ >+ {{ $t("common.next") }}+ </button></div></div></template>@@ -60,22 +90,33 @@ import {baseDirectoryWebUrl,Database,DatabaseId,+ Principal,Project,ProjectId,Repository,+ UNKNOWN_ID,} from "../../types";import { sortDatabaseList } from "../../utils";import { cloneDeep } from "lodash-es";import VCSTipsInfo from "./VCSTipsInfo.vue";-import {- default as ProjectStandardView,- State as StandardModeState,+import ProjectStandardView, {+ State as ProjectStandardState,} from "./ProjectStandardView.vue";+import ProjectTenantView, {+ State as ProjectTenantState,+} from "./ProjectTenantView.vue";+import CommonTenantView, {+ State as CommonTenantState,+} from "./CommonTenantView.vue";+import { NTabs, NTabPane } from "naive-ui";import { useEventListener } from "@vueuse/core";-type LocalState = StandardModeState & {- project?: Project;-};+type LocalState = ProjectStandardState &+ ProjectTenantState &+ CommonTenantState & {+ project?: Project;+ tab: "standard" | "tenant";+ };export default defineComponent({name: "AlterSchemaPrepForm",@@ -83,6 +124,10 @@ export default defineComponent({VCSTipsInfo,DatabaseTable,ProjectStandardView,+ ProjectTenantView,+ CommonTenantView,+ NTabs,+ NTabPane,},props: {projectId: {@@ -95,7 +140,9 @@ export default defineComponent({const store = useStore();const router = useRouter();- const currentUser = computed(() => store.getters["auth/currentUser"]());+ const currentUser = computed(+ () => store.getters["auth/currentUser"]() as Principal+ );useEventListener(window, "keydown", (e) => {if (e.code === "Escape") {@@ -107,8 +154,11 @@ export default defineComponent({project: props.projectId? store.getters["project/projectById"](props.projectId): undefined,+ tab: "standard",alterType: "SINGLE_DB",selectedDatabaseIdForEnvironment: new Map(),+ tenantProjectId: undefined,+ selectedDatabaseName: undefined,});const isTenantProject = computed((): boolean => {@@ -134,6 +184,18 @@ export default defineComponent({return sortDatabaseList(cloneDeep(list), environmentList.value);});+ const standardProjectDatabaseList = computed(() => {+ return databaseList.value.filter(+ (db) => db.project.tenantMode !== "TENANT"+ );+ });++ const tenantProjectDatabaseList = computed(() => {+ return databaseList.value.filter(+ (db) => db.project.tenantMode === "TENANT"+ );+ });+const allowGenerateMultiDb = computed(() => {return state.selectedDatabaseIdForEnvironment.size > 0;});@@ -167,6 +229,49 @@ export default defineComponent({});};+ const allowGenerateTenant = computed(() => {+ if (!state.selectedDatabaseName) return false;++ // TODO: return false when database list filtered by deployment config is empty++ return true;+ });++ const generateTenant = async () => {+ emit("dismiss");++ const projectId = props.projectId || state.tenantProjectId;+ if (!projectId) return;++ const project = store.getters["project/projectById"](+ projectId+ ) as Project;++ if (project.id === UNKNOWN_ID) return;++ if (project.workflowType === "UI") {+ router.push({+ name: "workspace.issue.detail",+ params: {+ issueSlug: "new",+ },+ query: {+ template: "bb.issue.database.schema.update",+ name: `[${state.selectedDatabaseName}] Alter schema`,+ project: project.id,+ databaseName: state.selectedDatabaseName,+ mode: "tenant",+ },+ });+ } else if (project.workflowType === "VCS") {+ store+ .dispatch("repository/fetchRepositoryByProjectId", project.id)+ .then((repository: Repository) => {+ window.open(baseDirectoryWebUrl(repository), "_blank");+ });+ }+ };+const selectDatabase = (database: Database) => {emit("dismiss");@@ -199,13 +304,29 @@ export default defineComponent({emit("dismiss");};+ const wrapperClass = computed(() => {+ // provide a wider modal to tenant view+ if (props.projectId) {+ if (isTenantProject.value) return "w-192";+ else return "w-160";+ } else {+ if (state.tab === "standard") return "w-160";+ return "w-192";+ }+ });+return {+ wrapperClass,state,isTenantProject,environmentList,databaseList,+ standardProjectDatabaseList,+ tenantProjectDatabaseList,allowGenerateMultiDb,generateMultDb,+ allowGenerateTenant,+ generateTenant,selectDatabase,cancel,};diff --git a/frontend/src/components/AlterSchemaPrepForm/CommonTenantView.vue b/frontend/src/components/AlterSchemaPrepForm/CommonTenantView.vuenew file mode 100644index 0000000000..c61c85ec1b--- /dev/null+++ b/frontend/src/components/AlterSchemaPrepForm/CommonTenantView.vue@@ -0,0 +1,67 @@+<template>+ <!-- eslint-disable vue/no-mutating-props -->++ <div class="flex items-center py-1">+ <label for="project" class="textlabel mr-4">+ {{ $t("common.projects") }}+ </label>+ <div class="w-64">+ <ProjectSelect+ id="project"+ class="mt-1"+ name="project"+ :mode="ProjectMode.Tenant"+ :selected-id="props.state.tenantProjectId"+ @select-project-id="(id: number) => props.state.tenantProjectId = id"+ />+ </div>+ </div>+ <div v-if="state.tenantProjectId">+ <ProjectTenantView+ :state="state"+ :database-list="filteredDatabaseList"+ :environment-list="environmentList"+ :project="project"+ @dismiss="$emit('dismiss')"+ />+ </div>+</template>++<script lang="ts" setup>+import { defineProps, defineEmits, computed } from "vue";+import { useStore } from "vuex";+import { Database, Environment, Project, ProjectId } from "../../types";+import ProjectSelect, { Mode as ProjectMode } from "../ProjectSelect.vue";+import ProjectTenantView, {+ State as ProjectTenantState,+} from "./ProjectTenantView.vue";++export type State = ProjectTenantState & {+ tenantProjectId: ProjectId | undefined;+};++const props = defineProps<{+ state: State;+ databaseList: Database[];+ environmentList: Environment[];+}>();++defineEmits<{+ (event: "dismiss"): void;+}>();++const store = useStore();++const project = computed(() => {+ return store.getters["project/projectById"](+ props.state.tenantProjectId+ ) as Project;+});++const filteredDatabaseList = computed(() => {+ if (!props.state.tenantProjectId) return [];+ return props.databaseList.filter(+ (db) => db.project.id === props.state.tenantProjectId+ );+});+</script>diff --git a/frontend/src/components/AlterSchemaPrepForm/ProjectStandardView.vue b/frontend/src/components/AlterSchemaPrepForm/ProjectStandardView.vueindex aa3dcedb4e..1c33c671f2 100644--- a/frontend/src/components/AlterSchemaPrepForm/ProjectStandardView.vue+++ b/frontend/src/components/AlterSchemaPrepForm/ProjectStandardView.vue@@ -1,7 +1,7 @@<template><!-- eslint-disable vue/no-mutating-props -->- <div v-if="project?.workflowType === 'UI'" class="mt-2 textlabel">+ <div v-if="project?.workflowType === 'UI'" class="my-2 textlabel -ml-1"><div class="radio-set-row"><div class="radio"><label class="label">diff --git a/frontend/src/components/AlterSchemaPrepForm/ProjectTenantView.vue b/frontend/src/components/AlterSchemaPrepForm/ProjectTenantView.vueindex c67911724c..7c959f3c0a 100644--- a/frontend/src/components/AlterSchemaPrepForm/ProjectTenantView.vue+++ b/frontend/src/components/AlterSchemaPrepForm/ProjectTenantView.vue@@ -1,11 +1,180 @@<template>- <div>TODO: this will NOT be visible for now</div>+ <!-- eslint-disable vue/no-mutating-props -->++ <div class="project-tenant-view">+ <template v-if="!!project">+ <template v-if="deployment?.id === UNKNOWN_ID">+ <i18n-t+ tag="p"+ keypath="deployment-config.project-has-no-deployment-config"+ >+ <template #go>+ <router-link+ to="#deployment-config"+ active-class=""+ exact-active-class=""+ class="px-1 underline hover:bg-link-hover"+ @click="$emit('dismiss')"+ >+ {{ $t("deployment-config.go-and-config") }}+ </router-link>+ </template>+ </i18n-t>+ </template>+ <template v-else>+ <div v-if="databaseListGroupByName.length === 0" class="textinfolabel">+ <i18n-t keypath="project.overview.no-db-prompt" tag="p">+ <template #newDb>+ <span class="text-main">{{ $t("quick-action.new-db") }}</span>+ </template>+ <template #transferInDb>+ <span class="text-main">+ {{ $t("quick-action.transfer-in-db") }}+ </span>+ </template>+ </i18n-t>+ </div>+ <NCollapse+ v-else+ display-directive="if"+ accordion+ :expanded-names="state.selectedDatabaseName"+ @update:expanded-names="+ (names) => (state.selectedDatabaseName = names[0])+ "+ >+ <NCollapseItem+ v-for="{ name, list } in databaseListGroupByName"+ :key="name"+ :title="name"+ :name="name"+ >+ <template #header>+ <span class="text-base">{{ name }}</span>+ <span v-if="name === state.selectedDatabaseName">+ <heroicons-outline:check class="w-5 h-5 ml-2 text-success" />+ </span>+ </template>+ <template #header-extra>+ <span class="text-control-placeholder">+ {{ $t("deployment-config.n-databases", list.length) }}+ </span>+ </template>++ <DeployDatabaseTable+ :database-list="list"+ :label-list="labelList"+ :environment-list="environmentList"+ :deployment="deployment!"+ />+ </NCollapseItem>+ </NCollapse>+ </template>+ </template>+ </div></template>-<script lang="ts">-import { defineComponent } from "vue";+<script lang="ts" setup>+/* eslint-disable vue/no-mutating-props */++import { computed, defineProps, defineEmits, watchEffect, watch } from "vue";+import { useStore } from "vuex";+import {+ Database,+ DeploymentConfig,+ Environment,+ Label,+ Project,+ UNKNOWN_ID,+} from "../../types";+import { NCollapse, NCollapseItem } from "naive-ui";+import { groupBy } from "lodash-es";+import { DeployDatabaseTable } from "../TenantDatabaseTable";++export type State = {+ selectedDatabaseName: string | undefined;+};++const props = defineProps<{+ databaseList: Database[];+ environmentList: Environment[];+ project?: Project;+ state: State;+}>();++defineEmits<{+ (event: "dismiss"): void;+}>();++const store = useStore();++const fetchData = () => {+ store.dispatch("label/fetchLabelList");+ if (props.project) {+ store.dispatch(+ "deployment/fetchDeploymentConfigByProjectId",+ props.project.id+ );+ }+};++watchEffect(fetchData);-export default defineComponent({- name: "ProjectTenantView",+const labelList = computed(() => store.getters["label/labelList"]() as Label[]);++const deployment = computed(() => {+ if (props.project) {+ return store.getters["deployment/deploymentConfigByProjectId"](+ props.project.id+ ) as DeploymentConfig;+ } else {+ return undefined;+ }});++const databaseListGroupByName = computed(+ (): { name: string; list: Database[] }[] => {+ const dict = groupBy(props.databaseList, "name");+ return Object.keys(dict).map((name) => ({+ name,+ list: dict[name],+ }));+ }+);++watch(+ databaseListGroupByName,+ (groups) => {+ // reset selection when databaseList changed+ if (groups.length > 0) {+ props.state.selectedDatabaseName = groups[0].name;+ } else {+ props.state.selectedDatabaseName = undefined;+ }+ },+ { immediate: true }+);</script>++<style scoped lang="postcss">+.project-tenant-view {+ @apply w-192;+}++.project-tenant-view :global(.n-collapse-item) {+ @apply mt-0 !important;+}++.project-tenant-view+ :global(.n-collapse-item.n-collapse-item--active + .n-collapse-item) {+ @apply border-0 !important;+}++.project-tenant-view :global(.n-collapse-item__header) {+ @apply pt-4 pb-4 border-control-light !important;+}++.project-tenant-view :global(.n-collapse-item__content-inner) {+ @apply pt-0 !important;+}+</style>diff --git a/frontend/src/components/AlterSchemaPrepForm/VCSTipsInfo.vue b/frontend/src/components/AlterSchemaPrepForm/VCSTipsInfo.vueindex f6d380f68b..c245062f3f 100644--- a/frontend/src/components/AlterSchemaPrepForm/VCSTipsInfo.vue+++ b/frontend/src/components/AlterSchemaPrepForm/VCSTipsInfo.vue@@ -5,9 +5,9 @@</div></template><template v-else>- <div class="flex flex-row space-x-2">- <heroicons-outline:collection class="w-8 h-8 text-control -mt-1.5" />- <p class="textlabel">+ <div class="flex flex-row space-x-2 align-top">+ <heroicons-outline:collection class="w-4 h-4 text-control mt-0.5" />+ <p class="textlabel flex-1">{{ $t("alter-schema.vcs-info") }}</p></div>diff --git a/frontend/src/components/CreateDatabasePrepForm.vue b/frontend/src/components/CreateDatabasePrepForm.vueindex 669a248e7d..7b48415b79 100644--- a/frontend/src/components/CreateDatabasePrepForm.vue+++ b/frontend/src/components/CreateDatabasePrepForm.vue@@ -3,7 +3,8 @@<div class="grid gap-y-6 gap-x-4 grid-cols-4"><div class="col-span-2 col-start-2 w-64"><label for="name" class="textlabel">- {{ $t('create-db.new-database-name') }} <span class="text-red-600">*</span>+ {{ $t("create-db.new-database-name") }}+ <span class="text-red-600">*</span></label><inputid="name"@@ -13,10 +14,9 @@type="text"class="textfield mt-1 w-full"/>- <span v-if="isReservedName" class="text-red-600"- >- <i18n-t keypath="create-db.reserved-db-error" >- <template v-slot:databaseName>+ <span v-if="isReservedName" class="text-red-600">+ <i18n-t keypath="create-db.reserved-db-error">+ <template #databaseName>{{ state.databaseName }}</template></i18n-t></span@@ -25,30 +25,28 @@<div class="col-span-2 col-start-2 w-64"><label for="project" class="textlabel">- {{ $t('common.projects') }} <span style="color: red">*</span>+ {{ $t("common.projects") }} <span style="color: red">*</span></label>- <!-- eslint-disable vue/attribute-hyphenation --><ProjectSelectid="project"class="mt-1"name="project":disabled="!allowEditProject"- :selectedId="state.projectId"+ :selected-id="state.projectId"@select-project-id="selectProject"/></div><div class="col-span-2 col-start-2 w-64"><label for="environment" class="textlabel">- {{ $t('common.environments') }} <span style="color: red">*</span>+ {{ $t("common.environments") }} <span style="color: red">*</span></label>- <!-- eslint-disable vue/attribute-hyphenation --><EnvironmentSelectid="environment"class="mt-1 w-full"name="environment":disabled="!allowEditEnvironment"- :selectedId="state.environmentId"+ :selected-id="state.environmentId"@select-environment-id="selectEnvironment"/></div>@@ -60,7 +58,7 @@:instance="selectedInstance"/><label for="instance" class="textlabel">- {{ $t('common.instances') }} <span class="text-red-600">*</span>+ {{ $t("common.instances") }} <span class="text-red-600">*</span></label></div><div class="flex flex-row space-x-2 items-center">@@ -77,6 +75,24 @@</div></div>+ <div v-if="isTenantProject" class="col-span-2 col-start-2 w-64">+ <div class="flex flex-row items-center space-x-1">+ <label for="instance" class="textlabel">+ {{ $t("common.labels") }} <span class="text-red-600">*</span>+ </label>+ </div>+ <div class="flex flex-col space-y-1">+ <DatabaseLabels+ :label-list="state.labelList"+ :editable="true"+ class="flex-col items-start mt-1 gap-1"+ />+ <div v-if="labelsError.length > 0" class="text-red-600">+ {{ labelsError }}+ </div>+ </div>+ </div>+<templatev-if="selectedInstance.engine != 'CLICKHOUSE' &&@@ -87,8 +103,8 @@<label for="charset" class="textlabel">{{selectedInstance.engine == "POSTGRES"- ? $t('db.encoding')- : $t('db.character-set')+ ? $t("db.encoding")+ : $t("db.character-set")}}</label><input@@ -102,7 +118,9 @@</div><div class="col-span-2 col-start-2 w-64">- <label for="collation" class="textlabel"> {{ $t('db.collation') }} </label>+ <label for="collation" class="textlabel">+ {{ $t("db.collation") }}+ </label><inputid="collation"v-model="state.collation"@@ -118,7 +136,7 @@<div v-if="showAssigneeSelect" class="col-span-2 col-start-2 w-64"><label for="user" class="textlabel">- {{ $t('common.assignee') }} <span class="text-red-600">*</span>+ {{ $t("common.assignee") }} <span class="text-red-600">*</span></label><!-- DBA and Owner always have all access, so we only need to grant to developer --><!-- eslint-disable vue/attribute-hyphenation -->@@ -140,14 +158,14 @@class="btn-normal py-2 px-4"@click.prevent="cancel">- {{ $t('common.cancel') }}+ {{ $t("common.cancel") }}</button><buttonclass="btn-primary ml-3 inline-flex justify-center py-2 px-4":disabled="!allowCreate"@click.prevent="create">- {{ $t('common.create') }}+ {{ $t("common.create") }}</button></div></div>@@ -161,6 +179,7 @@ import {onUnmounted,PropType,watchEffect,+ defineComponent,} from "vue";import { useStore } from "vuex";import { useRouter } from "vue-router";@@ -170,6 +189,7 @@ import EnvironmentSelect from "../components/EnvironmentSelect.vue";import ProjectSelect from "../components/ProjectSelect.vue";import MemberSelect from "../components/MemberSelect.vue";import InstanceEngineIcon from "../components/InstanceEngineIcon.vue";+import DatabaseLabels from "./DatabaseLabels";import {EnvironmentId,InstanceId,@@ -178,24 +198,29 @@ import {SYSTEM_BOT_ID,PrincipalId,Backup,- StageCreate,defaultCharset,defaultCollation,unknown,+ Project,+ DatabaseLabel,+ CreateDatabaseContext,+ Environment,} from "../types";-import { isDBAOrOwner, issueSlug } from "../utils";+import { isDBAOrOwner, issueSlug, validateLabels } from "../utils";+import { useI18n } from "vue-i18n";interface LocalState {projectId?: ProjectId;environmentId?: EnvironmentId;instanceId?: InstanceId;+ labelList: DatabaseLabel[];databaseName?: string;characterSet: string;collation: string;assigneeId?: PrincipalId;}-export default {+export default defineComponent({name: "CreateDatabasePrepForm",components: {InstanceSelect,@@ -203,24 +228,30 @@ export default {ProjectSelect,MemberSelect,InstanceEngineIcon,+ DatabaseLabels,},props: {projectId: {type: Number as PropType<ProjectId>,+ default: undefined,},environmentId: {type: Number as PropType<EnvironmentId>,+ default: undefined,},instanceId: {type: Number as PropType<InstanceId>,+ default: undefined,},// If specified, then we are creating a database from the backup.backup: {type: Object as PropType<Backup>,+ default: undefined,},},emits: ["dismiss"],setup(props, { emit }) {+ const { t } = useI18n();const store = useStore();const router = useRouter();@@ -255,6 +286,7 @@ export default {projectId: props.projectId,environmentId: props.environmentId,instanceId: props.instanceId,+ labelList: [],characterSet: "",collation: "",assigneeId: showAssigneeSelect.value ? undefined : SYSTEM_BOT_ID,@@ -264,10 +296,32 @@ export default {return state.databaseName?.toLowerCase() == "bytebase";});+ const isTenantProject = computed((): boolean => {+ if (!state.projectId) return false;+ const project = store.getters["project/projectById"](+ state.projectId+ ) as Project;++ return project.tenantMode === "TENANT";+ });++ const labelsError = computed((): string => {+ const error = validateLabels(state.labelList);+ if (error) return t(error);+ return "";+ });++ const invalidLabels = computed((): boolean => {+ if (!isTenantProject.value) return false;+ if (state.labelList.length === 0) return true;+ return !!labelsError.value;+ });+const allowCreate = computed(() => {return (!isEmpty(state.databaseName) &&!isReservedName.value &&+ !invalidLabels.value &&state.projectId &&state.environmentId &&state.instanceId &&@@ -317,7 +371,6 @@ export default {};const create = async () => {-var newIssue: IssueCreate;if (props.backup) {newIssue = {@@ -333,11 +386,15 @@ export default {createContext: {instanceId: state.instanceId!,databaseName: state.databaseName,- characterSet: state.characterSet || defaultCharset(selectedInstance.value.engine),- collation: state.collation || defaultCollation(selectedInstance.value.engine),+ characterSet:+ state.characterSet ||+ defaultCharset(selectedInstance.value.engine),+ collation:+ state.collation ||+ defaultCollation(selectedInstance.value.engine),backupId: props.backup.id,backupName: props.backup.name,- },+ },payload: {},};} else {@@ -354,22 +411,49 @@ export default {createContext: {instanceId: state.instanceId!,databaseName: state.databaseName,- characterSet: state.characterSet || defaultCharset(selectedInstance.value.engine),- collation: state.collation || defaultCollation(selectedInstance.value.engine),+ characterSet:+ state.characterSet ||+ defaultCharset(selectedInstance.value.engine),+ collation:+ state.collation ||+ defaultCollation(selectedInstance.value.engine),},payload: {},};}+ if (isTenantProject.value) {+ const context = newIssue.createContext as CreateDatabaseContext;+ context.labels = JSON.stringify(state.labelList);+ }store.dispatch("issue/createIssue", newIssue).then((createdIssue) => {router.push(`/issue/${issueSlug(createdIssue.name, createdIssue.id)}`);});};+ // update `state.labelList` when selected Environment changed+ watchEffect(() => {+ const envId = state.environmentId;+ const { labelList } = state;+ const key = "bb.environment";+ const index = labelList.findIndex((label) => label.key === key);+ if (envId) {+ const env = store.getters["environment/environmentById"](+ state.environmentId+ ) as Environment;+ if (index >= 0) labelList[index].value = env.name;+ else labelList.unshift({ key, value: env.name });+ } else {+ if (index >= 0) labelList.splice(index, 1);+ }+ });+return {defaultCharset,defaultCollation,state,isReservedName,+ isTenantProject,+ labelsError,allowCreate,allowEditProject,allowEditEnvironment,@@ -384,5 +468,5 @@ export default {create,};},-};+});</script>diff --git a/frontend/src/components/DatabaseLabels/DatabaseLabel.vue b/frontend/src/components/DatabaseLabels/DatabaseLabel.vuenew file mode 100644index 0000000000..35b21fd6d1--- /dev/null+++ b/frontend/src/components/DatabaseLabels/DatabaseLabel.vue@@ -0,0 +1,112 @@+<template>+ <!-- eslint-disable vue/no-mutating-props -->+ <div class="database-label" :class="{ editable }">+ <div class="select key">+ <span>{{ hidePrefix(label.key) }}</span>+ <span v-if="editable" class="dropdown-icon">+ <heroicons-solid:selector class="h-4 w-4 text-control-light" />+ </span>+ <select v-if="editable" v-model="label.key">+ <option v-for="(key, i) in keys" :key="i" :value="key">+ {{ hidePrefix(key) }}+ </option>+ </select>+ </div>+ <div v-if="!editable" class="colon">:</div>+ <div class="select value">+ <span>{{ label.value }}</span>+ <span v-if="editable" class="dropdown-icon">+ <heroicons-solid:selector class="h-4 w-4 text-control-light" />+ </span>+ <select v-if="editable" v-model="label.value">+ <option v-for="(value, i) in values" :key="i" :value="value">+ {{ value }}+ </option>+ </select>+ </div>+ <div v-if="editable" class="remove" @click="$emit('remove')">+ <heroicons-solid:x class="w-3 h-3 text-control" />+ </div>+ </div>+</template>++<script lang="ts">+/* eslint-disable vue/no-mutating-props */++import { computed, defineComponent, PropType, watch } from "vue";+import { DatabaseLabel, Label } from "../../types";+import { hidePrefix } from "../../utils";++export default defineComponent({+ name: "DatabaseLabel",+ props: {+ // bound value will be mutated directly+ // this is an anti-pattern in vue+ // but we do it here to make this component simple and stupid+ label: {+ type: Object as PropType<DatabaseLabel>,+ required: true,+ },+ editable: {+ type: Boolean,+ default: false,+ },+ availableLabelList: {+ type: Array as PropType<Label[]>,+ default: () => [],+ },+ },+ emits: ["remove"],+ setup(props) {+ const keys = computed(() =>+ props.availableLabelList.map((label) => label.key)+ );+ const values = computed(() => {+ if (!props.label.key) return [];+ const labelDefinition = props.availableLabelList.find(+ (l) => l.key === props.label.key+ );+ if (!labelDefinition) return [];+ return labelDefinition.valueList;+ });++ watch(+ () => props.label.key,+ () => {+ if (!props.editable) return false; // if not editable, do nothing++ // otherwise when key changed, reset value selection+ props.label.value = values.value[0] || "";+ }+ );++ return {+ keys,+ values,+ hidePrefix,+ };+ },+});+</script>++<style scoped lang="postcss">+.database-label {+ @apply h-6 relative z-0 flex items-center text-sm rounded overflow-hidden px-2 whitespace-nowrap+ bg-blue-100 border-blue-300 border select-none;+}+.select {+ @apply h-full relative flex items-center overflow-hidden;+}+.select .dropdown-icon {+ @apply ml-0 mr-1 flex items-center p-0 rounded-sm pointer-events-none; /* cursor-pointer hover:bg-gray-300;*/+}+.select select {+ @apply absolute w-full h-full inset-0 p-0 m-0 opacity-0 !important;+}+.colon {+ @apply ml-0.5 mr-2;+}+.remove {+ @apply ml-0 -mr-1 p-px cursor-pointer hover:bg-blue-300 rounded-sm;+}+</style>diff --git a/frontend/src/components/DatabaseLabels/DatabaseLabels.vue b/frontend/src/components/DatabaseLabels/DatabaseLabels.vuenew file mode 100644index 0000000000..3e568d6462--- /dev/null+++ b/frontend/src/components/DatabaseLabels/DatabaseLabels.vue@@ -0,0 +1,128 @@+<template>+ <div class="flex gap-2">+ <DatabaseLabel+ v-for="(label, i) in labelList"+ :key="i"+ :label="label"+ :editable="isEditableLabel(label)"+ :available-label-list="availableLabelList"+ @remove="removeLabel(i)"+ />+ <template v-if="editable">+ <NPopover trigger="hover" :disabled="allowAdd">+ <template #trigger>+ <button+ class="add-button"+ :class="{ disabled: !allowAdd }"+ @click="addLabel"+ >+ <heroicons-solid:plus class="w-4 h-4" />+ </button>+ </template>++ <div class="text-red-600 whitespace-nowrap">+ {{+ $t("label.error.max-label-count-exceeded", {+ count: MAX_DATABASE_LABEL_COUNT,+ })+ }}+ </div>+ </NPopover>+ </template>+ </div>+</template>++<script lang="ts">+/* eslint-disable vue/no-mutating-props */++import { computed, defineComponent, PropType, watchEffect } from "vue";+import { useStore } from "vuex";+import { DatabaseLabel, Label } from "../../types";+import { NPopover } from "naive-ui";+import { isReservedLabel, isReservedDatabaseLabel } from "../../utils";++const MAX_DATABASE_LABEL_COUNT = 4;++export default defineComponent({+ name: "DatabaseLabels",+ components: { NPopover },+ props: {+ labelList: {+ type: Array as PropType<DatabaseLabel[]>,+ default: () => [],+ },+ editable: {+ type: Boolean,+ default: false,+ },+ },+ setup(props) {+ const store = useStore();++ const allowAdd = computed(+ () => props.labelList.length < MAX_DATABASE_LABEL_COUNT+ );++ const prepareLabelList = () => {+ // need not to fetchLabelList if not editable+ if (!props.editable) return;+ store.dispatch("label/fetchLabelList");+ };+ watchEffect(prepareLabelList);++ const labelList = computed(+ () => store.getters["label/labelList"]() as Label[]+ );++ const availableLabelList = computed(() =>+ labelList.value.filter((label) => !isReservedLabel(label))+ );++ const addLabel = () => {+ if (!allowAdd.value) return;++ const key = labelList.value[0]?.key || "";+ const value = labelList.value[0]?.valueList[0] || "";+ props.labelList.push({+ key,+ value,+ });+ };++ const removeLabel = (index: number) => {+ props.labelList.splice(index, 1);+ };++ const isEditableLabel = (label: DatabaseLabel): boolean => {+ if (labelList.value.length === 0) {+ // not ready yet, disable editing temporarily+ // this also avoid some UI blinking+ return false;+ }++ return props.editable && !isReservedDatabaseLabel(label, labelList.value);+ };++ return {+ MAX_DATABASE_LABEL_COUNT,+ availableLabelList,+ isEditableLabel,+ allowAdd,+ addLabel,+ removeLabel,+ };+ },+});+</script>++<style scoped lang="postcss">+.add-button {+ @apply h-6 px-1 py-1 inline-flex items-center+ rounded bg-white border border-control-border+ hover:bg-control-bg-hover+ cursor-pointer;+}+.add-button.disabled {+ @apply cursor-not-allowed bg-control-bg;+}+</style>diff --git a/frontend/src/components/DatabaseLabels/DatabaseLabelsEditor.vue b/frontend/src/components/DatabaseLabels/DatabaseLabelsEditor.vuenew file mode 100644index 0000000000..b8d822b33f--- /dev/null+++ b/frontend/src/components/DatabaseLabels/DatabaseLabelsEditor.vue@@ -0,0 +1,142 @@+<template>+ <div class="database-labels-editor flex items-center">+ <DatabaseLabels+ :label-list="state.labelList"+ :editable="allowEdit && state.mode === 'EDIT'"+ />+ <div+ v-if="state.mode === 'VIEW' && state.labelList.length === 0"+ class="text-sm text-control-placeholder"+ >+ {{ $t("label.no-label") }}+ </div>+ <div+ v-if="allowEdit"+ class="buttons flex items-center gap-1 ml-1 text-control"+ >+ <template v-if="state.mode === 'VIEW'">+ <button class="icon-btn lite" @click="state.mode = 'EDIT'">+ <heroicons-outline:pencil class="w-4 h-4" />+ </button>+ </template>+ <template v-else>+ <button class="icon-btn text-error" @click="cancel">+ <heroicons-solid:x class="w-4 h-4" />+ </button>++ <NPopover trigger="hover" :disabled="!state.error">+ <template #trigger>+ <button+ class="icon-btn text-success"+ :class="{ disabled: !!state.error }"+ @click="save"+ >+ <heroicons-solid:check class="w-4 h-4" />+ </button>+ </template>++ <div class="text-red-600 whitespace-nowrap">+ {{ state.error }}+ </div>+ </NPopover>+ </template>+ </div>+ </div>+</template>++<script lang="ts">+import { cloneDeep } from "lodash-es";+import { defineComponent, PropType, reactive, watch } from "vue";+import { useI18n } from "vue-i18n";+import { DatabaseLabel } from "../../types";+import { validateLabels } from "../../utils";+import { NPopover } from "naive-ui";++type LocalState = {+ mode: "VIEW" | "EDIT";+ labelList: DatabaseLabel[];+ error: string | undefined;+};++export default defineComponent({+ name: "DatabaseLabelsEditor",+ components: { NPopover },+ props: {+ labelList: {+ type: Array as PropType<DatabaseLabel[]>,+ default: () => [],+ },+ allowEdit: {+ type: Boolean,+ default: true,+ },+ },+ emits: ["save"],+ setup(props, { emit }) {+ const { t } = useI18n();++ const state = reactive<LocalState>({+ mode: "VIEW",+ labelList: cloneDeep(props.labelList),+ error: undefined,+ });++ watch(+ () => props.labelList,+ (labelList) => {+ // state.labelList are a local deep-copy of props.labelList+ // <DatabaseLabels /> will mutate state.labelList directly+ // when save button clicked, we emit a event to notify the parent+ // component to dispatch a real save action+ state.labelList = cloneDeep(labelList);+ state.error = undefined;+ }+ );++ watch(+ () => state.labelList,+ (labels) => {+ const error = validateLabels(labels);+ if (error) {+ state.error = t(error);+ } else {+ state.error = undefined;+ }+ },+ { deep: true }+ );++ const cancel = () => {+ state.mode = "VIEW";+ state.labelList = cloneDeep(props.labelList);+ state.error = undefined;+ };+ const save = () => {+ if (state.error) return;+ emit("save", state.labelList);+ state.mode = "VIEW";+ };++ return {+ state,+ cancel,+ save,+ };+ },+});+</script>++<style scoped lang="postcss">+.icon-btn {+ @apply h-6 px-1 py-1 inline-flex items-center+ rounded bg-white border border-control-border+ hover:bg-control-bg-hover+ cursor-pointer;+}+.icon-btn.disabled {+ @apply cursor-not-allowed bg-control-bg;+}+.icon-btn.lite {+ @apply px-1 border-none hover:bg-control-bg-hover;+}+</style>diff --git a/frontend/src/components/DatabaseLabels/index.ts b/frontend/src/components/DatabaseLabels/index.tsnew file mode 100644index 0000000000..1518cc2993--- /dev/null+++ b/frontend/src/components/DatabaseLabels/index.ts@@ -0,0 +1,6 @@+import DatabaseLabels from "./DatabaseLabels.vue";+import DatabaseLabelsEditor from "./DatabaseLabelsEditor.vue";++export default DatabaseLabels;++export { DatabaseLabels, DatabaseLabelsEditor };diff --git a/frontend/src/components/DatabaseTable.vue b/frontend/src/components/DatabaseTable.vueindex 660ab2e909..7157d0c325 100644--- a/frontend/src/components/DatabaseTable.vue+++ b/frontend/src/components/DatabaseTable.vue@@ -9,7 +9,9 @@:bottom-bordered="bordered"@click-row="clickDatabase">- <template #body="{ rowData: database }">+ <template+ #body="{ rowData: database }: { rowData: (typeof databaseList)[number] }"+ ><BBTableCell :left-padding="4" class="w-16"><div class="flex flex-row items-center space-x-1 tooltip-wrapper"><span>{{ database.name }}</span>@@ -37,37 +39,35 @@stroke="currentColor"viewBox="0 0 24 24"xmlns="http://www.w3.org/2000/svg"- />+ ></svg><template v-else-if="database.project.workflowType == 'VCS'">- <span class="tooltip">- {{- $t("database.version-control-enabled")- }}+ <span class="tooltip whitespace-nowrap">+ {{ $t("database.version-control-enabled") }}</span>- <heroicons-outline:collection class="w-4 h-4 text-control hover:text-control-hover" />+ <heroicons-outline:collection+ class="w-4 h-4 text-control hover:text-control-hover"+ /></template></div></div></BBTableCell>- <BBTableCell- v-if="showEnvironmentColumn"- class="w-16"- >{{ environmentName(database.instance.environment) }}</BBTableCell>+ <BBTableCell v-if="showEnvironmentColumn" class="w-16">+ {{ environmentName(database.instance.environment) }}+ </BBTableCell><BBTableCell v-if="showInstanceColumn" class="w-32"><div class="flex flex-row items-center space-x-1"><InstanceEngineIcon :instance="database.instance" /><span>{{ instanceName(database.instance) }}</span></div></BBTableCell>- <BBTableCell v-if="showMiscColumn" class="w-4">{{ database.syncStatus }}</BBTableCell>- <BBTableCell- v-if="showMiscColumn"- class="w-16"- >{{ humanizeTs(database.lastSuccessfulSyncTs) }}</BBTableCell>+ <BBTableCell v-if="showMiscColumn" class="w-4">+ {{ database.syncStatus }}+ </BBTableCell>+ <BBTableCell v-if="showMiscColumn" class="w-16">+ {{ humanizeTs(database.lastSuccessfulSyncTs) }}+ </BBTableCell><BBTableCell v-if="showSqlEditorLink" class="w-16">- <button class="btn-icon" @click.stop="- gotoSqlEditor(database)- ">+ <button class="btn-icon" @click.stop="gotoSqlEditor(database)"><heroicons-outline:terminal class="w-4 h-4" /></button></BBTableCell>@@ -76,19 +76,19 @@</template><script lang="ts">-import { computed, PropType, reactive } from "vue";+import { computed, defineComponent, PropType } from "vue";import { useStore } from "vuex";import { useRouter } from "vue-router";import { connectionSlug, databaseSlug } from "../utils";import { Database } from "../types";import { BBTableColumn } from "../bbkit/types";import InstanceEngineIcon from "./InstanceEngineIcon.vue";-import { cloneDeep, isEmpty } from "lodash-es";+import { cloneDeep } from "lodash-es";import { useI18n } from "vue-i18n";type Mode = "ALL" | "ALL_SHORT" | "INSTANCE" | "PROJECT" | "PROJECT_SHORT";-export default {+export default defineComponent({name: "DatabaseTable",components: { InstanceEngineIcon },props: {@@ -104,6 +104,10 @@ export default {default: true,type: Boolean,},+ rowClickable: {+ default: true,+ type: Boolean,+ },customClick: {default: false,type: Boolean,@@ -247,7 +251,7 @@ export default {if (props.mode == "ALL_SHORT" || props.mode == "PROJECT_SHORT") {return false;}- return true+ return true;});const gotoSqlEditor = (database: Database) => {@@ -260,6 +264,8 @@ export default {};const clickDatabase = function (section: number, row: number) {+ if (!props.rowClickable) return;+const database = props.databaseList[row];if (props.customClick) {emit("select-database", database);@@ -279,5 +285,5 @@ export default {clickDatabase,};},-};+});</script>diff --git a/frontend/src/components/DeploymentConfigTool/DeploymentConfigTool.vue b/frontend/src/components/DeploymentConfigTool/DeploymentConfigTool.vuenew file mode 100644index 0000000000..b8303f61de--- /dev/null+++ b/frontend/src/components/DeploymentConfigTool/DeploymentConfigTool.vue@@ -0,0 +1,80 @@+<template>+ <div v-if="!!schedule" class="bb-deployment-config divide-y py-2">+ <DeploymentStage+ v-for="(deployment, i) in schedule.deployments"+ :key="i"+ :index="i"+ :max="schedule.deployments.length"+ :deployment="deployment"+ :allow-edit="allowEdit"+ :show-header="true"+ :database-list="databaseList"+ :label-list="labelList"+ @remove="removeStage(deployment)"+ @prev="reorder(i, -1)"+ @next="reorder(i, 1)"+ >+ </DeploymentStage>+ </div>+</template>++<script lang="ts">+/* eslint-disable vue/no-mutating-props */++import { defineComponent, PropType } from "vue";+import {+ AvailableLabel,+ Database,+ Deployment,+ DeploymentSchedule,+} from "../../types";+import DeploymentStage from "./DeploymentStage.vue";++export default defineComponent({+ name: "DeploymentConfigTool",+ components: { DeploymentStage },+ props: {+ allowEdit: {+ type: Boolean,+ default: false,+ },+ schedule: {+ type: Object as PropType<DeploymentSchedule>,+ required: true,+ },+ databaseList: {+ type: Array as PropType<Database[]>,+ default: () => [],+ },+ labelList: {+ type: Array as PropType<AvailableLabel[]>,+ default: () => [],+ },+ },+ setup(props) {+ const removeStage = (deployment: Deployment) => {+ const array = props.schedule.deployments;+ const index = array.indexOf(deployment);+ if (index >= 0) {+ array.splice(index, 1);+ }+ };++ const reorder = (index: number, diff: number) => {+ const swap = (i: number, j: number) => {+ const array = props.schedule.deployments;+ const tmp = array[i];+ array[i] = array[j];+ array[j] = tmp;+ };+ const target = index + diff;+ swap(index, target);+ };++ return {+ removeStage,+ reorder,+ };+ },+});+</script>diff --git a/frontend/src/components/DeploymentConfigTool/DeploymentStage.vue b/frontend/src/components/DeploymentConfigTool/DeploymentStage.vuenew file mode 100644index 0000000000..ee472b6ebf--- /dev/null+++ b/frontend/src/components/DeploymentConfigTool/DeploymentStage.vue@@ -0,0 +1,146 @@+<template>+ <!-- eslint-disable vue/no-mutating-props -->++ <div class="deployment-stage flex w-full relative">+ <div+ v-if="allowEdit"+ class="reorder flex flex-col items-center justify-between pr-2 py-0"+ >+ <button+ class="text-control hover:text-control-hover"+ :class="[index > 0 ? 'visible' : 'invisible']"+ @click="$emit('prev')"+ >+ <heroicons-solid:arrow-circle-up class="w-6 h-6" />+ </button>+ <button+ class="text-control hover:text-control-hover"+ :class="[index < max - 1 ? 'visible' : 'invisible']"+ @click="$emit('next')"+ >+ <heroicons-solid:arrow-circle-down class="w-6 h-6" />+ </button>+ </div>+ <div class="main flex-1 space-y-2 py-2 w-full">+ <h3 v-if="showHeader" class="text-lg leading-6 font-medium text-main">+ <template v-if="allowEdit">+ <input+ v-model="deployment.name"+ type="text"+ :placeholder="$t('deployment-config.name-placeholder')"+ class="text-main rounded-md border-control-border focus:ring-control focus:border-control disabled:bg-gray-50"+ />+ </template>+ <template v-else>+ {{ deployment.name }}+ </template>+ </h3>+ <div class="space-y-2 overflow-hidden">+ <div+ v-for="(selector, j) in deployment.spec.selector.matchExpressions"+ :key="j"+ class="flex content-start"+ >+ <SelectorItem+ :editable="allowEdit"+ :selector="selector"+ :label-list="labelList"+ @remove="removeSelector(selector)"+ />+ </div>+ </div>+ <button v-if="allowEdit" class="btn-normal btn-add" @click="addSelector">+ {{ $t("deployment-config.add-selector") }}+ </button>+ </div>++ <span+ v-if="allowEdit"+ class="absolute right-2 top-2 p-1 text-control cursor-pointer hover:bg-gray-200 rounded-sm"+ @click="$emit('remove')"+ >+ <heroicons:solid:x class="w-4 h-4" />+ </span>+ </div>+</template>++<script lang="ts">+import { defineComponent, PropType } from "vue";+import {+ AvailableLabel,+ Database,+ Deployment,+ LabelSelectorRequirement,+} from "../../types";+import SelectorItem from "./SelectorItem.vue";++export default defineComponent({+ name: "DeploymentStage",+ components: { SelectorItem },+ props: {+ deployment: {+ type: Object as PropType<Deployment>,+ required: true,+ },+ index: {+ type: Number,+ default: -1,+ },+ max: {+ type: Number,+ default: -1,+ },+ allowEdit: {+ type: Boolean,+ default: false,+ },+ databaseList: {+ type: Array as PropType<Database[]>,+ default: () => [],+ },+ labelList: {+ type: Array as PropType<AvailableLabel[]>,+ default: () => [],+ },+ showHeader: {+ type: Boolean,+ default: true,+ },+ },+ emits: ["remove", "prev", "next"],+ setup(props) {+ const removeSelector = (selector: LabelSelectorRequirement) => {+ const array = props.deployment.spec.selector.matchExpressions;+ const index = array.indexOf(selector);+ if (index >= 0) {+ array.splice(index, 1);+ }+ };++ const addSelector = () => {+ const array = props.deployment.spec.selector.matchExpressions;+ const label = props.labelList[0];+ const rule: LabelSelectorRequirement = {+ key: label?.key || "",+ operator: "In",+ values: [],+ };+ if (label && label.valueList.length > 0) {+ rule.values.push(label.valueList[0]);+ }+ array.push(rule);+ };++ return {+ removeSelector,+ addSelector,+ };+ },+});+</script>++<style scoped lang="postcss">+.btn-add {+ @apply py-1.5 !important;+}+</style>diff --git a/frontend/src/components/DeploymentConfigTool/LabelSelect.vue b/frontend/src/components/DeploymentConfigTool/LabelSelect.vuenew file mode 100644index 0000000000..b9c6f0470b--- /dev/null+++ b/frontend/src/components/DeploymentConfigTool/LabelSelect.vue@@ -0,0 +1,220 @@+<template>+ <div class="bb-label-select" :class="{ disabled }">+ <VBinder>+ <VTarget>+ <div class="select-wrapper" @click="open">+ <template v-if="!empty">+ <slot name="value" :value="state.value">+ <template v-if="Array.isArray(state.value)">+ <ResponsiveTags :tags="state.value" />+ </template>+ <span v-else>{{ modifier(state.value) }}</span>+ </slot>+ </template>+ <template v-else>+ <slot name="placeholder" :placeholder="placeholder">+ <div class="placeholder">+ {{ placeholder }}+ </div>+ </slot>+ </template>+ <slot name="arrow" :open="state.open">+ <span+ v-if="!disabled"+ class="absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none"+ >+ <heroicons-solid:selector class="h-5 w-5 text-control-light" />+ </span>+ </slot>+ </div>+ </VTarget>+ <VFollower :show="state.open" placement="bottom-start">+ <transition appear name="fade-fast">+ <div+ v-if="state.open"+ ref="popup"+ class="rounded-md bg-white shadow-lg"+ >+ <ul+ tabindex="-1"+ role="listbox"+ aria-labelledby="listbox-label"+ aria-activedescendant="listbox-item-3"+ class="max-h-56 rounded-md py-1 ring-1 ring-black ring-opacity-5 overflow-auto focus:outline-none sm:text-sm"+ >+ <!--+ Select option, manage highlight styles based on mouseenter/mouseleave and keyboard navigation.++ Highlighted: "text-white bg-indigo-600", Not Highlighted: "text-gray-900"+ -->+ <slot+ v-for="(item, index) in options"+ :key="index"+ name="item"+ :item="item"+ :index="index"+ :selected="isSelected(item)"+ :toggleSelection="() => toggleSelection(item)"+ >+ <li+ role="option"+ class="flex items-center text-main hover:text-main-text hover:bg-main-hover cursor-default select-none relative py-2 px-3"+ @click="toggleSelection(item)"+ >+ <span class="flex-1">+ {{ modifier(item) }}+ </span>+ <span+ class="ml-1"+ :class="[isSelected(item) ? 'visible' : 'invisible']"+ >+ <heroicons-solid:check class="h-5 w-5" />+ </span>+ </li>+ </slot>+ </ul>+ </div>+ </transition>+ </VFollower>+ </VBinder>+ </div>+</template>++<script lang="ts">+import { reactive, PropType, watch, defineComponent, ref, computed } from "vue";+import { VBinder, VTarget, VFollower } from "vueuc";+import { onClickOutside } from "@vueuse/core";+import ResponsiveTags from "./ResponsiveTags.vue";++interface LocalState {+ open: boolean;+ value: string | string[];+}++export default defineComponent({+ name: "LabelSelect",+ components: {+ VBinder,+ VTarget,+ VFollower,+ ResponsiveTags,+ },+ props: {+ value: {+ type: [String, Array] as PropType<string | string[]>,+ required: true,+ },+ options: {+ type: Array as PropType<string[]>,+ default: () => [],+ },+ placeholder: {+ default: "",+ type: String,+ },+ disabled: {+ default: false,+ type: Boolean,+ },+ popupFitWidth: {+ type: Boolean,+ default: true,+ },+ multiple: {+ type: Boolean,+ default: false,+ },+ modifier: {+ type: Function as PropType<(str: string) => string>,+ default: (str: string) => str,+ },+ },+ emits: ["update:value"],+ setup(props, { emit }) {+ const popup = ref<HTMLElement>();++ const state = reactive<LocalState>({+ open: false,+ value: props.value,+ });++ watch(+ () => props.value,+ (cur) => {+ state.value = cur;+ }+ );++ const open = () => {+ if (props.disabled) {+ return;+ }++ state.open = !state.open;+ };++ const close = () => {+ state.open = false;+ };++ onClickOutside(popup, close);++ const empty = computed(() => {+ if (Array.isArray(state.value)) {+ return state.value.length === 0;+ } else {+ return !state.value;+ }+ });++ const isSelected = (item: string) => {+ if (Array.isArray(state.value)) {+ return state.value.includes(item);+ } else {+ return item === state.value;+ }+ };++ const toggleSelection = (item: string) => {+ if (Array.isArray(state.value)) {+ const index = state.value.indexOf(item);+ if (index >= 0) {+ state.value.splice(index, 1);+ } else {+ state.value.push(item);+ }+ } else {+ state.value = item;+ close();+ }+ emit("update:value", state.value);+ };++ return {+ popup,+ state,+ open,+ close,+ empty,+ isSelected,+ toggleSelection,+ };+ },+});+</script>++<style scoped lang="postcss">+.bb-label-select {+ @apply overflow-hidden;+}++.select-wrapper {+ @apply h-8 pl-3 pr-8 py-1.5 overflow-hidden max-w-full;+}+.disabled .select-wrapper {+ @apply pr-3;+}+.placeholder {+ @apply whitespace-nowrap text-control-light;+}+</style>diff --git a/frontend/src/components/DeploymentConfigTool/ResponsiveTags.vue b/frontend/src/components/DeploymentConfigTool/ResponsiveTags.vuenew file mode 100644index 0000000000..177cbf4caa--- /dev/null+++ b/frontend/src/components/DeploymentConfigTool/ResponsiveTags.vue@@ -0,0 +1,139 @@+<template>+ <span ref="wrapper" class="tags">+ <span v-for="(value, i) in visible" :key="i" class="tag">+ {{ value }}+ </span>+ <span v-if="rest.length > 0" class="tag rest">+ <span>+ {{ rest.length }} ...</span>+ </span>+ </span>+</template>++<script lang="ts">+import {+ computed,+ defineComponent,+ nextTick,+ onMounted,+ PropType,+ ref,+ watch,+} from "vue";+import { useResizeObserver, useWindowSize } from "@vueuse/core";++export default defineComponent({+ name: "ResponsiveTags",+ props: {+ tags: {+ type: Array as PropType<string[]>,+ default: () => [],+ },+ },+ setup(props) {+ const clip = ref(0);+ const visible = computed(() => props.tags.slice(0, clip.value));+ const rest = computed(() => props.tags.slice(clip.value));+ const wrapper = ref<HTMLElement>();+ const wrapperWidth = ref(0); // available after first render+ const winWidth = useWindowSize().width;+ const adjusting = ref(false);++ type Direction = "more" | "less";++ useResizeObserver(wrapper, (entries) => {+ const elem = entries[0].target;+ wrapperWidth.value = elem.clientWidth;+ });++ function maybeLess() {+ const elem = wrapper.value!;+ // use the latest dom value+ // because size ref maybe not flushed yet+ const innerWidth = elem.scrollWidth;+ const outerWidth = elem.clientWidth;+ if (innerWidth > outerWidth) {+ if (clip.value > 0) {+ clip.value--;+ return true;+ }+ }+ return false;+ }++ function maybeMore() {+ const elem = wrapper.value!;+ // use the latest dom value+ // because size ref maybe not flushed yet+ const innerWidth = elem.scrollWidth;+ const outerWidth = elem.clientWidth;+ if (innerWidth <= outerWidth) {+ if (clip.value < props.tags.length) {+ clip.value++;+ return true;+ }+ }+ return false;+ }++ async function adjust(dir: Direction) {+ if (adjusting.value) return;+ adjusting.value = true;++ if (dir === "more") {+ while (maybeMore()) {+ await nextTick();+ }+ // the last `maybeMore` may cause overflow+ // so call `maybeLess` to check it+ maybeLess();+ } else {+ while (maybeLess()) {+ await nextTick();+ }+ }++ adjusting.value = false;+ }++ const onWidthChange = (newWidth: number, oldWidth: number) => {+ if (oldWidth === 0) return;+ const dir: Direction = newWidth > oldWidth ? "more" : "less";+ adjust(dir);+ };++ // debouncedWatch(wrapperWidth, onWidthChange, { debounce: 50 });+ // debouncedWatch(winWidth, onWidthChange, { debounce: 50 });+ watch(wrapperWidth, onWidthChange);+ watch(winWidth, onWidthChange);++ onMounted(() => {+ adjust("more");+ });++ watch(+ () => props.tags,+ () => {+ // reset when props changed+ clip.value = 0;+ nextTick(() => adjust("more"));+ }+ );++ return {+ clip,+ rest,+ visible,+ wrapper,+ };+ },+});+</script>++<style scoped lang="postcss">+.tags {+ @apply flex flex-1 gap-1 overflow-hidden max-h-full;+}+.tag {+ @apply inline-flex items-center bg-blue-100 border-blue-300 border px-2 rounded whitespace-nowrap;+}+</style>diff --git a/frontend/src/components/DeploymentConfigTool/SelectorItem.vue b/frontend/src/components/DeploymentConfigTool/SelectorItem.vuenew file mode 100644index 0000000000..22eb5ba708--- /dev/null+++ b/frontend/src/components/DeploymentConfigTool/SelectorItem.vue@@ -0,0 +1,115 @@+<template>+ <!-- eslint-disable vue/no-mutating-props -->+ <div class="selector-item" :class="{ editable }">+ <LabelSelect+ v-model:value="selector.key"+ :options="keys"+ :disabled="!editable"+ :modifier="hidePrefix"+ class="select key"+ />+ <LabelSelect+ v-model:value="selector.operator"+ :options="OPERATORS"+ :disabled="!editable"+ class="select operator"+ />+ <LabelSelect+ v-if="selector.operator === 'In'"+ v-model:value="selector.values"+ :options="values"+ :disabled="!editable"+ :multiple="true"+ :placeholder="$t('label.placeholder.select-values')"+ class="select values"+ />+ <div v-if="editable" class="remove" @click="$emit('remove')">+ <heroicons-outline:x class="w-4 h-4 text-control" />+ </div>+ </div>+</template>++<script lang="ts">+/* eslint-disable vue/no-mutating-props */++import { computed, defineComponent, PropType, watch } from "vue";+import {+ AvailableLabel,+ LabelSelectorRequirement,+ OperatorType,+} from "../../types";+import { hidePrefix } from "../../utils";+import LabelSelect from "./LabelSelect.vue";++const OPERATORS: OperatorType[] = ["In", "Exists"];++export default defineComponent({+ name: "SelectorItem",+ components: { LabelSelect },+ props: {+ selector: {+ type: Object as PropType<LabelSelectorRequirement>,+ required: true,+ },+ labelList: {+ type: Array as PropType<AvailableLabel[]>,+ default: () => [],+ },+ editable: {+ type: Boolean,+ default: false,+ },+ },+ emits: ["remove"],+ setup(props) {+ const keys = computed(() => props.labelList.map((label) => label.key));+ const values = computed(() => {+ if (!props.selector.key) return [];+ const labelDefinition = props.labelList.find(+ (l) => l.key === props.selector.key+ );+ if (!labelDefinition) return [];+ return labelDefinition.valueList;+ });++ const resetValues = () => {+ props.selector.values = [];+ };++ watch(() => props.selector.key, resetValues);+ watch(() => props.selector.operator, resetValues);++ return { OPERATORS, hidePrefix, keys, values };+ },+});+</script>++<style scoped lang="postcss">+.selector-item {+ @apply relative max-w-full flex shadow-sm rounded-md overflow-hidden;+}+.selector-item > * {+ @apply text-sm select-none text-main bg-white border border-control-border rounded-md cursor-default relative z-0;+}+.selector-item.editable > *:hover {+ @apply z-10 bg-control-bg-hover;+}+.selector-item > :not(:first-child, :last-child) {+ @apply rounded-l-none rounded-r-none;+}+.selector-item > :first-child {+ @apply rounded-r-none;+}+.selector-item > :last-child {+ @apply rounded-l-none;+}+.selector-item > :not(:first-child) {+ @apply -ml-px;+}+.select {+ @apply flex items-center relative;+}+.remove {+ @apply flex items-center pl-2 pr-2;+}+</style>diff --git a/frontend/src/components/DeploymentConfigTool/index.ts b/frontend/src/components/DeploymentConfigTool/index.tsnew file mode 100644index 0000000000..3a862908f9--- /dev/null+++ b/frontend/src/components/DeploymentConfigTool/index.ts@@ -0,0 +1,6 @@+import DeploymentConfigTool from "./DeploymentConfigTool.vue";+import DeploymentStage from "./DeploymentStage.vue";++export default DeploymentConfigTool;++export { DeploymentConfigTool, DeploymentStage };diff --git a/frontend/src/components/Issue/IssueActivityPanel.vue b/frontend/src/components/Issue/IssueActivityPanel.vueindex b14be5088b..cb3f530afc 100644--- a/frontend/src/components/Issue/IssueActivityPanel.vue+++ b/frontend/src/components/Issue/IssueActivityPanel.vue@@ -613,7 +613,7 @@ export default defineComponent({link = `/issue/${issueSlug(props.issue.name,props.issue.id- )}?task=${taskSlug(task)}`;+ )}?task=${taskSlug(task.name, task.id)}`;}return {name: `${task.name} (${task.stage.name})`,diff --git a/frontend/src/components/Issue/IssueDetailLayout.vue b/frontend/src/components/Issue/IssueDetailLayout.vuenew file mode 100644index 0000000000..602415c690--- /dev/null+++ b/frontend/src/components/Issue/IssueDetailLayout.vue@@ -0,0 +1,1098 @@+<template>+ <div+ id="issue-detail-top"+ class="flex-1 overflow-auto focus:outline-none"+ tabindex="0"+ >+ <IssueBanner v-if="!create" :issue="issue" />++ <!-- Highlight Panel -->+ <div class="bg-white px-4 pb-4">+ <IssueHighlightPanel+ :issue="issue"+ :create="create"+ :allow-edit="allowEditNameAndDescription"+ @update-name="updateName"+ >+ <IssueStatusTransitionButtonGroup+ :create="create"+ :allow-rollback="allowRollback"+ :issue="issue"+ :issue-template="issueTemplate"+ @create="doCreate"+ @rollback="doRollback"+ @change-issue-status="changeIssueStatus"+ @change-task-status="changeTaskStatus"+ />+ </IssueHighlightPanel>+ </div>++ <!-- Stage Flow Bar -->+ <template v-if="showPipelineFlowBar">+ <template v-if="isTenantDeployMode">+ <PipelineTenantFlow+ v-if="project"+ :create="create"+ :project="project"+ :pipeline="issue.pipeline"+ :selected-stage="selectedStage"+ :selected-task="selectedTask"+ class="border-t border-b"+ @select-stage-id="selectStageId"+ @select-task="selectTask"+ />+ </template>+ <template v-else>+ <PipelineSimpleFlow+ :create="create"+ :pipeline="issue.pipeline"+ :selected-stage="selectedStage"+ @select-stage-id="selectStageId"+ />+ </template>+ <div v-if="!create" class="px-4 py-4 md:flex md:flex-col border-b">+ <IssueStagePanel+ :stage="selectedStage"+ :selected-task="selectedTask"+ :single-mode="isTenantDeployMode"+ />+ </div>+ </template>++ <!-- Output Panel -->+ <!-- Only render the top border if PipelineFlowBar is not displayed, otherwise it would overlap with the bottom border of that -->+ <div+ v-if="showIssueOutputPanel"+ class="px-2 py-4 md:flex md:flex-col"+ :class="showPipelineFlowBar ? '' : 'lg:border-t'"+ >+ <IssueOutputPanel+ :issue="issue"+ :output-field-list="issueTemplate.outputFieldList"+ :allow-edit="allowEditOutput"+ @update-custom-field="updateCustomField"+ />+ </div>++ <!-- Main Content -->+ <main+ class="flex-1 relative overflow-y-auto focus:outline-none"+ :class="+ showPipelineFlowBar && !showIssueOutputPanel+ ? ''+ : 'lg:border-t lg:border-block-border'+ "+ tabindex="-1"+ >+ <div class="flex max-w-3xl mx-auto px-6 lg:max-w-full">+ <div class="flex flex-col flex-1 lg:flex-row-reverse lg:col-span-2">+ <div+ class="py-6 lg:pl-4 lg:w-96 xl:w-112 lg:border-l lg:border-block-border"+ >+ <IssueSidebar+ :issue="issue"+ :database="database"+ :instance="instance"+ :create="create"+ :selected-stage="selectedStage"+ :task="selectedTask"+ :input-field-list="issueTemplate.inputFieldList"+ :allow-edit="allowEditSidebar"+ @update-assignee-id="updateAssigneeId"+ @update-earliest-allowed-time="updateEarliestAllowedTime"+ @add-subscriber-id="addSubscriberId"+ @remove-subscriber-id="removeSubscriberId"+ @update-custom-field="updateCustomField"+ @select-stage-id="selectStageId"+ @select-task-id="selectTaskId"+ />+ </div>+ <div class="lg:hidden border-t border-block-border" />+ <div class="w-full py-4 pr-4">+ <section v-if="showIssueTaskStatementPanel" class="border-b mb-4">+ <div v-if="!create" class="mb-4">+ <TaskCheckBar+ :task="selectedTask"+ @run-checks="runTaskChecks"+ />+ </div>+ <template v-if="isTenantDeployMode">+ <!--+ For tenant deploy mode, we provide only one statement panel.+ It's editable only when creating an issue.+ It will never show Rollback SQL.+ It is not allowed to "Apply to other stages".+ -->+ <IssueTaskStatementPanel+ :sql-hint="sqlHint(false)"+ :statement="selectedStatement"+ :create="create"+ :allow-edit="create"+ :rollback="false"+ :show-apply-statement="false"+ @update-statement="updateStatement"+ />+ </template>+ <template v-else>+ <!-- The way this is written is awkward and is to workaround an issue in IssueTaskStatementPanel.+ The statement panel is in non-edit mode when not creating the issue, and we use v-highlight+ to apply syntax highlighting when the panel is in non-edit mode. However, the v-highlight+ doesn't seem to work well with the reactivity. So for non-edit mode when !props.create, we+ list every IssueTaskStatementPanel for each stage and use v-if to show the active one. -->+ <template v-if="create">+ <IssueTaskStatementPanel+ :sql-hint="sqlHint(false)"+ :statement="selectedStatement"+ :create="create"+ :allow-edit="true"+ :rollback="false"+ :show-apply-statement="showIssueTaskStatementApply"+ @update-statement="updateStatement"+ @apply-statement-to-other-stages="+ applyStatementToOtherStages+ "+ />+ </template>+ <template+ v-for="(stage, index) in issue.pipeline.stageList"+ v-else+ :key="index"+ >+ <template v-if="selectedStage.id == stage.id">+ <IssueTaskStatementPanel+ :sql-hint="sqlHint(false)"+ :statement="statement(stage)"+ :create="create"+ :allow-edit="allowEditStatement"+ :rollback="false"+ :show-apply-statement="showIssueTaskStatementApply"+ @update-statement="updateStatement"+ />+ </template>+ </template>+ </template>+ </section>+ <section+ v-if="showIssueTaskRollbackStatementPanel"+ class="border-b mb-4"+ >+ <template v-if="create">+ <IssueTaskStatementPanel+ :sql-hint="sqlHint(true)"+ :statement="selectedRollbackStatement"+ :create="create"+ :allow-edit="false"+ :rollback="true"+ :show-apply-statement="showIssueTaskStatementApply"+ @update-statement="updateRollbackStatement"+ @apply-statement-to-other-stages="+ applyRollbackStatementToOtherStages+ "+ />+ </template>+ <template+ v-for="(stage, index) in issue.pipeline.stageList"+ v-else+ :key="index"+ >+ <template v-if="selectedStage.id == stage.id">+ <IssueTaskStatementPanel+ :sql-hint="sqlHint(true)"+ :statement="rollbackStatement(stage)"+ :create="create"+ :allow-edit="false"+ :rollback="true"+ :show-apply-statement="showIssueTaskStatementApply"+ @update-statement="updateRollbackStatement"+ />+ </template>+ </template>+ </section>+ <IssueDescriptionPanel+ :issue="issue"+ :create="create"+ :allow-edit="allowEditNameAndDescription"+ @update-description="updateDescription"+ />+ <section+ v-if="!create"+ aria-labelledby="activity-title"+ class="mt-4"+ >+ <IssueActivityPanel+ :issue="issue"+ :issue-template="issueTemplate"+ @add-subscriber-id="addSubscriberId"+ />+ </section>+ </div>+ </div>+ </div>+ </main>+ </div>+</template>++<script lang="ts">+/* eslint-disable vue/no-mutating-props */++import {+ computed,+ defineComponent,+ nextTick,+ onMounted,+ PropType,+ watchEffect,+} from "vue";+import { useStore } from "vuex";+import { useRoute, useRouter } from "vue-router";+import { cloneDeep, isEqual } from "lodash-es";+import {+ idFromSlug,+ issueSlug,+ pipelineType,+ PipelineType,+ indexFromSlug,+ activeStage,+ stageSlug,+ activeTask,+ taskSlug,+} from "../../utils";+import IssueBanner from "./IssueBanner.vue";+import IssueHighlightPanel from "./IssueHighlightPanel.vue";+import IssueStagePanel from "./IssueStagePanel.vue";+import IssueStatusTransitionButtonGroup from "./IssueStatusTransitionButtonGroup.vue";+import IssueOutputPanel from "./IssueOutputPanel.vue";+import IssueSidebar from "./IssueSidebar.vue";+import IssueTaskStatementPanel from "./IssueTaskStatementPanel.vue";+import IssueDescriptionPanel from "./IssueDescriptionPanel.vue";+import IssueActivityPanel from "./IssueActivityPanel.vue";+import PipelineSimpleFlow from "./PipelineSimpleFlow.vue";+import PipelineTenantFlow from "./PipelineTenantFlow.vue";+import TaskCheckBar from "./TaskCheckBar.vue";+import {+ Issue,+ IssueCreate,+ IssuePatch,+ PrincipalId,+ Database,+ Instance,+ Stage,+ StageId,+ IssueStatus,+ TaskId,+ TaskStatusPatch,+ TaskStatus,+ IssueStatusPatch,+ Task,+ TaskDatabaseSchemaUpdatePayload,+ StageCreate,+ TaskCreate,+ TaskDatabaseCreatePayload,+ TaskGeneralPayload,+ Project,+ MigrationType,+ TaskPatch,+ UpdateSchemaContext,+} from "../../types";+import {+ defaulTemplate as defaultTemplate,+ templateForType,+ InputField,+ OutputField,+} from "../../plugins";+import { isEmpty } from "lodash-es";++export default defineComponent({+ name: "IssueDetailLayout",+ components: {+ IssueBanner,+ IssueHighlightPanel,+ IssueStagePanel,+ IssueOutputPanel,+ IssueTaskStatementPanel,+ IssueDescriptionPanel,+ IssueActivityPanel,+ IssueSidebar,+ IssueStatusTransitionButtonGroup,+ PipelineSimpleFlow,+ PipelineTenantFlow,+ TaskCheckBar,+ },+ props: {+ create: {+ type: Boolean,+ required: true,+ },+ issue: {+ type: Object as PropType<Issue | IssueCreate>,+ required: true,+ },+ },+ emits: {+ "status-changed": (eager: boolean) => true,+ },+ setup(props, { emit }) {+ const store = useStore();+ const router = useRouter();+ const route = useRoute();++ const currentUser = computed(() => store.getters["auth/currentUser"]());++ watchEffect(function prepare() {+ if (props.create) {+ store.dispatch(+ "project/fetchProjectById",+ (props.issue as IssueCreate).projectId+ );+ }+ });++ const issueTemplate = computed(+ () => templateForType(props.issue.type) || defaultTemplate()+ );++ const project = computed((): Project => {+ if (props.create) {+ return store.getters["project/projectById"](+ (props.issue as IssueCreate).projectId+ );+ }+ return (props.issue as Issue).project;+ });++ const updateName = (+ newName: string,+ postUpdated: (updatedIssue: Issue) => void+ ) => {+ if (props.create) {+ props.issue.name = newName;+ } else {+ patchIssue(+ {+ name: newName,+ },+ postUpdated+ );+ }+ };++ const updateStatement = (+ newStatement: string,+ postUpdated?: (updatedTask: Task) => void+ ) => {+ if (props.create) {+ if (isTenantDeployMode.value) {+ // For tenant deploy mode, we apply the statement to all stages and all tasks+ const issueCreate = props.issue as IssueCreate;+ const context = issueCreate.createContext as UpdateSchemaContext;+ issueCreate.pipeline?.stageList.forEach((stage: StageCreate) => {+ stage.taskList.forEach((task) => {+ task.statement = newStatement;+ });+ });+ // We also apply it to the CreateContext+ context.updateSchemaDetailList.forEach(+ (detail) => (detail.statement = newStatement)+ );+ } else {+ // otherwise apply it to the only one task in stage+ // i.e. selectedStage.taskList[0]+ const stage = selectedStage.value as StageCreate;+ stage.taskList[0].statement = newStatement;+ }+ } else {+ if (isTenantDeployMode.value) {+ // <del>For tenant deploy mode, we patch the issue's create context</del>+ // nope, we are not allowed to update statement in tenant deploy mode anyway+ } else {+ // otherwise, patch the task+ patchTask(+ (selectedTask.value as Task).id,+ {+ statement: newStatement,+ },+ postUpdated+ );+ }+ }+ };++ const applyStatementToOtherStages = (newStatement: string) => {+ for (const stage of (props.issue as IssueCreate).pipeline!.stageList) {+ for (const task of stage.taskList) {+ if (+ task.type == "bb.task.general" ||+ task.type == "bb.task.database.create" ||+ task.type == "bb.task.database.schema.update"+ ) {+ task.statement = newStatement;+ }+ }+ }+ };++ const updateRollbackStatement = (newStatement: string) => {+ const stage = selectedStage.value as StageCreate;+ stage.taskList[0].rollbackStatement = newStatement;+ };++ const applyRollbackStatementToOtherStages = (newStatement: string) => {+ for (const stage of (props.issue as IssueCreate).pipeline!.stageList) {+ for (const task of stage.taskList) {+ if (task.type == "bb.task.database.schema.update") {+ task.rollbackStatement = newStatement;+ }+ }+ }+ };++ const updateDescription = (+ newDescription: string,+ postUpdated: (updatedIssue: Issue) => void+ ) => {+ if (props.create) {+ props.issue.description = newDescription;+ } else {+ patchIssue(+ {+ description: newDescription,+ },+ postUpdated+ );+ }+ };++ const updateAssigneeId = (newAssigneeId: PrincipalId) => {+ if (props.create) {+ (props.issue as IssueCreate).assigneeId = newAssigneeId;+ } else {+ patchIssue({+ assigneeId: newAssigneeId,+ });+ }+ };++ const updateEarliestAllowedTime = (newEarliestAllowedTsMs: number) => {+ if (props.create) {+ selectedTask.value.earliestAllowedTs = newEarliestAllowedTsMs;+ } else {+ const taskPatch: TaskPatch = {+ earliestAllowedTs: newEarliestAllowedTsMs,+ };+ patchTask((selectedTask.value as Task).id, taskPatch);+ }+ };++ const addSubscriberId = (subscriberId: PrincipalId) => {+ store.dispatch("issueSubscriber/createSubscriber", {+ issueId: (props.issue as Issue).id,+ subscriberId,+ });+ };++ const removeSubscriberId = (subscriberId: PrincipalId) => {+ store.dispatch("issueSubscriber/deleteSubscriber", {+ issueId: (props.issue as Issue).id,+ subscriberId,+ });+ };++ const updateCustomField = (field: InputField | OutputField, value: any) => {+ if (!isEqual(props.issue.payload[field.id], value)) {+ if (props.create) {+ props.issue.payload[field.id] = value;+ } else {+ const newPayload = cloneDeep(props.issue.payload);+ newPayload[field.id] = value;+ patchIssue({+ payload: newPayload,+ });+ }+ }+ };++ const doCreate = () => {+ const issue = cloneDeep(props.issue) as IssueCreate;+ if (isTenantDeployMode.value) {+ // multi-tenancy issue's pipeline is generated on server-side+ // so empty the local pipeline+ delete issue.pipeline;+ issue.payload = {};+ }+ store.dispatch("issue/createIssue", issue).then((createdIssue) => {+ // Use replace to omit the new issue url in the navigation history.+ router.replace(+ `/issue/${issueSlug(createdIssue.name, createdIssue.id)}`+ );+ });+ };++ const doRollback = () => {+ router.push({+ name: "workspace.issue.detail",+ params: {+ issueSlug: "new",+ },+ query: {+ template: "bb.issue.database.schema.update",+ rollbackIssue: (props.issue as Issue).id,+ },+ });+ };++ const changeIssueStatus = (newStatus: IssueStatus, comment: string) => {+ const issueStatusPatch: IssueStatusPatch = {+ status: newStatus,+ comment: comment,+ };++ store+ .dispatch("issue/updateIssueStatus", {+ issueId: (props.issue as Issue).id,+ issueStatusPatch,+ })+ .then(() => {+ // pollIssue(POST_CHANGE_POLL_INTERVAL);+ });+ };++ const changeTaskStatus = (+ task: Task,+ newStatus: TaskStatus,+ comment: string+ ) => {+ // Switch to the stage view containing this task+ selectStageId(task.stage.id);+ nextTick().then(() => {+ selectTaskId(task.id);+ });++ const taskStatusPatch: TaskStatusPatch = {+ status: newStatus,+ comment: comment,+ };++ store+ .dispatch("task/updateStatus", {+ issueId: (props.issue as Issue).id,+ pipelineId: (props.issue as Issue).pipeline.id,+ taskId: task.id,+ taskStatusPatch,+ })+ .then(() => {+ // pollIssue(POST_CHANGE_POLL_INTERVAL);+ emit("status-changed", true);+ });+ };++ const runTaskChecks = (task: Task) => {+ store+ .dispatch("task/runChecks", {+ issueId: (props.issue as Issue).id,+ pipelineId: (props.issue as Issue).pipeline.id,+ taskId: task.id,+ })+ .then(() => {+ // pollIssue(POST_CHANGE_POLL_INTERVAL);+ emit("status-changed", true);+ });+ };++ const patchIssue = (+ issuePatch: IssuePatch,+ postUpdated?: (updatedIssue: Issue) => void+ ) => {+ store+ .dispatch("issue/patchIssue", {+ issueId: (props.issue as Issue).id,+ issuePatch,+ })+ .then((updatedIssue) => {+ // issue/patchIssue already fetches the new issue, so we schedule+ // the next poll in NORMAL_POLL_INTERVAL+ // pollIssue(NORMAL_POLL_INTERVAL);+ emit("status-changed", false);+ if (postUpdated) {+ postUpdated(updatedIssue);+ }+ });+ };++ const patchTask = (+ taskId: TaskId,+ taskPatch: TaskPatch,+ postUpdated?: (updatedTask: Task) => void+ ) => {+ store+ .dispatch("task/patchTask", {+ issueId: (props.issue as Issue).id,+ pipelineId: (props.issue as Issue).pipeline.id,+ taskId,+ taskPatch,+ })+ .then((updatedTask) => {+ // For now, the only task/patchTask is to change statement, which will trigger async task check.+ // Thus we use the short poll interval+ // pollIssue(POST_CHANGE_POLL_INTERVAL);+ emit("status-changed", true);+ if (postUpdated) {+ postUpdated(updatedTask);+ }+ });+ };++ const currentPipelineType = computed((): PipelineType => {+ return pipelineType(props.issue.pipeline!);+ });++ const selectedStage = computed((): Stage | StageCreate => {+ const stageSlug = router.currentRoute.value.query.stage as string;+ const taskSlug = router.currentRoute.value.query.task as string;+ // For stage slug, we support both index based and id based.+ // Index based is used when creating the new task and is the one used when clicking the UI.+ // Id based is used when the context only has access to the stage id (e.g. Task only contains StageId)+ if (stageSlug) {+ const index = indexFromSlug(stageSlug);+ if (index < props.issue.pipeline!.stageList.length) {+ return props.issue.pipeline!.stageList[index];+ }+ const stageId = idFromSlug(stageSlug);+ const stageList = (props.issue as Issue).pipeline.stageList;+ for (const stage of stageList) {+ if (stage.id == stageId) {+ return stage;+ }+ }+ } else if (!props.create && taskSlug) {+ const taskId = idFromSlug(taskSlug);+ const stageList = (props.issue as Issue).pipeline.stageList;+ for (const stage of stageList) {+ for (const task of stage.taskList) {+ if (task.id == taskId) {+ return stage;+ }+ }+ }+ }+ if (props.create) {+ return props.issue.pipeline!.stageList[0];+ }+ return activeStage((props.issue as Issue).pipeline);+ });++ const selectStageId = (+ stageId: StageId,+ task: string | undefined = undefined+ ) => {+ const stageList = props.issue.pipeline!.stageList;+ const index = stageList.findIndex((item, index) => {+ if (props.create) {+ return index == stageId;+ }+ return (item as Stage).id == stageId;+ });+ router.replace({+ name: "workspace.issue.detail",+ query: {+ ...router.currentRoute.value.query,+ stage: stageSlug(stageList[index].name, index),+ task,+ },+ });+ };++ const selectTask = (stageId: StageId, taskSlug: string) => {+ selectStageId(stageId, taskSlug);+ };++ const selectTaskId = (taskId: TaskId) => {+ const taskList = selectedStage.value.taskList as Task[];+ const task = taskList.find((t) => t.id === taskId);+ if (!task) return;+ const slug = taskSlug(task.name, task.id);+ const stage = selectedStage.value as Stage;+ selectTask(stage.id, slug);+ };++ const selectedTask = computed((): Task | TaskCreate => {+ const taskSlug = route.query.task as string;+ const { taskList } = selectedStage.value;+ if (taskSlug) {+ const index = indexFromSlug(taskSlug);+ if (index < taskList.length) {+ return taskList[index];+ }+ const id = idFromSlug(taskSlug);+ for (let i = 0; i < taskList.length; i++) {+ const task = taskList[i] as Task;+ if (task.id === id) {+ return task;+ }+ }+ }+ return taskList[0];+ });++ const statement = (stage: Stage): string => {+ const task = stage.taskList[0];+ switch (task.type) {+ case "bb.task.general":+ return ((task as Task).payload as TaskGeneralPayload).statement || "";+ case "bb.task.database.create":+ return (+ ((task as Task).payload as TaskDatabaseCreatePayload).statement ||+ ""+ );+ case "bb.task.database.schema.update":+ return (+ ((task as Task).payload as TaskDatabaseSchemaUpdatePayload)+ .statement || ""+ );+ case "bb.task.database.restore":+ return "";+ }+ };++ const rollbackStatement = (stage: Stage): string => {+ const task = stage.taskList[0];+ return (+ (task.payload as TaskDatabaseSchemaUpdatePayload).rollbackStatement ||+ ""+ );+ };++ const isTenantDeployMode = computed((): boolean => {+ if (+ props.issue.type === "bb.issue.database.schema.update" &&+ project.value.tenantMode === "TENANT"+ ) {+ const stages = props.issue.pipeline?.stageList;+ // We need this check, because when we do a "Establish new baseline" to+ // one of a tenant mode project's databases, we will create an issue+ // with type "bb.issue.database.schema.update" with dummy SQL statement.+ // In this case, it's schema.update, and it's TENANT mode, but it's not+ // a tenancy-based deployment+ // But we down-grade "1x1" pipeline to simple database deploy, that is+ // when we click "Alter Schema" in database detail page to alter exactly+ // ONE database's schema+ if (stages) {+ if (stages.length > 1) {+ // n stages, it's tenant mode+ // we won't down-grade to multi-database deployment here+ return true;+ }+ if (stages.length === 1 && stages[0].taskList.length > 1) {+ // 1 stage, n tasks, yes it's tenant mode+ return true;+ }+ }+ }+ return false;+ });++ const selectedStatement = computed((): string => {+ if (isTenantDeployMode.value) {+ if (props.create) {+ const issueCreate = props.issue as IssueCreate;+ const context = issueCreate.createContext as UpdateSchemaContext;+ return context.updateSchemaDetailList[0].statement;+ } else {+ const issue = props.issue as Issue;+ const task = issue.pipeline.stageList[0].taskList[0];+ const payload = task.payload as TaskDatabaseSchemaUpdatePayload;+ return payload.statement;+ }+ } else {+ if (router.currentRoute.value.query.sql) {+ const sql = router.currentRoute.value.query.sql as string;+ updateStatement(sql);+ }++ const task = (selectedStage.value as StageCreate).taskList[0];+ return task.statement;+ }+ });++ const selectedRollbackStatement = computed((): string => {+ const task = (selectedStage.value as StageCreate).taskList[0];+ return task.rollbackStatement;+ });++ const selectedMigrateType = computed((): MigrationType => {+ if (+ !props.create &&+ selectedTask.value.type == "bb.task.database.schema.update"+ ) {+ return (+ (selectedTask.value as Task)+ .payload as TaskDatabaseSchemaUpdatePayload+ ).migrationType;+ }+ return "MIGRATE";+ });++ const allowEditSidebar = computed(() => {+ // For now, we only allow assignee to update the field when the issue+ // is 'OPEN'. This reduces flexibility as creator must ask assignee to+ // change any fields if there is typo. On the other hand, this avoids+ // the trouble that the creator changes field value when the creator+ // is performing the issue based on the old value.+ // For now, we choose to be on the safe side at the cost of flexibility.+ return (+ props.create ||+ ((props.issue as Issue).status == "OPEN" &&+ (props.issue as Issue).assignee?.id == currentUser.value.id)+ );+ });++ const allowEditOutput = computed(() => {+ return (+ props.create ||+ ((props.issue as Issue).status == "OPEN" &&+ (props.issue as Issue).assignee?.id == currentUser.value.id)+ );+ });++ const allowEditNameAndDescription = computed(() => {+ return (+ props.create ||+ ((props.issue as Issue).status == "OPEN" &&+ ((props.issue as Issue).assignee?.id == currentUser.value.id ||+ (props.issue as Issue).creator.id == currentUser.value.id))+ );+ });++ const allowEditStatement = computed(() => {+ // if creating an issue, it's editable+ if (props.create) {+ return true;+ }+ const checkTask = (task: Task) => {+ return (+ task.status == "PENDING" ||+ task.status == "PENDING_APPROVAL" ||+ task.status == "FAILED"+ );+ };++ const issue = props.issue as Issue;+ // if not creating, we are allowed to edit sql statement only when:+ // 1. issue.status is OPEN+ // 2. AND currentUser is the creator+ // 3. AND workflowType is UI+ if (issue.status !== "OPEN") return false;+ if (issue.creator.id !== currentUser.value.id) return false;+ if (issue.project.workflowType !== "UI") return false;++ if (isTenantDeployMode.value) {+ // <del>then if in tenant deploy mode, EVERY task must be PENDING or PENDING_APPROVAL or FAILED</del>+ // nope, we are not allowed to update statement in tenant deploy mode anyway+ // const allTasks = issue.pipeline.stageList.flatMap(+ // (stage) => stage.taskList+ // );+ // return allTasks.every((task) => checkTask(task));+ return false;+ } else {+ // otherwise, check `selectedTask`, expected to be PENDING or PENDING_APPROVAL or FAILED+ return checkTask(selectedTask.value as Task);+ }+ });++ // For now, we only support rollback for schema update issue when all below conditions met:+ // 0. NOT tenant deploy mode+ // 1. Issue is in DONE or CANCELED state+ // 2. There is at least one completed schema update task and the task contains the rollback statement.+ const allowRollback = computed(() => {+ if (isTenantDeployMode.value) {+ return false;+ }+ if (!props.create) {+ if (props.issue.type == "bb.issue.database.schema.update") {+ if (+ (props.issue as Issue).status == "DONE" ||+ (props.issue as Issue).status == "CANCELED"+ ) {+ for (const stage of (props.issue as Issue).pipeline.stageList) {+ for (const task of stage.taskList) {+ if (+ task.status == "DONE" &&+ task.type == "bb.task.database.schema.update" &&+ !isEmpty(+ (task.payload as TaskDatabaseSchemaUpdatePayload)+ .rollbackStatement+ )+ ) {+ return true;+ }+ }+ }+ }+ }+ }+ return false;+ });++ const showCancelBanner = computed(() => {+ return !props.create && (props.issue as Issue).status == "CANCELED";+ });++ const showSuccessBanner = computed(() => {+ return !props.create && (props.issue as Issue).status == "DONE";+ });++ const showPendingApproval = computed(() => {+ if (props.create) {+ return false;+ }++ const task = activeTask((props.issue as Issue).pipeline);+ return task.status == "PENDING_APPROVAL";+ });++ const showPipelineFlowBar = computed(() => {+ return currentPipelineType.value != "NO_PIPELINE";+ });++ const showIssueOutputPanel = computed(() => {+ return !props.create && issueTemplate.value.outputFieldList.length > 0;+ });++ const showIssueTaskStatementPanel = computed(() => {+ const task = selectedTask.value;+ return (+ task.type == "bb.task.general" ||+ task.type == "bb.task.database.create" ||+ task.type == "bb.task.database.schema.update"+ );+ });++ const showIssueTaskRollbackStatementPanel = computed(() => {+ if (isTenantDeployMode.value) return false;+ if (project.value.workflowType == "UI") {+ if (props.issue.type == "bb.issue.database.schema.update") {+ return true;+ }+ }+ return false;+ });++ const showIssueTaskStatementApply = computed(() => {+ if (!props.create) {+ return false;+ }+ if (isTenantDeployMode.value) {+ return false;+ }+ let count = 0;+ for (const stage of (props.issue as IssueCreate).pipeline!.stageList) {+ for (const task of stage.taskList) {+ if (+ task.type == "bb.task.general" ||+ task.type == "bb.task.database.create" ||+ task.type == "bb.task.database.schema.update"+ ) {+ count++;+ }+ }+ }+ return count > 1;+ });++ const database = computed((): Database | undefined => {+ if (props.create) {+ const databaseId = (selectedTask.value as TaskCreate).databaseId;+ if (databaseId) {+ return store.getters["database/databaseById"](databaseId);+ }+ return undefined;+ }+ return (selectedTask.value as Task).database;+ });++ const instance = computed((): Instance => {+ if (props.create) {+ // If database is available, then we derive the instance from database because we always fetch database's instance.+ if (database.value) {+ return database.value.instance;+ }+ return store.getters["instance/instanceById"](+ (selectedTask.value as TaskCreate).instanceId+ );+ }+ return (selectedTask.value as Task).instance;+ });++ const sqlHint = (isRollBack: boolean): string | undefined => {+ if (+ !isRollBack &&+ !props.create &&+ selectedMigrateType.value == "BASELINE"+ ) {+ return `This is a baseline migration and bytebase won't apply the SQL to the database, it will only record a baseline history`;+ }+ if (!isRollBack && instance.value.engine === "SNOWFLAKE") {+ return `Use <<schema>>.<<table>> to specify a Snowflake table`;+ }+ return undefined;+ };++ onMounted(() => {+ // Always scroll to top, the scrollBehavior doesn't seem to work.+ // The hypothesis is that because the scroll bar is in the nested+ // route, thus setting the scrollBehavior in the global router+ // won't work.+ document.getElementById("issue-detail-top")!.scrollIntoView();+ });++ return {+ database,+ instance,+ sqlHint,+ updateName,+ updateDescription,+ updateStatement,+ updateEarliestAllowedTime,+ applyStatementToOtherStages,+ updateRollbackStatement,+ applyRollbackStatementToOtherStages,+ updateAssigneeId,+ addSubscriberId,+ removeSubscriberId,+ updateCustomField,+ doCreate,+ doRollback,+ changeIssueStatus,+ changeTaskStatus,+ runTaskChecks,+ currentPipelineType,+ currentUser,+ project,+ isTenantDeployMode,+ issueTemplate,+ selectedStage,+ selectedTask,+ selectStageId,+ selectTask,+ selectTaskId,+ statement,+ rollbackStatement,+ selectedStatement,+ selectedRollbackStatement,+ selectedMigrateType,+ allowEditSidebar,+ allowEditOutput,+ allowEditNameAndDescription,+ allowEditStatement,+ allowRollback,+ showCancelBanner,+ showSuccessBanner,+ showPendingApproval,+ showPipelineFlowBar,+ showIssueOutputPanel,+ showIssueTaskStatementPanel,+ showIssueTaskRollbackStatementPanel,+ showIssueTaskStatementApply,+ };+ },+});+</script>diff --git a/frontend/src/components/Issue/IssueSidebar.vue b/frontend/src/components/Issue/IssueSidebar.vueindex a6780f0b12..6183c31497 100644--- a/frontend/src/components/Issue/IssueSidebar.vue+++ b/frontend/src/components/Issue/IssueSidebar.vue@@ -81,6 +81,20 @@</div></template>+ <template v-if="showTaskSelect">+ <h2 class="textlabel flex items-center col-span-1 col-start-1">+ {{ $t("common.task") }}+ </h2>+ <div class="col-span-2">+ <TaskSelect+ :pipeline="issue.pipeline"+ :stage="selectedStage"+ :selected-id="task.id"+ @select-task-id="(taskId) => $emit('select-task-id', taskId)"+ />+ </div>+ </template>+<h2 class="textlabel flex items-center col-span-1 col-start-1"><span class="mr-1">{{ $t("common.when") }}</span><div class="tooltip-wrapper">@@ -162,6 +176,21 @@>{{ environmentName(environment) }}</router-link>++ <template v-if="isTenantProject && database">+ <h2 class="textlabel flex items-start col-span-1 col-start-1">+ {{ $t("common.labels") }}+ </h2>+ <div class="col-span-2">+ <div>+ <DatabaseLabels+ :editable="false"+ :label-list="database.labels"+ class="flex-col items-start"+ />+ </div>+ </div>+ </template></div><divclass="mt-6 border-t border-block-border pt-6 grid gap-y-6 gap-x-6 grid-cols-3"@@ -229,9 +258,11 @@ import { NDatePicker } from "naive-ui";import PrincipalAvatar from "../PrincipalAvatar.vue";import MemberSelect from "../MemberSelect.vue";import StageSelect from "./StageSelect.vue";+import TaskSelect from "./TaskSelect.vue";import IssueStatusIcon from "./IssueStatusIcon.vue";import IssueSubscriberPanel from "./IssueSubscriberPanel.vue";import InstanceEngineIcon from "../InstanceEngineIcon.vue";+import { DatabaseLabels } from "../DatabaseLabels";import { InputField } from "../../plugins";import {@@ -267,6 +298,8 @@ export default defineComponent({PrincipalAvatar,MemberSelect,StageSelect,+ TaskSelect,+ DatabaseLabels,IssueStatusIcon,IssueSubscriberPanel,InstanceEngineIcon,@@ -312,6 +345,7 @@ export default defineComponent({"remove-subscriber-id","update-custom-field","select-stage-id",+ "select-task-id",],setup(props, { emit }) {const store = useStore();@@ -380,12 +414,22 @@ export default defineComponent({return (props.issue as Issue).project;});+ const isTenantProject = computed((): boolean => {+ return project.value.tenantMode === "TENANT";+ });+const showStageSelect = computed((): boolean => {return (!props.create && allTaskList((props.issue as Issue).pipeline).length > 1);});+ const showTaskSelect = computed((): boolean => {+ if (props.create) return false;+ const { taskList } = props.selectedStage;+ return taskList.length > 1;+ });+const showInstance = computed((): boolean => {return isDBAOrOwner(currentUser.value.role);});@@ -448,15 +492,13 @@ export default defineComponent({return isDatabaseCreated.value ? "(created)" : "(pending create)";});- // TODO: errors detected by Vetur below is related to https://github.com/bytebase/bytebase/issues/56- // Will fix this in another branch.const clickDatabase = () => {// If the database has not been created yet, do nothing- if (props.database && props.database.value) {+ if (props.database) {router.push({name: "workspace.database.detail",params: {- databaseSlug: databaseSlug(props.database.value),+ databaseSlug: databaseSlug(props.database),},});} else {@@ -485,8 +527,10 @@ export default defineComponent({environment,databaseName,project,+ isTenantProject,showInstance,showStageSelect,+ showTaskSelect,allowEditAssignee,allowEditEarliestAllowedTime,allowEditCustomField,diff --git a/frontend/src/components/Issue/IssueStagePanel.vue b/frontend/src/components/Issue/IssueStagePanel.vueindex a478bdf083..f42d863eb0 100644--- a/frontend/src/components/Issue/IssueStagePanel.vue+++ b/frontend/src/components/Issue/IssueStagePanel.vue@@ -1,13 +1,22 @@<template><div class="space-y-4">- <div v-for="(task, index) in stage.taskList" :key="index">+ <div v-for="(task, index) in filteredTaskList" :key="index"><div class="flex flex-row items-center space-x-1"><heroicons-solid:arrow-narrow-right- v-if="stage.taskList.length > 1 && activeTask.id == task.id"+ v-if="+ !singleMode &&+ filteredTaskList.length > 1 &&+ activeTask.id == task.id+ "class="w-5 h-5 text-info"/>- <div v-if="stage.taskList.length > 1" class="textlabel">- <span v-if="stage.taskList.length > 1"> Step {{ index + 1 }} - </span>+ <div+ v-if="!singleMode && filteredTaskList.length > 1"+ class="textlabel"+ >+ <span v-if="filteredTaskList.length > 1">+ Step {{ index + 1 }} -+ </span>{{ task.name }}</div></div>@@ -33,6 +42,14 @@ export default defineComponent({required: true,type: Object as PropType<Stage>,},+ selectedTask: {+ type: Object as PropType<Task>,+ default: undefined,+ },+ singleMode: {+ type: Boolean,+ default: false,+ },},setup(props) {const state = reactive<LocalState>({});@@ -41,9 +58,17 @@ export default defineComponent({return activeTaskInStage(props.stage);});+ const filteredTaskList = computed(() => {+ if (props.singleMode && props.selectedTask) {+ return [props.selectedTask];+ }+ return props.stage.taskList;+ });+return {state,activeTask,+ filteredTaskList,};},});diff --git a/frontend/src/components/Issue/PipelineTenantFlow.vue b/frontend/src/components/Issue/PipelineTenantFlow.vuenew file mode 100644index 0000000000..0f4bf6033b--- /dev/null+++ b/frontend/src/components/Issue/PipelineTenantFlow.vue@@ -0,0 +1,369 @@+<template>+ <div class="w-full">+ <div class="lg:flex divide-y lg:divide-y-0 border-b">+ <div+ v-for="(item, i) in itemList"+ :key="i"+ class="stage-wrapper flex-1 md:flex md:flex-col items-center justify-start"+ >+ <div class="stage-header" :class="stageClass(item.stage)">+ <span class="pl-4 py-2 flex items-center text-sm font-medium">+ <TaskStatusIcon+ :create="create"+ :active="isActiveStage(item.stage)"+ :status="item.taskStatus"+ />+ <div+ class="text cursor-pointer hover:underline hidden lg:ml-4 lg:flex lg:flex-col"+ @click.prevent="clickItem(item)"+ >+ <span class="text-xs">+ {{ item.stageName }}+ </span>+ <span class="text-sm">{{ item.taskName }}</span>+ </div>+ <div+ class="text ml-4 cursor-pointer flex items-center space-x-2 lg:hidden"+ @click.prevent="clickItem(item)"+ >+ <span class="text-sm min-w-32">{{ item.stageName }} </span>+ <span class="text-sm flex-1">{{ item.taskName }}</span>+ </div>+ <div class="tooltip-wrapper" @click.prevent="clickItem(item)">+ <span class="tooltip whitespace-nowrap"+ >Missing SQL statement</span+ >+ <span+ v-if="!item.valid"+ class="ml-2 w-5 h-5 flex justify-center rounded-full select-none bg-error text-white hover:bg-error-hover"+ >+ <span class="text-center font-normal" aria-hidden="true"+ >!</span+ >+ </span>+ </div>+ </span>++ <!-- Arrow separator -->+ <div+ v-if="i < itemList.length - 1"+ class="hidden lg:block absolute top-0 right-0 h-full w-5"+ aria-hidden="true"+ >+ <svg+ class="h-full w-full text-gray-300"+ viewBox="0 0 22 80"+ fill="none"+ preserveAspectRatio="none"+ >+ <path+ d="M0 -2L20 40L0 82"+ vector-effect="non-scaling-stroke"+ stroke="currentcolor"+ stroke-linejoin="round"+ />+ </svg>+ </div>+ </div>+ </div>+ </div>++ <div class="task-list gap-2 p-2 md:grid md:grid-cols-2 lg:grid-cols-4">+ <div+ v-for="(task, j) in taskList"+ :key="j"+ class="task px-2 py-1 cursor-pointer border rounded"+ :class="taskClass(task)"+ @click="clickTask(selectedStageId, task.name, create ? j + 1 : task.id)"+ >+ <div class="flex items-center pb-1">+ <TaskStatusIcon+ :create="create"+ :active="isActiveTask(task)"+ :status="task.status"+ class="transform scale-75"+ />+ <heroicons-solid:arrow-narrow-right+ v-if="isActiveTask(task)"+ class="name w-5 h-5"+ />+ <div class="name">{{ j + 1 }} - {{ databaseForTask(task).name }}</div>+ </div>+ <div class="flex items-center px-1 py-1 whitespace-pre-wrap">+ <InstanceEngineIcon :instance="databaseForTask(task).instance" />+ <span+ class="flex-1 ml-2 overflow-x-hidden whitespace-nowrap overflow-ellipsis"+ >+ {{ instanceName(databaseForTask(task).instance) }}+ </span>+ </div>+ </div>+ </div>+ </div>+</template>++<script lang="ts">+import { computed, defineComponent, PropType, watchEffect } from "vue";+import {+ Pipeline,+ TaskStatus,+ TaskId,+ Stage,+ StageId,+ StageCreate,+ PipelineCreate,+ Task,+ TaskCreate,+ Project,+ Database,+} from "../../types";+import { activeTask, activeTaskInStage, taskSlug } from "../../utils";+import { isEmpty } from "lodash-es";+import { useStore } from "vuex";+import TaskStatusIcon from "./TaskStatusIcon.vue";++interface FlowItem {+ stageId: StageId;+ stageName: string;+ taskId: TaskId;+ taskName: string;+ taskStatus: TaskStatus;+ valid: boolean;+ stage: Stage | StageCreate;+ taskList: (Task | TaskCreate)[];+}++export default defineComponent({+ name: "PipelineTenantFlow",+ components: {+ TaskStatusIcon,+ },+ props: {+ create: {+ required: true,+ type: Boolean,+ },+ project: {+ required: true,+ type: Object as PropType<Project>,+ },+ pipeline: {+ required: true,+ type: Object as PropType<Pipeline | PipelineCreate>,+ },+ selectedStage: {+ required: true,+ type: Object as PropType<Stage | StageCreate>,+ },+ selectedTask: {+ type: Object as PropType<Task | TaskCreate | undefined>,+ default: undefined,+ },+ },+ emits: ["select-stage-id", "select-task"],+ setup(props, { emit }) {+ const store = useStore();++ watchEffect(function prepare() {+ if (props.create) {+ store.dispatch(+ "database/fetchDatabaseListByProjectId",+ props.project.id+ );+ }+ });++ const databaseForTask = (task: Task | TaskCreate): Database => {+ if (props.create) {+ return store.getters["database/databaseById"](+ (task as TaskCreate).databaseId+ ) as Database;+ } else {+ return (task as Task).database!;+ }+ };++ const isSelectedStage = (stage: Stage | StageCreate): boolean => {+ return stage === props.selectedStage;+ };++ const isSelectedTask = (task: Task | TaskCreate): boolean => {+ return task === props.selectedTask;+ };++ const isActiveStage = (stage: Stage | StageCreate): boolean => {+ if (props.create) return false;++ const task = activeTaskInStage(stage as Stage);+ if (activeTask(props.pipeline as Pipeline).id === task.id) {+ return true;+ }+ return false;+ };++ const isActiveTask = (task: Task | TaskCreate): boolean => {+ if (props.create) return false;+ task = task as Task;+ return activeTask(props.pipeline as Pipeline).id === task.id;+ };++ const itemList = computed<FlowItem[]>(() => {+ return props.pipeline.stageList.map((stage, index) => {+ let activeTask = stage.taskList[0];+ let taskName = activeTask.name;+ let valid = true;+ if (props.create) {+ for (const task of stage.taskList) {+ if (+ task.type == "bb.task.database.create" ||+ task.type == "bb.task.database.schema.update"+ ) {+ if (isEmpty((task as TaskCreate).statement)) {+ valid = false;+ break;+ }+ }+ }+ } else {+ activeTask = activeTaskInStage(stage as Stage);+ if (stage.taskList.length > 1) {+ for (let i = 0; i < stage.taskList.length; i++) {+ if ((stage.taskList[i] as Task).id == (activeTask as Task).id) {+ taskName = `${activeTask.name} (${i + 1}/${+ stage.taskList.length+ })`;+ break;+ }+ }+ }+ }++ return {+ stageId: props.create ? index : (stage as Stage).id,+ stageName: stage.name,+ taskId: props.create ? index : (activeTask as Task).id,+ taskName: taskName,+ taskStatus: activeTask.status,+ stage,+ taskList: stage.taskList,+ valid,+ };+ });+ });++ const taskList = computed(() => {+ return props.selectedStage.taskList;+ });++ const selectedStageId = computed(() => {+ if (!props.create) {+ return (props.selectedStage as Stage).id;+ } else {+ return props.pipeline.stageList.indexOf(props.selectedStage as any);+ }+ });++ const stageClass = (stage: Stage | StageCreate): string[] => {+ const classes: string[] = [];+ if (props.create) classes.push("create");+ if (isSelectedStage(stage)) classes.push("selected");+ if (isActiveStage(stage)) classes.push("active");+ const task = activeTaskInStage(stage as Stage);+ classes.push(`status_${task.status.toLowerCase()}`);++ return classes;+ };++ const taskClass = (task: Task | TaskCreate) => {+ const classes: string[] = [];+ if (isSelectedTask(task)) classes.push("selected");+ if (isActiveTask(task)) classes.push("active");+ if (props.create) classes.push("create");+ classes.push(`status_${task.status.toLowerCase()}`);+ return classes;+ };++ const clickItem = (item: FlowItem) => {+ emit("select-stage-id", item.stageId);+ };++ const clickTask = (stageId: number, taskName: string, taskId: number) => {+ const ts = taskSlug(taskName, taskId);+ emit("select-task", stageId, ts);+ };++ return {+ isSelectedStage,+ isSelectedTask,+ isActiveStage,+ isActiveTask,+ itemList,+ taskList,+ selectedStageId,+ activeTask,+ stageClass,+ taskClass,+ clickItem,+ clickTask,+ databaseForTask,+ };+ },+});+</script>++<style scoped lang="postcss">+.stage-header {+ @apply cursor-default flex items-center justify-start w-full relative;+}++.stage-header.selected .text {+ @apply underline;+}+.stage-header.active .text {+ @apply font-bold;+}+.stage-header.status_done .text {+ @apply text-control;+}+.stage-header.status_pending .text,+.stage-header.status_pending_approval .text {+ @apply text-control;+}+.stage-header.active.status_pending .text,+.stage-header.active.status_pending_approval .text {+ @apply text-info;+}+.stage-header.status_running .text {+ @apply text-info;+}+.stage-header.status_failed .text {+ @apply text-red-500;+}++.task.selected {+ @apply border-info;+}+.task .name {+ @apply ml-1 overflow-x-hidden whitespace-nowrap overflow-ellipsis;+}+.task.active .name {+ @apply font-bold;+}+.task.status_done .name {+ @apply text-control;+}+.task.status_pending .name,+.task.status_pending_approval .name {+ @apply text-control;+}+.task.active.status_pending .name,+.task.active.status_pending_approval .name {+ @apply text-info;+}+.task.status_running .name {+ @apply text-info;+}+.task.status_failed .name {+ @apply text-red-500;+}+</style>diff --git a/frontend/src/components/Issue/TaskRunTable.vue b/frontend/src/components/Issue/TaskRunTable.vueindex 87376da0f6..f1ca41548e 100644--- a/frontend/src/components/Issue/TaskRunTable.vue+++ b/frontend/src/components/Issue/TaskRunTable.vue@@ -155,9 +155,10 @@ export default defineComponent({link: `/instance/${instanceSlug(props.task.instance)}`,};} else if (- taskRun.code == MigrationErrorCode.MIGRAITON_ALREADY_APPLIED ||- taskRun.code == MigrationErrorCode.MGIRATION_OUT_OF_ORDER ||- taskRun.code == MigrationErrorCode.MIGRATION_BASELINE_MISSING+ props.task.database &&+ (taskRun.code == MigrationErrorCode.MIGRAITON_ALREADY_APPLIED ||+ taskRun.code == MigrationErrorCode.MGIRATION_OUT_OF_ORDER ||+ taskRun.code == MigrationErrorCode.MIGRATION_BASELINE_MISSING)) {return {title: t("task.view-migration-history"),diff --git a/frontend/src/components/Issue/TaskSelect.vue b/frontend/src/components/Issue/TaskSelect.vuenew file mode 100644index 0000000000..f4f140db1e--- /dev/null+++ b/frontend/src/components/Issue/TaskSelect.vue@@ -0,0 +1,79 @@+<template>+ <select+ class="btn-select w-full disabled:cursor-not-allowed"+ @change="+ (e: any) => {+ $emit('select-task-id', parseInt(e.target.value, 10));+ }+ "+ >+ <template v-for="(task, index) in stage.taskList" :key="index">+ <option :value="task.id" :selected="task.id == state.selectedId">+ {{ index + 1 }} -+ {{+ isActiveTask(task.id)+ ? $t("issue.stage-select.active", { name: task.name })+ : task.name+ }}+ </option>+ </template>+ </select>+</template>++<script lang="ts">+import { computed, defineComponent, PropType, reactive, watch } from "vue";+import { UNKNOWN_ID, Pipeline, TaskId, Stage } from "../../types";+import { activeStage, activeTaskInStage } from "../../utils";++interface LocalState {+ selectedId: number;+}++export default defineComponent({+ name: "TaskSelect",+ props: {+ pipeline: {+ required: true,+ type: Object as PropType<Pipeline>,+ },+ stage: {+ required: true,+ type: Object as PropType<Stage>,+ },+ selectedId: {+ default: UNKNOWN_ID,+ type: Number as PropType<TaskId>,+ },+ },+ emits: ["select-task-id"],+ setup(props) {+ const state = reactive<LocalState>({+ selectedId: props.selectedId,+ });++ watch(+ () => props.selectedId,+ (cur, _) => {+ state.selectedId = cur;+ }+ );++ const isActiveStage = computed((): boolean => {+ const stage = activeStage(props.pipeline);+ return stage.id === props.stage.id;+ });++ const isActiveTask = (taskId: TaskId): boolean => {+ if (!isActiveStage.value) return false;+ const task = activeTaskInStage(props.stage);+ return task.id === taskId;+ };++ return {+ state,+ isActiveStage,+ isActiveTask,+ };+ },+});+</script>diff --git a/frontend/src/components/Issue/TaskSpinner.vue b/frontend/src/components/Issue/TaskSpinner.vueindex d07afd9071..136816d722 100644--- a/frontend/src/components/Issue/TaskSpinner.vue+++ b/frontend/src/components/Issue/TaskSpinner.vue@@ -25,6 +25,6 @@import { defineComponent } from "vue";export default defineComponent({- name: "Spinner",+ name: "TaskSpinner",});</script>diff --git a/frontend/src/components/Issue/TaskStatusIcon.vue b/frontend/src/components/Issue/TaskStatusIcon.vuenew file mode 100644index 0000000000..4176eacbea--- /dev/null+++ b/frontend/src/components/Issue/TaskStatusIcon.vue@@ -0,0 +1,73 @@+<template>+ <div+ class="relative flex flex-shrink-0 items-center justify-center rounded-full select-none w-6 h-6"+ :class="classes"+ >+ <template v-if="status === 'PENDING'">+ <span+ v-if="active"+ class="h-2 w-2 bg-info rounded-full"+ aria-hidden="true"+ ></span>+ <span+ v-else+ class="h-1.5 w-1.5 bg-control rounded-full"+ aria-hidden="true"+ ></span>+ </template>+ <template v-else-if="status === 'PENDING_APPROVAL'">+ <heroicons-outline:user class="w-4 h-4" />+ </template>+ <template v-else-if="status === 'RUNNING'">+ <span+ class="h-2.5 w-2.5 bg-info rounded-full"+ style="animation: pulse 2.5s cubic-bezier(0.4, 0, 0.6, 1) infinite"+ aria-hidden="true"+ ></span>+ </template>+ <template v-else-if="status === 'DONE'">+ <heroicons-solid:check class="w-5 h-5" />+ </template>+ <template v-else-if="status === 'FAILED'">+ <span+ class="h-2.5 w-2.5 rounded-full text-center pb-6 font-medium text-base"+ aria-hidden="true"+ >!</span+ >+ </template>+ </div>+</template>++<script lang="ts" setup>+import { computed, defineProps } from "vue";+import { TaskStatus } from "../../types";++const props = defineProps<{+ create: boolean;+ active: boolean;+ status: TaskStatus;+}>();++const classes = computed((): string => {+ switch (props.status) {+ case "PENDING":+ if (!props.create && props.active) {+ return "bg-white border-2 border-info text-info ";+ }+ return "bg-white border-2 border-control";+ case "PENDING_APPROVAL":+ if (!props.create && props.active) {+ return "bg-white border-2 border-info text-info";+ }+ return "bg-white border-2 border-control";+ case "RUNNING":+ return "bg-white border-2 border-info text-info";+ case "DONE":+ return "bg-success text-white";+ case "FAILED":+ return "bg-error text-white";+ default:+ return "";+ }+});+</script>diff --git a/frontend/src/components/Issue/index.ts b/frontend/src/components/Issue/index.tsindex 616a7ae6db..d1fcbcb9f8 100644--- a/frontend/src/components/Issue/index.ts+++ b/frontend/src/components/Issue/index.ts@@ -1,3 +1,4 @@+import IssueDetailLayout from "./IssueDetailLayout.vue";import IssueBanner from "./IssueBanner.vue";import IssueHighlightPanel from "./IssueHighlightPanel.vue";import IssueStagePanel from "./IssueStagePanel.vue";@@ -12,6 +13,7 @@ import TaskCheckBar from "./TaskCheckBar.vue";import IssueTable from "./IssueTable.vue";export {+ IssueDetailLayout,IssueBanner,IssueHighlightPanel,IssueStagePanel,diff --git a/frontend/src/components/ProjectCreate.vue b/frontend/src/components/ProjectCreate.vueindex da26ab4214..8c2c9cca67 100644--- a/frontend/src/components/ProjectCreate.vue+++ b/frontend/src/components/ProjectCreate.vue@@ -29,6 +29,35 @@@input="state.project.key = $event.target.value"/></div>+ <div class="col-span-1">+ <div for="name" class="text-lg leading-6 font-medium text-control">+ {{ $t("common.mode") }}<span class="text-red-600">*</span>+ </div>+ <div class="mt-2 textlabel">+ <div class="radio-set-row">+ <div class="radio">+ <input+ v-model="state.project.tenantMode"+ tabindex="-1"+ type="radio"+ class="btn"+ value="DISABLED"+ />+ <label class="label">{{ $t("project.mode.standard") }}</label>+ </div>+ <div class="radio">+ <input+ v-model="state.project.tenantMode"+ tabindex="-1"+ type="radio"+ class="btn"+ value="TENANT"+ />+ <label class="label">{{ $t("project.mode.tenant") }}</label>+ </div>+ </div>+ </div>+ </div></div><!-- Create button group --><div class="pt-4 flex justify-end">@@ -51,7 +80,13 @@</template><script lang="ts">-import { computed, reactive, onMounted, onUnmounted } from "vue";+import {+ computed,+ reactive,+ onMounted,+ onUnmounted,+ defineComponent,+} from "vue";import { useStore } from "vuex";import { useRouter } from "vue-router";import isEmpty from "lodash-es/isEmpty";@@ -63,7 +98,7 @@ interface LocalState {project: ProjectCreate;}-export default {+export default defineComponent({name: "ProjectCreate",props: {},emits: ["dismiss"],@@ -76,6 +111,7 @@ export default {project: {name: "New Project",key: randomString(3).toUpperCase(),+ tenantMode: "DISABLED",},});@@ -130,5 +166,5 @@ export default {create,};},-};+});</script>diff --git a/frontend/src/components/ProjectDeploymentConfigPanel.vue b/frontend/src/components/ProjectDeploymentConfigPanel.vuenew file mode 100644index 0000000000..b495ddf37c--- /dev/null+++ b/frontend/src/components/ProjectDeploymentConfigPanel.vue@@ -0,0 +1,235 @@+<template>+ <div class="max-w-3xl mx-auto">+ <BBAttention+ v-if="deployment?.id === EMPTY_ID"+ :style="'WARN'"+ :title="$t('common.deployment-config')"+ :description="$t('deployment-config.this-is-example-deployment-config')"+ >+ </BBAttention>+ <div class="divide-y">+ <DeploymentConfigTool+ v-if="deployment"+ :schedule="deployment.schedule"+ :allow-edit="allowEdit"+ :label-list="availableLabelList"+ :database-list="databaseList"+ />+ <div v-if="allowEdit" class="pt-4 flex justify-between items-center">+ <button class="btn-normal" @click="addStage">+ {{ $t("deployment-config.add-stage") }}+ </button>+ <NPopover :disabled="!state.error" trigger="hover">+ <template #trigger>+ <div+ class="btn-primary"+ :class="+ state.error ? 'bg-accent opacity-50 cursor-not-allowed' : ''+ "+ @click="update"+ >+ {{ $t("common.update") }}+ </div>+ </template>++ <span v-if="state.error" class="text-red-600">+ {{ $t(state.error) }}+ </span>+ </NPopover>+ </div>+ </div>+ </div>+</template>++<script lang="ts">+import {+ computed,+ defineComponent,+ nextTick,+ PropType,+ reactive,+ ref,+ watch,+ watchEffect,+} from "vue";+import { useStore } from "vuex";+import {+ Project,+ Environment,+ Label,+ Database,+ AvailableLabel,+ DeploymentConfig,+ UNKNOWN_ID,+ EMPTY_ID,+ empty,+ DeploymentConfigPatch,+ LabelSelectorRequirement,+} from "../types";+import DeploymentConfigTool from "./DeploymentConfigTool";+import { cloneDeep } from "lodash-es";+import { useI18n } from "vue-i18n";+import { NPopover } from "naive-ui";+import { generateDefaultSchedule, validateDeploymentConfig } from "../utils";++type LocalState = {+ error: string | undefined;+ ready: boolean;+};++export default defineComponent({+ name: "ProjectDeploymentConfigurationPanel",+ components: { DeploymentConfigTool, NPopover },+ props: {+ project: {+ required: true,+ type: Object as PropType<Project>,+ },+ allowEdit: {+ default: true,+ type: Boolean,+ },+ },+ setup(props) {+ const store = useStore();+ const { t } = useI18n();+ const deployment = ref<DeploymentConfig>();++ const state = reactive<LocalState>({+ ready: false,+ error: undefined,+ });++ const prepareList = () => {+ store.dispatch("environment/fetchEnvironmentList");+ store.dispatch("label/fetchLabelList");+ store.dispatch("database/fetchDatabaseListByProjectId", props.project.id);+ store.dispatch(+ "deployment/fetchDeploymentConfigByProjectId",+ props.project.id+ );+ };++ const environmentList = computed(+ () => store.getters["environment/environmentList"]() as Environment[]+ );++ const labelList = computed(+ () => store.getters["label/labelList"]() as Label[]+ );++ const databaseList = computed(+ () =>+ store.getters["database/databaseListByProjectId"](+ props.project.id+ ) as Database[]+ );++ watchEffect(prepareList);++ const availableLabelList = computed((): AvailableLabel[] => {+ return labelList.value.map((label) => {+ return { key: label.key, valueList: [...label.valueList] };+ });+ });++ watchEffect(() => {+ const dep = store.getters["deployment/deploymentConfigByProjectId"](+ props.project.id+ ) as DeploymentConfig;+ if (dep.id === UNKNOWN_ID) {+ // if the project has no related deployment-config+ // just generate a "staged-by-env" example to users+ // this is not saved immediately, it's a draft+ // users need to edit and save it before creating a deployment issue+ if (environmentList.value.length > 0) {+ deployment.value = empty("DEPLOYMENT_CONFIG") as DeploymentConfig;+ deployment.value.schedule = generateDefaultSchedule(+ environmentList.value+ );+ }+ } else {+ // otherwise we clone the saved deployment-config+ // <DeploymentConfigTool /> will mutate `deployment.value` directly+ // when update button clicked, we save the draft to backend+ // we don't show a "cancel" button because if users don't want to save+ // the draft, they can just leave the page without any saving action+ // even more we may deliver a confirm modal when leaving the page with a+ // dirty but not saved draft+ deployment.value = cloneDeep(dep);+ }+ nextTick(() => {+ // then we reset the local state+ state.ready = true;+ state.error = undefined;+ });+ });++ const addStage = () => {+ if (!deployment.value) return;+ const rule: LabelSelectorRequirement = {+ key: "bb.environment",+ operator: "In",+ values: [],+ };+ if (environmentList.value.length > 0) {+ rule.values.push(environmentList.value[0].name);+ }++ deployment.value.schedule.deployments.push({+ name: "New Stage",+ spec: {+ selector: {+ matchExpressions: [rule],+ },+ },+ });+ };++ const validate = () => {+ if (!deployment.value) return;+ state.error = validateDeploymentConfig(deployment.value);+ };++ const update = () => {+ if (!deployment.value) return;+ if (state.error) return;++ const deploymentConfigPatch: DeploymentConfigPatch = {+ payload: JSON.stringify(deployment.value.schedule),+ };+ store.dispatch("deployment/patchDeploymentConfigByProjectId", {+ projectId: props.project.id,+ deploymentConfigPatch,+ });+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "SUCCESS",+ title: t("deployment-config.update-success"),+ });+ };++ watch(+ deployment,+ (dep) => {+ if (!dep) return;+ if (!state.ready) return;+ validate();+ },+ { deep: true }+ );++ return {+ EMPTY_ID,+ state,+ environmentList,+ labelList,+ databaseList,+ availableLabelList,+ deployment,+ addStage,+ update,+ };+ },+});+</script>diff --git a/frontend/src/components/ProjectOverviewPanel.vue b/frontend/src/components/ProjectOverviewPanel.vueindex f4f9eaf458..87c22bd75c 100644--- a/frontend/src/components/ProjectOverviewPanel.vue+++ b/frontend/src/components/ProjectOverviewPanel.vue@@ -15,19 +15,43 @@</div><div class="space-y-2">- <p class="text-lg font-medium leading-7 text-main">+ <div+ class="text-lg font-medium leading-7 text-main flex items-center justify-between"+ >{{ $t("common.database") }}- </p>+ <div v-if="isTenantProject">+ <label for="search" class="sr-only">Search</label>+ <div class="relative rounded-md shadow-sm">+ <div+ class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"+ aria-hidden="true"+ >+ <heroicons-solid:search class="mr-3 h-4 w-4 text-control" />+ </div>+ <input+ v-model="state.databaseNameFilter"+ type="text"+ autocomplete="off"+ name="search"+ class="focus:ring-main focus:border-main block w-full pl-9 sm:text-sm border-control-border rounded-md"+ :placeholder="$t('database.search-database-name')"+ />+ </div>+ </div>+ </div><BBAttentionv-if="project.id == DEFAULT_PROJECT_ID":style="`INFO`":title="$t('project.overview.info-slot-content')"/>- <DatabaseTable- v-if="databaseList.length > 0"- :mode="'PROJECT'"- :database-list="databaseList"- />+ <template v-if="databaseList.length > 0">+ <TenantDatabaseTable+ v-if="isTenantProject"+ :database-list="databaseList"+ :filter="state.databaseNameFilter"+ />+ <DatabaseTable v-else :mode="'PROJECT'" :database-list="databaseList" />+ </template><div v-else class="text-center textinfolabel"><i18n-t keypath="project.overview.no-db-prompt" tag="p"><template #newDb>@@ -72,10 +96,17 @@</template><script lang="ts">-import { reactive, watchEffect, PropType } from "vue";+import {+ reactive,+ watchEffect,+ PropType,+ computed,+ defineComponent,+} from "vue";import { useStore } from "vuex";import ActivityTable from "../components/ActivityTable.vue";import DatabaseTable from "../components/DatabaseTable.vue";+import TenantDatabaseTable from "./TenantDatabaseTable";import { IssueTable } from "../components/Issue";import {Activity,@@ -92,13 +123,15 @@ interface LocalState {activityList: Activity[];progressIssueList: Issue[];closedIssueList: Issue[];+ databaseNameFilter: string;}-export default {+export default defineComponent({name: "ProjectOverviewPanel",components: {ActivityTable,DatabaseTable,+ TenantDatabaseTable,IssueTable,},props: {@@ -118,6 +151,7 @@ export default {activityList: [],progressIssueList: [],closedIssueList: [],+ databaseNameFilter: "",});const prepareActivityList = () => {@@ -156,10 +190,15 @@ export default {watchEffect(prepareIssueList);+ const isTenantProject = computed((): boolean => {+ return props.project.tenantMode === "TENANT";+ });+return {DEFAULT_PROJECT_ID,state,+ isTenantProject,};},-};+});</script>diff --git a/frontend/src/components/ProjectSelect.vue b/frontend/src/components/ProjectSelect.vueindex e26f2d9aba..4bba4a5f0c 100644--- a/frontend/src/components/ProjectSelect.vue+++ b/frontend/src/components/ProjectSelect.vue@@ -3,8 +3,8 @@class="btn-select w-full disabled:cursor-not-allowed":disabled="disabled"@change="- (e) => {- $emit('select-project-id', parseInt(e.target.value));+ (e: any) => {+ $emit('select-project-id', parseInt(e.target.value, 10));}">@@ -54,6 +54,7 @@import {computed,ComputedRef,+ defineComponent,PropType,reactive,watch,@@ -73,7 +74,12 @@ interface LocalState {selectedId: number;}-export default {+export enum Mode {+ Standard = 1,+ Tenant = 2,+}++export default defineComponent({name: "ProjectSelect",props: {selectedId: {@@ -92,6 +98,10 @@ export default {default: false,type: Boolean,},+ mode: {+ type: Number as PropType<Mode>,+ default: Mode.Standard | Mode.Tenant,+ },},emits: ["select-project-id"],setup(props) {@@ -118,15 +128,25 @@ export default {);const projectList = computed((): Project[] => {- const list = store.getters["project/projectListByUser"](+ let list = store.getters["project/projectListByUser"](currentUser.value.id,["NORMAL", "ARCHIVED"]- );+ ) as Project[];if (props.includeDefaultProject) {list.unshift(store.getters["project/projectById"](DEFAULT_PROJECT_ID));}+ list = list.filter((project) => {+ if (project.tenantMode === "DISABLED" && props.mode & Mode.Standard) {+ return true;+ }+ if (project.tenantMode === "TENANT" && props.mode & Mode.Tenant) {+ return true;+ }+ return false;+ });+if (!hasAdminFeature.value || isDBAOrOwner(currentUser.value.role)) {return list;}@@ -175,5 +195,5 @@ export default {selectedIdNotInList,};},-};+});</script>diff --git a/frontend/src/components/TenantDatabaseTable/DatabaseMatrix.vue b/frontend/src/components/TenantDatabaseTable/DatabaseMatrix.vuenew file mode 100644index 0000000000..bffbc6120c--- /dev/null+++ b/frontend/src/components/TenantDatabaseTable/DatabaseMatrix.vue@@ -0,0 +1,257 @@+<template>+ <slot v-if="showHeader" name="header">+ <div class="text-base font-medium">{{ name }}</div>+ </slot>++ <BBTable+ :data-source="filteredMatrixList"+ :show-header="true"+ :custom-header="true"+ :left-bordered="bordered"+ :right-bordered="bordered"+ :top-bordered="bordered"+ :bottom-bordered="bordered"+ :row-clickable="false"+ >+ <template #header>+ <tr>+ <BBTableHeaderCell compact class="w-1/12 pl-3 pr-2">+ <YAxisSwitch+ v-if="yAxisLabel"+ v-model:label="yAxisLabel"+ :label-list="selectableLabelList"+ />+ </BBTableHeaderCell>++ <BBTableHeaderCell+ v-for="xValue in filteredXAxisValueList"+ :key="xValue"+ :style="{+ width: `${(100 - 1 / 12) / filteredXAxisValueList.length - 1}%`,+ }"+ class="text-center"+ >+ <template v-if="xValue">{{ xValue }}</template>+ <template v-else>{{ $t("label.empty-label-value") }}</template>+ </BBTableHeaderCell>+ </tr>+ </template>++ <template #body="{ rowData: matrix }">+ <BBTableCell+ :left-padding="4"+ class="pr-2 whitespace-nowrap"+ :class="{+ 'text-control-placeholder': !matrix.labelValue,+ }"+ >+ <template v-if="matrix.labelValue">{{ matrix.labelValue }}</template>+ <template v-else>{{ $t("label.empty-label-value") }}</template>+ </BBTableCell>+ <BBTableCell v-for="(dbList, i) in matrix.databaseMatrix" :key="i">+ <div class="flex flex-col items-center space-y-1">+ <DatabaseMatrixItem+ v-for="db in dbList"+ :key="db.id"+ :database="db"+ :custom-click="customClick"+ @select-database="(db) => $emit('select-database', db)"+ />+ <span v-if="dbList.length === 0">-</span>+ </div>+ </BBTableCell>+ </template>+ </BBTable>+</template>++<script lang="ts">+import { computed, defineComponent, PropType, ref, watchEffect } from "vue";+import {+ Database,+ Environment,+ Label,+ LabelKeyType,+ LabelValueType,+} from "../../types";+import DatabaseMatrixItem from "./DatabaseMatrixItem.vue";+import { groupBy } from "lodash-es";+import { findDefaultGroupByLabel, getLabelValue } from "../../utils";+import YAxisSwitch from "./YAxisSwitch.vue";++type DatabaseMatrix = {+ labelValue: LabelValueType;+ databaseMatrix: Database[][];+};++export default defineComponent({+ name: "TenantDatabaseMatrix",+ components: { DatabaseMatrixItem, YAxisSwitch },+ props: {+ bordered: {+ default: true,+ type: Boolean,+ },+ customClick: {+ default: false,+ type: Boolean,+ },+ name: {+ type: String,+ default: "",+ },+ showHeader: {+ type: Boolean,+ default: true,+ },+ databaseList: {+ type: Object as PropType<Database[]>,+ required: true,+ },+ environmentList: {+ type: Array as PropType<Environment[]>,+ required: true,+ },+ labelList: {+ type: Array as PropType<Label[]>,+ required: true,+ },+ },+ emits: ["select-database"],+ setup(props) {+ // make "bb.environment" non-selectable because it was already specified to the x-axis+ const selectableLabelList = computed(() => {+ const excludes = new Set(["bb.environment"]);+ return props.labelList.filter((label) => !excludes.has(label.key));+ });++ /**+ * databases are grouped by `yAxisLabel` then by `xAxisLabel`+ * for now, `xAxisLabel` will always be 'bb.environment'+ */+ const yAxisLabel = ref<LabelKeyType>();+ const xAxisLabel = ref<LabelKeyType>("bb.environment");++ const filteredXAxisValueList = ref<LabelValueType[]>([]);+ const filteredMatrixList = ref<DatabaseMatrix[]>([]);++ // find the default label key to firstBy (y-axis)+ watchEffect(() => {+ // "bb.environment" is excluded because it was specified to the x-axis+ yAxisLabel.value = findDefaultGroupByLabel(+ selectableLabelList.value,+ props.databaseList+ );+ });++ // pre-filtered y-axis values+ const yAxisValueList = computed((): string[] => {+ const key = yAxisLabel.value;+ if (!key) {+ // y-axis is undefined+ return [];+ }++ // order based on label.valueList+ // plus one more "<empty value>"+ const label = props.labelList.find((label) => label.key === key);+ if (!label) return [];+ return [...label.valueList, ""];+ });++ // pre-filtered x-axis values+ const xAxisValueList = computed(() => {+ // order based on label.valueList+ // plus one more "<empty value>"+ const key = xAxisLabel.value;+ const label = props.labelList.find((label) => label.key === key);+ if (!label) return [];+ return [...label.valueList, ""];+ });++ // first, group databases by `yAxisLabel` into some rows+ const groupedRowList = computed(() => {+ const key = yAxisLabel.value;+ if (!key) {+ // y-axis is undefined+ return [];+ }+ const dict = groupBy(props.databaseList, (db) => getLabelValue(db, key));+ return yAxisValueList.value.map((labelValue) => {+ const databaseList = dict[labelValue] || [];+ return {+ labelValue,+ databaseList,+ };+ });+ });++ // then, group each row by `xAxisLabel` into some columns+ // now the `matrices` is pre-filtered (with empty rows or columns)+ const matrixList = computed((): DatabaseMatrix[] => {+ const key = xAxisLabel.value;+ return groupedRowList.value.map(+ ({ labelValue: yValue, databaseList }) => {+ const databaseMatrix: Database[][] = xAxisValueList.value.map(+ (xValue) =>+ databaseList.filter((db) => getLabelValue(db, key) === xValue)+ );+ return {+ labelValue: yValue,+ databaseMatrix,+ };+ }+ );+ });++ // now filter the axes and matrices+ // we only remove rows/cols of "<empty value>"+ // but keep other empty rows/cols because we want to give a whole view to+ // the project.+ // e.g. if we hide "Prod" because there are no databases labeled as+ // "bb:environment: Prod", we are then not able to judge whether there is+ // no such an environment named "Prod" or "Prod" has no databases.+ watchEffect(() => {+ filteredXAxisValueList.value = [...xAxisValueList.value];+ // if every row's "<empty value>" has no databases+ // we should hide the "<empty value>" col+ const shouldClipLastCol = matrixList.value.every(+ (row) =>+ row.databaseMatrix.length > 0 &&+ row.databaseMatrix[row.databaseMatrix.length - 1].length === 0+ );+ if (shouldClipLastCol) filteredXAxisValueList.value.pop();++ filteredMatrixList.value = [];+ for (let i = 0; i < matrixList.value.length; i++) {+ const row = {+ labelValue: matrixList.value[i].labelValue,+ databaseMatrix: [...matrixList.value[i].databaseMatrix],+ };+ if (shouldClipLastCol) {+ row.databaseMatrix.pop();+ }+ filteredMatrixList.value.push(row);+ }+ // if every col of "<empty value>" row is empty+ // we should hide the "<empty value>" row+ if (+ filteredMatrixList.value.length > 0 &&+ filteredMatrixList.value[+ filteredMatrixList.value.length - 1+ ].databaseMatrix.every((item) => item.length === 0)+ ) {+ filteredMatrixList.value.pop();+ }+ });++ return {+ selectableLabelList,+ yAxisLabel,+ yAxisValueList,+ xAxisValueList,+ filteredXAxisValueList,+ filteredMatrixList,+ };+ },+});+</script>diff --git a/frontend/src/components/TenantDatabaseTable/DatabaseMatrixItem.vue b/frontend/src/components/TenantDatabaseTable/DatabaseMatrixItem.vuenew file mode 100644index 0000000000..8b938439ab--- /dev/null+++ b/frontend/src/components/TenantDatabaseTable/DatabaseMatrixItem.vue@@ -0,0 +1,112 @@+<template>+ <NPopover trigger="hover">+ <template #trigger>+ <div class="bb-database-matrix-item" @click="clickDatabase">+ <div class="sync-status whitespace-nowrap">+ <span class="tooltip-wrapper">+ <heroicons-solid:check+ v-if="database.syncStatus === 'OK'"+ class="w-4 h-4 text-success"+ />+ <heroicons-outline:exclamation+ v-else+ class="w-4 h-4 text-warning"+ />+ </span>+ <span class="flex-1">{{ database.syncStatus }}</span>+ </div>++ <div>{{ $t("common.version") }}: {{ database.schemaVersion }}</div>+ </div>+ </template>++ <div class="popover">+ <div class="instance flex items-center whitespace-pre-wrap">+ <InstanceEngineIcon :instance="database.instance" />+ <span class="flex-1">{{ instanceName(database.instance) }}</span>+ </div>++ <div class="last-sync flex items-center">+ {{ $t("db.last-successful-sync") }}+ {{ humanizeTs(database.lastSuccessfulSyncTs) }}+ </div>++ <div+ v-if="database.labels.length > 0"+ class="labels whitespace-nowrap flex-col items-start"+ >+ <div class="mb-2">{{ $t("common.labels") }}</div>+ <DatabaseLabels+ :label-list="database.labels"+ :editable="false"+ class="flex-col items-start"+ />+ </div>+ </div>+ </NPopover>+</template>++<script lang="ts">+import { defineComponent, PropType } from "vue";+import { useRouter } from "vue-router";+import { Database } from "../../types";+import { databaseSlug } from "../../utils";+import InstanceEngineIcon from "../InstanceEngineIcon.vue";+import DatabaseLabels from "../DatabaseLabels";+import { NPopover } from "naive-ui";++export default defineComponent({+ name: "DatabaseMatrixItem",+ components: {+ InstanceEngineIcon,+ DatabaseLabels,+ NPopover,+ },+ props: {+ database: {+ type: Object as PropType<Database>,+ required: true,+ },+ clickable: {+ type: Boolean,+ default: true,+ },+ customClick: {+ type: Boolean,+ default: false,+ },+ },+ emits: ["select-database"],+ setup(props, { emit }) {+ const router = useRouter();++ const clickDatabase = () => {+ const { clickable, customClick, database } = props;+ if (!clickable) return;++ if (customClick) {+ emit("select-database", database);+ } else {+ router.push(`/db/${databaseSlug(database)}`);+ }+ };++ return { clickDatabase };+ },+});+</script>++<style scoped lang="postcss">+.bb-database-matrix-item {+ @apply border-gray-300 border rounded px-2 py-0 divide-y cursor-pointer select-none hover:bg-gray-50;+}+.bb-database-matrix-item > * {+ @apply flex items-center py-1 gap-1;+}+.popover {+ @apply bg-white divide-y cursor-pointer select-none;+}+.popover > * {+ @apply py-1 gap-1;+}+</style>diff --git a/frontend/src/components/TenantDatabaseTable/DeployDatabaseTable.vue b/frontend/src/components/TenantDatabaseTable/DeployDatabaseTable.vuenew file mode 100644index 0000000000..adb11cdd56--- /dev/null+++ b/frontend/src/components/TenantDatabaseTable/DeployDatabaseTable.vue@@ -0,0 +1,197 @@+<template>+ <div>+ <BBTable+ :data-source="groupedStageList"+ :show-header="true"+ :custom-header="true"+ :row-clickable="false"+ >+ <template #header>+ <tr>+ <BBTableHeaderCell compact class="w-1/12 pl-3 pr-2">+ <YAxisSwitch v-model:label="state.label" :label-list="labelList" />+ </BBTableHeaderCell>++ <BBTableHeaderCell+ v-for="(xValue, i) in xAxisValueList"+ :key="xValue"+ :style="{ width: headerColumnWidth }"+ compact+ class="text-center py-2"+ >+ <NPopover placement="top" trigger="hover">+ <template #trigger>+ <span+ class="px-1.5 py-1 relative rounded inline-flex items-center hover:bg-control-bg-hover cursor-pointer select-none"+ >+ {{ xValue }}+ </span>+ </template>+ <div class="space-y-1">+ <div class="textlabel">+ {{ $t("deployment-config.selectors") }}+ </div>+ <DeploymentStage+ :allow-edit="false"+ :show-header="false"+ :deployment="deployment.schedule.deployments[i]"+ />+ </div>+ </NPopover>+ </BBTableHeaderCell>++ <BBTableHeaderCell v-if="hasRest" compact class="text-center py-2">+ <NPopover placement="top" trigger="hover">+ <template #trigger>+ <span+ class="px-1.5 py-1 relative rounded inline-flex items-center hover:bg-control-bg-hover cursor-pointer select-none"+ >+ <heroicons-outline:exclamation+ class="h-4 w-4 mr-1 text-warning"+ />+ {{ $t("common.others") }}+ </span>+ </template>+ <div class="flex items-center text-sm">+ {{ $t("deployment-config.wont-be-deployed") }}+ </div>+ </NPopover>+ </BBTableHeaderCell>+ </tr>+ </template>++ <template #body="{ rowData: matrix }">+ <BBTableCell+ :left-padding="4"+ class="pr-2 whitespace-nowrap"+ :class="{+ 'text-control-placeholder': !matrix.labelValue,+ }"+ >+ <template v-if="matrix.labelValue">{{ matrix.labelValue }}</template>+ <template v-else>{{ $t("label.empty-label-value") }}</template>+ </BBTableCell>+ <BBTableCell v-for="(dbList, i) in matrix.stages" :key="i">+ <div class="flex flex-col items-center space-y-1">+ <DatabaseMatrixItem+ v-for="db in dbList"+ :key="db.id"+ :database="db"+ :clickable="false"+ />+ <span v-if="dbList.length === 0">-</span>+ </div>+ </BBTableCell>++ <BBTableCell v-if="hasRest">+ <div class="flex flex-col items-center space-y-1">+ <DatabaseMatrixItem+ v-for="db in matrix.rest"+ :key="db.id"+ :database="db"+ :clickable="false"+ />+ <span v-if="matrix.rest.length === 0">-</span>+ </div>+ </BBTableCell>+ </template>+ </BBTable>+ </div>+</template>++<script lang="ts" setup>+import { groupBy } from "lodash-es";+import { computed, defineProps, reactive, withDefaults } from "vue";+import type {+ Database,+ DeploymentConfig,+ Environment,+ Label,+} from "../../types";+import { getLabelValue, getPipelineFromDeploymentSchedule } from "../../utils";+import { NPopover } from "naive-ui";+import { DeploymentStage } from "../DeploymentConfigTool";+import YAxisSwitch from "./YAxisSwitch.vue";++const props = withDefaults(+ defineProps<{+ databaseList: Database[];+ labelList: Label[];+ environmentList: Environment[];+ deployment: DeploymentConfig;+ bordered?: boolean;+ showRest?: boolean;+ }>(),+ {+ bordered: true,+ showRest: true,+ }+);++const state = reactive({+ label: "bb.environment",+});++const yAxisValueList = computed(() => {+ // order based on label.valueList+ // plus one more "<empty value>"+ const key = state.label;+ const label = props.labelList.find((label) => label.key === key);+ if (!label) return [];+ return [...label.valueList, ""];+});++const xAxisValueList = computed(() => {+ // x-axis is generated by deployment stages+ return props.deployment.schedule.deployments.map((dep) => dep.name);+});++const databaseGroupList = computed(() => {+ const key = state.label;+ const dict = groupBy(props.databaseList, (db) => getLabelValue(db, key));+ const rows = yAxisValueList.value.map((labelValue) => {+ const databaseList = dict[labelValue] || [];+ return {+ labelValue,+ databaseList,+ };+ });++ if (rows.length > 0 && rows[rows.length - 1].databaseList.length === 0) {+ // ignore "<empty value>" row if no databases+ rows.pop();+ }++ return rows;+});++const groupedStageList = computed(() => {+ return databaseGroupList.value.map(({ labelValue, databaseList }) => {+ const stages = getPipelineFromDeploymentSchedule(+ databaseList,+ props.deployment.schedule+ );+ const affectedIds = stages.flatMap((dbs) => dbs.map((db) => db.id));+ const dict = new Set(affectedIds);+ const rest = props.showRest+ ? databaseList.filter((db) => !dict.has(db.id))+ : [];++ return {+ labelValue,+ stages,+ rest,+ };+ });+});++const hasRest = computed(() => {+ return groupedStageList.value.some((group) => group.rest.length > 0);+});++const headerColumnWidth = computed(() => {+ let base = xAxisValueList.value.length;+ if (hasRest.value) base += 1;+ return `${(100 - 1 / 12) / base - 1}%`;+});+</script>diff --git a/frontend/src/components/TenantDatabaseTable/TenantDatabaseTable.vue b/frontend/src/components/TenantDatabaseTable/TenantDatabaseTable.vuenew file mode 100644index 0000000000..7b9c98961a--- /dev/null+++ b/frontend/src/components/TenantDatabaseTable/TenantDatabaseTable.vue@@ -0,0 +1,93 @@+<template>+ <div class="flex flex-col space-y-4">+ <DatabaseMatrix+ v-for="dbGroup in databaseListGroupByName"+ :key="dbGroup.name"+ :name="dbGroup.name"+ :database-list="dbGroup.databaseList"+ :environment-list="environmentList"+ :label-list="labelList"+ />+ </div>+</template>++<script lang="ts">+import { computed, defineComponent, PropType, watchEffect } from "vue";+import { useStore } from "vuex";+import { Database, Environment, Label } from "../../types";+import { groupBy } from "lodash-es";+import DatabaseMatrix from "./DatabaseMatrix.vue";++type Mode = "ALL" | "ALL_SHORT" | "INSTANCE" | "PROJECT" | "PROJECT_SHORT";++type DatabaseGroupByName = {+ name: string;+ databaseList: Database[];+};++export default defineComponent({+ name: "TenantDatabaseTable",+ components: { DatabaseMatrix },+ props: {+ bordered: {+ default: true,+ type: Boolean,+ },+ mode: {+ default: "ALL",+ type: String as PropType<Mode>,+ },+ customClick: {+ default: false,+ type: Boolean,+ },+ databaseList: {+ type: Object as PropType<Database[]>,+ required: true,+ },+ filter: {+ type: String,+ default: "",+ },+ },+ emits: ["select-database"],+ setup(props) {+ const store = useStore();++ const prepareList = () => {+ store.dispatch("environment/fetchEnvironmentList");+ store.dispatch("label/fetchLabelList");+ };+ watchEffect(prepareList);++ const labelList = computed(+ () => store.getters["label/labelList"]() as Label[]+ );+ const environmentList = computed(+ () => store.getters["environment/environmentList"]() as Environment[]+ );++ const filteredDatabaseList = computed(() => {+ if (!props.filter) return props.databaseList;++ return props.databaseList.filter((database) =>+ database.name.toLowerCase().includes(props.filter.toLowerCase())+ );+ });++ const databaseListGroupByName = computed((): DatabaseGroupByName[] => {+ const dict = groupBy(filteredDatabaseList.value, "name");+ return Object.keys(dict).map((name) => ({+ name,+ databaseList: dict[name],+ }));+ });++ return {+ labelList,+ environmentList,+ databaseListGroupByName,+ };+ },+});+</script>diff --git a/frontend/src/components/TenantDatabaseTable/YAxisSwitch.vue b/frontend/src/components/TenantDatabaseTable/YAxisSwitch.vuenew file mode 100644index 0000000000..e10866d953--- /dev/null+++ b/frontend/src/components/TenantDatabaseTable/YAxisSwitch.vue@@ -0,0 +1,46 @@+<template>+ <div+ class="pl-1 py-1 relative rounded inline-flex items-center hover:bg-control-bg-hover cursor-pointer select-none"+ @click="switchValue"+ >+ <span>{{ hidePrefix(label) }}</span>+ <heroicons-solid:selector class="h-4 w-4 text-control-light" />+ <select+ v-if="labelList.length > 2"+ :value="label"+ class="absolute w-full h-full inset-0 opacity-0"+ @change="(e: any) => $emit('update:label', e.target.value)"+ >+ <option v-for="opt in labelList" :key="opt.key" :value="opt.key">+ {{ hidePrefix(opt.key) }}+ </option>+ </select>+ </div>+</template>++<script lang="ts" setup>+import { defineProps, defineEmits } from "vue";+import { Label, LabelKeyType } from "../../types";+import { hidePrefix } from "../../utils";++const props = defineProps<{+ label: LabelKeyType;+ labelList: Label[];+}>();++const emit = defineEmits<{+ (event: "update:label", label: LabelKeyType): void;+}>();++const switchValue = () => {+ const list = props.labelList;+ if (list.length === 0) return;+ if (list.length === 1) return;+ if (list.length > 2) return;++ const index = list.findIndex((label) => label.key === props.label);+ if (index < 0) return;+ const next = (index + 1) % list.length;+ emit("update:label", list[next].key);+};+</script>diff --git a/frontend/src/components/TenantDatabaseTable/index.ts b/frontend/src/components/TenantDatabaseTable/index.tsnew file mode 100644index 0000000000..b00de02976--- /dev/null+++ b/frontend/src/components/TenantDatabaseTable/index.ts@@ -0,0 +1,7 @@+import TenantDatabaseTable from "./TenantDatabaseTable.vue";+import DatabaseMatrix from "./DatabaseMatrix.vue";+import DeployDatabaseTable from "./DeployDatabaseTable.vue";++export default TenantDatabaseTable;++export { TenantDatabaseTable, DatabaseMatrix, DeployDatabaseTable };diff --git a/frontend/src/layouts/ProjectLayout.vue b/frontend/src/layouts/ProjectLayout.vueindex 8d36df9aa0..3c55cff5fc 100644--- a/frontend/src/layouts/ProjectLayout.vue+++ b/frontend/src/layouts/ProjectLayout.vue@@ -4,6 +4,12 @@</div><h1 class="px-6 pb-4 text-xl font-bold leading-6 text-main truncate">{{ project.name }}+ <span+ v-if="project.tenantMode === 'TENANT'"+ class="text-sm font-normal px-2 ml-2 rounded whitespace-nowrap inline-flex items-center bg-gray-200"+ >+ {{ $t("project.mode.tenant") }}+ </span></h1><BBTabFilterclass="px-3 pb-2 border-b border-block-border"@@ -11,7 +17,7 @@:tab-item-list="tabItemList":selected-index="state.selectedIndex"@select-index="- (index) => {+ (index: number) => {selectTab(index);}"@@ -28,13 +34,14 @@</template><script lang="ts">-import { computed, onMounted, reactive, watch } from "vue";+import { computed, defineComponent, onMounted, reactive, watch } from "vue";import { useStore } from "vuex";import { useRouter } from "vue-router";import { idFromSlug, isProjectOwner } from "../utils";import ArchiveBanner from "../components/ArchiveBanner.vue";import { BBTabFilterItem } from "../bbkit/types";import { useI18n } from "vue-i18n";+import { Project } from "../types";const OVERVIEW_TAB = 0;const WEBHOOK_TAB = 4;@@ -48,7 +55,7 @@ interface LocalState {selectedIndex: number;}-export default {+export default defineComponent({name: "ProjectLayout",components: {ArchiveBanner,@@ -60,6 +67,7 @@ export default {},projectWebhookSlug: {type: String,+ default: undefined,},},setup(props) {@@ -69,8 +77,14 @@ export default {const currentUser = computed(() => store.getters["auth/currentUser"]());+ const project = computed((): Project => {+ return store.getters["project/projectById"](+ idFromSlug(props.projectSlug)+ );+ });+const projectTabItemList = computed((): ProjectTabItem[] => {- return [+ const list: ProjectTabItem[] = [{ name: t("common.overview"), hash: "overview" },{ name: t("common.migration-history"), hash: "migration-history" },{ name: t("common.activities"), hash: "activity" },@@ -78,18 +92,23 @@ export default {{ name: t("common.webhooks"), hash: "webhook" },{ name: t("common.settings"), hash: "setting" },];+ // TODO: we can't put DeploymentConfig before Settings for now+ // because BBTabFilter works on numeric index+ // making indices dynamic needs a refactor+ if (project.value.tenantMode === "TENANT") {+ list.push({+ name: t("common.deployment-config"),+ hash: "deployment-config",+ });+ }++ return list;});const state = reactive<LocalState>({selectedIndex: OVERVIEW_TAB,});- const project = computed(() => {- return store.getters["project/projectById"](- idFromSlug(props.projectSlug)- );- });-// Only the project owner can edit the project general info and configure version control.// This means even the workspace owner won't be able to edit it.// On the other hand, we allow workspace owner to change project membership in case@@ -168,5 +187,5 @@ export default {selectTab,};},-};+});</script>diff --git a/frontend/src/locales/en.yml b/frontend/src/locales/en.ymlindex 1071679efb..820e4a0017 100644--- a/frontend/src/locales/en.yml+++ b/frontend/src/locales/en.yml@@ -94,6 +94,7 @@ common:snapshot: Snapshotstatus: Statusstage: Stage+ task: Tasksql: SQLunassigned: Unassignednew: New@@ -142,6 +143,7 @@ common:created: Createdlabel: Labellabels: Labels+ mode: Moderoletype: Role Typereadonly: readonlyuser: User@@ -153,9 +155,11 @@ common:agents: Agentsbillings: Billingsall: All+ deployment-config: Deployment Configby: byok: OKshare: Share+ others: Othersor: orexport: Exporttips: Tips@@ -198,6 +202,13 @@ task:ended: Endedview-migration: View migrationview-migration-history: View migration history+ status:+ running: Running+ failed: Failed+ canceled: Canceled+ success: Success+ warn: Warning+ error: Errorbanner:demo-intro: This is a demo version of Bytebase.demo-intro-readonly: This is a demo version of Bytebase in read-only mode.@@ -918,6 +929,9 @@ project:restore:title: Restore projectbtn-text: Restore this @.lower:{'common.project'}+ mode:+ standard: Standard+ tenant: Tenantinbox:mark-all-as-read: Mark all as readview-older: View older@@ -997,6 +1011,26 @@ archive:project-search-bar-placeholder: Search @.lower:{'common.project'} nameinstance-search-bar-placeholder: Search @.lower:{'common.instance'} nameenvironment-search-bar-placeholder: Search @.lower:{'common.environment'} name+deployment-config:+ stage-n: Stage {n}+ add-selector: Add selector+ update-success: Successfully updated deployment config.+ this-is-example-deployment-config: This is the deployment config example. You need to edit and save it.+ n-databases: '{n} database | {n} databases'+ selectors: Selectors+ wont-be-deployed: Will not be deployed+ add-stage: Add stage+ name-placeholder: Stage name...+ error:+ at-least-one-stage: At least 1 stage+ stage-name-required: Stage name is required+ at-least-one-selector: At least 1 selector in each stage+ env-in-selector-required: '"environment In" is required in each stage'+ env-selector-must-has-one-value: '"environment In" must has exactly one value'+ key-required: Key is required+ values-required: Values are required+ project-has-no-deployment-config: This project has no deployment config yet. Please {go} first.+ go-and-config: Go and configdatasource:successfully-deleted-data-source-name: Successfully deleted data source '{0}'.create-data-source: Create data source@@ -1057,6 +1091,8 @@ sql-editor:can-not-execute-query: Can not execute query when loading data.rows: row | rowslabel:+ empty-label-value: <Empty Value>+ no-label: No labelserror:key-necessary: Key is requiredvalue-necessary: Value is required@@ -1065,3 +1101,7 @@ label:max-length-exceeded: Length cannot exceed {len} charactersmax-label-count-exceeded: Cannot exceed {count} labelscannot-edit-reserved-label: Cannot edit reserved label "{key}"+ placeholder:+ select-key: Select key...+ select-value: Select value...+ select-values: Select values...diff --git a/frontend/src/locales/zh-CN.yml b/frontend/src/locales/zh-CN.ymlindex 6969610a87..a136df1a90 100644--- a/frontend/src/locales/zh-CN.yml+++ b/frontend/src/locales/zh-CN.yml@@ -94,6 +94,7 @@ common:snapshot: 快照status: 状态stage: 阶段+ task: 任务sql: SQLunassigned: 未指派new: 创建@@ -142,6 +143,7 @@ common:created: 已创建label: 标签labels: 标签+ mode: 模式roletype: 角色类型readonly: 只读user: 用户@@ -153,9 +155,11 @@ common:agents: Agentsbillings: 计费all: 全部+ deployment-config: 部署配置by: 由ok: OKshare: 分享+ others: 其他or: 或者export: 导出tips: 提示信息@@ -195,6 +199,13 @@ task:view-migration: 查看迁移view-migration-history: 查看迁移历史earliest-allowed-time-unset: 未设置+ status:+ running: 运行中+ failed: 失败+ canceled: 取消+ success: 成功+ warn: 警告+ error: 错误banner:demo-intro: 这是 Bytebase 的演示版本。demo-intro-readonly: 这是 Bytebase 的只读演示版本@@ -813,6 +824,9 @@ project:restore:title: 恢复项目btn-text: 恢复这个@:common.project+ mode:+ standard: 标准+ tenant: 多租户inbox:mark-all-as-read: 全部标记为已读view-older: 查看更早@@ -866,6 +880,26 @@ archive:project-search-bar-placeholder: 搜索@.lower:{'common.project'}的名称instance-bar-placeholder: 搜索@.lower:{'common.instance'}的名称environment-bar-placeholder: 搜索@.lower:{'common.environment'}的名称+deployment-config:+ stage-n: 阶段 {n}+ add-selector: 添加选择条件+ update-success: 成功更新部署配置+ this-is-example-deployment-config: 这是部署配置的样例,你需要在此基础上编辑并保存。+ n-databases: '{n} 个数据库'+ selectors: 选择条件+ wont-be-deployed: 不会被部署+ add-stage: 添加阶段+ name-placeholder: 阶段名称…+ error:+ at-least-one-stage: 至少需要 1 个阶段+ stage-name-required: 需要指定阶段名称+ at-least-one-selector: 每个阶段至少需要 1 个选择条件+ env-in-selector-required: 每个阶段都需要有 "environment In" 选择条件+ env-selector-must-has-one-value: '"environment In" 必须有且只有 1 个值'+ key-required: 需要指定 Key+ values-required: 需要指定值+ project-has-no-deployment-config: 这个项目还没有部署配置。请先{go}。+ go-and-config: 去配置datasource:successfully-deleted-data-source-name: 成功删除数据源'{0}'。create-data-source: 创建数据源@@ -923,6 +957,8 @@ sql-editor:can-not-execute-query: 加载数据时无法执行查询rows: 条记录label:+ empty-label-value: <空值>+ no-label: 没有标签error:key-necessary: 需要指定 Keyvalue-necessary: 需要指定值@@ -931,3 +967,7 @@ label:max-length-exceeded: 长度不能超过 {len} 字符max-label-count-exceeded: 不能多于 {count} 个标签cannot-edit-reserved-label: 不能编辑预留标签 "{key}"+ placeholder:+ select-key: 选择 Key…+ select-value: 选择值…+ select-values: 选择值…diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.tsindex 702e6d8ba4..1a3fb7c5c2 100644--- a/frontend/src/router/index.ts+++ b/frontend/src/router/index.ts@@ -322,7 +322,8 @@ const routes: Array<RouteRecordRaw> = [path: "subscription",name: "setting.workspace.subscription",meta: { title: () => t("settings.sidebar.subscription") },- component: () => import("../views/SettingWorkspaceSubscription.vue"),+ component: () =>+ import("../views/SettingWorkspaceSubscription.vue"),props: true,},{diff --git a/frontend/src/store/modules/database.ts b/frontend/src/store/modules/database.tsindex ac51c33e10..8a738f74ff 100644--- a/frontend/src/store/modules/database.ts+++ b/frontend/src/store/modules/database.ts@@ -5,6 +5,7 @@ import {Database,DatabaseCreate,DatabaseId,+ DatabaseLabel,DatabaseState,DataSource,empty,@@ -74,6 +75,24 @@ function convert(}}+ const labels: DatabaseLabel[] = [];+ try {+ const array = JSON.parse(database.attributes.labels as any);+ if (Array.isArray(array)) {+ array.forEach((item) => {+ if (+ item &&+ typeof item["key"] === "string" &&+ typeof item["value"] === "string"+ ) {+ labels.push(item);+ }+ });+ }+ } catch {+ // nothing to catch+ }+// Only able to assign an empty data source list / anomaly list, otherwise would cause circular dependency.// This should be fine as e.g. we shouldn't access data source via dataSource.database.dataSourceListconst databaseWPartial = {@@ -85,10 +104,12 @@ function convert(| "dataSourceList"| "sourceBackup"| "anomalyList"+ | "labels">),id: parseInt(database.id),instance,project,+ labels,dataSourceList: [],sourceBackup,anomalyList: [],@@ -376,6 +397,35 @@ const actions = {return updatedDatabase;},++ async patchDatabaseLabels(+ { commit, rootGetters }: any,+ {+ databaseId,+ labels,+ }: {+ databaseId: DatabaseId;+ labels: DatabaseLabel[];+ }+ ) {+ const data = (+ await axios.patch(`/api/database/${databaseId}`, {+ data: {+ type: "databasePatch",+ attributes: {+ labels: JSON.stringify(labels),+ },+ },+ })+ ).data;+ const updatedDatabase = convert(data.data, data.included, rootGetters);++ commit("upsertDatabaseList", {+ databaseList: [updatedDatabase],+ });++ return updatedDatabase;+ },};const mutations = {diff --git a/frontend/src/store/modules/deployment.ts b/frontend/src/store/modules/deployment.tsnew file mode 100644index 0000000000..a559718d75--- /dev/null+++ b/frontend/src/store/modules/deployment.ts@@ -0,0 +1,121 @@+import axios from "axios";+import {+ ResourceObject,+ ProjectId,+ DeploymentState,+ DeploymentConfig,+ EMPTY_ID,+ empty,+ unknown,+ UNKNOWN_ID,+ DeploymentConfigPatch,+} from "../../types";++function convert(+ deployment: ResourceObject,+ includedList: ResourceObject[],+ rootGetters: any+): DeploymentConfig {+ if (parseInt(deployment.id, 10) === EMPTY_ID) {+ return empty("DEPLOYMENT_CONFIG") as DeploymentConfig;+ }++ let schedule: DeploymentConfig["schedule"] = (+ unknown("DEPLOYMENT_CONFIG") as DeploymentConfig+ ).schedule;+ try {+ schedule = JSON.parse(deployment.attributes.payload as string);+ } catch {+ // nothing+ }++ return {+ ...(deployment.attributes as Omit<DeploymentConfig, "id" | "schedule">),+ id: parseInt(deployment.id, 10),+ schedule,+ };+}++const state: () => DeploymentState = () => ({+ deploymentConfigByProjectId: new Map(),+});++const getters = {+ deploymentConfigByProjectId:+ (state: DeploymentState) =>+ (projectId: ProjectId): DeploymentConfig => {+ if (projectId == EMPTY_ID) {+ return empty("DEPLOYMENT_CONFIG") as DeploymentConfig;+ }++ return (+ state.deploymentConfigByProjectId.get(projectId) ||+ (unknown("DEPLOYMENT_CONFIG") as DeploymentConfig)+ );+ },+};++const actions = {+ async fetchDeploymentConfigByProjectId(+ { commit, rootGetters }: any,+ projectId: ProjectId+ ) {+ const data = (await axios.get(`/api/project/${projectId}/deployment`)).data;++ const deploymentConfig = convert(data.data, data.included, rootGetters);+ const { id } = deploymentConfig;+ if (id !== EMPTY_ID && id !== UNKNOWN_ID) {+ commit("setDeploymentConfigByProjectId", { projectId, deploymentConfig });+ }+ },++ async patchDeploymentConfigByProjectId(+ { commit, rootGetters }: any,+ {+ projectId,+ deploymentConfigPatch,+ }: { projectId: ProjectId; deploymentConfigPatch: DeploymentConfigPatch }+ ) {+ const data = (+ await axios.patch(`/api/project/${projectId}/deployment`, {+ data: {+ type: "deploymentConfigPatch",+ attributes: deploymentConfigPatch,+ },+ })+ ).data;+ const updatedDeploymentConfig = convert(+ data.data,+ data.included,+ rootGetters+ );+ commit("setDeploymentConfigByProjectId", {+ projectId,+ deploymentConfig: updatedDeploymentConfig,+ });+ return updatedDeploymentConfig;+ },+};++const mutations = {+ setDeploymentConfigByProjectId(+ state: DeploymentState,+ {+ projectId,+ deploymentConfig,+ }: {+ projectId: ProjectId;+ deploymentConfig: DeploymentConfig;+ }+ ) {+ state.deploymentConfigByProjectId.set(projectId, deploymentConfig);+ },+};++export default {+ namespaced: true,+ state,+ getters,+ actions,+ mutations,+};diff --git a/frontend/src/store/modules/issue.ts b/frontend/src/store/modules/issue.tsindex a0a6b9b850..22f72011a4 100644--- a/frontend/src/store/modules/issue.ts+++ b/frontend/src/store/modules/issue.ts@@ -178,6 +178,25 @@ const actions = {return createdIssue;},+ async validateIssue({ commit, rootGetters }: any, newIssue: IssueCreate) {+ const data = (+ await axios.post(`/api/issue`, {+ data: {+ type: "IssueCreate",+ attributes: {+ ...newIssue,+ // Server expects payload as string, so we stringify first.+ createContext: JSON.stringify(newIssue.createContext),+ payload: JSON.stringify(newIssue.payload),+ validateOnly: true,+ },+ },+ })+ ).data;+ const createdIssue = convert(data.data, data.included, rootGetters);+ return createdIssue;+ },+async patchIssue({ commit, dispatch, rootGetters }: any,{diff --git a/frontend/src/store/modules/stage.ts b/frontend/src/store/modules/stage.tsindex a33bcbbc32..a1d390487a 100644--- a/frontend/src/store/modules/stage.ts+++ b/frontend/src/store/modules/stage.ts@@ -17,11 +17,13 @@ function convertPartial(includedList: ResourceObject[],rootGetters: any): Omit<Stage, "pipeline"> {- const environmentId = (- stage.relationships!.environment.data as ResourceIdentifier- ).id;- let environment: Environment = unknown("ENVIRONMENT") as Environment;- environment.id = parseInt(environmentId);+ let environment = unknown("ENVIRONMENT") as Environment;+ if (stage.relationships?.environment.data) {+ const environmentId = (+ stage.relationships.environment.data as ResourceIdentifier+ ).id;+ environment.id = parseInt(environmentId, 10);+ }const taskList: Task[] = [];const taskIdList = stage.relationships!.task.data as ResourceIdentifier[];diff --git a/frontend/src/store/modules/task.ts b/frontend/src/store/modules/task.tsindex 371900e72a..8cc193dd35 100644--- a/frontend/src/store/modules/task.ts+++ b/frontend/src/store/modules/task.ts@@ -115,10 +115,12 @@ function convertPartial(}}- const instanceId = (task.relationships!.instance.data as ResourceIdentifier)- .id;let instance: Instance = empty("INSTANCE") as Instance;- instance.id = parseInt(instanceId);+ if (task.relationships?.instance.data) {+ const instanceId = (task.relationships.instance.data as ResourceIdentifier)+ .id;+ instance.id = parseInt(instanceId, 10);+ }let database = undefined;for (const item of includedList || []) {diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.tsindex 6ce1e4340f..ee2dbbe9b0 100644--- a/frontend/src/types/common.ts+++ b/frontend/src/types/common.ts@@ -17,6 +17,7 @@ import { Project, ProjectMember } from "./project";import { ProjectWebhook } from "./projectWebhook";import { Repository } from "./repository";import { VCS } from "./vcs";+import { DeploymentConfig } from "./deployment";// System bot idexport const SYSTEM_BOT_ID = 1;@@ -124,7 +125,8 @@ export type ResourceType =| "BOOKMARK"| "VCS"| "REPOSITORY"- | "ANOMALY";+ | "ANOMALY"+ | "DEPLOYMENT_CONFIG";export const unknown = (type: ResourceType@@ -149,7 +151,8 @@ export const unknown = (| Bookmark| VCS| Repository- | Anomaly => {+ | Anomaly+ | DeploymentConfig => {// Have to omit creator and updater to avoid recursion.const UNKNOWN_PRINCIPAL: Principal = {id: UNKNOWN_ID,@@ -244,6 +247,7 @@ export const unknown = (id: UNKNOWN_ID,instance: UNKNOWN_INSTANCE,project: UNKNOWN_PROJECT,+ labels: [],dataSourceList: [],anomalyList: [],creator: UNKNOWN_PRINCIPAL,@@ -255,6 +259,7 @@ export const unknown = (collation: "",syncStatus: "NOT_FOUND",lastSuccessfulSyncTs: 0,+ schemaVersion: "",};const UNKNOWN_DATA_SOURCE: DataSource = {@@ -433,6 +438,18 @@ export const unknown = (},};+ const UNKNOWN_DEPLOYMENT_CONFIG: DeploymentConfig = {+ id: UNKNOWN_ID,+ creator: UNKNOWN_PRINCIPAL,+ createdTs: 0,+ updater: UNKNOWN_PRINCIPAL,+ updatedTs: 0,+ project: UNKNOWN_PROJECT,+ schedule: {+ deployments: [],+ },+ };+switch (type) {case "PRINCIPAL":return UNKNOWN_PRINCIPAL;@@ -476,6 +493,8 @@ export const unknown = (return UNKONWN_REPOSITORY;case "ANOMALY":return UNKNOWN_ANOMALY;+ case "DEPLOYMENT_CONFIG":+ return UNKNOWN_DEPLOYMENT_CONFIG;}};@@ -503,7 +522,8 @@ export const empty = (| Bookmark| VCS| Repository- | Anomaly => {+ | Anomaly+ | DeploymentConfig => {// Have to omit creator and updater to avoid recursion.const EMPTY_PRINCIPAL: Principal = {id: EMPTY_ID,@@ -598,6 +618,7 @@ export const empty = (project: EMPTY_PROJECT,dataSourceList: [],anomalyList: [],+ labels: [],creator: EMPTY_PRINCIPAL,createdTs: 0,updater: EMPTY_PRINCIPAL,@@ -607,6 +628,7 @@ export const empty = (collation: "",syncStatus: "NOT_FOUND",lastSuccessfulSyncTs: 0,+ schemaVersion: "",};const EMPTY_DATA_SOURCE: DataSource = {@@ -785,6 +807,18 @@ export const empty = (},};+ const EMPTY_DEPLOYMENT_CONFIG: DeploymentConfig = {+ id: EMPTY_ID,+ creator: EMPTY_PRINCIPAL,+ createdTs: 0,+ updater: EMPTY_PRINCIPAL,+ updatedTs: 0,+ project: EMPTY_PROJECT,+ schedule: {+ deployments: [],+ },+ };+switch (type) {case "PRINCIPAL":return EMPTY_PRINCIPAL;@@ -828,5 +862,7 @@ export const empty = (return EMPTY_REPOSITORY;case "ANOMALY":return EMPTY_ANOMALY;+ case "DEPLOYMENT_CONFIG":+ return EMPTY_DEPLOYMENT_CONFIG;}};diff --git a/frontend/src/types/database.ts b/frontend/src/types/database.tsindex 0e3a494738..d65c00f315 100644--- a/frontend/src/types/database.ts+++ b/frontend/src/types/database.ts@@ -9,6 +9,7 @@ import { DatabaseId, InstanceId, IssueId, ProjectId } from "./id";import { Instance } from "./instance";import { Principal } from "./principal";import { Project } from "./project";+import { DatabaseLabel } from "./label";// "OK" means we find the database with the same name.// "NOT_FOUND" means no matching database name found, this usually means someone changes the underlying db name without Bytebase knowledge.@@ -36,6 +37,8 @@ export type Database = {name: string;characterSet: string;collation: string;+ schemaVersion: string;+ labels: DatabaseLabel[];};export type DatabaseCreate = {@@ -48,9 +51,11 @@ export type DatabaseCreate = {characterSet: string;collation: string;issueId?: IssueId;+ labels?: DatabaseLabel[];};export type DatabasePatch = {// Related fields- projectId: ProjectId;+ projectId?: ProjectId;+ labels?: DatabaseLabel[];};diff --git a/frontend/src/types/deployment.ts b/frontend/src/types/deployment.tsnew file mode 100644index 0000000000..fe07f512c5--- /dev/null+++ b/frontend/src/types/deployment.ts@@ -0,0 +1,49 @@+import { Project } from ".";+import { DeploymentConfigId } from "./id";+import { LabelKeyType, LabelValueType } from "./label";+import { Principal } from "./principal";++export type DeploymentConfig = {+ id: DeploymentConfigId;++ // Standard fields+ creator: Principal;+ createdTs: number;+ updater: Principal;+ updatedTs: number;++ // Related fields+ project: Project;++ // Domain specific fields+ schedule: DeploymentSchedule;+};++export type DeploymentConfigPatch = {+ payload: string;+};++export type DeploymentSchedule = {+ deployments: Deployment[];+};++export type Deployment = {+ name: string;+ spec: DeploymentSpec;+};++export type DeploymentSpec = {+ selector: LabelSelector;+};++export type LabelSelector = {+ matchExpressions: LabelSelectorRequirement[];+};++export type LabelSelectorRequirement = {+ key: LabelKeyType;+ operator: OperatorType;+ values: LabelValueType[];+};++export type OperatorType = "In" | "Exists";diff --git a/frontend/src/types/id.ts b/frontend/src/types/id.tsindex ea3e624abc..0ba99e7bdc 100644--- a/frontend/src/types/id.ts+++ b/frontend/src/types/id.ts@@ -74,3 +74,5 @@ export type CommandRegisterId = IdType;export type ContainerId = IssueId;export type LabelId = IdType;++export type DeploymentConfigId = IdType;diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 462db4fd76..d8b3ef5328 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -34,5 +34,6 @@ export * from "./tableIndex";export * from "./vcs";export * from "./view";export * from "./label";+export * from "./deployment";export * from "./sqlEditor";export * from "./editorSelector";diff --git a/frontend/src/types/issue.ts b/frontend/src/types/issue.tsindex d0e2f50fb4..9ccf7b7342 100644--- a/frontend/src/types/issue.ts+++ b/frontend/src/types/issue.ts@@ -1,4 +1,11 @@-import { BackupId, DatabaseId, InstanceId, IssueId, PrincipalId, ProjectId } from "./id";+import {+ BackupId,+ DatabaseId,+ InstanceId,+ IssueId,+ PrincipalId,+ ProjectId,+} from "./id";import { Pipeline, PipelineCreate } from "./pipeline";import { Principal } from "./principal";import { Project } from "./project";@@ -27,6 +34,7 @@ export type CreateDatabaseContext = {collation: string;backupId: BackupId;backupName: string;+ labels?: string; // JSON encoded};export type UpdateSchemaDetail = {@@ -40,10 +48,10 @@ export type UpdateSchemaContext = {updateSchemaDetailList: UpdateSchemaDetail[];};-export type EmptyContext = {-};+// eslint-disable-next-line @typescript-eslint/ban-types+export type EmptyContext = {};-export type IssueCreateContext =+export type IssueCreateContext =| CreateDatabaseContext| UpdateSchemaContext| EmptyContext;@@ -76,7 +84,7 @@ export type Issue = {export type IssueCreate = {// Related fieldsprojectId: ProjectId;- pipeline: PipelineCreate;+ pipeline?: PipelineCreate;// Domain specific fieldsname: string;diff --git a/frontend/src/types/label.ts b/frontend/src/types/label.tsindex fe21669811..2754587f71 100644--- a/frontend/src/types/label.ts+++ b/frontend/src/types/label.ts@@ -21,3 +21,13 @@ export type Label = {export type LabelPatch = {valueList?: LabelValueType[];};++export type DatabaseLabel = {+ key: LabelKeyType;+ value: LabelValueType;+};++export type AvailableLabel = {+ key: LabelKeyType;+ valueList: LabelValueType[];+};diff --git a/frontend/src/types/project.ts b/frontend/src/types/project.tsindex c0c95fa3bb..fbbd27d36c 100644--- a/frontend/src/types/project.ts+++ b/frontend/src/types/project.ts@@ -39,6 +39,7 @@ export type ProjectCreate = {// Domain specific fieldsname: string;key: string;+ tenantMode: ProjectTenantMode;};export type ProjectPatch = {diff --git a/frontend/src/utils/deployment.ts b/frontend/src/utils/deployment.tsnew file mode 100644index 0000000000..a3d01ea614--- /dev/null+++ b/frontend/src/utils/deployment.ts@@ -0,0 +1,76 @@+import {+ DeploymentConfig,+ DeploymentSchedule,+ DeploymentSpec,+ Environment,+} from "../types";++export const generateDefaultSchedule = (environmentList: Environment[]) => {+ const schedule: DeploymentSchedule = {+ deployments: [],+ };+ environmentList.forEach((env) => {+ schedule.deployments.push({+ name: `${env.name} Stage`,+ spec: {+ selector: {+ matchExpressions: [+ {+ key: "bb.environment",+ operator: "In",+ values: [env.name],+ },+ ],+ },+ },+ });+ });+ return schedule;+};++export const validateDeploymentConfig = (+ config: DeploymentConfig+): string | undefined => {+ const { deployments } = config.schedule;+ if (deployments.length === 0) {+ return "deployment-config.error.at-least-one-stage";+ }++ for (let i = 0; i < config.schedule.deployments.length; i++) {+ const deployment = config.schedule.deployments[i];+ if (!deployment.name.trim()) {+ return "deployment-config.error.stage-name-required";+ }+ const error = validateDeploymentSpec(deployment.spec);+ if (error) return error;+ }++ return undefined;+};++export const validateDeploymentSpec = (+ deployment: DeploymentSpec+): string | undefined => {+ const rules = deployment.selector.matchExpressions;+ if (rules.length === 0) {+ return "deployment-config.error.at-least-one-selector";+ }+ const envRule = rules.find((rule) => rule.key === "bb.environment");+ if (!envRule || envRule.operator !== "In") {+ return "deployment-config.error.env-in-selector-required";+ }+ if (envRule.values.length !== 1) {+ return "deployment-config.error.env-selector-must-has-one-value";+ }++ for (let i = 0; i < rules.length; i++) {+ const rule = rules[i];+ if (!rule.key) {+ return "deployment-config.error.key-required";+ }+ if (rule.operator === "In" && rule.values.length === 0) {+ return "deployment-config.error.values-required";+ }+ }+ return undefined;+};diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.tsindex 096ac3ab96..4c7f5f84e7 100644--- a/frontend/src/utils/index.ts+++ b/frontend/src/utils/index.ts@@ -10,3 +10,4 @@ export * from "./role";export * from "./slug";export * from "./util";export * from "./label";+export * from "./deployment";diff --git a/frontend/src/utils/label.ts b/frontend/src/utils/label.tsindex ad45780582..a57bb0fbd0 100644--- a/frontend/src/utils/label.ts+++ b/frontend/src/utils/label.ts@@ -1,4 +1,14 @@-import { Label } from "../types";+import { countBy, groupBy, uniqBy } from "lodash-es";+import {+ Database,+ DatabaseLabel,+ DeploymentSchedule,+ Label,+ LabelKeyType,+ LabelSelector,+ LabelSelectorRequirement,+ LabelValueType,+} from "../types";// reserved labels (e.g. bb.environment) have zero ID and their values are immutable.// see api/label.go for more details@@ -7,3 +17,148 @@ export const RESERVED_LABEL_ID = 0;export const isReservedLabel = (label: Label): boolean => {return label.id === RESERVED_LABEL_ID;};++export const isReservedDatabaseLabel = (+ dbLabel: DatabaseLabel,+ labelList: Label[]+): boolean => {+ const label = labelList.find((label) => label.key === dbLabel.key);+ if (!label) return false;+ return label.id === RESERVED_LABEL_ID;+};++export const hidePrefix = (key: LabelKeyType): LabelKeyType => {+ return key.replace(/^bb\./, "");+};++export const getLabelValue = (+ db: Database,+ key: LabelKeyType+): LabelValueType => {+ const label = db.labels.find((target) => target.key === key);+ if (!label) return "";+ return label.value;+};++export const groupingDatabaseListByLabelKey = (+ databaseList: Database[],+ key: LabelKeyType,+ emptyValue: LabelValueType = ""+): Array<{ labelValue: LabelValueType; databaseList: Database[] }> => {+ const dict = groupBy(databaseList, (db) => {+ const label = db.labels.find((target) => target.key === key);+ if (!label) return emptyValue;+ return label.value;+ });+ return Object.keys(dict).map((value) => ({+ labelValue: value,+ databaseList: dict[value],+ }));+};++export const validateLabels = (labels: DatabaseLabel[]): string | undefined => {+ for (let i = 0; i < labels.length; i++) {+ const label = labels[i];+ if (!label.key) return "label.error.key-necessary";+ if (!label.value) return "label.error.value-necessary";+ }+ if (labels.length !== uniqBy(labels, "key").length) {+ return "label.error.key-duplicated";+ }+ return undefined;+};++export const findDefaultGroupByLabel = (+ labelList: Label[],+ databaseList: Database[]+): string | undefined => {+ const availableKeys = labelList.map((label) => label.key);++ // concat all databases' keys into one array+ const databaseLabelKeys = databaseList.flatMap((db) =>+ db.labels+ .map((label) => label.key)+ .filter((key) => availableKeys.includes(key))+ );+ if (databaseLabelKeys.length > 0) {+ // counting up the keys' frequency+ const countsDict = countBy(databaseLabelKeys);+ const countsList = Object.keys(countsDict).map((key) => ({+ key,+ count: countsDict[key],+ }));+ // return the most frequent used key+ countsList.sort((a, b) => b.count - a.count);+ return countsList[0].key;+ } else {+ // just use the first label key+ return availableKeys[0];+ }+};++export const filterDatabaseListByLabelSelector = (+ databaseList: Database[],+ labelSelector: LabelSelector+): Database[] => {+ return databaseList.filter((db) =>+ isDatabaseMatchesSelector(db, labelSelector)+ );+};++export const getPipelineFromDeploymentSchedule = (+ databaseList: Database[],+ schedule: DeploymentSchedule+): Database[][] => {+ const stages: Database[][] = [];++ const collectedIds = new Set<Database["id"]>();+ schedule.deployments.forEach((deployment) => {+ const dbs: Database[] = [];+ databaseList.forEach((db) => {+ if (collectedIds.has(db.id)) return;+ if (isDatabaseMatchesSelector(db, deployment.spec.selector)) {+ dbs.push(db);+ collectedIds.add(db.id);+ }+ });+ stages.push(dbs);+ });++ return stages;+};++export const isDatabaseMatchesSelector = (+ database: Database,+ selector: LabelSelector+): boolean => {+ const rules = selector.matchExpressions;+ return rules.every((rule) => {+ switch (rule.operator) {+ case "In":+ return checkLabelIn(database, rule);+ case "Exists":+ return checkLabelExists(database, rule);+ default:+ // unknown operators are taken as mismatch+ console.warn(`known operator "${rule.operator}"`);+ return false;+ }+ });+};++const checkLabelIn = (+ db: Database,+ rule: LabelSelectorRequirement+): boolean => {+ const label = db.labels.find((label) => label.key === rule.key);+ if (!label) return false;++ return rule.values.some((value) => value === label.value);+};++const checkLabelExists = (+ db: Database,+ rule: LabelSelectorRequirement+): boolean => {+ return db.labels.some((label) => label.key === rule.key);+};diff --git a/frontend/src/utils/slug.ts b/frontend/src/utils/slug.tsindex 2302e121bb..ec2805bd56 100644--- a/frontend/src/utils/slug.ts+++ b/frontend/src/utils/slug.ts@@ -8,7 +8,6 @@ import {MigrationHistoryId,Project,ProjectWebhook,- Task,VCS,} from "../types";import { IdType } from "../types/id";@@ -52,8 +51,8 @@ export function stageSlug(stageName: string, stageIndex: number): string {return [slug(stageName), stageIndex + 1].join("-");}-export function taskSlug(task: Task): string {- return [slug(task.name), task.id].join("-");+export function taskSlug(name: string, id: number): string {+ return [slug(name), id].join("-");}export function databaseSlug(database: Database): string {diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vueindex f7f37c9833..3586000de9 100644--- a/frontend/src/views/DatabaseDetail.vue+++ b/frontend/src/views/DatabaseDetail.vue@@ -2,7 +2,9 @@<div class="flex-1 overflow-auto focus:outline-none" tabindex="0"><main class="flex-1 relative overflow-y-auto"><!-- Highlight Panel -->- <div class="px-4 pb-4 space-y-2 md:space-y-0 md:flex md:items-center md:justify-between">+ <div+ class="px-4 pb-4 space-y-2 md:space-y-0 md:flex md:items-center md:justify-between"+ ><div class="flex-1 min-w-0"><!-- Summary --><div class="flex items-center">@@ -10,54 +12,70 @@<div class="flex items-center"><h1class="pt-2 pb-2.5 text-xl font-bold leading-6 text-main truncate"- >{{ database.name }}</h1>+ >+ {{ database.name }}+ </h1></div></div></div>- <dl class="flex flex-col space-y-1 md:space-y-0 md:flex-row md:flex-wrap">+ <dl+ class="flex flex-col space-y-1 md:space-y-0 md:flex-row md:flex-wrap"+ ><dt class="sr-only">{{ $t("common.environment") }}</dt><dd class="flex items-center text-sm md:mr-4">- <span class="textlabel">{{ $t("common.environment") }} - </span>+ <span class="textlabel"+ >{{ $t("common.environment") }} - </span+ ><router-link:to="`/environment/${environmentSlug(database.instance.environment)}`"class="normal-link"- >{{ environmentName(database.instance.environment) }}</router-link>+ >{{+ environmentName(database.instance.environment)+ }}</router-link+ ></dd><dt class="sr-only">{{ $t("common.instance") }}</dt><dd class="flex items-center text-sm md:mr-4"><InstanceEngineIcon :instance="database.instance" />- <span class="ml-1 textlabel">{{ $t("common.instance") }} - </span>+ <span class="ml-1 textlabel"+ >{{ $t("common.instance") }} - </span+ ><router-link:to="`/instance/${instanceSlug(database.instance)}`"class="normal-link"- >{{ instanceName(database.instance) }}</router-link>+ >{{ instanceName(database.instance) }}</router-link+ ></dd><dt class="sr-only">{{ $t("common.project") }}</dt><dd class="flex items-center text-sm md:mr-4">- <span class="textlabel">{{ $t("common.project") }} - </span>+ <span class="textlabel"+ >{{ $t("common.project") }} - </span+ ><router-link:to="`/project/${projectSlug(database.project)}`"class="normal-link"- >{{ projectName(database.project) }}</router-link>+ >{{ projectName(database.project) }}</router-link+ ></dd><template v-if="database.sourceBackup"><dt class="sr-only">{{ $t("db.parent") }}</dt><dd class="flex items-center text-sm md:mr-4 tooltip-wrapper"><span class="textlabel">- {{- $t("database.restored-from")- }}+ {{ $t("database.restored-from") }}</span>- <router-link :to="`/db/${database.sourceBackup.databaseId}`" class="normal-link">+ <router-link+ :to="`/db/${database.sourceBackup.databaseId}`"+ class="normal-link"+ ><!-- Do not display the name of the backup's database because that requires a fetch --><span class="tooltip">{{- $t(- "database.database-name-is-restored-from-another-database-backup",- [database.name]- )+ $t(+ "database.database-name-is-restored-from-another-database-backup",+ [database.name]+ )}}</span>{{ $t("database.database-backup") }}@@ -71,6 +89,16 @@</button></dd></dl>+ <div v-if="isTenantProject" class="flex items-center mt-2 h-7">+ <label class="textlabel">+ {{ $t("common.labels") }} - + </label>+ <DatabaseLabelsEditor+ :label-list="database.labels"+ :allow-edit="allowAdmin"+ @save="updateLabels"+ />+ </div></div><div class="flex items-center space-x-2"><button@@ -80,9 +108,16 @@@click.prevent="tryTransferProject"><span>{{ $t("database.transfer-project") }}</span>- <heroicons-outline:switch-horizontal class="-mr-1 ml-2 h-5 w-5 text-control-light" />+ <heroicons-outline:switch-horizontal+ class="-mr-1 ml-2 h-5 w-5 text-control-light"+ /></button>- <button v-if="allowEdit" type="button" class="btn-normal" @click.prevent="alterSchema">+ <button+ v-if="allowEdit"+ type="button"+ class="btn-normal"+ @click.prevent="alterSchema"+ ><span>{{ alterSchemaText }}</span><heroicons-outline:external-linkv-if="database.project.workflowType == 'VCS'"@@ -121,16 +156,20 @@type="button"class="btn-normal py-2 px-4"@click.prevent="state.showModal = false"- >{{ $t("common.cancel") }}</button>+ >+ {{ $t("common.cancel") }}+ </button><buttontype="button"class="btn-primary ml-3 inline-flex justify-center py-2 px-4":disabled="state.editingProjectId == database.project.id"@click.prevent="- updateProject(state.editingProjectId);-state.showModal = false;+ updateProject(state.editingProjectId);+ state.showModal = false;"- >{{ $t("common.transfer") }}</button>+ >+ {{ $t("common.transfer") }}+ </button></div></BBModal><BBTabFilter@@ -139,7 +178,7 @@ state.showModal = false;:tab-item-list="tabItemList":selected-index="state.selectedIndex"@select-index="- (index) => {+ (index: number) => {selectTab(index);}"@@ -149,7 +188,10 @@ state.showModal = false;<DatabaseOverviewPanel :database="database" /></template><template v-if="state.selectedIndex == MIGRATION_HISTORY_TAB">- <DatabaseMigrationHistoryPanel :database="database" :allow-edit="allowEdit" />+ <DatabaseMigrationHistoryPanel+ :database="database"+ :allow-edit="allowEdit"+ /></template><template v-if="state.selectedIndex == BACKUP_TAB"><DatabaseBackupPanel@@ -171,19 +213,17 @@ import DatabaseBackupPanel from "../components/DatabaseBackupPanel.vue";import DatabaseMigrationHistoryPanel from "../components/DatabaseMigrationHistoryPanel.vue";import DatabaseOverviewPanel from "../components/DatabaseOverviewPanel.vue";import InstanceEngineIcon from "../components/InstanceEngineIcon.vue";-import {- idFromSlug,- isDBAOrOwner,- connectionSlug,-} from "../utils";+import { DatabaseLabelsEditor } from "../components/DatabaseLabels";+import { idFromSlug, isDBAOrOwner, connectionSlug } from "../utils";import {ProjectId,UNKNOWN_ID,DEFAULT_PROJECT_ID,Repository,baseDirectoryWebUrl,+ Database,+ DatabaseLabel,} from "../types";-import { isEmpty } from "lodash-es";import { BBTabFilterItem } from "../bbkit/types";import { useI18n } from "vue-i18n";@@ -210,6 +250,7 @@ export default defineComponent({DatabaseMigrationHistoryPanel,DatabaseBackupPanel,InstanceEngineIcon,+ DatabaseLabelsEditor,},props: {databaseSlug: {@@ -236,12 +277,16 @@ export default defineComponent({const currentUser = computed(() => store.getters["auth/currentUser"]());- const database = computed(() => {+ const database = computed((): Database => {return store.getters["database/databaseById"](idFromSlug(props.databaseSlug));});+ const isTenantProject = computed(() => {+ return database.value.project.tenantMode === "TENANT";+ });+const isCurrentUserDBAOrOwner = computed((): boolean => {return isDBAOrOwner(currentUser.value.role);});@@ -375,6 +420,13 @@ export default defineComponent({});};+ const updateLabels = (labels: DatabaseLabel[]) => {+ store.dispatch("database/patchDatabaseLabels", {+ databaseId: database.value.id,+ labels,+ });+ };+const selectTab = (index: number) => {state.selectedIndex = index;router.replace({@@ -426,6 +478,7 @@ export default defineComponent({MIGRATION_HISTORY_TAB,BACKUP_TAB,state,+ isTenantProject,database,allowChangeProject,allowAdmin,@@ -435,6 +488,7 @@ export default defineComponent({alterSchema,alterSchemaText,updateProject,+ updateLabels,selectTab,gotoSqlEditor,};diff --git a/frontend/src/views/IssueDetail.vue b/frontend/src/views/IssueDetail.vueindex f4477dd096..8da19c0d1c 100644--- a/frontend/src/views/IssueDetail.vue+++ b/frontend/src/views/IssueDetail.vue@@ -1,197 +1,16 @@<template>- <div- id="issue-detail-top"- class="flex-1 overflow-auto focus:outline-none"- tabindex="0"- >- <IssueBanner v-if="!state.create" :issue="issue" />-- <!-- Highlight Panel -->- <div class="bg-white px-4 pb-4">- <IssueHighlightPanel- :issue="issue"- :create="state.create"- :allow-edit="allowEditNameAndDescription"- @update-name="updateName"- >- <IssueStatusTransitionButtonGroup- :create="state.create"- :allow-rollback="allowRollback"- :issue="issue"- :issue-template="issueTemplate"- @create="doCreate"- @rollback="doRollback"- @change-issue-status="changeIssueStatus"- @change-task-status="changeTaskStatus"- />- </IssueHighlightPanel>- </div>-- <!-- Stage Flow Bar -->- <template v-if="showPipelineFlowBar">- <PipelineSimpleFlow- :create="state.create"- :pipeline="issue.pipeline"- :selected-stage="selectedStage"- @select-stage-id="selectStageId"- />- <div v-if="!state.create" class="px-4 py-4 md:flex md:flex-col border-b">- <IssueStagePanel :stage="selectedStage" />- </div>- </template>-- <!-- Output Panel -->- <!-- Only render the top border if PipelineFlowBar is not displayed, otherwise it would overlap with the bottom border of that -->- <div- v-if="showIssueOutputPanel"- class="px-2 py-4 md:flex md:flex-col"- :class="showPipelineFlowBar ? '' : 'lg:border-t'"- >- <IssueOutputPanel- :issue="issue"- :output-field-list="issueTemplate.outputFieldList"- :allow-edit="allowEditOutput"- @update-custom-field="updateCustomField"- />- </div>-- <!-- Main Content -->- <main- class="flex-1 relative overflow-y-auto focus:outline-none"- :class="- showPipelineFlowBar && !showIssueOutputPanel- ? ''- : 'lg:border-t lg:border-block-border'- "- tabindex="-1"- >- <div class="flex max-w-3xl mx-auto px-6 lg:max-w-full">- <div class="flex flex-col flex-1 lg:flex-row-reverse lg:col-span-2">- <div- class="py-6 lg:pl-4 lg:w-96 xl:w-112 lg:border-l lg:border-block-border"- >- <IssueSidebar- :issue="issue"- :task="selectedTask"- :database="database"- :instance="instance"- :create="state.create"- :selected-stage="selectedStage"- :input-field-list="issueTemplate.inputFieldList"- :allow-edit="allowEditSidebar"- @update-assignee-id="updateAssigneeId"- @update-earliest-allowed-time="updateEarliestAllowedTime"- @add-subscriber-id="addSubscriberId"- @remove-subscriber-id="removeSubscriberId"- @update-custom-field="updateCustomField"- @select-stage-id="selectStageId"- />- </div>- <div class="lg:hidden border-t border-block-border" />- <div class="w-full py-4 pr-4">- <section v-if="showIssueTaskStatementPanel" class="border-b mb-4">- <div v-if="!state.create" class="mb-4">- <TaskCheckBar- :task="selectedTask"- @run-checks="runTaskChecks"- />- </div>- <!-- The way this is written is awkward and is to workaround an issue in IssueTaskStatementPanel.- The statement panel is in non-edit mode when not creating the issue, and we use v-highlight- to apply syntax highlighting when the panel is in non-edit mode. However, the v-highlight- doesn't seem to work well with the reactivity. So for non-edit mode when !state.create, we- list every IssueTaskStatementPanel for each stage and use v-if to show the active one. -->- <template v-if="state.create">- <IssueTaskStatementPanel- :sql-hint="sqlHint(false)"- :statement="selectedStatement"- :create="state.create"- :allow-edit="true"- :rollback="false"- :show-apply-statement="showIssueTaskStatementApply"- @update-statement="updateStatement"- @apply-statement-to-other-stages="applyStatementToOtherStages"- />- </template>- <template- v-for="(stage, index) in issue.pipeline.stageList"- v-else- :key="index"- >- <template v-if="selectedStage.id == stage.id">- <IssueTaskStatementPanel- :sql-hint="sqlHint(false)"- :statement="statement(stage)"- :create="state.create"- :allow-edit="allowEditStatement"- :rollback="false"- :show-apply-statement="showIssueTaskStatementApply"- @update-statement="updateStatement"- />- </template>- </template>- </section>- <section- v-if="showIssueTaskRollbackStatementPanel"- class="border-b mb-4"- >- <template v-if="state.create">- <IssueTaskStatementPanel- :sql-hint="sqlHint(true)"- :statement="selectedRollbackStatement"- :create="state.create"- :allow-edit="false"- :rollback="true"- :show-apply-statement="showIssueTaskStatementApply"- @update-statement="updateRollbackStatement"- @apply-statement-to-other-stages="- applyRollbackStatementToOtherStages- "- />- </template>- <template- v-for="(stage, index) in issue.pipeline.stageList"- v-else- :key="index"- >- <template v-if="selectedStage.id == stage.id">- <IssueTaskStatementPanel- :sql-hint="sqlHint(true)"- :statement="rollbackStatement(stage)"- :create="state.create"- :allow-edit="false"- :rollback="true"- :show-apply-statement="showIssueTaskStatementApply"- @update-statement="updateRollbackStatement"- />- </template>- </template>- </section>- <IssueDescriptionPanel- :issue="issue"- :create="state.create"- :allow-edit="allowEditNameAndDescription"- @update-description="updateDescription"- />- <section- v-if="!state.create"- aria-labelledby="activity-title"- class="mt-4"- >- <IssueActivityPanel- :issue="issue"- :issue-template="issueTemplate"- @add-subscriber-id="addSubscriberId"- />- </section>- </div>- </div>- </div>- </main>+ <IssueDetailLayout+ v-if="issue"+ :issue="issue"+ :create="state.create"+ @status-changed="onStatusChanged"+ />+ <div v-else class="w-full h-full flex justify-center items-center">+ <NSpin /></div></template>-<script lang="ts" setup>+<script lang="ts">import {computed,onMounted,@@ -200,74 +19,34 @@ import {watchEffect,reactive,ref,- defineProps,+ defineComponent,} from "vue";import { useStore } from "vuex";-import { useRouter } from "vue-router";-import cloneDeep from "lodash-es/cloneDeep";-import isEqual from "lodash-es/isEqual";-import {- idFromSlug,- issueSlug,- pipelineType,- PipelineType,- indexFromSlug,- activeStage,- stageSlug,- activeTask,-} from "../utils";-import {- IssueBanner,- IssueHighlightPanel,- IssueStagePanel,- IssueStatusTransitionButtonGroup,- IssueOutputPanel,- IssueSidebar,- IssueTaskStatementPanel,- IssueDescriptionPanel,- IssueActivityPanel,- PipelineSimpleFlow,- TaskCheckBar,-} from "../components/Issue";+import { useRoute, useRouter } from "vue-router";+import { idFromSlug } from "../utils";+import { IssueDetailLayout } from "../components/Issue";import {UNKNOWN_ID,Issue,IssueCreate,IssueType,- IssuePatch,- PrincipalId,Database,- Instance,Environment,- Stage,- StageId,- IssueStatus,- TaskId,- TaskStatusPatch,- TaskStatus,- IssueStatusPatch,- Task,TaskDatabaseSchemaUpdatePayload,- StageCreate,- TaskCreate,- TaskDatabaseCreatePayload,- TaskGeneralPayload,NORMAL_POLL_INTERVAL,POLL_JITTER,POST_CHANGE_POLL_INTERVAL,Project,- MigrationType,- TaskPatch,Policy,+ unknown,} from "../types";import {- defaulTemplate,+ defaulTemplate as defaultTemplate,templateForType,- InputField,- OutputField,IssueTemplate,} from "../plugins";import { isEmpty } from "lodash-es";+import { NSpin } from "naive-ui";interface LocalState {// Needs to maintain this state and set it to false manually after creating the issue.@@ -279,863 +58,443 @@ interface LocalState {pollIssueTimer?: ReturnType<typeof setTimeout>;}-const props = defineProps<{ issueSlug: string }>();+export default defineComponent({+ name: "IssueDetail",+ components: {+ IssueDetailLayout,+ NSpin,+ },+ props: {+ issueSlug: {+ required: true,+ type: String,+ },+ },++ setup(props) {+ const store = useStore();+ const router = useRouter();+ const route = useRoute();++ const currentUser = computed(() => store.getters["auth/currentUser"]());++ let newIssueTemplate = ref<IssueTemplate>(defaultTemplate());++ const refreshTemplate = () => {+ const issueType = router.currentRoute.value.query.template as IssueType;+ if (issueType) {+ const template = templateForType(issueType);+ if (template) {+ newIssueTemplate.value = template;+ } else {+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "WARN",+ title: `Unknown template '${issueType}'.`,+ description: "Fallback to the default template",+ });+ }+ }++ if (!newIssueTemplate.value) {+ newIssueTemplate.value = defaultTemplate();+ }+ };++ // Vue doesn't natively react to query parameter change+ // so we need to manually watch here.+ watch(+ () => router.currentRoute.value.query.template,+ () => {+ refreshTemplate();+ }+ );-const store = useStore();-const router = useRouter();+ watchEffect(refreshTemplate);-const currentUser = computed(() => store.getters["auth/currentUser"]());+ const state = reactive<LocalState>({+ create: props.issueSlug.toLowerCase() == "new",+ newIssue: undefined,+ });-let newIssueTemplate = ref<IssueTemplate>(defaulTemplate());+ const issue = computed((): Issue | IssueCreate => {+ return state.create+ ? state.newIssue+ : store.getters["issue/issueById"](idFromSlug(props.issueSlug));+ });-const refreshTemplate = () => {- const issueType = router.currentRoute.value.query.template as IssueType;- if (issueType) {- const template = templateForType(issueType);- if (template) {- newIssueTemplate.value = template;- } else {- store.dispatch("notification/pushNotification", {- module: "bytebase",- style: "WARN",- title: `Unknown template '${issueType}'.`,- description: "Fallback to the default template",+ const buildNewTenantSchemaUpdateIssue = async (+ project: Project+ ): Promise<IssueCreate> => {+ const baseTemplate = newIssueTemplate.value.buildIssue({+ environmentList: [],+ approvalPolicyList: [],+ databaseList: [],+ currentUser: currentUser.value,});- }- }+ const issueCreate: IssueCreate = {+ projectId: project.id,+ name: (route.query.name as string) || baseTemplate.name,+ type: "bb.issue.database.schema.update",+ description: baseTemplate.description,+ assigneeId: currentUser.value.id,+ createContext: {+ migrationType: "MIGRATE",+ updateSchemaDetailList: [+ {+ databaseName: route.query.databaseName,+ statement: "/* YOUR_SQL_HERE */",+ rollbackStatement: "",+ },+ ],+ },+ payload: {},+ };+ const issue: Issue = await store.dispatch(+ "issue/validateIssue",+ issueCreate+ );- if (!newIssueTemplate.value) {- newIssueTemplate.value = defaulTemplate();- }-};+ issueCreate.assigneeId = baseTemplate.assigneeId;+ issueCreate.pipeline = {+ name: issue.pipeline.name,+ stageList: issue.pipeline.stageList.map((stage) => ({+ name: stage.name,+ environmentId: stage.environment.id,+ taskList: stage.taskList.map((task) => {+ const payload = task.payload as TaskDatabaseSchemaUpdatePayload;+ return {+ name: task.name,+ status: task.status,+ type: task.type,+ instanceId: task.instance.id,+ databaseId: task.database?.id,+ migrationType: payload.migrationType,+ statement: payload.statement,+ rollbackStatement: payload.rollbackStatement,+ earliestAllowedTs: task.earliestAllowedTs,+ };+ }),+ })),+ };-// Vue doesn't natively react to query parameter change-// so we need to manually watch here.-watch(- () => router.currentRoute.value.query.template,- () => {- refreshTemplate();- }-);+ return issueCreate;+ };-watchEffect(refreshTemplate);+ const maybeBuildTenantDeployIssue = async (): Promise<+ IssueCreate | false+ > => {+ if (route.query.mode !== "tenant") {+ return false;+ }-const buildNewIssue = (): IssueCreate => {- var newIssue: IssueCreate;+ const projectId = route.query.project+ ? parseInt(route.query.project as string)+ : UNKNOWN_ID;+ let project = unknown("PROJECT") as Project;+ if (projectId !== UNKNOWN_ID) {+ project = await store.dispatch("project/fetchProjectById", projectId);+ }+ const issueType = route.query.template as IssueType;+ if (+ project.tenantMode === "TENANT" &&+ issueType === "bb.issue.database.schema.update"+ ) {+ return buildNewTenantSchemaUpdateIssue(project);+ }+ return false;+ };- // Create rollback issue- if (router.currentRoute.value.query.rollbackIssue) {- const rollbackIssue: Issue = store.getters["issue/issueById"](- parseInt(router.currentRoute.value.query.rollbackIssue as string)- );+ const buildNewIssue = async (): Promise<IssueCreate | undefined> => {+ const tenant = await maybeBuildTenantDeployIssue();+ if (tenant) {+ return tenant;+ }- let validState = false;- let title = "";+ var newIssue: IssueCreate;+ // Create rollback issue+ if (router.currentRoute.value.query.rollbackIssue) {+ const rollbackIssue: Issue = store.getters["issue/issueById"](+ parseInt(router.currentRoute.value.query.rollbackIssue as string)+ );- // We expect user to create rollback from the original issue, which should have already fetched- // issue remotely. Otherwise, this will return UNKNOWN_ID- if (rollbackIssue.id == UNKNOWN_ID) {- title = "INVALID STATE, please create rollback from the original issue.";- } else {- if (rollbackIssue.type != "bb.issue.database.schema.update") {- title = "INVALID STATE, only support to rollback update schema issue.";- } else if (- rollbackIssue.status != "DONE" &&- rollbackIssue.status != "CANCELED"- ) {- title =- "INVALID STATE, only support to rollback issue in closed state.";- } else {- for (const stage of rollbackIssue.pipeline.stageList) {- for (const task of stage.taskList) {- if (- task.status == "DONE" &&- task.type == "bb.task.database.schema.update" &&- !isEmpty(- (task.payload as TaskDatabaseSchemaUpdatePayload)- .rollbackStatement- )- ) {- validState = true;- break;+ let validState = false;+ let title = "";++ // We expect user to create rollback from the original issue, which should have already fetched+ // issue remotely. Otherwise, this will return UNKNOWN_ID+ if (rollbackIssue.id == UNKNOWN_ID) {+ title =+ "INVALID STATE, please create rollback from the original issue.";+ } else {+ if (rollbackIssue.type != "bb.issue.database.schema.update") {+ title =+ "INVALID STATE, only support to rollback update schema issue.";+ } else if (+ rollbackIssue.status != "DONE" &&+ rollbackIssue.status != "CANCELED"+ ) {+ title =+ "INVALID STATE, only support to rollback issue in closed state.";+ } else {+ for (const stage of rollbackIssue.pipeline.stageList) {+ for (const task of stage.taskList) {+ if (+ task.status == "DONE" &&+ task.type == "bb.task.database.schema.update" &&+ !isEmpty(+ (task.payload as TaskDatabaseSchemaUpdatePayload)+ .rollbackStatement+ )+ ) {+ validState = true;+ break;+ }+ }+ if (validState) {+ break;+ }+ }++ if (!validState) {+ title =+ "INVALID STATE, no applicable update schema task to rollback.";}- }- if (validState) {- break;}}- if (!validState) {- title =- "INVALID STATE, no applicable update schema task to rollback.";+ if (validState) {+ let environmentList: Environment[] = [];+ const approvalPolicyList: Policy[] = [];+ const databaseList: Database[] = [];+ const statementList: string[] = [];+ const rollbackStatementList: string[] = [];+ for (+ let i = rollbackIssue.pipeline.stageList.length - 1;+ i >= 0;+ i--+ ) {+ const stage = rollbackIssue.pipeline.stageList[i];+ for (let j = stage.taskList.length - 1; j >= 0; j--) {+ const task = stage.taskList[j];+ if (+ task.status == "DONE" &&+ task.type == "bb.task.database.schema.update" &&+ !isEmpty(+ (task.payload as TaskDatabaseSchemaUpdatePayload)+ .rollbackStatement+ )+ ) {+ environmentList.push(stage.environment);+ approvalPolicyList.push(+ store.getters["policy/policyByEnvironmentIdAndType"](+ stage.environment.id,+ "bb.policy.pipeline-approval"+ )+ );+ databaseList.push(task.database!);+ statementList.push(+ (task.payload as TaskDatabaseSchemaUpdatePayload)+ .rollbackStatement+ );+ rollbackStatementList.push(+ (task.payload as TaskDatabaseSchemaUpdatePayload).statement+ );+ }+ }+ }++ if (environmentList.length == 0) {+ newIssue = {+ ...defaultTemplate().buildIssue({+ environmentList: [],+ approvalPolicyList: [],+ databaseList: [],+ currentUser: currentUser.value,+ }),+ name: "INVALID STATE, no applicable update schema task to rollback.",+ projectId: UNKNOWN_ID,+ };+ } else {+ newIssue = {+ ...newIssueTemplate.value.buildIssue({+ environmentList,+ approvalPolicyList,+ databaseList,+ statementList,+ rollbackStatementList,+ currentUser: currentUser.value,+ }),+ projectId: rollbackIssue.project.id,+ name: `[Rollback] issue/${rollbackIssue.id} - ${rollbackIssue.name}`,+ description: rollbackIssue.description+ ? `====Original issue description BEGIN====\n\n${rollbackIssue.description}\n\n====Original issue description END====\n\n`+ : "",+ assigneeId: rollbackIssue.assignee.id,+ };+ }+ } else {+ newIssue = {+ ...defaultTemplate().buildIssue({+ environmentList: [],+ approvalPolicyList: [],+ databaseList: [],+ currentUser: currentUser.value,+ }),+ name: title,+ projectId: UNKNOWN_ID,+ };}+ newIssue.rollbackIssueId = rollbackIssue.id;}- }+ // Create issue from normal query parameter+ else {+ const databaseList: Database[] = [];+ if (router.currentRoute.value.query.databaseList) {+ for (const databaseId of (+ router.currentRoute.value.query.databaseList as string+ ).split(","))+ databaseList.push(+ store.getters["database/databaseById"](databaseId)+ );+ }- if (validState) {- let environmentList: Environment[] = [];- const approvalPolicyList: Policy[] = [];- const databaseList: Database[] = [];- const statementList: string[] = [];- const rollbackStatementList: string[] = [];- for (let i = rollbackIssue.pipeline.stageList.length - 1; i >= 0; i--) {- const stage = rollbackIssue.pipeline.stageList[i];- for (let j = stage.taskList.length - 1; j >= 0; j--) {- const task = stage.taskList[j];- if (- task.status == "DONE" &&- task.type == "bb.task.database.schema.update" &&- !isEmpty(- (task.payload as TaskDatabaseSchemaUpdatePayload)- .rollbackStatement+ const environmentList: Environment[] = [];+ const approvalPolicyList: Policy[] = [];+ if (router.currentRoute.value.query.environment) {+ environmentList.push(+ store.getters["environment/environmentById"](+ router.currentRoute.value.query.environment)- ) {- environmentList.push(stage.environment);- approvalPolicyList.push(- store.getters["policy/policyByEnvironmentIdAndType"](- stage.environment.id,- "bb.policy.pipeline-approval"- )- );- databaseList.push(task.database!);- statementList.push(- (task.payload as TaskDatabaseSchemaUpdatePayload)- .rollbackStatement- );- rollbackStatementList.push(- (task.payload as TaskDatabaseSchemaUpdatePayload).statement- );+ );+ } else if (databaseList.length > 0) {+ for (const database of databaseList) {+ environmentList.push(database.instance.environment);}+ } else {+ environmentList.push(+ ...store.getters["environment/environmentList"]()+ );+ }++ for (const environment of environmentList) {+ approvalPolicyList.push(+ store.getters["policy/policyByEnvironmentIdAndType"](+ environment.id,+ "bb.policy.pipeline-approval"+ )+ );}- }- if (environmentList.length == 0) {- newIssue = {- ...defaulTemplate().buildIssue({- environmentList: [],- approvalPolicyList: [],- databaseList: [],- currentUser: currentUser.value,- }),- name: "INVALID STATE, no applicable update schema task to rollback.",- projectId: UNKNOWN_ID,- };- } else {newIssue = {...newIssueTemplate.value.buildIssue({environmentList,approvalPolicyList,databaseList,- statementList,- rollbackStatementList,currentUser: currentUser.value,}),- projectId: rollbackIssue.project.id,- name: `[Rollback] issue/${rollbackIssue.id} - ${rollbackIssue.name}`,- description: rollbackIssue.description- ? `====Original issue description BEGIN====\n\n${rollbackIssue.description}\n\n====Original issue description END====\n\n`- : "",- assigneeId: rollbackIssue.assignee.id,+ projectId: router.currentRoute.value.query.project+ ? parseInt(router.currentRoute.value.query.project as string)+ : UNKNOWN_ID,};- }- } else {- newIssue = {- ...defaulTemplate().buildIssue({- environmentList: [],- approvalPolicyList: [],- databaseList: [],- currentUser: currentUser.value,- }),- name: title,- projectId: UNKNOWN_ID,- };- }- newIssue.rollbackIssueId = rollbackIssue.id;- }- // Create issue from normal query parameter- else {- const databaseList: Database[] = [];- if (router.currentRoute.value.query.databaseList) {- for (const databaseId of (- router.currentRoute.value.query.databaseList as string- ).split(","))- databaseList.push(store.getters["database/databaseById"](databaseId));- }- const environmentList: Environment[] = [];- const approvalPolicyList: Policy[] = [];- if (router.currentRoute.value.query.environment) {- environmentList.push(- store.getters["environment/environmentById"](- router.currentRoute.value.query.environment- )- );- } else if (databaseList.length > 0) {- for (const database of databaseList) {- environmentList.push(database.instance.environment);- }- } else {- environmentList.push(...store.getters["environment/environmentList"]());- }+ // For demo mode, we assign the issue to the current user, so it can also experience the assignee user flow.+ if (store.getters["actuator/isDemo"]()) {+ newIssue.assigneeId = currentUser.value.id;+ }- for (const environment of environmentList) {- approvalPolicyList.push(- store.getters["policy/policyByEnvironmentIdAndType"](- environment.id,- "bb.policy.pipeline-approval"- )- );- }+ if (router.currentRoute.value.query.name) {+ newIssue.name = router.currentRoute.value.query.name as string;+ }+ if (router.currentRoute.value.query.description) {+ newIssue.description = router.currentRoute.value.query+ .description as string;+ }+ if (router.currentRoute.value.query.assignee) {+ newIssue.assigneeId = parseInt(+ router.currentRoute.value.query.assignee as string+ );+ }+ }+ for (const field of newIssueTemplate.value.inputFieldList) {+ const value = router.currentRoute.value.query[field.slug] as string;+ if (value) {+ if (field.type == "Boolean") {+ newIssue.payload[field.id] =+ value != "0" && value.toLowerCase() != "false";+ } else {+ newIssue.payload[field.id] = value;+ }+ }+ }- newIssue = {- ...newIssueTemplate.value.buildIssue({- environmentList,- approvalPolicyList,- databaseList,- currentUser: currentUser.value,- }),- projectId: router.currentRoute.value.query.project- ? parseInt(router.currentRoute.value.query.project as string)- : UNKNOWN_ID,+ return newIssue;};- // For demo mode, we assign the issue to the current user, so it can also experience the assignee user flow.- if (store.getters["actuator/isDemo"]()) {- newIssue.assigneeId = currentUser.value.id;- }-- if (router.currentRoute.value.query.name) {- newIssue.name = router.currentRoute.value.query.name as string;- }- if (router.currentRoute.value.query.description) {- newIssue.description = router.currentRoute.value.query- .description as string;- }- if (router.currentRoute.value.query.assignee) {- newIssue.assigneeId = parseInt(- router.currentRoute.value.query.assignee as string- );- }- }- for (const field of newIssueTemplate.value.inputFieldList) {- const value = router.currentRoute.value.query[field.slug] as string;- if (value) {- if (field.type == "Boolean") {- newIssue.payload[field.id] =- value != "0" && value.toLowerCase() != "false";- } else {- newIssue.payload[field.id] = value;+ // pollIssue invalidates the current timer and schedule a new timer in <<interval>> microseconds+ const pollIssue = (interval: number) => {+ if (state.pollIssueTimer) {+ clearInterval(state.pollIssueTimer);}- }- }-- return newIssue;-};--const state = reactive<LocalState>({- create: props.issueSlug.toLowerCase() == "new",- newIssue:- props.issueSlug.toLowerCase() == "new" ? buildNewIssue() : undefined,-});--// pollIssue invalidates the current timer and schedule a new timer in <<interval>> microseconds-const pollIssue = (interval: number) => {- if (state.pollIssueTimer) {- clearInterval(state.pollIssueTimer);- }-- state.pollIssueTimer = setTimeout(() => {- store.dispatch("issue/fetchIssueById", idFromSlug(props.issueSlug));- pollIssue(Math.min(interval * 2, NORMAL_POLL_INTERVAL));- }, Math.max(1000, Math.min(interval, NORMAL_POLL_INTERVAL) + (Math.random() * 2 - 1) * POLL_JITTER));-};-const pollOnCreateStateChange = () => {- let interval = NORMAL_POLL_INTERVAL;- // We will poll faster if meets either of the condition- // 1. Created the database create issue, expect creation result quickly.- // 2. Update the database schema, will do connection and syntax check.- if (- (issue.value.type == "bb.issue.database.create" ||- issue.value.type == "bb.issue.database.schema.update") &&- Date.now() - (issue.value as Issue).updatedTs * 1000 < 5000- ) {- interval = POST_CHANGE_POLL_INTERVAL;- }- pollIssue(interval);-};--onMounted(() => {- // Always scroll to top, the scrollBehavior doesn't seem to work.- // The hypothesis is that because the scroll bar is in the nested- // route, thus setting the scrollBehavior in the global router- // won't work.- document.getElementById("issue-detail-top")!.scrollIntoView();- if (!state.create) {- pollOnCreateStateChange();- }-});--onUnmounted(() => {- if (state.pollIssueTimer) {- clearInterval(state.pollIssueTimer);- }-});--watch(- () => props.issueSlug,- (cur) => {- const oldCreate = state.create;- state.create = cur.toLowerCase() == "new";- if (!state.create && oldCreate) {- pollOnCreateStateChange();- } else if (state.create && !oldCreate) {- clearInterval(state.pollIssueTimer!);- state.newIssue = buildNewIssue();- }- }-);--const issue = computed((): Issue | IssueCreate => {- return state.create- ? state.newIssue- : store.getters["issue/issueById"](idFromSlug(props.issueSlug));-});--const issueTemplate = computed(- () => templateForType(issue.value.type) || defaulTemplate()-);--const project = computed((): Project => {- if (state.create) {- return store.getters["project/projectById"](- (issue.value as IssueCreate).projectId- );- }- return (issue.value as Issue).project;-});--const updateName = (- newName: string,- postUpdated: (updatedIssue: Issue) => void-) => {- if (state.create) {- state.newIssue!.name = newName;- } else {- patchIssue(- {- name: newName,- },- postUpdated- );- }-};--const updateStatement = (- newStatement: string,- postUpdated?: (updatedTask: Task) => void-) => {- if (state.create) {- const stage = selectedStage.value as StageCreate;- stage.taskList[0].statement = newStatement;- } else {- patchTask(- (selectedTask.value as Task).id,- {- statement: newStatement,- },- postUpdated- );- }-};+ state.pollIssueTimer = setTimeout(() => {+ store.dispatch("issue/fetchIssueById", idFromSlug(props.issueSlug));+ pollIssue(Math.min(interval * 2, NORMAL_POLL_INTERVAL));+ }, Math.max(1000, Math.min(interval, NORMAL_POLL_INTERVAL) + (Math.random() * 2 - 1) * POLL_JITTER));+ };-const applyStatementToOtherStages = (newStatement: string) => {- for (const stage of (issue.value as IssueCreate).pipeline.stageList) {- for (const task of stage.taskList) {+ const pollOnCreateStateChange = () => {+ let interval = NORMAL_POLL_INTERVAL;+ // We will poll faster if meets either of the condition+ // 1. Created the database create issue, expect creation result quickly.+ // 2. Update the database schema, will do connection and syntax check.if (- task.type == "bb.task.general" ||- task.type == "bb.task.database.create" ||- task.type == "bb.task.database.schema.update"+ (issue.value.type == "bb.issue.database.create" ||+ issue.value.type == "bb.issue.database.schema.update") &&+ Date.now() - (issue.value as Issue).updatedTs * 1000 < 5000) {- task.statement = newStatement;- }- }- }-};--const updateRollbackStatement = (newStatement: string) => {- const stage = selectedStage.value as StageCreate;- stage.taskList[0].rollbackStatement = newStatement;-};--const applyRollbackStatementToOtherStages = (newStatement: string) => {- for (const stage of (issue.value as IssueCreate).pipeline.stageList) {- for (const task of stage.taskList) {- if (task.type == "bb.task.database.schema.update") {- task.rollbackStatement = newStatement;+ interval = POST_CHANGE_POLL_INTERVAL;}- }- }-};--const updateDescription = (- newDescription: string,- postUpdated: (updatedIssue: Issue) => void-) => {- if (state.create) {- state.newIssue!.description = newDescription;- } else {- patchIssue(- {- description: newDescription,- },- postUpdated- );- }-};--const updateAssigneeId = (newAssigneeId: PrincipalId) => {- if (state.create) {- state.newIssue!.assigneeId = newAssigneeId;- } else {- patchIssue({- assigneeId: newAssigneeId,- });- }-};--const updateEarliestAllowedTime = (newEarliestAllowedTsMs: number) => {- if (state.create) {- selectedTask.value.earliestAllowedTs = newEarliestAllowedTsMs;- } else {- const taskPatch: TaskPatch = {- earliestAllowedTs: newEarliestAllowedTsMs,+ pollIssue(interval);};- patchTask((selectedTask.value as Task).id, taskPatch);- }-};--const addSubscriberId = (subscriberId: PrincipalId) => {- store.dispatch("issueSubscriber/createSubscriber", {- issueId: (issue.value as Issue).id,- subscriberId,- });-};--const removeSubscriberId = (subscriberId: PrincipalId) => {- store.dispatch("issueSubscriber/deleteSubscriber", {- issueId: (issue.value as Issue).id,- subscriberId,- });-};--const updateCustomField = (field: InputField | OutputField, value: any) => {- if (!isEqual(issue.value.payload[field.id], value)) {- if (state.create) {- state.newIssue!.payload[field.id] = value;- } else {- const newPayload = cloneDeep(issue.value.payload);- newPayload[field.id] = value;- patchIssue({- payload: newPayload,- });- }- }-};--const doCreate = () => {- store.dispatch("issue/createIssue", state.newIssue).then((createdIssue) => {- // Use replace to omit the new issue url in the navigation history.- router.replace(`/issue/${issueSlug(createdIssue.name, createdIssue.id)}`);- });-};--const doRollback = () => {- router.push({- name: "workspace.issue.detail",- params: {- issueSlug: "new",- },- query: {- template: "bb.issue.database.schema.update",- rollbackIssue: (issue.value as Issue).id,- },- });-};--const changeIssueStatus = (newStatus: IssueStatus, comment: string) => {- const issueStatusPatch: IssueStatusPatch = {- status: newStatus,- comment: comment,- };-- store- .dispatch("issue/updateIssueStatus", {- issueId: (issue.value as Issue).id,- issueStatusPatch,- })- .then(() => {- pollIssue(POST_CHANGE_POLL_INTERVAL);- });-};--const changeTaskStatus = (- task: Task,- newStatus: TaskStatus,- comment: string-) => {- // Switch to the stage view containing this task- selectStageId(task.stage.id);-- const taskStatusPatch: TaskStatusPatch = {- status: newStatus,- comment: comment,- };-- store- .dispatch("task/updateStatus", {- issueId: (issue.value as Issue).id,- pipelineId: (issue.value as Issue).pipeline.id,- taskId: task.id,- taskStatusPatch,- })- .then(() => {- pollIssue(POST_CHANGE_POLL_INTERVAL);- });-};--const runTaskChecks = (task: Task) => {- store- .dispatch("task/runChecks", {- issueId: (issue.value as Issue).id,- pipelineId: (issue.value as Issue).pipeline.id,- taskId: task.id,- })- .then(() => {- pollIssue(POST_CHANGE_POLL_INTERVAL);- });-};-const patchIssue = (- issuePatch: IssuePatch,- postUpdated?: (updatedIssue: Issue) => void-) => {- store- .dispatch("issue/patchIssue", {- issueId: (issue.value as Issue).id,- issuePatch,- })- .then((updatedIssue) => {- // issue/patchIssue already fetches the new issue, so we schedule- // the next poll in NORMAL_POLL_INTERVAL- pollIssue(NORMAL_POLL_INTERVAL);- if (postUpdated) {- postUpdated(updatedIssue);+ onMounted(async () => {+ if (!state.create) {+ pollOnCreateStateChange();+ } else {+ state.newIssue = await buildNewIssue();}});-};-const patchTask = (- taskId: TaskId,- taskPatch: TaskPatch,- postUpdated?: (updatedTask: Task) => void-) => {- store- .dispatch("task/patchTask", {- issueId: (issue.value as Issue).id,- pipelineId: (issue.value as Issue).pipeline.id,- taskId,- taskPatch,- })- .then((updatedTask) => {- // For now, the only task/patchTask is to change statement, which will trigger async task check.- // Thus we use the short poll interval- pollIssue(POST_CHANGE_POLL_INTERVAL);- if (postUpdated) {- postUpdated(updatedTask);+ onUnmounted(() => {+ if (state.pollIssueTimer) {+ clearInterval(state.pollIssueTimer);}});-};--const currentPipelineType = computed((): PipelineType => {- return pipelineType(issue.value.pipeline);-});--const selectedStage = computed((): Stage | StageCreate => {- const stageSlug = router.currentRoute.value.query.stage as string;- const taskSlug = router.currentRoute.value.query.task as string;- // For stage slug, we support both index based and id based.- // Index based is used when creating the new task and is the one used when clicking the UI.- // Id based is used when the context only has access to the stage id (e.g. Task only contains StageId)- if (stageSlug) {- const index = indexFromSlug(stageSlug);- if (index < issue.value.pipeline.stageList.length) {- return issue.value.pipeline.stageList[index];- }- const stageId = idFromSlug(stageSlug);- const stageList = (issue.value as Issue).pipeline.stageList;- for (const stage of stageList) {- if (stage.id == stageId) {- return stage;- }- }- } else if (!state.create && taskSlug) {- const taskId = idFromSlug(taskSlug);- const stageList = (issue.value as Issue).pipeline.stageList;- for (const stage of stageList) {- for (const task of stage.taskList) {- if (task.id == taskId) {- return stage;- }- }- }- }- if (state.create) {- return issue.value.pipeline.stageList[0];- }- return activeStage((issue.value as Issue).pipeline);-});--const selectStageId = (stageId: StageId) => {- const stageList = issue.value.pipeline.stageList;- const index = stageList.findIndex((item, index) => {- if (state.create) {- return index == stageId;- }- return (item as Stage).id == stageId;- });- router.replace({- name: "workspace.issue.detail",- query: {- ...router.currentRoute.value.query,- task: undefined,- stage: stageSlug(stageList[index].name, index),- },- });-};--const selectedTask = computed((): Task | TaskCreate => {- return selectedStage.value.taskList[0];-});--const statement = (stage: Stage): string => {- const task = stage.taskList[0];- switch (task.type) {- case "bb.task.general":- return ((task as Task).payload as TaskGeneralPayload).statement || "";- case "bb.task.database.create":- return (- ((task as Task).payload as TaskDatabaseCreatePayload).statement || ""- );- case "bb.task.database.schema.update":- return (- ((task as Task).payload as TaskDatabaseSchemaUpdatePayload).statement ||- ""- );- case "bb.task.database.restore":- return "";- }-};--const rollbackStatement = (stage: Stage): string => {- const task = stage.taskList[0];- return (- (task.payload as TaskDatabaseSchemaUpdatePayload).rollbackStatement || ""- );-};-const selectedStatement = computed((): string => {- if (router.currentRoute.value.query.sql) {- const sql = router.currentRoute.value.query.sql as string;- updateStatement(sql);- }-- const task = (selectedStage.value as StageCreate).taskList[0];- return task.statement;-});--const selectedRollbackStatement = computed((): string => {- const task = (selectedStage.value as StageCreate).taskList[0];- return task.rollbackStatement;-});--const selectedMigrateType = computed((): MigrationType => {- if (- !state.create &&- selectedTask.value.type == "bb.task.database.schema.update"- ) {- return (- (selectedTask.value as Task).payload as TaskDatabaseSchemaUpdatePayload- ).migrationType;- }- return "MIGRATE";-});--const allowEditSidebar = computed(() => {- // For now, we only allow assignee to update the field when the issue- // is 'OPEN'. This reduces flexibility as creator must ask assignee to- // change any fields if there is typo. On the other hand, this avoids- // the trouble that the creator changes field value when the creator- // is performing the issue based on the old value.- // For now, we choose to be on the safe side at the cost of flexibility.- return (- state.create ||- ((issue.value as Issue).status == "OPEN" &&- (issue.value as Issue).assignee?.id == currentUser.value.id)- );-});--const allowEditOutput = computed(() => {- return (- state.create ||- ((issue.value as Issue).status == "OPEN" &&- (issue.value as Issue).assignee?.id == currentUser.value.id)- );-});--const allowEditNameAndDescription = computed(() => {- return (- state.create ||- ((issue.value as Issue).status == "OPEN" &&- ((issue.value as Issue).assignee?.id == currentUser.value.id ||- (issue.value as Issue).creator.id == currentUser.value.id))- );-});--const allowEditStatement = computed(() => {- return (- state.create ||- ((issue.value as Issue).status == "OPEN" &&- (issue.value as Issue).creator.id == currentUser.value.id &&- // Only allow if it's UI workflow- (issue.value as Issue).project.workflowType == "UI" &&- (selectedTask.value.status == "PENDING" ||- selectedTask.value.status == "PENDING_APPROVAL" ||- selectedTask.value.status == "FAILED"))- );-});--// For now, we only support rollback for schema update issue when all below conditions met:-// 1. Issue is in DONE or CANCELED state-// 2. There is at least one completed schema update task and the task contains the rollback statement.-const allowRollback = computed(() => {- if (!state.create) {- if (issue.value.type == "bb.issue.database.schema.update") {- if (- (issue.value as Issue).status == "DONE" ||- (issue.value as Issue).status == "CANCELED"- ) {- for (const stage of (issue.value as Issue).pipeline.stageList) {- for (const task of stage.taskList) {- if (- task.status == "DONE" &&- task.type == "bb.task.database.schema.update" &&- !isEmpty(- (task.payload as TaskDatabaseSchemaUpdatePayload)- .rollbackStatement- )- ) {- return true;- }- }+ watch(+ () => props.issueSlug,+ async (cur) => {+ const oldCreate = state.create;+ state.create = cur.toLowerCase() == "new";+ if (!state.create && oldCreate) {+ pollOnCreateStateChange();+ } else if (state.create && !oldCreate) {+ clearInterval(state.pollIssueTimer as any);+ state.newIssue = await buildNewIssue();}}- }- }- return false;-});--const showCancelBanner = computed(() => {- return !state.create && (issue.value as Issue).status == "CANCELED";-});--const showSuccessBanner = computed(() => {- return !state.create && (issue.value as Issue).status == "DONE";-});--const showPendingApproval = computed(() => {- if (state.create) {- return false;- }-- const task = activeTask((issue.value as Issue).pipeline);- return task.status == "PENDING_APPROVAL";-});--const showPipelineFlowBar = computed(() => {- return currentPipelineType.value != "NO_PIPELINE";-});--const showIssueOutputPanel = computed(() => {- return !state.create && issueTemplate.value.outputFieldList.length > 0;-});--const showIssueTaskStatementPanel = computed(() => {- const task = selectedTask.value;- return (- task.type == "bb.task.general" ||- task.type == "bb.task.database.create" ||- task.type == "bb.task.database.schema.update"- );-});--const showIssueTaskRollbackStatementPanel = computed(() => {- if (project.value.workflowType == "UI") {- return issue.value.type == "bb.issue.database.schema.update";- }- return false;-});--const showIssueTaskStatementApply = computed(() => {- if (!state.create) {- return false;- }- let count = 0;- for (const stage of (issue.value as IssueCreate).pipeline.stageList) {- for (const task of stage.taskList) {- if (- task.type == "bb.task.general" ||- task.type == "bb.task.database.create" ||- task.type == "bb.task.database.schema.update"- ) {- count++;- }- }- }- return count > 1;-});+ );-const database = computed((): Database | undefined => {- if (state.create) {- const databaseId = selectedStage.value.taskList[0].databaseId;- if (databaseId) {- return store.getters["database/databaseById"](databaseId);- }- return undefined;- }- return selectedStage.value.taskList[0].database;-});+ const onStatusChanged = (eager: boolean) => {+ pollIssue(eager ? POST_CHANGE_POLL_INTERVAL : NORMAL_POLL_INTERVAL);+ };-const instance = computed((): Instance => {- if (state.create) {- // If database is available, then we derive the instance from database because we always fetch database's instance.- if (database.value) {- return database.value.instance;- }- return store.getters["instance/instanceById"](- selectedStage.value.taskList[0].instanceId- );- }- return selectedStage.value.taskList[0].instance;+ return {+ state,+ issue,+ onStatusChanged,+ };+ },});--const sqlHint = (isRollBack: boolean): string | undefined => {- if (!isRollBack && !state.create && selectedMigrateType.value == "BASELINE") {- return `This is a baseline migration and bytebase won't apply the SQL to the database, it will only record a baseline history`;- }- if (!isRollBack && instance.value.engine === "SNOWFLAKE") {- return `Use <<schema>>.<<table>> to specify a Snowflake table`;- }- return undefined;-};</script>diff --git a/frontend/src/views/ProjectDashboard.vue b/frontend/src/views/ProjectDashboard.vueindex 3506090797..d1b79c0c62 100644--- a/frontend/src/views/ProjectDashboard.vue+++ b/frontend/src/views/ProjectDashboard.vue@@ -4,7 +4,7 @@<BBTableSearchref="searchField":placeholder="$t('project.dashboard.search-bar-placeholder')"- @change-text="(text) => changeSearchText(text)"+ @change-text="(text: string) => changeSearchText(text)"/></div><ProjectTable :project-list="filteredList(state.projectList)" />@@ -28,7 +28,14 @@</template><script lang="ts">-import { watchEffect, computed, onMounted, reactive, ref } from "vue";+import {+ watchEffect,+ computed,+ onMounted,+ reactive,+ ref,+ defineComponent,+} from "vue";import { useStore } from "vuex";import ProjectTable from "../components/ProjectTable.vue";import { Project, UNKNOWN_ID } from "../types";@@ -39,8 +46,8 @@ interface LocalState {showGuide: boolean;}-export default {- name: "Home",+export default defineComponent({+ name: "ProjectDashboard",components: {ProjectTable,},@@ -120,5 +127,5 @@ export default {changeSearchText,};},-};+});</script>diff --git a/frontend/src/views/ProjectDetail.vue b/frontend/src/views/ProjectDetail.vueindex 6b8d4fbcc8..f4086fb268 100644--- a/frontend/src/views/ProjectDetail.vue+++ b/frontend/src/views/ProjectDetail.vue@@ -37,10 +37,17 @@:allow-edit="allowEdit"/></template>+ <template v-else-if="selectedTab == DEPLOYMENT_CONFIG_TAB">+ <ProjectDeploymentConfigPanel+ id="deployment-config"+ :project="project"+ :allow-edit="allowEdit"+ />+ </template></template><script lang="ts">-import { computed, watchEffect } from "vue";+import { computed, defineComponent, watchEffect } from "vue";import { useStore } from "vuex";import { idFromSlug, sortDatabaseList } from "../utils";import ProjectActivityPanel from "../components/ProjectActivityPanel.vue";@@ -49,6 +56,7 @@ import ProjectOverviewPanel from "../components/ProjectOverviewPanel.vue";import ProjectVersionControlPanel from "../components/ProjectVersionControlPanel.vue";import ProjectWebhookPanel from "../components/ProjectWebhookPanel.vue";import ProjectSettingPanel from "../components/ProjectSettingPanel.vue";+import ProjectDeploymentConfigPanel from "../components/ProjectDeploymentConfigPanel.vue";import { cloneDeep } from "lodash-es";const OVERVIEW_TAB = 0;@@ -57,8 +65,9 @@ const ACTIVITY_TAB = 2;const VERSION_CONTROL_TAB = 3;const PROJECT_HOOK_TAB = 4;const SETTING_TAB = 5;+const DEPLOYMENT_CONFIG_TAB = 6;-export default {+export default defineComponent({name: "ProjectDetail",components: {ProjectActivityPanel,@@ -67,6 +76,7 @@ export default {ProjectVersionControlPanel,ProjectWebhookPanel,ProjectSettingPanel,+ ProjectDeploymentConfigPanel,},props: {projectSlug: {@@ -115,9 +125,10 @@ export default {VERSION_CONTROL_TAB,PROJECT_HOOK_TAB,SETTING_TAB,+ DEPLOYMENT_CONFIG_TAB,project,databaseList,};},-};+});</script>diff --git a/frontend/src/views/SettingWorkspaceLabel.vue b/frontend/src/views/SettingWorkspaceLabel.vueindex 54ef83d5d4..afabd02c49 100644--- a/frontend/src/views/SettingWorkspaceLabel.vue+++ b/frontend/src/views/SettingWorkspaceLabel.vue@@ -10,7 +10,7 @@><template #body="{ rowData: label }"><BBTableCell :left-padding="4" class="w-36 table-cell">- {{ label.key }}+ {{ hidePrefix(label.key) }}</BBTableCell><BBTableCell class="whitespace-nowrap"><div class="tags">@@ -40,7 +40,7 @@<script lang="ts">import { computed, defineComponent, watchEffect } from "vue";import { useStore } from "vuex";-import { isDBAOrOwner } from "../utils";+import { isDBAOrOwner, hidePrefix } from "../utils";import { Principal, Label, LabelPatch } from "../types";import { BBTableColumn } from "../bbkit/types";import { BBTable, BBTableCell } from "../bbkit";@@ -117,6 +117,7 @@ export default defineComponent({return {COLUMN_LIST,labelList,+ hidePrefix,allowEdit,allowRemove,addValue,