Skip to content

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

refactor(frontend): change history v1 API (#6374)

Liu Jieee26170ff40
diff --git a/frontend/src/components/BackupTable.vue b/frontend/src/components/BackupTable.vue
index ce46adf7c0..147221cc90 100644
--- a/frontend/src/components/BackupTable.vue
+++ b/frontend/src/components/BackupTable.vue
@@ -16,11 +16,10 @@
<BBTableHeaderCell class="w-16" :title="columnList[1].title" />
<BBTableHeaderCell class="w-48" :title="columnList[2].title" />
<BBTableHeaderCell class="w-16" :title="columnList[3].title" />
- <BBTableHeaderCell class="w-16" :title="columnList[4].title" />
<BBTableHeaderCell
v-if="allowEdit"
class="w-4"
- :title="columnList[5].title"
+ :title="columnList[4].title"
/>
</template>
<template #body="{ rowData: backup }">
@@ -63,17 +62,6 @@
: backup.comment
}}
</BBTableCell>
- <BBTableCell>
- <div class="flex flex-row space-x-2">
- <div
- class="normal-link"
- @click.prevent="gotoMigrationHistory(backup)"
- >
- {{ backup.migrationHistoryVersion }}
- </div>
- <BBSpin v-if="state.loadingMigrationHistory" />
- </div>
- </BBTableCell>
<BBTableCell class="tooltip-wrapper">
<span class="tooltip whitespace-nowrap">
{{ dayjs(backup.createdTs * 1000).format("YYYY-MM-DD HH:mm") }}
@@ -158,12 +146,11 @@ import {
Backup,
ComposedDatabase,
IssueCreate,
- MigrationHistory,
PITRContext,
SYSTEM_BOT_ID,
} from "../types";
-import { databaseV1Slug, issueSlug, migrationHistorySlug } from "../utils";
-import { featureToRef, useLegacyInstanceStore, useIssueStore } from "@/store";
+import { issueSlug } from "../utils";
+import { featureToRef, useIssueStore } from "@/store";
import CreateDatabasePrepForm from "../components/CreateDatabasePrepForm.vue";
import {
default as RestoreTargetForm,
@@ -224,9 +211,6 @@ const EDIT_COLUMN_LIST: BBTableColumn[] = [
{
title: t("common.comment"),
},
- {
- title: t("common.schema-version"),
- },
{
title: t("common.time"),
},
@@ -245,9 +229,6 @@ const NON_EDIT_COLUMN_LIST: BBTableColumn[] = [
{
title: t("common.comment"),
},
- {
- title: t("common.schema-version"),
- },
{
title: t("common.time"),
},
@@ -302,36 +283,6 @@ const statusIconClass = (backup: Backup) => {
}
};
-const gotoMigrationHistory = (backup: Backup) => {
- state.loadingMigrationHistory = true;
- useLegacyInstanceStore()
- .fetchMigrationHistoryByVersion({
- instanceId: Number(props.database.instanceEntity.uid),
- databaseName: props.database.databaseName,
- version: backup.migrationHistoryVersion,
- })
- .then((history: MigrationHistory) => {
- router
- .push({
- name: "workspace.database.history.detail",
- params: {
- databaseSlug: databaseV1Slug(props.database),
- migrationHistorySlug: migrationHistorySlug(
- history.id,
- history.version
- ),
- },
- hash: "#schema",
- })
- .then(() => {
- state.loadingMigrationHistory = false;
- });
- })
- .catch(() => {
- state.loadingMigrationHistory = false;
- });
-};
-
const columnList = computed(() => {
return props.allowEdit ? EDIT_COLUMN_LIST : NON_EDIT_COLUMN_LIST;
});
diff --git a/frontend/src/components/Breadcrumb.vue b/frontend/src/components/Breadcrumb.vue
index 73e141fee6..fd7c8e2fc3 100644
--- a/frontend/src/components/Breadcrumb.vue
+++ b/frontend/src/components/Breadcrumb.vue
@@ -67,7 +67,7 @@ import { useI18n } from "vue-i18n";
import { useTitle } from "@vueuse/core";
import { Bookmark, UNKNOWN_ID, BookmarkCreate, RouteMapList } from "../types";
-import { idFromSlug } from "../utils";
+import { databaseV1Slug, idFromSlug } from "../utils";
import {
useCurrentUser,
useRouterStore,
@@ -135,7 +135,6 @@ export default defineComponent({
const databaseSlug = routeSlug.databaseSlug;
const tableName = routeSlug.tableName;
const dataSourceSlug = routeSlug.dataSourceSlug;
- const migrationHistory = routeSlug.migrationHistorySlug;
const vcsSlug = routeSlug.vcsSlug;
const sqlReviewPolicySlug = routeSlug.sqlReviewPolicySlug;
const ssoName = routeSlug.ssoName;
@@ -176,7 +175,7 @@ export default defineComponent({
path: "/db",
});
- if (tableName || dataSourceSlug || migrationHistory) {
+ if (tableName || dataSourceSlug) {
const database = useDatabaseV1Store().getDatabaseByUID(
String(idFromSlug(databaseSlug))
);
@@ -184,12 +183,6 @@ export default defineComponent({
name: database.name,
path: `/db/${databaseSlug}`,
});
- if (migrationHistory) {
- list.push({
- name: t("common.change"),
- path: `/db/${databaseSlug}#change-history`,
- });
- }
}
} else if (vcsSlug) {
list.push({
@@ -224,6 +217,18 @@ export default defineComponent({
);
}
}
+ if (route.name === "workspace.database.history.detail") {
+ const parent = `instances/${route.params.instance}/databases/${route.params.database}`;
+ const database = useDatabaseV1Store().getDatabaseByName(parent);
+ list.push({
+ name: database.databaseName,
+ path: `/db/${databaseV1Slug(database)}`,
+ });
+ list.push({
+ name: t("common.change"),
+ path: `/db/${databaseV1Slug(database)}#change-history`,
+ });
+ }
const {
title: routeTitle,
diff --git a/frontend/src/components/ChangeHistory/ChangeHistoryStatusIcon.vue b/frontend/src/components/ChangeHistory/ChangeHistoryStatusIcon.vue
new file mode 100644
index 0000000000..2930b12e4d
--- /dev/null
+++ b/frontend/src/components/ChangeHistory/ChangeHistoryStatusIcon.vue
@@ -0,0 +1,49 @@
+<template>
+ <span
+ class="flex items-center justify-center rounded-full select-none"
+ :class="iconClass()"
+ >
+ <template v-if="status === ChangeHistory_Status.PENDING">
+ <span
+ class="h-2 w-2 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 === ChangeHistory_Status.DONE">
+ <heroicons-solid:check class="w-4 h-4" />
+ </template>
+ <template v-else-if="status === ChangeHistory_Status.FAILED">
+ <span
+ class="h-2 w-2 rounded-full text-center pb-6 font-normal text-base"
+ aria-hidden="true"
+ >!</span
+ >
+ </template>
+ </span>
+</template>
+
+<script lang="ts" setup>
+import { PropType } from "vue";
+
+import { ChangeHistory_Status } from "@/types/proto/v1/database_service";
+
+const props = defineProps({
+ status: {
+ required: true,
+ type: Number as PropType<ChangeHistory_Status>,
+ },
+});
+
+const iconClass = () => {
+ const iconClass = "w-5 h-5";
+ switch (props.status) {
+ case ChangeHistory_Status.PENDING:
+ return iconClass + " bg-white border-2 border-info text-info";
+ case ChangeHistory_Status.DONE:
+ return iconClass + " bg-success text-white";
+ case ChangeHistory_Status.FAILED:
+ return iconClass + " bg-error text-white";
+ }
+};
+</script>
diff --git a/frontend/src/components/ChangeHistory/ChangeHistoryTable.vue b/frontend/src/components/ChangeHistory/ChangeHistoryTable.vue
new file mode 100644
index 0000000000..981f72faed
--- /dev/null
+++ b/frontend/src/components/ChangeHistory/ChangeHistoryTable.vue
@@ -0,0 +1,197 @@
+<template>
+ <BBTable
+ :column-list="columnList"
+ :section-data-source="historySectionList"
+ :compact-section="mode == 'DATABASE'"
+ :show-header="true"
+ :left-bordered="true"
+ :right-bordered="true"
+ data-label="bb-change-history-table"
+ @click-row="clickHistory"
+ >
+ <template #header>
+ <template v-if="mode == 'DATABASE'">
+ <BBTableHeaderCell
+ :left-padding="4"
+ class="w-2"
+ :title="columnList[0].title"
+ />
+ <BBTableHeaderCell class="w-8" :title="columnList[1].title" />
+ <BBTableHeaderCell class="w-16" :title="columnList[2].title" />
+ <BBTableHeaderCell class="w-16" :title="columnList[3].title" />
+ <BBTableHeaderCell class="w-48" :title="columnList[4].title" />
+ <BBTableHeaderCell class="w-16" :title="columnList[5].title" />
+ <BBTableHeaderCell class="w-16" :title="columnList[6].title" />
+ <BBTableHeaderCell class="w-16" :title="columnList[7].title" />
+ </template>
+ <template v-else>
+ <BBTableHeaderCell
+ :left-padding="4"
+ class="w-2"
+ :title="columnList[0].title"
+ />
+ <BBTableHeaderCell class="w-16" :title="columnList[1].title" />
+ <BBTableHeaderCell class="w-16" :title="columnList[2].title" />
+ <BBTableHeaderCell class="w-48" :title="columnList[3].title" />
+ <BBTableHeaderCell class="w-16" :title="columnList[4].title" />
+ <BBTableHeaderCell class="w-16" :title="columnList[5].title" />
+ <BBTableHeaderCell class="w-16" :title="columnList[6].title" />
+ </template>
+ </template>
+ <template #body="{ rowData: history }: { rowData: ChangeHistory }">
+ <BBTableCell :left-padding="4">
+ <ChangeHistoryStatusIcon :status="history.status" />
+ </BBTableCell>
+ <BBTableCell v-if="mode == 'DATABASE'">
+ {{ changeHistory_SourceToJSON(history.source) }}
+ </BBTableCell>
+ <BBTableCell>
+ {{ history.version }}
+ <span
+ v-if="
+ history.type === ChangeHistory_Type.BASELINE ||
+ history.type === ChangeHistory_Type.BRANCH
+ "
+ class="textinfolabel"
+ >({{ history.type }})</span
+ >
+ </BBTableCell>
+ <BBTableCell>
+ <template v-if="extractReviewId(history.review)">
+ <!--Short circuit the click event to prevent propagating to row click-->
+ <router-link
+ :to="`/issue/${extractReviewId(history.review)}`"
+ class="normal-link"
+ @click.stop=""
+ >{{ extractReviewId(history.review) }}
+ </router-link>
+ </template>
+ </BBTableCell>
+ <BBTableCell>
+ <SQLPreviewPopover
+ :statement="history.statement"
+ :max-length="100"
+ placement="bottom"
+ />
+ </BBTableCell>
+ <BBTableCell>
+ {{ humanizeDurationV1(history.executionDuration) }}
+ </BBTableCell>
+ <BBTableCell>
+ {{ humanizeDate(history.createTime) }}
+ </BBTableCell>
+ <BBTableCell>
+ {{ creatorOfChangeHistory(history)?.title }}
+ </BBTableCell>
+ </template>
+ </BBTable>
+</template>
+
+<script lang="ts" setup>
+import { computed, PropType } from "vue";
+import { useRouter } from "vue-router";
+import { useI18n } from "vue-i18n";
+
+import { ComposedDatabase } from "@/types";
+import { BBTableSectionDataSource } from "@/bbkit/types";
+import {
+ extractReviewId,
+ humanizeDate,
+ extractUserResourceName,
+ changeHistoryLink,
+} from "@/utils";
+import SQLPreviewPopover from "@/components/misc/SQLPreviewPopover.vue";
+import ChangeHistoryStatusIcon from "./ChangeHistoryStatusIcon.vue";
+import {
+ ChangeHistory,
+ changeHistory_SourceToJSON,
+ ChangeHistory_Type,
+} from "@/types/proto/v1/database_service";
+import { useUserStore } from "@/store";
+
+type Mode = "DATABASE" | "PROJECT";
+
+const props = defineProps({
+ mode: {
+ default: "DATABASE",
+ type: String as PropType<Mode>,
+ },
+ databaseSectionList: {
+ required: true,
+ type: Array as PropType<ComposedDatabase[]>,
+ },
+ historySectionList: {
+ required: true,
+ type: Array as PropType<BBTableSectionDataSource<ChangeHistory>[]>,
+ },
+});
+
+const router = useRouter();
+
+const { t } = useI18n();
+
+const columnList = computed(() => {
+ if (props.mode === "DATABASE") {
+ return [
+ {
+ title: "",
+ },
+ {
+ title: t("change-history.workflow"),
+ },
+ {
+ title: t("common.version"),
+ },
+ {
+ title: t("common.issue"),
+ },
+ {
+ title: "SQL",
+ },
+ {
+ title: t("common.duration"),
+ },
+ {
+ title: t("common.created-at"),
+ },
+ {
+ title: t("common.creator"),
+ },
+ ];
+ } else if (props.mode === "PROJECT") {
+ return [
+ { title: "" },
+ {
+ title: t("common.version"),
+ },
+ {
+ title: t("common.issue"),
+ },
+ {
+ title: "SQL",
+ },
+ {
+ title: t("common.duration"),
+ },
+ {
+ title: t("common.created-at"),
+ },
+ {
+ title: t("common.creator"),
+ },
+ ];
+ } else {
+ return [];
+ }
+});
+
+const clickHistory = (section: number, row: number) => {
+ const history = props.historySectionList[section].list[row];
+ router.push(changeHistoryLink(history));
+};
+
+const creatorOfChangeHistory = (history: ChangeHistory) => {
+ const email = extractUserResourceName(history.creator);
+ return useUserStore().getUserByEmail(email);
+};
+</script>
diff --git a/frontend/src/components/ChangeHistory/index.ts b/frontend/src/components/ChangeHistory/index.ts
new file mode 100644
index 0000000000..3bdcb6c036
--- /dev/null
+++ b/frontend/src/components/ChangeHistory/index.ts
@@ -0,0 +1,4 @@
+import ChangeHistoryTable from "./ChangeHistoryTable.vue";
+import ChangeHistoryStatusIcon from "./ChangeHistoryStatusIcon.vue";
+
+export { ChangeHistoryTable, ChangeHistoryStatusIcon };
diff --git a/frontend/src/components/DatabaseMigrationHistoryPanel.vue b/frontend/src/components/DatabaseChangeHistoryPanel.vue
similarity index 60%
rename from frontend/src/components/DatabaseMigrationHistoryPanel.vue
rename to frontend/src/components/DatabaseChangeHistoryPanel.vue
index f864a66b21..f5ee3b80f7 100644
--- a/frontend/src/components/DatabaseMigrationHistoryPanel.vue
+++ b/frontend/src/components/DatabaseChangeHistoryPanel.vue
@@ -32,19 +32,9 @@
/>
</div>
</div>
- <MigrationHistoryTable
- v-if="state.migrationSetupStatus == 'OK'"
+ <ChangeHistoryTable
:database-section-list="[database]"
- :history-section-list="migrationHistorySectionList"
- />
- <BBAttention
- v-else
- :style="`WARN`"
- :title="attentionTitle"
- :action-text="
- allowConfigInstance ? $t('change-history.config-instance') : ''
- "
- @click-action="configInstance"
+ :history-section-list="changeHistorySectionList"
/>
</div>
@@ -71,24 +61,15 @@ import { computed, onBeforeMount, PropType, reactive } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
-import MigrationHistoryTable from "@/components/MigrationHistoryTable.vue";
-import {
- ComposedDatabase,
- DEFAULT_PROJECT_V1_NAME,
- MigrationHistory,
- MigrationSchemaStatus,
-} from "@/types";
+import { ComposedDatabase, DEFAULT_PROJECT_V1_NAME } from "@/types";
import { BBTableSectionDataSource } from "@/bbkit/types";
-import {
- hasWorkspacePermissionV1,
- instanceV1HasAlterSchema,
- instanceV1Slug,
-} from "@/utils";
-import { useCurrentUserV1, useLegacyInstanceStore } from "@/store";
+import { instanceV1HasAlterSchema } from "@/utils";
+import { useChangeHistoryStore } from "@/store";
import { TenantMode } from "@/types/proto/v1/project_service";
+import { ChangeHistory } from "@/types/proto/v1/database_service";
+import { ChangeHistoryTable } from "@/components/ChangeHistory";
interface LocalState {
- migrationSetupStatus: MigrationSchemaStatus;
showBaselineModal: boolean;
loading: boolean;
}
@@ -106,40 +87,27 @@ const props = defineProps({
const { t } = useI18n();
-const instanceStore = useLegacyInstanceStore();
+const changeHistoryStore = useChangeHistoryStore();
const router = useRouter();
const state = reactive<LocalState>({
- migrationSetupStatus: "OK",
showBaselineModal: false,
loading: false,
});
-const currentUserV1 = useCurrentUserV1();
-
-const prepareMigrationHistoryList = () => {
+const prepareChangeHistoryList = () => {
state.loading = true;
- instanceStore
- .fetchMigrationHistory({
- instanceId: Number(props.database.instanceEntity.uid),
- databaseName: props.database.databaseName,
- })
- .then(() => {
- state.loading = false;
+ changeHistoryStore
+ .fetchChangeHistoryList({
+ parent: props.database.name,
})
- .catch(() => {
+ .finally(() => {
state.loading = false;
});
};
-onBeforeMount(prepareMigrationHistoryList);
+onBeforeMount(prepareChangeHistoryList);
-const allowConfigInstance = computed(() => {
- return hasWorkspacePermissionV1(
- "bb.permission.workspace.manage-instance",
- currentUserV1.value.userRole
- );
-});
const isTenantProject = computed(() => {
return (
props.database.projectEntity.tenantMode === TenantMode.TENANT_MODE_ENABLED
@@ -158,8 +126,6 @@ const showEstablishBaselineButton = computed(() => {
const allowMigrate = computed(() => {
if (!props.allowEdit) return false;
- if (state.migrationSetupStatus !== "OK") return false;
-
if (props.database.projectEntity.name === DEFAULT_PROJECT_V1_NAME) {
return false;
}
@@ -169,47 +135,21 @@ const allowMigrate = computed(() => {
return !isTenantProject.value;
});
-const attentionTitle = computed((): string => {
- if (state.migrationSetupStatus == "NOT_EXIST") {
- return (
- t("change-history.instance-missing-change-schema", {
- name: props.database.instance,
- }) +
- (allowConfigInstance.value ? "" : " " + t("change-history.contact-dba"))
- );
- } else if (state.migrationSetupStatus == "UNKNOWN") {
- return (
- t("change-history.instance-bad-connection", {
- name: props.database.instance,
- }) +
- (allowConfigInstance.value ? "" : " " + t("change-history.contact-dba"))
- );
- }
- return "";
-});
-
-const migrationHistoryList = computed(() => {
- return instanceStore.getMigrationHistoryListByInstanceIdAndDatabaseName(
- Number(props.database.instanceEntity.uid),
- props.database.databaseName
- );
+const changeHistoryList = computed(() => {
+ return changeHistoryStore.changeHistoryListByDatabase(props.database.name);
});
-const migrationHistorySectionList = computed(
- (): BBTableSectionDataSource<MigrationHistory>[] => {
+const changeHistorySectionList = computed(
+ (): BBTableSectionDataSource<ChangeHistory>[] => {
return [
{
title: "",
- list: migrationHistoryList.value,
+ list: changeHistoryList.value,
},
];
}
);
-const configInstance = () => {
- router.push(`/instance/${instanceV1Slug(props.database.instanceEntity)}`);
-};
-
const doCreateBaseline = () => {
state.showBaselineModal = false;
diff --git a/frontend/src/components/DatabaseDetail/MigrationHistoryBrief.vue b/frontend/src/components/DatabaseDetail/ChangeHistoryBrief.vue
similarity index 60%
rename from frontend/src/components/DatabaseDetail/MigrationHistoryBrief.vue
rename to frontend/src/components/DatabaseDetail/ChangeHistoryBrief.vue
index 0b4af96e2c..28271fee69 100644
--- a/frontend/src/components/DatabaseDetail/MigrationHistoryBrief.vue
+++ b/frontend/src/components/DatabaseDetail/ChangeHistoryBrief.vue
@@ -6,26 +6,26 @@
</label>
<div class="flex-1">
<a
- :href="migrationHistoryLink"
+ :href="link"
target="__BLANK"
class="normal-link flex items-center gap-x-1"
>
- {{ migrationHistory.version }}
+ {{ changeHistory.version }}
</a>
</div>
</div>
- <div v-if="migrationHistory.issueId" class="flex items-center gap-x-4">
+ <div v-if="changeHistory" class="flex items-center gap-x-4">
<label class="w-1/4 flex justify-end textlabel">
{{ $t("common.issue") }}
</label>
<div class="flex-1">
<a
- :href="`/issue/${migrationHistory.issueId}`"
+ :href="`/issue/${extractReviewId(changeHistory.review)}`"
target="__BLANK"
class="normal-link flex items-center gap-x-1"
>
- {{ migrationHistory.issueId }}
+ {{ extractReviewId(changeHistory.review) }}
</a>
</div>
</div>
@@ -36,7 +36,7 @@
</label>
<div class="flex-1">
<NPopover
- :disabled="migrationHistory.statement.length < MAX_SQL_LENGTH"
+ :disabled="changeHistory.statement.length < MAX_SQL_LENGTH"
style="max-height: 300px"
placement="bottom"
overlap
@@ -44,7 +44,7 @@
scrollable
>
<highlight-code-block
- :code="migrationHistory.statement"
+ :code="changeHistory.statement"
class="whitespace-pre-wrap"
/>
@@ -71,7 +71,9 @@
<label class="w-1/4 flex justify-end textlabel">
{{ $t("common.creator") }}
</label>
- <div class="flex-1">{{ migrationHistory.creator }}</div>
+ <div v-if="creator" class="flex-1">
+ {{ creator.title }} ({{ creator.email }})
+ </div>
</div>
</div>
</template>
@@ -79,41 +81,47 @@
<script lang="ts" setup>
import { computed, PropType } from "vue";
import dayjs from "dayjs";
-import { Database, MigrationHistory } from "@/types";
-import { databaseSlug, migrationHistorySlug } from "@/utils";
+import {
+ extractUserResourceName,
+ extractReviewId,
+ changeHistoryLink as makeChangeHistoryLink,
+} from "@/utils";
+import { ComposedDatabase } from "@/types";
+import { ChangeHistory } from "@/types/proto/v1/database_service";
+import { useUserStore } from "@/store";
const props = defineProps({
database: {
- type: Object as PropType<Database>,
+ type: Object as PropType<ComposedDatabase>,
required: true,
},
- migrationHistory: {
- type: Object as PropType<MigrationHistory>,
+ changeHistory: {
+ type: Object as PropType<ChangeHistory>,
required: true,
},
});
const MAX_SQL_LENGTH = 100;
-const migrationHistoryLink = computed(() => {
- const { database, migrationHistory } = props;
- return `/db/${databaseSlug(database)}/history/${migrationHistorySlug(
- migrationHistory.id,
- migrationHistory.version
- )}`;
+const link = computed(() => {
+ return makeChangeHistoryLink(props.changeHistory);
});
const createdAt = computed(() => {
- return dayjs(props.migrationHistory.createdTs * 1000).format(
- "YYYY-MM-DD HH:mm:ss"
- );
+ const date = props.changeHistory.createTime ?? new Date(0);
+ return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
});
const timezone = computed(() => "UTC" + dayjs().format("ZZ"));
const displayStatement = computed((): string => {
- const { migrationHistory } = props;
- return migrationHistory.statement.length > MAX_SQL_LENGTH
- ? migrationHistory.statement.substring(0, MAX_SQL_LENGTH) + "..."
- : migrationHistory.statement;
+ const { changeHistory } = props;
+ return changeHistory.statement.length > MAX_SQL_LENGTH
+ ? changeHistory.statement.substring(0, MAX_SQL_LENGTH) + "..."
+ : changeHistory.statement;
+});
+
+const creator = computed(() => {
+ const email = extractUserResourceName(props.changeHistory.creator);
+ return useUserStore().getUserByEmail(email);
});
</script>
diff --git a/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue b/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue
index 38882a449c..d722afa2c4 100644
--- a/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue
+++ b/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue
@@ -61,11 +61,11 @@
</div>
<template
- v-if="state.step === 'LAST_MIGRATION_INFO' && lastMigrationHistory"
+ v-if="state.step === 'LAST_MIGRATION_INFO' && lastChangeHistory"
>
- <MigrationHistoryBrief
+ <ChangeHistoryBrief
:database="database"
- :migration-history="lastMigrationHistory"
+ :change-history="lastChangeHistory"
/>
</template>
@@ -148,7 +148,7 @@
v-if="state.step === 'LAST_MIGRATION_INFO'"
type="button"
class="btn-primary py-2 px-4"
- @click.prevent="initLastMigrationParams"
+ @click.prevent="initLastChangeParams"
>
{{ $t("common.next") }}
</button>
@@ -195,6 +195,7 @@ import { CreatePITRDatabaseContext } from "./utils";
import BBContextMenuButton, {
type ButtonAction,
} from "@/bbkit/BBContextMenuButton.vue";
+import ChangeHistoryBrief from "./ChangeHistoryBrief.vue";
type PITRTarget = "IN-PLACE" | "NEW";
@@ -244,7 +245,7 @@ const hasPITRFeature = featureToRef("bb.feature.pitr");
const timezone = computed(() => "UTC" + dayjs().format("ZZ"));
-const { pitrAvailable, doneBackupList, lastMigrationHistory, createPITRIssue } =
+const { pitrAvailable, doneBackupList, lastChangeHistory, createPITRIssue } =
usePITRLogic(toRef(props, "database"));
const pitrButtonDisabled = computed((): boolean => {
@@ -337,9 +338,12 @@ const openDialog = (step: Step = "PITR_FORM", mode: Mode = "CUSTOM") => {
state.mode = mode;
};
-const initLastMigrationParams = () => {
- if (lastMigrationHistory.value) {
- state.pitrTimestampMS = (lastMigrationHistory.value.createdTs - 1) * 1000;
+const initLastChangeParams = () => {
+ if (lastChangeHistory.value) {
+ const timestampMS = (
+ lastChangeHistory.value.createTime ?? new Date(0)
+ ).getTime();
+ state.pitrTimestampMS = timestampMS - 1000;
}
state.step = "PITR_FORM";
@@ -392,7 +396,7 @@ const onConfirm = async () => {
issueNameParts.push(`to [${datetime} ${timezone.value}]`);
} else {
issueNameParts.push(
- `before migration version [${lastMigrationHistory.value!.version}]`
+ `before migration version [${lastChangeHistory.value!.version}]`
);
}
const issue = await createPITRIssue(
diff --git a/frontend/src/components/DatabaseSelect.vue b/frontend/src/components/DatabaseSelect.vue
index cd5bb68a71..065574ffc8 100644
--- a/frontend/src/components/DatabaseSelect.vue
+++ b/frontend/src/components/DatabaseSelect.vue
@@ -113,7 +113,6 @@ export default defineComponent({
) {
// TODO: we do not support filtering database list by environment in v1
// API so we need to fetch them all
- // databaseStore.fetchDatabaseListByEnvironmentId(props.environmentId);
databaseStore.fetchDatabaseList({
parent: "instances/-",
});
diff --git a/frontend/src/components/InstanceForm/InstanceForm.vue b/frontend/src/components/InstanceForm/InstanceForm.vue
index b8a4dc5f47..8393b16174 100644
--- a/frontend/src/components/InstanceForm/InstanceForm.vue
+++ b/frontend/src/components/InstanceForm/InstanceForm.vue
@@ -636,7 +636,6 @@ import {
useSettingV1Store,
useActuatorV1Store,
useEnvironmentV1Store,
- useLegacyInstanceStore,
useInstanceV1Store,
useGracefulRequest,
featureToRef,
@@ -1209,9 +1208,6 @@ const updateEditState = async (instance: Instance) => {
// Backend will sync the schema when connection info changed, so we need to fetch the synced schema here.
instanceV1Store.fetchInstanceRoleListByName(instance.name);
-
- // Legacy API compatibility
- useLegacyInstanceStore().fetchInstanceById(Number(instance.uid));
};
const handleWarningModalOkClick = async () => {
diff --git a/frontend/src/components/Issue/IssueSidebar.vue b/frontend/src/components/Issue/IssueSidebar.vue
index a8239dc1f9..12ea373b9d 100644
--- a/frontend/src/components/Issue/IssueSidebar.vue
+++ b/frontend/src/components/Issue/IssueSidebar.vue
@@ -566,15 +566,14 @@ watchEffect(() => {
} else {
const name = databaseName.value;
if (name) {
- useDatabaseV1Store()
- .getOrFetchDatabaseByName(`${props.instance.name}/databases/${name!}`)
- .then((db) => {
- if (db && db.uid !== String(UNKNOWN_ID)) {
- databaseEntity.value = db;
- } else {
- databaseEntity.value = undefined;
- }
- });
+ const existed = useDatabaseV1Store().getDatabaseByName(
+ `${props.instance.name}/databases/${name}`
+ );
+ if (existed && existed.uid !== String(UNKNOWN_ID)) {
+ databaseEntity.value = existed;
+ } else {
+ databaseEntity.value = undefined;
+ }
} else {
databaseEntity.value = undefined;
}
diff --git a/frontend/src/components/Issue/IssueTaskSDLPanel.vue b/frontend/src/components/Issue/IssueTaskSDLPanel.vue
index 0a01cc9d0a..20caf1ef0d 100644
--- a/frontend/src/components/Issue/IssueTaskSDLPanel.vue
+++ b/frontend/src/components/Issue/IssueTaskSDLPanel.vue
@@ -94,16 +94,16 @@ import LearnMoreLink from "@/components/LearnMoreLink.vue";
import {
hasFeature,
pushNotification,
- useLegacyDatabaseStore,
- useLegacyInstanceStore,
+ useChangeHistoryStore,
+ useDatabaseV1Store,
} from "@/store";
import { useIssueLogic } from "./logic";
import { Task, TaskDatabaseSchemaUpdateSDLPayload, TaskId } from "@/types";
import MonacoEditor from "../MonacoEditor";
import { sqlServiceClient } from "@/grpcweb";
-import { convertEngineType } from "@/types";
import { useSQLAdviceMarkers } from "./logic/useSQLAdviceMarkers";
import { useSilentRequest } from "@/plugins/silent-request";
+import { engineToJSON } from "@/types/proto/v1/common";
type TabView = "diff" | "statement" | "schema";
@@ -126,6 +126,7 @@ interface LocalState {
tab: TabView;
}
+const databaseStore = useDatabaseV1Store();
const { selectedTask } = useIssueLogic();
const state = reactive<LocalState>({
@@ -145,7 +146,7 @@ const useSDLState = () => {
const map = reactive(new Map<TaskId, SDLState>());
- const findLatestMigrationId = (task: Task) => {
+ const findLatestChangeHistoryId = (task: Task) => {
if (task.status !== "DONE") return undefined;
const list = task.taskRunList;
for (let i = list.length - 1; i >= 0; i--) {
@@ -157,27 +158,31 @@ const useSDLState = () => {
return undefined;
};
- const migrationId = computed(() => {
+ const changeHistoryId = computed(() => {
const task = selectedTask.value as Task;
- return findLatestMigrationId(task);
+ return findLatestChangeHistoryId(task);
});
const fetchOngoingSDLDetail = async (
task: Task
): Promise<SDLDetail | undefined> => {
- const database = task.database;
- if (!database) return undefined;
- const previousSDL = await useLegacyDatabaseStore().fetchDatabaseSchemaById(
- task.database!.id,
- true // fetch SDL format
+ if (!task.database) return undefined;
+ const database = await databaseStore.getOrFetchDatabaseByUID(
+ String(task.database.id)
);
+ const previousSDL = (
+ await databaseStore.fetchDatabaseSchema(
+ `${database.name}/schema`,
+ true // fetch SDL format
+ )
+ ).schema;
const payload = task.payload as TaskDatabaseSchemaUpdateSDLPayload;
if (!payload) return undefined;
const expectedSDL = payload.statement;
const getSchemaDiff = async () => {
const { data } = await axios.post("/v1/sql/schema/diff", {
- engineType: database.instance.engine,
+ engineType: engineToJSON(database.instanceEntity.engine),
sourceSchema: previousSDL ?? "",
targetSchema: expectedSDL ?? "",
});
@@ -186,7 +191,7 @@ const useSDLState = () => {
const diffDDL = await useSilentRequest(getSchemaDiff);
const { currentSchema, expectedSchema } = await sqlServiceClient.pretty({
- engine: convertEngineType(database.instance.engine),
+ engine: database.instanceEntity.engine,
currentSchema: previousSDL ?? "",
expectedSchema: expectedSDL ?? "",
});
@@ -204,30 +209,32 @@ const useSDLState = () => {
};
};
- const fetchSDLDetailFromMigrationHistory = async (
+ const fetchSDLDetailFromChangeHistory = async (
task: Task,
- migrationId: string | undefined
+ changeHistoryId: string | undefined
): Promise<SDLDetail | undefined> => {
- if (!migrationId) {
+ if (!changeHistoryId) {
return undefined;
}
- const history = await useSilentRequest(() =>
- useLegacyInstanceStore().fetchMigrationHistoryById({
- instanceId: task.instance.id,
- migrationHistoryId: migrationId,
- sdl: true,
- })
+ if (!task.database) return undefined;
+ const database = await databaseStore.getOrFetchDatabaseByUID(
+ String(task.database.id)
);
- // The latestMigrationId might change during fetching the
- // migrationHistory.
+ const history = await useChangeHistoryStore().fetchChangeHistory({
+ name: `${database.name}/changeHistories/${changeHistoryId}`,
+ sdlFormat: true,
+ });
+ console.log(history);
+ // The latestChangeHistoryId might change during fetching the
+ // ChangeHistory.
// Should give up the result.
- const latestMigrationId = findLatestMigrationId(task);
- if (history.id !== latestMigrationId) {
+ const latestChangeHistoryId = findLatestChangeHistoryId(task);
+ if (history.uid !== latestChangeHistoryId) {
throw new Error();
}
return {
error: "",
- previousSDL: history.schemaPrev,
+ previousSDL: history.prevSchema,
prettyExpectedSDL: history.schema,
expectedSDL: history.schema,
diffDDL: history.statement,
@@ -238,9 +245,9 @@ const useSDLState = () => {
[
() => (selectedTask.value as Task).id,
() => (selectedTask.value as Task).status,
- migrationId,
+ changeHistoryId,
],
- async ([taskId, taskStatus, migrationId]) => {
+ async ([taskId, taskStatus, changeHistoryId]) => {
const task = selectedTask.value as Task;
if (!map.has(taskId)) {
map.set(taskId, emptyState(task));
@@ -252,9 +259,9 @@ const useSDLState = () => {
};
try {
if (taskStatus === "DONE") {
- const detail = await fetchSDLDetailFromMigrationHistory(
+ const detail = await fetchSDLDetailFromChangeHistory(
task,
- migrationId
+ changeHistoryId
);
finish(detail);
} else {
diff --git a/frontend/src/components/Issue/TaskRunTable.vue b/frontend/src/components/Issue/TaskRunTable.vue
index 28695f306d..b723929a6b 100644
--- a/frontend/src/components/Issue/TaskRunTable.vue
+++ b/frontend/src/components/Issue/TaskRunTable.vue
@@ -65,11 +65,13 @@
<script lang="ts" setup>
import { computed, PropType } from "vue";
-import { BBTableColumn } from "../../bbkit/types";
-import { MigrationErrorCode, Task, TaskRun, TaskRunStatus } from "../../types";
-import { databaseSlug, instanceSlug, migrationHistorySlug } from "../../utils";
import { useI18n } from "vue-i18n";
+import { BBTableColumn } from "@/bbkit/types";
+import { MigrationErrorCode, Task, TaskRun, TaskRunStatus } from "@/types";
+import { changeHistorySlug, databaseSlug, instanceSlug } from "@/utils";
+import { useDatabaseV1Store } from "@/store";
+
type CommentLink = {
title: string;
link: string;
@@ -146,14 +148,16 @@ const commentLink = (task: Task, taskRun: TaskRun): CommentLink => {
case "bb.task.database.schema.update":
case "bb.task.database.schema.update-sdl":
case "bb.task.database.data.update": {
+ const db = useDatabaseV1Store().getDatabaseByUID(
+ String(task.database!.id)
+ );
+ const link = `/${db.name}/changeHistories/${changeHistorySlug(
+ taskRun.result.migrationId!,
+ taskRun.result.version!
+ )}`;
return {
title: t("task.view-change"),
- link: `/db/${databaseSlug(
- task.database!
- )}/history/${migrationHistorySlug(
- taskRun.result.migrationId!,
- taskRun.result.version!
- )}`,
+ link,
};
}
// TODO(jim): format for gh-ost related tasks
diff --git a/frontend/src/components/MigrationHistoryStatusIcon.vue b/frontend/src/components/MigrationHistoryStatusIcon.vue
deleted file mode 100644
index 7a48d61898..0000000000
--- a/frontend/src/components/MigrationHistoryStatusIcon.vue
+++ /dev/null
@@ -1,56 +0,0 @@
-<template>
- <span
- class="flex items-center justify-center rounded-full select-none"
- :class="iconClass()"
- >
- <template v-if="status === `PENDING`">
- <span
- class="h-2 w-2 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-4 h-4" />
- </template>
- <template v-else-if="status === `FAILED`">
- <span
- class="h-2 w-2 rounded-full text-center pb-6 font-normal text-base"
- aria-hidden="true"
- >!</span
- >
- </template>
- </span>
-</template>
-
-<script lang="ts">
-import { defineComponent, PropType } from "vue";
-import { MigrationStatus } from "../types";
-
-export default defineComponent({
- name: "MigrationHistoryStatusIcon",
- props: {
- status: {
- required: true,
- type: String as PropType<MigrationStatus>,
- },
- },
- setup(props) {
- const iconClass = () => {
- const iconClass = "w-5 h-5";
- switch (props.status) {
- case "PENDING":
- return iconClass + " bg-white border-2 border-info text-info";
- case "DONE":
- return iconClass + " bg-success text-white";
- case "FAILED":
- return iconClass + " bg-error text-white";
- }
- };
-
- return {
- iconClass,
- };
- },
-});
-</script>
diff --git a/frontend/src/components/MigrationHistoryTable.vue b/frontend/src/components/MigrationHistoryTable.vue
deleted file mode 100644
index 087dd78c8c..0000000000
--- a/frontend/src/components/MigrationHistoryTable.vue
+++ /dev/null
@@ -1,199 +0,0 @@
-<template>
- <BBTable
- :column-list="columnList"
- :section-data-source="historySectionList"
- :compact-section="mode == 'DATABASE'"
- :show-header="true"
- :left-bordered="true"
- :right-bordered="true"
- data-label="bb-change-history-table"
- @click-row="clickHistory"
- >
- <template #header>
- <template v-if="mode == 'DATABASE'">
- <BBTableHeaderCell
- :left-padding="4"
- class="w-2"
- :title="columnList[0].title"
- />
- <BBTableHeaderCell class="w-8" :title="columnList[1].title" />
- <BBTableHeaderCell class="w-16" :title="columnList[2].title" />
- <BBTableHeaderCell class="w-16" :title="columnList[3].title" />
- <BBTableHeaderCell class="w-48" :title="columnList[4].title" />
- <BBTableHeaderCell class="w-16" :title="columnList[5].title" />
- <BBTableHeaderCell class="w-16" :title="columnList[6].title" />
- <BBTableHeaderCell class="w-16" :title="columnList[7].title" />
- </template>
- <template v-else>
- <BBTableHeaderCell
- :left-padding="4"
- class="w-2"
- :title="columnList[0].title"
- />
- <BBTableHeaderCell class="w-16" :title="columnList[1].title" />
- <BBTableHeaderCell class="w-16" :title="columnList[2].title" />
- <BBTableHeaderCell class="w-48" :title="columnList[3].title" />
- <BBTableHeaderCell class="w-16" :title="columnList[4].title" />
- <BBTableHeaderCell class="w-16" :title="columnList[5].title" />
- <BBTableHeaderCell class="w-16" :title="columnList[6].title" />
- </template>
- </template>
- <template #body="{ rowData: history }">
- <BBTableCell :left-padding="4">
- <MigrationHistoryStatusIcon :status="history.status" />
- </BBTableCell>
- <BBTableCell v-if="mode == 'DATABASE'">
- {{ history.source }}
- </BBTableCell>
- <BBTableCell>
- {{ history.version }}
- <span
- v-if="history.type == 'BASELINE' || history.type == 'BRANCH'"
- class="textinfolabel"
- >({{ history.type }})</span
- >
- </BBTableCell>
- <BBTableCell>
- <template v-if="history.issueId">
- <!--Short circuit the click event to prevent propagating to row click-->
- <router-link
- :to="`/issue/${history.issueId}`"
- class="normal-link"
- @click.stop=""
- >{{ history.issueId }}
- </router-link>
- </template>
- </BBTableCell>
- <BBTableCell>
- <SQLPreviewPopover
- :statement="history.statement"
- :max-length="100"
- placement="bottom"
- />
- </BBTableCell>
- <BBTableCell>
- {{ nanosecondsToString(history.executionDurationNs) }}
- </BBTableCell>
- <BBTableCell>
- {{ humanizeTs(history.createdTs) }}
- </BBTableCell>
- <BBTableCell>
- {{ history.creator }}
- </BBTableCell>
- </template>
- </BBTable>
-</template>
-
-<script lang="ts">
-import { computed, defineComponent, PropType } from "vue";
-import { useRouter } from "vue-router";
-import { useI18n } from "vue-i18n";
-import { ComposedDatabase, MigrationHistory } from "@/types";
-import { BBTableSectionDataSource } from "@/bbkit/types";
-import {
- databaseV1Slug,
- migrationHistorySlug,
- nanosecondsToString,
-} from "@/utils";
-import MigrationHistoryStatusIcon from "./MigrationHistoryStatusIcon.vue";
-import SQLPreviewPopover from "./misc/SQLPreviewPopover.vue";
-
-type Mode = "DATABASE" | "PROJECT";
-
-export default defineComponent({
- name: "MigrationHistoryTable",
- components: {
- SQLPreviewPopover,
- MigrationHistoryStatusIcon,
- },
- props: {
- mode: {
- default: "DATABASE",
- type: String as PropType<Mode>,
- },
- databaseSectionList: {
- required: true,
- type: Array as PropType<ComposedDatabase[]>,
- },
- historySectionList: {
- required: true,
- type: Array as PropType<BBTableSectionDataSource<MigrationHistory>[]>,
- },
- },
- setup(props) {
- const router = useRouter();
-
- const { t } = useI18n();
-
- const columnList = computed(() => {
- if (props.mode === "DATABASE") {
- return [
- {
- title: "",
- },
- {
- title: t("change-history.workflow"),
- },
- {
- title: t("common.version"),
- },
- {
- title: t("common.issue"),
- },
- {
- title: "SQL",
- },
- {
- title: t("common.duration"),
- },
- {
- title: t("common.created-at"),
- },
- {
- title: t("common.creator"),
- },
- ];
- } else if (props.mode === "PROJECT") {
- return [
- { title: "" },
- {
- title: t("common.version"),
- },
- {
- title: t("common.issue"),
- },
- {
- title: "SQL",
- },
- {
- title: t("common.duration"),
- },
- {
- title: t("common.created-at"),
- },
- {
- title: t("common.creator"),
- },
- ];
- } else {
- return [];
- }
- });
-
- const clickHistory = (section: number, row: number) => {
- const history = props.historySectionList[section].list[row];
- router.push(
- `/db/${databaseV1Slug(
- props.databaseSectionList[section]
- )}/history/${migrationHistorySlug(history.id, history.version)}`
- );
- };
-
- return {
- columnList,
- nanosecondsToString,
- clickHistory,
- };
- },
-});
-</script>
diff --git a/frontend/src/components/ProjectChangeHistoryPanel.vue b/frontend/src/components/ProjectChangeHistoryPanel.vue
new file mode 100644
index 0000000000..ef60d802e8
--- /dev/null
+++ b/frontend/src/components/ProjectChangeHistoryPanel.vue
@@ -0,0 +1,95 @@
+<template>
+ <div class="flex flex-col space-y-4">
+ <template v-if="state.changeHistorySectionList.length > 0">
+ <div class="text-center textinfolabel">
+ {{ $t("change-history.list-limit") }}
+ </div>
+ <ChangeHistoryTable
+ :mode="'PROJECT'"
+ :database-section-list="state.databaseSectionList"
+ :history-section-list="state.changeHistorySectionList"
+ />
+ </template>
+ <template v-else>
+ <!-- This example requires Tailwind CSS v2.0+ -->
+ <div class="text-center">
+ <heroicons-outline:inbox class="mx-auto w-16 h-16 text-control-light" />
+ <h3 class="mt-2 text-sm font-medium text-main">
+ {{ $t("change-history.no-history-in-project") }}
+ </h3>
+ <p class="mt-1 text-sm text-control-light">
+ {{ $t("change-history.recording-info") }}
+ </p>
+ </div>
+ </template>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { PropType, reactive, watchEffect } from "vue";
+
+import { ChangeHistoryTable } from "@/components/ChangeHistory";
+import { ComposedDatabase } from "@/types";
+import { BBTableSectionDataSource } from "@/bbkit/types";
+import { databaseV1Slug } from "@/utils";
+import { useChangeHistoryStore } from "@/store";
+import { ChangeHistory } from "@/types/proto/v1/database_service";
+
+// Show at most 5 recent migration history for each database
+const MAX_MIGRATION_HISTORY_COUNT = 5;
+
+interface LocalState {
+ databaseSectionList: ComposedDatabase[];
+ changeHistorySectionList: BBTableSectionDataSource<ChangeHistory>[];
+}
+
+const props = defineProps({
+ databaseList: {
+ required: true,
+ type: Object as PropType<ComposedDatabase[]>,
+ },
+});
+
+const changeHistoryStore = useChangeHistoryStore();
+
+const state = reactive<LocalState>({
+ databaseSectionList: [],
+ changeHistorySectionList: [],
+});
+
+const fetchChangeHistory = async (databaseList: ComposedDatabase[]) => {
+ state.databaseSectionList = [];
+ state.changeHistorySectionList = [];
+ for (const database of databaseList) {
+ const changeHistoryList = await changeHistoryStore.fetchChangeHistoryList({
+ parent: database.name,
+ pageSize: MAX_MIGRATION_HISTORY_COUNT,
+ });
+ if (changeHistoryList.length > 0) {
+ state.databaseSectionList.push(database);
+
+ const title = `${database.databaseName} (${database.instanceEntity.environmentEntity.title})`;
+ const index = state.changeHistorySectionList.findIndex(
+ (item: BBTableSectionDataSource<ChangeHistory>) => {
+ return item.title == title;
+ }
+ );
+ const newItem = {
+ title: title,
+ link: `/db/${databaseV1Slug(database)}#change-history`,
+ list: changeHistoryList,
+ };
+ if (index >= 0) {
+ state.changeHistorySectionList[index] = newItem;
+ } else {
+ state.changeHistorySectionList.push(newItem);
+ }
+ }
+ }
+};
+
+const prepareChangeHistoryList = () => {
+ fetchChangeHistory(props.databaseList);
+};
+watchEffect(prepareChangeHistoryList);
+</script>
diff --git a/frontend/src/components/ProjectMigrationHistoryPanel.vue b/frontend/src/components/ProjectMigrationHistoryPanel.vue
deleted file mode 100644
index 56b293baab..0000000000
--- a/frontend/src/components/ProjectMigrationHistoryPanel.vue
+++ /dev/null
@@ -1,97 +0,0 @@
-<template>
- <div class="flex flex-col space-y-4">
- <template v-if="state.migrationHistorySectionList.length > 0">
- <div class="text-center textinfolabel">
- {{ $t("change-history.list-limit") }}
- </div>
- <MigrationHistoryTable
- :mode="'PROJECT'"
- :database-section-list="state.databaseSectionList"
- :history-section-list="state.migrationHistorySectionList"
- />
- </template>
- <template v-else>
- <!-- This example requires Tailwind CSS v2.0+ -->
- <div class="text-center">
- <heroicons-outline:inbox class="mx-auto w-16 h-16 text-control-light" />
- <h3 class="mt-2 text-sm font-medium text-main">
- {{ $t("change-history.no-history-in-project") }}
- </h3>
- <p class="mt-1 text-sm text-control-light">
- {{ $t("change-history.recording-info") }}
- </p>
- </div>
- </template>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { PropType, reactive, watchEffect } from "vue";
-import MigrationHistoryTable from "../components/MigrationHistoryTable.vue";
-import { ComposedDatabase, MigrationHistory } from "../types";
-import { BBTableSectionDataSource } from "../bbkit/types";
-import { databaseV1Slug } from "../utils";
-import { useLegacyInstanceStore } from "@/store";
-
-// Show at most 5 recent migration history for each database
-const MAX_MIGRATION_HISTORY_COUNT = 5;
-
-interface LocalState {
- databaseSectionList: ComposedDatabase[];
- migrationHistorySectionList: BBTableSectionDataSource<MigrationHistory>[];
-}
-
-const props = defineProps({
- databaseList: {
- required: true,
- type: Object as PropType<ComposedDatabase[]>,
- },
-});
-
-const instanceStore = useLegacyInstanceStore();
-
-const state = reactive<LocalState>({
- databaseSectionList: [],
- migrationHistorySectionList: [],
-});
-
-const fetchMigrationHistory = (databaseList: ComposedDatabase[]) => {
- state.databaseSectionList = [];
- state.migrationHistorySectionList = [];
- for (const database of databaseList) {
- instanceStore
- .fetchMigrationHistory({
- instanceId: Number(database.instanceEntity.uid),
- databaseName: database.databaseName,
- limit: MAX_MIGRATION_HISTORY_COUNT,
- })
- .then((migrationHistoryList: MigrationHistory[]) => {
- if (migrationHistoryList.length > 0) {
- state.databaseSectionList.push(database);
-
- const title = `${database.databaseName} (${database.instanceEntity.environmentEntity.title})`;
- const index = state.migrationHistorySectionList.findIndex(
- (item: BBTableSectionDataSource<MigrationHistory>) => {
- return item.title == title;
- }
- );
- const newItem = {
- title: title,
- link: `/db/${databaseV1Slug(database)}#change-history`,
- list: migrationHistoryList,
- };
- if (index >= 0) {
- state.migrationHistorySectionList[index] = newItem;
- } else {
- state.migrationHistorySectionList.push(newItem);
- }
- }
- });
- }
-};
-
-const prepareMigrationHistoryList = () => {
- fetchMigrationHistory(props.databaseList);
-};
-watchEffect(prepareMigrationHistoryList);
-</script>
diff --git a/frontend/src/components/RequestDatabasePrepForm.vue b/frontend/src/components/RequestDatabasePrepForm.vue
index 7baa0846a0..da492fc7db 100644
--- a/frontend/src/components/RequestDatabasePrepForm.vue
+++ b/frontend/src/components/RequestDatabasePrepForm.vue
@@ -133,17 +133,19 @@ import {
defineComponent,
} from "vue";
import { useRouter } from "vue-router";
-import isEmpty from "lodash-es/isEmpty";
-import ProjectSelect from "../components/ProjectSelect.vue";
-import DatabaseSelect from "../components/DatabaseSelect.vue";
-import EnvironmentSelect from "../components/EnvironmentSelect.vue";
-import { UNKNOWN_ID } from "../types";
-import { allowDatabaseAccess } from "../utils";
+import { isEmpty } from "lodash-es";
+
+import ProjectSelect from "@/components/ProjectSelect.vue";
+import DatabaseSelect from "@/components/DatabaseSelect.vue";
+import EnvironmentSelect from "@/components/EnvironmentSelect.vue";
+import { UNKNOWN_ID } from "@/types";
+import { allowDatabaseV1Access } from "@/utils";
import {
useCurrentUserV1,
- useLegacyDatabaseStore,
useEnvironmentV1Store,
+ useDatabaseV1Store,
} from "@/store";
+import { DataSourceType } from "@/types/proto/v1/instance_service";
interface LocalState {
environmentId: string;
@@ -160,7 +162,7 @@ export default defineComponent({
components: { ProjectSelect, DatabaseSelect, EnvironmentSelect },
emits: ["dismiss"],
setup(props, { emit }) {
- const databaseStore = useLegacyDatabaseStore();
+ const databaseStore = useDatabaseV1Store();
const router = useRouter();
const currentUserV1 = useCurrentUserV1();
@@ -197,11 +199,11 @@ export default defineComponent({
return false;
}
- const database = databaseStore.getDatabaseById(state.databaseId);
- return allowDatabaseAccess(
+ const database = databaseStore.getDatabaseByUID(state.databaseId);
+ return allowDatabaseV1Access(
database,
currentUserV1.value,
- state.readonly ? "RO" : "RW"
+ state.readonly ? DataSourceType.READ_ONLY : DataSourceType.ADMIN
);
});
@@ -233,14 +235,14 @@ export default defineComponent({
},
query: {
template: "bb.issue.database.create",
- name: `[${environment.name}] Request new database '${state.databaseName}'`,
+ name: `[${environment.title}] Request new database '${state.databaseName}'`,
environment: state.environmentId,
project: state.projectId,
databaseName: state.databaseName,
},
});
} else {
- const database = databaseStore.getDatabaseById(state.databaseId);
+ const database = databaseStore.getDatabaseByUID(state.databaseId);
router.push({
name: "workspace.issue.detail",
params: {
@@ -248,9 +250,9 @@ export default defineComponent({
},
query: {
template: "bb.issue.database.grant",
- name: `[${environment.name}] Request database '${database.name}' ${
- state.readonly ? "Readonly access" : "Read & Write access"
- }`,
+ name: `[${environment.title}] Request database '${
+ database.databaseName
+ }' ${state.readonly ? "Readonly access" : "Read & Write access"}`,
environment: state.environmentId,
project: state.projectId,
databaseList: state.databaseId,
diff --git a/frontend/src/components/TransferDatabaseForm/TransferSingleDatabase.vue b/frontend/src/components/TransferDatabaseForm/TransferSingleDatabase.vue
index 1704f3650b..e4f888c7b2 100644
--- a/frontend/src/components/TransferDatabaseForm/TransferSingleDatabase.vue
+++ b/frontend/src/components/TransferDatabaseForm/TransferSingleDatabase.vue
@@ -49,7 +49,7 @@
</template>
<script setup lang="ts">
-import { computed, ref, watch, watchEffect } from "vue";
+import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { cloneDeep } from "lodash-es";
@@ -163,6 +163,4 @@ watch(targetProject, (tar) => {
watch(sourceProject, (src) => {
targetProject.value = src;
});
-
-watchEffect(() => console.log(JSON.stringify(editingLabels.value)));
</script>
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
index 3ae4dc7876..429a62a4ee 100644
--- a/frontend/src/main.ts
+++ b/frontend/src/main.ts
@@ -27,6 +27,7 @@ import {
environmentSlug,
humanizeTs,
humanizeDuration,
+ humanizeDurationV1,
humanizeDate,
instanceName,
instanceSlug,
@@ -140,6 +141,7 @@ app.config.globalProperties.console = console;
app.config.globalProperties.dayjs = dayjs;
app.config.globalProperties.humanizeTs = humanizeTs;
app.config.globalProperties.humanizeDuration = humanizeDuration;
+app.config.globalProperties.humanizeDurationV1 = humanizeDurationV1;
app.config.globalProperties.humanizeDate = humanizeDate;
app.config.globalProperties.isDev = isDev();
app.config.globalProperties.isRelease = isRelease();
diff --git a/frontend/src/plugins/issue/logic/initialize/index.ts b/frontend/src/plugins/issue/logic/initialize/index.ts
index ccb938f2ad..a30658220d 100644
--- a/frontend/src/plugins/issue/logic/initialize/index.ts
+++ b/frontend/src/plugins/issue/logic/initialize/index.ts
@@ -113,11 +113,11 @@ const buildNewIssue = async (
const prepareDatabaseListForIssueCreation = async (query: LocationQuery) => {
const databaseStore = useDatabaseV1Store();
// For preparing the database if user visits creating issue url directly.
- // It's horrible to fetchDatabaseById one-by-one when query.databaseList
+ // It's horrible to fetchDatabaseByUID one-by-one when query.databaseList
// is big (100+ sometimes)
// So we are fetching databaseList by project since that's better cached.
if (query.project) {
- // If we found query.project, we can directly fetchDatabaseListByProjectId
+ // If we found query.project, we can directly search database list by project
const projectId = query.project as string;
const project = await useProjectV1Store().getOrFetchProjectByUID(projectId);
await databaseStore.searchDatabaseList({
diff --git a/frontend/src/plugins/pitr/index.ts b/frontend/src/plugins/pitr/index.ts
index f74aebfd8b..2e0ba34cf7 100644
--- a/frontend/src/plugins/pitr/index.ts
+++ b/frontend/src/plugins/pitr/index.ts
@@ -3,19 +3,19 @@ import {
CreateDatabaseContext,
ComposedDatabase,
IssueCreate,
- MigrationHistory,
PITRContext,
} from "@/types";
import {
useBackupListByDatabaseId,
+ useChangeHistoryStore,
useCurrentUserV1,
- useLegacyInstanceStore,
useIssueStore,
} from "@/store";
import { useI18n } from "vue-i18n";
import { extractUserUID, semverCompare } from "@/utils";
import { Instance } from "@/types/proto/v1/instance_service";
import { Engine } from "@/types/proto/v1/common";
+import { head } from "lodash-es";
export const MIN_PITR_SUPPORT_MYSQL_VERSION = "8.0.0";
@@ -30,7 +30,7 @@ export const isPITRAvailableOnInstanceV1 = (instance: Instance): boolean => {
export const usePITRLogic = (database: Ref<ComposedDatabase>) => {
const { t } = useI18n();
const currentUserV1 = useCurrentUserV1();
- const instanceStore = useLegacyInstanceStore();
+ const changeHistoryStore = useChangeHistoryStore();
const backupList = useBackupListByDatabaseId(
computed(() => Number(database.value.uid))
@@ -62,24 +62,22 @@ export const usePITRLogic = (database: Ref<ComposedDatabase>) => {
};
});
- const prepareMigrationHistoryList = async () => {
- instanceStore.fetchMigrationHistory({
- instanceId: Number(database.value.instanceEntity.uid),
- databaseName: database.value.databaseName,
+ const prepareChangeHistoryList = async () => {
+ changeHistoryStore.fetchChangeHistoryList({
+ parent: database.value.name,
});
};
- watch(database, prepareMigrationHistoryList, { immediate: true });
+ watch(() => database.value.name, prepareChangeHistoryList, {
+ immediate: true,
+ });
- const migrationHistoryList = computed(() => {
- return instanceStore.getMigrationHistoryListByInstanceIdAndDatabaseName(
- Number(database.value.instanceEntity.uid),
- database.value.databaseName
- );
+ const changeHistoryList = computed(() => {
+ return changeHistoryStore.changeHistoryListByDatabase(database.value.name);
});
- const lastMigrationHistory = computed((): MigrationHistory | undefined => {
- return migrationHistoryList.value[0];
+ const lastChangeHistory = computed(() => {
+ return head(changeHistoryList.value);
});
const createPITRIssue = async (
@@ -115,8 +113,8 @@ export const usePITRLogic = (database: Ref<ComposedDatabase>) => {
backupList,
doneBackupList,
pitrAvailable,
- migrationHistoryList,
- lastMigrationHistory,
+ changeHistoryList,
+ lastChangeHistory,
createPITRIssue,
};
};
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 9fbe35af5c..31617e5793 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -17,7 +17,6 @@ import SQLEditorLayout from "@/layouts/SQLEditorLayout.vue";
import SheetDashboardLayout from "@/layouts/SheetDashboardLayout.vue";
import { t } from "@/plugins/i18n";
import {
- Database,
DEFAULT_PROJECT_ID,
DEFAULT_PROJECT_V1_NAME,
QuickActionType,
@@ -29,8 +28,8 @@ import {
hasWorkspacePermissionV1,
idFromSlug,
sheetNameFromSlug,
- migrationHistoryIdFromSlug,
isOwnerOfProjectV1,
+ extractChangeHistoryUID,
} from "@/utils";
import Signin from "@/views/auth/Signin.vue";
import Signup from "@/views/auth/Signup.vue";
@@ -46,7 +45,6 @@ import {
useSheetV1Store,
useAuthStore,
useActuatorV1Store,
- useLegacyDatabaseStore,
useLegacyInstanceStore,
useRouterStore,
useDBSchemaStore,
@@ -61,6 +59,7 @@ import {
useCurrentUserV1,
useInstanceV1Store,
useDatabaseV1Store,
+ useChangeHistoryStore,
} from "@/store";
import { useConversationStore } from "@/plugins/ai/store";
import { State } from "@/types/proto/v1/common";
@@ -877,27 +876,30 @@ const routes: Array<RouteRecordRaw> = [
component: () => import("../views/TableDetail.vue"),
props: true,
},
- {
- path: "history/:migrationHistorySlug",
- name: "workspace.database.history.detail",
- meta: {
- title: (route: RouteLocationNormalized) => {
- const slug = route.params.migrationHistorySlug as string;
- const migrationHistory =
- useLegacyInstanceStore().getMigrationHistoryById(
- migrationHistoryIdFromSlug(slug)
- );
- return migrationHistory?.version ?? "";
- },
- allowBookmark: true,
- },
- component: () => import("../views/MigrationHistoryDetail.vue"),
- props: (to) => ({
- key: to.fullPath, // force refresh the component when slug changed
- }),
- },
],
},
+ {
+ path: "instances/:instance/databases/:database/changeHistories/:changeHistorySlug",
+ name: "workspace.database.history.detail",
+ meta: {
+ title: (route) => {
+ const parent = `instances/${route.params.instance}/databases/${route.params.database}`;
+ const uid = extractChangeHistoryUID(
+ route.params.changeHistorySlug as string
+ );
+ const name = `${parent}/changeHistories/${uid}`;
+ const history =
+ useChangeHistoryStore().getChangeHistoryByName(name);
+
+ return history?.version ?? "";
+ },
+ },
+ components: {
+ content: () => import("../views/ChangeHistoryDetail.vue"),
+ leftSidebar: DashboardSidebar,
+ },
+ props: { content: true, leftSidebar: true },
+ },
{
path: "instance/:instanceSlug",
components: {
@@ -1052,7 +1054,6 @@ router.beforeEach((to, from, next) => {
console.debug("Router %s -> %s", from.name, to.name);
const authStore = useAuthStore();
- const databaseStore = useLegacyDatabaseStore();
const dbSchemaStore = useDBSchemaStore();
const instanceStore = useLegacyInstanceStore();
const routerStore = useRouterStore();
@@ -1324,6 +1325,28 @@ router.beforeEach((to, from, next) => {
return;
}
+ if (to.name === "workspace.database.history.detail") {
+ const parent = `instances/${to.params.instance}/databases/${to.params.database}`;
+ const uid = extractChangeHistoryUID(to.params.changeHistorySlug as string);
+ Promise.all([
+ useDatabaseV1Store().getOrFetchDatabaseByName(parent),
+ useChangeHistoryStore().fetchChangeHistory({
+ name: `${parent}/changeHistories/${uid}`,
+ }),
+ ])
+ .then(() => {
+ next();
+ })
+ .catch((error) => {
+ next({
+ name: "error.404",
+ replace: false,
+ });
+ throw error;
+ });
+ return;
+ }
+
const routerSlug = routerStore.routeSlug(to);
const principalId = routerSlug.principalId;
const environmentSlug = routerSlug.environmentSlug;
@@ -1333,7 +1356,6 @@ router.beforeEach((to, from, next) => {
const instanceSlug = routerSlug.instanceSlug;
const databaseSlug = routerSlug.databaseSlug;
const dataSourceSlug = routerSlug.dataSourceSlug;
- const migrationHistorySlug = routerSlug.migrationHistorySlug;
const vcsSlug = routerSlug.vcsSlug;
const connectionSlug = routerSlug.connectionSlug;
const sheetSlug = routerSlug.sheetSlug;
@@ -1427,35 +1449,17 @@ router.beforeEach((to, from, next) => {
}
useDatabaseV1Store()
.fetchDatabaseByUID(String(idFromSlug(databaseSlug)))
- .then(() => databaseStore.fetchDatabaseById(idFromSlug(databaseSlug)))
- .then((database: Database) => {
+ .then((database) => {
dbSchemaStore
- .getOrFetchDatabaseMetadataById(database.id, true)
+ .getOrFetchDatabaseMetadataById(Number(database.uid), true)
.then(() => {
- if (!dataSourceSlug && !migrationHistorySlug) {
+ if (!dataSourceSlug) {
next();
} else if (dataSourceSlug) {
useDataSourceStore()
.fetchDataSourceById({
dataSourceId: idFromSlug(dataSourceSlug),
- databaseId: database.id,
- })
- .then(() => {
- next();
- })
- .catch((error) => {
- next({
- name: "error.404",
- replace: false,
- });
- throw error;
- });
- } else if (migrationHistorySlug) {
- instanceStore
- .fetchMigrationHistoryById({
- instanceId: database.instance.id,
- migrationHistoryId:
- migrationHistoryIdFromSlug(migrationHistorySlug),
+ databaseId: Number(database.uid),
})
.then(() => {
next();
@@ -1481,13 +1485,9 @@ router.beforeEach((to, from, next) => {
}
if (instanceSlug) {
- instanceStore
- .fetchInstanceById(idFromSlug(instanceSlug))
- .then(() =>
- useInstanceV1Store().getOrFetchInstanceByUID(
- String(idFromSlug(instanceSlug))
- )
- )
+ instanceStore;
+ useInstanceV1Store()
+ .getOrFetchInstanceByUID(String(idFromSlug(instanceSlug)))
.then(() => {
next();
})
diff --git a/frontend/src/shims-vue-globals.d.ts b/frontend/src/shims-vue-globals.d.ts
index 0d656006a1..31b181d8a3 100644
--- a/frontend/src/shims-vue-globals.d.ts
+++ b/frontend/src/shims-vue-globals.d.ts
@@ -5,6 +5,7 @@ import type {
environmentSlug,
humanizeTs,
humanizeDuration,
+ humanizeDurationV1,
humanizeDate,
instanceName,
instanceSlug,
@@ -23,6 +24,7 @@ declare module "vue" {
dayjs: typeof dayjs;
humanizeTs: typeof humanizeTs;
humanizeDuration: typeof humanizeDuration;
+ humanizeDurationV1: typeof humanizeDurationV1;
humanizeDate: typeof humanizeDate;
isDev: boolean;
isRelease: boolean;
diff --git a/frontend/src/store/modules/database.ts b/frontend/src/store/modules/database.ts
index b85879c411..b64233c0d9 100644
--- a/frontend/src/store/modules/database.ts
+++ b/frontend/src/store/modules/database.ts
@@ -1,30 +1,20 @@
-import { isUndefined } from "lodash-es";
import { defineStore } from "pinia";
-import axios from "axios";
import { markRaw } from "vue";
import {
Database,
- DatabaseFind,
- DatabaseId,
DatabaseLabel,
DatabaseState,
DataSource,
- empty,
- EMPTY_ID,
Instance,
InstanceId,
Project,
ResourceIdentifier,
ResourceObject,
unknown,
- UNKNOWN_ID,
} from "@/types";
import { useDataSourceStore } from "./dataSource";
import { useLegacyInstanceStore } from "./instance";
import { useLegacyProjectStore } from "./project";
-import { hasWorkspacePermissionV1, isMemberOfProjectV1 } from "@/utils";
-import { useProjectV1Store } from "./v1";
-import { User } from "@/types/proto/v1/auth_service";
function convert(
database: ResourceObject,
@@ -118,27 +108,6 @@ function convert(
});
}
-const databaseSorter = (a: Database, b: Database): number => {
- let result = a.instance.name.localeCompare(b.instance.name);
- if (result != 0) {
- return result;
- }
-
- result = a.instance.environment.name.localeCompare(
- b.instance.environment.name
- );
- if (result != 0) {
- return result;
- }
-
- result = a.project.name.localeCompare(b.project.name);
- if (result != 0) {
- return result;
- }
-
- return a.name.localeCompare(b.name);
-};
-
export const useLegacyDatabaseStore = defineStore("legacy_database", {
state: (): DatabaseState => ({
databaseListByInstanceId: new Map(),
@@ -151,109 +120,6 @@ export const useLegacyDatabaseStore = defineStore("legacy_database", {
): Database {
return convert(database, includedList);
},
- getDatabaseList(): Database[] {
- const list: Database[] = [];
- for (const [_, databaseList] of this.databaseListByInstanceId) {
- list.push(...databaseList);
- }
- return list;
- },
- getDatabaseListByInstanceId(instanceId: InstanceId): Database[] {
- return this.databaseListByInstanceId.get(String(instanceId)) || [];
- },
- async getOrFetchDatabaseListByInstanceId(
- instanceId: InstanceId
- ): Promise<Database[]> {
- const databaseList = this.databaseListByInstanceId.get(
- String(instanceId)
- );
- if (isUndefined(databaseList)) {
- await this.fetchDatabaseListByInstanceId(String(instanceId));
- }
- return this.databaseListByInstanceId.get(String(instanceId)) || [];
- },
- getDatabaseListByUser(user: User): Database[] {
- const canManageDatabase = hasWorkspacePermissionV1(
- "bb.permission.workspace.manage-database",
- user.userRole
- );
- const list: Database[] = [];
- for (const [_, databaseList] of this.databaseListByInstanceId) {
- databaseList.forEach((item: Database) => {
- const projectV1 = useProjectV1Store().getProjectByUID(
- String(item.project.id)
- );
- if (
- canManageDatabase ||
- isMemberOfProjectV1(projectV1.iamPolicy, user)
- ) {
- list.push(item);
- }
- });
- }
- return list;
- },
- getDatabaseListByEnvironmentId(environmentId: string): Database[] {
- const list: Database[] = [];
- for (const [_, databaseList] of this.databaseListByInstanceId) {
- databaseList.forEach((item: Database) => {
- if (String(item.instance.environment.id) === environmentId) {
- list.push(item);
- }
- });
- }
- return list;
- },
- getDatabaseListByProjectId(projectId: string): Database[] {
- return this.databaseListByProjectId.get(projectId) || [];
- },
- getDatabaseById(databaseId: DatabaseId, instanceId?: InstanceId): Database {
- if (databaseId == EMPTY_ID) {
- return empty("DATABASE") as Database;
- }
-
- if (instanceId) {
- const list =
- this.databaseListByInstanceId.get(String(instanceId)) || [];
- return (
- list.find((item) => item.id == databaseId) ||
- (unknown("DATABASE") as Database)
- );
- }
-
- for (const [_, list] of this.databaseListByInstanceId) {
- const database = list.find((item) => item.id == databaseId);
- if (database) {
- return database;
- }
- }
-
- return unknown("DATABASE") as Database;
- },
- setDatabaseListByProjectId({
- databaseList,
- projectId,
- }: {
- databaseList: Database[];
- projectId: string;
- }) {
- this.databaseListByProjectId.set(projectId, databaseList);
- },
- removeDatabaseListFromProject(databaseList: Database[]) {
- for (const database of databaseList) {
- const listByProject = this.databaseListByProjectId.get(
- String(database.project.id)
- );
- if (listByProject) {
- const i = listByProject.findIndex(
- (item: Database) => item.id == database.id
- );
- if (i >= 0) {
- listByProject.splice(i, 1);
- }
- }
- }
- },
upsertDatabaseList({
databaseList,
instanceId,
@@ -303,163 +169,5 @@ export const useLegacyDatabaseStore = defineStore("legacy_database", {
}
}
},
- async fetchDatabaseList(databaseFind?: DatabaseFind) {
- const queryList = [];
- if (databaseFind?.projectId) {
- queryList.push(`project=${databaseFind.projectId}`);
- }
- if (databaseFind?.instanceId) {
- queryList.push(`instance=${databaseFind.instanceId}`);
- }
- if (databaseFind?.name) {
- queryList.push(`name=${databaseFind.name}`);
- }
- if (databaseFind?.syncStatus) {
- queryList.push(`syncStatus=${databaseFind.syncStatus}`);
- }
- const data = (await axios.get(`/api/database?${queryList.join("&")}`))
- .data;
- const databaseList: Database[] = data.data.map(
- (database: ResourceObject) => {
- return convert(database, data.included);
- }
- );
- databaseList.sort(databaseSorter);
-
- this.upsertDatabaseList({ databaseList });
-
- return databaseList;
- },
- async fetchDatabaseListByInstanceId(instanceId: InstanceId) {
- const databaseList = await this.fetchDatabaseList({
- instanceId,
- });
- this.databaseListByInstanceId.set(String(instanceId), databaseList);
- return databaseList;
- },
- async fetchDatabaseByInstanceIdAndName({
- instanceId,
- name,
- }: {
- instanceId: InstanceId;
- name: string;
- }) {
- const databaseList = await this.fetchDatabaseList({
- instanceId,
- name,
- });
-
- return databaseList[0];
- },
- async fetchDatabaseListByProjectId(projectId: string) {
- const databaseList = await this.fetchDatabaseList({
- projectId,
- });
-
- this.setDatabaseListByProjectId({ databaseList, projectId });
-
- return databaseList;
- },
- async fetchDatabaseListByEnvironmentId(environmentId: string) {
- // Don't fetch the data source info as the current user may not have access to the
- // database of this particular environment.
- const data = (
- await axios.get(`/api/database?environment=${environmentId}`)
- ).data;
- const databaseList: Database[] = data.data.map(
- (database: ResourceObject) => {
- return convert(database, data.included);
- }
- );
- databaseList.sort(databaseSorter);
-
- this.upsertDatabaseList({ databaseList });
-
- return databaseList;
- },
- async fetchDatabaseById(databaseId: DatabaseId) {
- const url = `/api/database/${databaseId}`;
- const data = (await axios.get(url)).data;
- const database = convert(data.data, data.included);
-
- this.upsertDatabaseList({
- databaseList: [database],
- });
-
- return database;
- },
- async getOrFetchDatabaseById(databaseId: DatabaseId) {
- const storedDatabase = this.getDatabaseById(databaseId);
- if (storedDatabase.id !== UNKNOWN_ID) {
- return storedDatabase;
- }
- return this.fetchDatabaseById(databaseId);
- },
- async fetchDatabaseSchemaById(
- databaseId: DatabaseId,
- sdl = false
- ): Promise<string> {
- let url = `/api/database/${databaseId}/schema`;
- if (sdl) {
- url += "?sdl=true";
- }
- const schema = (await axios.get(url)).data as string;
- return schema;
- },
- async transferProject({
- database,
- projectId,
- labels,
- }: {
- database: Database;
- projectId: string;
- labels?: DatabaseLabel[];
- }) {
- const attributes: any = { projectId: Number(projectId) };
- if (labels) {
- attributes.labels = JSON.stringify(labels);
- }
- const data = (
- await axios.patch(`/api/database/${database.id}`, {
- data: {
- type: "databasePatch",
- attributes,
- },
- })
- ).data;
-
- const updatedDatabase = convert(data.data, data.included);
- this.removeDatabaseListFromProject([database]);
- this.upsertDatabaseList({
- databaseList: [updatedDatabase],
- });
-
- return updatedDatabase;
- },
- async patchDatabaseLabels({
- 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);
-
- this.upsertDatabaseList({
- databaseList: [updatedDatabase],
- });
-
- return updatedDatabase;
- },
},
});
diff --git a/frontend/src/store/modules/instance.ts b/frontend/src/store/modules/instance.ts
index 8cbefc6719..68005abee6 100644
--- a/frontend/src/store/modules/instance.ts
+++ b/frontend/src/store/modules/instance.ts
@@ -1,25 +1,13 @@
import { defineStore } from "pinia";
-import axios from "axios";
import {
DataSource,
- empty,
- EMPTY_ID,
Environment,
Instance,
- InstanceCreate,
- InstanceId,
- InstancePatch,
InstanceState,
- INSTANCE_OPERATION_TIMEOUT,
- MigrationHistory,
- MigrationHistoryId,
ResourceIdentifier,
ResourceObject,
- RowStatus,
unknown,
- UNKNOWN_ID,
} from "@/types";
-import { InstanceUser } from "@/types/InstanceUser";
import { useLegacyEnvironmentStore } from "./environment";
import { useDataSourceStore } from "./dataSource";
@@ -83,23 +71,6 @@ function convert(
};
}
-function convertMigrationHistory(history: ResourceObject): MigrationHistory {
- const payload = history.attributes.payload
- ? JSON.parse((history.attributes.payload as string) || "{}")
- : {};
- return {
- ...(history.attributes as Omit<
- MigrationHistory,
- "id" | "issueId" | "payload"
- >),
- id: history.id,
- // This issueId is special since it's stored in the migration history table
- // and may refer to the issueId from the external system in the future.
- issueId: parseInt(history.attributes.issueId as string),
- payload,
- };
-}
-
export const useLegacyInstanceStore = defineStore("legacy_instance", {
state: (): InstanceState => ({
instanceById: new Map(),
@@ -114,292 +85,5 @@ export const useLegacyInstanceStore = defineStore("legacy_instance", {
): Instance {
return convert(instance, includedList);
},
- getInstanceList(rowStatusList?: RowStatus[]): Instance[] {
- const list = [];
- for (const [_, instance] of this.instanceById) {
- if (
- (!rowStatusList && instance.rowStatus == "NORMAL") ||
- (rowStatusList && rowStatusList.includes(instance.rowStatus))
- ) {
- list.push(instance);
- }
- }
- return list.sort((a: Instance, b: Instance) => {
- return b.id - a.id;
- });
- },
- getInstanceListByEnvironmentId(
- environmentId: string,
- rowStatusList?: RowStatus[]
- ): Instance[] {
- const list = this.getInstanceList(rowStatusList);
- return list.filter((item: Instance) => {
- return String(item.environment.id) === environmentId;
- });
- },
- getInstanceById(instanceId: InstanceId): Instance {
- if (instanceId == EMPTY_ID) {
- return empty("INSTANCE") as Instance;
- }
-
- return (
- this.instanceById.get(instanceId) || (unknown("INSTANCE") as Instance)
- );
- },
- getInstanceUserListById(instanceId: InstanceId): InstanceUser[] {
- return this.instanceUserListById.get(instanceId) || [];
- },
- formatEngine(instance: Instance): string {
- switch (instance.engine) {
- case "POSTGRES":
- return "PostgreSQL";
- // Use MySQL as default engine.
- default:
- return "MySQL";
- }
- },
- getMigrationHistoryById(
- migrationHistoryId: MigrationHistoryId
- ): MigrationHistory | undefined {
- return this.migrationHistoryById.get(migrationHistoryId);
- },
- getMigrationHistoryListByInstanceIdAndDatabaseName(
- instanceId: InstanceId,
- databaseName: string
- ): MigrationHistory[] {
- return (
- this.migrationHistoryListByIdAndDatabaseName.get(
- [instanceId, databaseName].join(".")
- ) || []
- );
- },
- setInstanceList(instanceList: Instance[]) {
- instanceList.forEach((instance) => {
- this.instanceById.set(instance.id, instance);
- });
- },
- setInstanceById({
- instanceId,
- instance,
- }: {
- instanceId: InstanceId;
- instance: Instance;
- }) {
- this.instanceById.set(instanceId, instance);
- },
- setInstanceUserListById({
- instanceId,
- instanceUserList,
- }: {
- instanceId: InstanceId;
- instanceUserList: InstanceUser[];
- }) {
- this.instanceUserListById.set(instanceId, instanceUserList);
- },
- setMigrationHistoryById({
- migrationHistoryId,
- migrationHistory,
- }: {
- migrationHistoryId: MigrationHistoryId;
- migrationHistory: MigrationHistory;
- }) {
- this.migrationHistoryById.set(migrationHistoryId, migrationHistory);
- },
- setMigrationHistoryListByInstanceIdAndDatabaseName({
- instanceId,
- databaseName,
- historyList,
- }: {
- instanceId: InstanceId;
- databaseName: string;
- historyList: MigrationHistory[];
- }) {
- this.migrationHistoryListByIdAndDatabaseName.set(
- [instanceId, databaseName].join("."),
- historyList
- );
- },
- async fetchInstanceList(rowStatusList?: RowStatus[]) {
- const path =
- "/api/instance" +
- (rowStatusList ? "?rowstatus=" + rowStatusList.join(",") : "");
- const data = (await axios.get(path)).data;
- const instanceList: Instance[] = data.data.map(
- (instance: ResourceObject) => {
- return convert(instance, data.included);
- }
- );
-
- this.setInstanceList(instanceList);
-
- return instanceList;
- },
- async fetchInstanceById(instanceId: InstanceId) {
- const data = (await axios.get(`/api/instance/${instanceId}`)).data;
- const instance = convert(data.data, data.included);
-
- this.setInstanceById({
- instanceId,
- instance,
- });
- return instance;
- },
- async getOrFetchInstanceById(instanceId: InstanceId) {
- const storedInstance = this.getInstanceById(instanceId);
- if (storedInstance.id !== UNKNOWN_ID) {
- return storedInstance;
- }
- return this.fetchInstanceById(instanceId);
- },
- async createInstance(newInstance: InstanceCreate) {
- const data = (
- await axios.post(
- `/api/instance`,
- {
- data: {
- type: "InstanceCreate",
- attributes: newInstance,
- },
- },
- {
- timeout: INSTANCE_OPERATION_TIMEOUT,
- }
- )
- ).data;
- const createdInstance = convert(data.data, data.included);
-
- this.setInstanceById({
- instanceId: createdInstance.id,
- instance: createdInstance,
- });
-
- return createdInstance;
- },
- async patchInstance({
- instanceId,
- instancePatch,
- }: {
- instanceId: InstanceId;
- instancePatch: InstancePatch;
- }) {
- const data = (
- await axios.patch(
- `/api/instance/${instanceId}`,
- {
- data: {
- type: "instancePatch",
- attributes: instancePatch,
- },
- },
- {
- timeout: INSTANCE_OPERATION_TIMEOUT,
- }
- )
- ).data;
- const updatedInstance = convert(data.data, data.included);
-
- this.setInstanceById({
- instanceId: updatedInstance.id,
- instance: updatedInstance,
- });
-
- return updatedInstance;
- },
- async deleteInstanceById(instanceId: InstanceId) {
- await axios.delete(`/api/instance/${instanceId}`);
- this.instanceById.delete(instanceId);
- },
- async fetchMigrationHistoryById({
- instanceId,
- migrationHistoryId,
- sdl,
- }: {
- instanceId: InstanceId;
- migrationHistoryId: MigrationHistoryId;
- sdl?: boolean;
- }) {
- let url = `/api/instance/${instanceId}/migration/history/${migrationHistoryId}`;
- if (sdl) {
- url += "?sdl=true";
- }
- const data = (
- await axios.get(url, {
- timeout: INSTANCE_OPERATION_TIMEOUT,
- })
- ).data;
- const migrationHistory = convertMigrationHistory(data.data);
-
- this.setMigrationHistoryById({
- migrationHistoryId,
- migrationHistory,
- });
- return migrationHistory;
- },
- async fetchMigrationHistoryByVersion({
- instanceId,
- databaseName,
- version,
- }: {
- instanceId: InstanceId;
- databaseName: string;
- version: string;
- }) {
- const data = (
- await axios.get(
- `/api/instance/${instanceId}/migration/history?database=${databaseName}&version=${version}`,
- {
- timeout: INSTANCE_OPERATION_TIMEOUT,
- }
- )
- ).data.data;
- const historyList: MigrationHistory[] = data.map(
- (history: ResourceObject) => {
- return convertMigrationHistory(history);
- }
- );
-
- if (historyList.length > 0) {
- this.setMigrationHistoryById({
- migrationHistoryId: historyList[0].id,
- migrationHistory: historyList[0],
- });
- return historyList[0];
- }
- throw new Error(
- `Migration version ${version} not found in database ${databaseName}.`
- );
- },
- async fetchMigrationHistory({
- instanceId,
- databaseName,
- limit,
- }: {
- instanceId: InstanceId;
- databaseName: string;
- limit?: number;
- }): Promise<MigrationHistory[]> {
- let url = `/api/instance/${instanceId}/migration/history?database=${databaseName}`;
- if (limit) {
- url += `&limit=${limit}`;
- }
- const data = (
- await axios.get(url, {
- timeout: INSTANCE_OPERATION_TIMEOUT,
- })
- ).data.data;
- const historyList: MigrationHistory[] = data.map(
- (history: ResourceObject) => {
- return convertMigrationHistory(history);
- }
- );
-
- this.setMigrationHistoryListByInstanceIdAndDatabaseName({
- instanceId,
- databaseName,
- historyList,
- });
-
- return historyList;
- },
},
});
diff --git a/frontend/src/store/modules/issue.ts b/frontend/src/store/modules/issue.ts
index 749a20aad4..0b64c3aea9 100644
--- a/frontend/src/store/modules/issue.ts
+++ b/frontend/src/store/modules/issue.ts
@@ -25,7 +25,6 @@ import { isDatabaseRelatedIssueType } from "@/utils";
import { getPrincipalFromIncludedList } from "./principal";
import { useActivityStore } from "./activity";
import { useLegacyDatabaseStore } from "./database";
-import { useLegacyInstanceStore } from "./instance";
import { usePipelineStore } from "./pipeline";
import { useLegacyProjectStore } from "./project";
import { convertEntityList } from "./utils";
@@ -195,24 +194,20 @@ export const useIssueStore = defineStore("issue", {
// unknown instance/database when navigating to other UI from the issue detail page
// since other UIs are getting instance/database by id from the store.
if (isDatabaseRelatedIssueType(issue.type)) {
- const instanceStore = useLegacyInstanceStore();
const databaseStore = useLegacyDatabaseStore();
const instanceV1Store = useInstanceV1Store();
const databaseV1Store = useDatabaseV1Store();
for (const stage of issue.pipeline!.stageList) {
for (const task of stage.taskList) {
- // Legacy compatibility
- instanceStore.setInstanceById({
- instanceId: task.instance.id,
- instance: task.instance,
- });
instanceV1Store.getOrFetchInstanceByUID(String(task.instance.id));
if (task.database) {
+ databaseV1Store.getOrFetchDatabaseByUID(String(task.database.id));
+
+ // Legacy compatibility
databaseStore.upsertDatabaseList({
databaseList: [task.database],
});
- databaseV1Store.getOrFetchDatabaseByUID(String(task.database.id));
}
}
}
diff --git a/frontend/src/store/modules/router.ts b/frontend/src/store/modules/router.ts
index eeef1c73b1..f0fdccd81d 100644
--- a/frontend/src/store/modules/router.ts
+++ b/frontend/src/store/modules/router.ts
@@ -114,20 +114,6 @@ export const useRouterStore = defineStore("router", {
}
}
- {
- // /db/:databaseSlug/history/:migrationHistorySlug
- // Total 3 elements, 2nd element is the database slug, 3rd element is the migration history slug
- const migrationHistoryComponents = currentRoute.path.match(
- "/db/([0-9a-zA-Z_-]+)/history/([0-9a-zA-Z_-]+)"
- ) || ["/", undefined, undefined];
- if (migrationHistoryComponents[1] && migrationHistoryComponents[2]) {
- return {
- databaseSlug: migrationHistoryComponents[1],
- migrationHistorySlug: migrationHistoryComponents[2],
- };
- }
- }
-
{
// /db/:databaseSlug
// Total 2 elements, 2nd element is the database slug
diff --git a/frontend/src/store/modules/sql.ts b/frontend/src/store/modules/sql.ts
index 13523fbf77..1d300163b7 100644
--- a/frontend/src/store/modules/sql.ts
+++ b/frontend/src/store/modules/sql.ts
@@ -11,7 +11,7 @@ import {
SingleSQLResult,
Attributes,
} from "@/types";
-import { useLegacyDatabaseStore } from "./database";
+import { useDatabaseV1Store, useInstanceV1Store } from "./v1";
export function convertSingleSQLResult(
attributes: Attributes
@@ -73,7 +73,12 @@ export const useSQLStore = defineStore("sql", {
const resultSet = convert(res.data);
if (!resultSet.error) {
// Refresh the corresponding list.
- useLegacyDatabaseStore().fetchDatabaseListByInstanceId(instanceId);
+ const instance = await useInstanceV1Store().getOrFetchInstanceByUID(
+ String(instanceId)
+ );
+ useDatabaseV1Store().fetchDatabaseList({
+ parent: instance.name,
+ });
}
return resultSet;
@@ -99,8 +104,7 @@ export const useSQLStore = defineStore("sql", {
const resultSet = convert(res.data);
if (!resultSet.error) {
// Refresh the corresponding list.
- // Legacy compatibility
- useLegacyDatabaseStore().fetchDatabaseById(databaseId);
+ useDatabaseV1Store().fetchDatabaseByUID(String(databaseId));
}
return resultSet;
diff --git a/frontend/src/store/modules/v1/changeHistory.ts b/frontend/src/store/modules/v1/changeHistory.ts
new file mode 100644
index 0000000000..4654c20155
--- /dev/null
+++ b/frontend/src/store/modules/v1/changeHistory.ts
@@ -0,0 +1,62 @@
+import { defineStore } from "pinia";
+import { reactive } from "vue";
+
+import { databaseServiceClient } from "@/grpcweb";
+import {
+ ChangeHistory,
+ GetChangeHistoryRequest,
+ ListChangeHistoriesRequest,
+} from "@/types/proto/v1/database_service";
+
+export const useChangeHistoryStore = defineStore("changeHistory_v1", () => {
+ const changeHistoryMapByName = reactive(new Map<string, ChangeHistory>());
+ const changeHistoryListMapByDatabase = reactive(
+ new Map<string, ChangeHistory[]>()
+ );
+
+ const upsertChangeHistoryMap = async (historyList: ChangeHistory[]) => {
+ for (let i = 0; i < historyList.length; i++) {
+ const history = historyList[i];
+ changeHistoryMapByName.set(history.name, history);
+ }
+ };
+ const upsertChangeHistoryListMap = async (
+ parent: string,
+ historyList: ChangeHistory[]
+ ) => {
+ changeHistoryListMapByDatabase.set(parent, historyList);
+ await upsertChangeHistoryMap(historyList);
+ };
+
+ const fetchChangeHistoryList = async (
+ params: Partial<ListChangeHistoriesRequest>
+ ) => {
+ const { parent } = params;
+ if (!parent) throw new Error('"parent" field is required');
+ const { changeHistories } = await databaseServiceClient.listChangeHistories(
+ params
+ );
+ await upsertChangeHistoryListMap(parent, changeHistories);
+ return changeHistories;
+ };
+ const changeHistoryListByDatabase = (name: string) => {
+ return changeHistoryListMapByDatabase.get(name) ?? [];
+ };
+ const fetchChangeHistory = async (
+ params: Partial<GetChangeHistoryRequest>
+ ) => {
+ const changeHistory = await databaseServiceClient.getChangeHistory(params);
+ await upsertChangeHistoryMap([changeHistory]);
+ return changeHistory;
+ };
+ const getChangeHistoryByName = (name: string) => {
+ return changeHistoryMapByName.get(name);
+ };
+
+ return {
+ fetchChangeHistoryList,
+ changeHistoryListByDatabase,
+ fetchChangeHistory,
+ getChangeHistoryByName,
+ };
+});
diff --git a/frontend/src/store/modules/v1/database.ts b/frontend/src/store/modules/v1/database.ts
index 04f6ca3412..ab25c965fb 100644
--- a/frontend/src/store/modules/v1/database.ts
+++ b/frontend/src/store/modules/v1/database.ts
@@ -131,9 +131,10 @@ export const useDatabaseV1Store = defineStore("database_v1", () => {
return composed;
};
- const fetchDatabaseSchema = async (name: string) => {
+ const fetchDatabaseSchema = async (name: string, sdlFormat = false) => {
const schema = await databaseServiceClient.getDatabaseSchema({
name,
+ sdlFormat,
});
return schema;
};
diff --git a/frontend/src/store/modules/v1/index.ts b/frontend/src/store/modules/v1/index.ts
index a3197fa697..deac00b14f 100644
--- a/frontend/src/store/modules/v1/index.ts
+++ b/frontend/src/store/modules/v1/index.ts
@@ -13,3 +13,4 @@ export * from "./instance";
export * from "./subscription";
export * from "./actuator";
export * from "./repository";
+export * from "./changeHistory";
diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.ts
index bfcccca154..17b8dd8efd 100644
--- a/frontend/src/types/common.ts
+++ b/frontend/src/types/common.ts
@@ -60,7 +60,6 @@ export type RouterSlug = {
databaseSlug?: string;
tableName?: string;
dataSourceSlug?: string;
- migrationHistorySlug?: string;
vcsSlug?: string;
connectionSlug?: string;
sheetSlug?: string;
diff --git a/frontend/src/types/utils.ts b/frontend/src/types/utils.ts
index 7b6e68d30d..f50e288415 100644
--- a/frontend/src/types/utils.ts
+++ b/frontend/src/types/utils.ts
@@ -7,3 +7,5 @@ export type ValidatedMessage = {
type: "warning" | "error";
message: string;
};
+
+export type ArgumentsType<T> = T extends (...args: infer U) => any ? U : never;
diff --git a/frontend/src/utils/slug.ts b/frontend/src/utils/slug.ts
index 04426451ec..99c2b631ba 100644
--- a/frontend/src/utils/slug.ts
+++ b/frontend/src/utils/slug.ts
@@ -5,7 +5,6 @@ import {
Environment,
Instance,
IssueId,
- MigrationHistoryId,
Project,
VCS,
SQLReviewPolicy,
@@ -32,11 +31,6 @@ export function sheetNameFromSlug(slug: string): string {
.join("-")}/${sheetNamePrefix}${parts[parts.length - 1]}`;
}
-export function migrationHistoryIdFromSlug(slug: string): MigrationHistoryId {
- const parts = slug.split("-");
- return parts[parts.length - 1];
-}
-
export function indexFromSlug(slug: string): number {
const parts = slug.split("-");
return parseInt(parts[parts.length - 1]) - 1;
@@ -83,13 +77,6 @@ export function dataSourceSlug(dataSource: DataSource): string {
return [slug(dataSource.name), dataSource.id].join("-");
}
-export function migrationHistorySlug(
- migrationHistoryId: MigrationHistoryId,
- version: string
-): string {
- return [slug(version), migrationHistoryId].join("-");
-}
-
export function fullDatabasePath(database: Database): string {
return `/db/${databaseSlug(database)}`;
}
diff --git a/frontend/src/utils/task.ts b/frontend/src/utils/task.ts
index 4ee7b35837..c1d5d95a2a 100644
--- a/frontend/src/utils/task.ts
+++ b/frontend/src/utils/task.ts
@@ -16,7 +16,6 @@ import {
TaskDatabaseSchemaUpdateSDLPayload,
TaskStatus,
TaskType,
- unknown,
unknownDatabase,
} from "@/types";
import { issueSlug, stageSlug, taskSlug } from "./slug";
@@ -70,7 +69,7 @@ export const extractDatabaseNameFromTask = (
}
// Fallback to <<Unknown database>>. Won't be happy to see it.
- return unknown("DATABASE").name;
+ return unknownDatabase().databaseName;
};
export const buildIssueLinkWithTask = (
diff --git a/frontend/src/utils/util.ts b/frontend/src/utils/util.ts
index 0bb4902174..02ca38ad82 100644
--- a/frontend/src/utils/util.ts
+++ b/frontend/src/utils/util.ts
@@ -5,6 +5,7 @@ import relativeTime from "dayjs/plugin/relativeTime";
import utc from "dayjs/plugin/utc";
import { escapeRegExp, round } from "lodash-es";
import semver from "semver";
+import type { Duration } from "@/types/proto/google/protobuf/duration";
dayjs.extend(dayOfYear);
dayjs.extend(duration);
@@ -38,6 +39,19 @@ export function humanizeDuration(seconds: number): string {
return `${seconds}s`;
}
+export const humanizeDurationV1 = (
+ duration: Duration | undefined,
+ brief = true
+) => {
+ if (!duration) return "-";
+ const { seconds, nanos } = duration;
+ const total = seconds + nanos / 1e9;
+ if (brief && total <= 1) {
+ return "Less than 1s";
+ }
+ return total.toFixed(2) + "s";
+};
+
export function bytesToString(size: number): string {
const unitList = ["B", "KB", "MB", "GB", "TB"];
let i = 0;
diff --git a/frontend/src/utils/v1/changeHistory.ts b/frontend/src/utils/v1/changeHistory.ts
new file mode 100644
index 0000000000..ece6f12d64
--- /dev/null
+++ b/frontend/src/utils/v1/changeHistory.ts
@@ -0,0 +1,22 @@
+import slug from "slug";
+import { UNKNOWN_ID } from "@/types";
+import { ChangeHistory } from "@/types/proto/v1/database_service";
+import { extractDatabaseResourceName } from "./database";
+import { extractInstanceResourceName } from "./instance";
+
+export const extractChangeHistoryUID = (changeHistorySlug: string) => {
+ const parts = changeHistorySlug.split("-");
+ return parts[parts.length - 1] ?? String(UNKNOWN_ID);
+};
+
+export const changeHistorySlug = (uid: string, version: string): string => {
+ return [slug(version), uid].join("-");
+};
+
+export const changeHistoryLink = (changeHistory: ChangeHistory): string => {
+ const { name, uid, version } = changeHistory;
+ const { database } = extractDatabaseResourceName(name);
+ const instance = extractInstanceResourceName(name);
+ const parent = `instances/${instance}/databases/${database}`;
+ return `/${parent}/changeHistories/${changeHistorySlug(uid, version)}`;
+};
diff --git a/frontend/src/utils/v1/database.ts b/frontend/src/utils/v1/database.ts
index 62c8819233..acab44325f 100644
--- a/frontend/src/utils/v1/database.ts
+++ b/frontend/src/utils/v1/database.ts
@@ -16,7 +16,8 @@ import {
} from "@/store";
import { hasWorkspacePermissionV1 } from "../role";
import { Engine, State } from "@/types/proto/v1/common";
-import { semverCompare } from "../util";
+import { isDev, semverCompare } from "../util";
+import { DataSourceType } from "@/types/proto/v1/instance_service";
export const databaseV1Slug = (db: ComposedDatabase) => {
return [slug(db.databaseName), db.uid].join("-");
@@ -29,7 +30,7 @@ export const extractDatabaseResourceName = (
database: string;
} => {
const pattern =
- /^(?<instance>instances\/[^/]+)\/databases\/(?<database>[^/]+)$/;
+ /(?:^|\/)(?<instance>instances\/[^/]+)\/databases\/(?<database>[^/]+)(?:$|\/)/;
const matches = resource.match(pattern);
if (matches) {
const { instance = UNKNOWN_INSTANCE_NAME, database = "" } =
@@ -194,3 +195,34 @@ export function allowGhostMigrationV1(
);
});
}
+
+export function allowDatabaseV1Access(
+ database: ComposedDatabase,
+ user: User,
+ type: DataSourceType
+): boolean {
+ // "ADMIN" data source should only be used by the system, thus it shouldn't
+ // touch this method at all. If it touches somehow, we will reject it and
+ // log a warning
+ if (type === DataSourceType.ADMIN) {
+ if (isDev()) {
+ console.trace(
+ "Should not check database access against ADMIN connection"
+ );
+ } else {
+ console.warn("Should not check database access against ADMIN connection");
+ }
+ return false;
+ }
+
+ if (
+ hasWorkspacePermissionV1(
+ "bb.permission.workspace.manage-instance",
+ user.userRole
+ )
+ ) {
+ return true;
+ }
+
+ return false;
+}
diff --git a/frontend/src/utils/v1/index.ts b/frontend/src/utils/v1/index.ts
index f236c3b363..53c60ba6ef 100644
--- a/frontend/src/utils/v1/index.ts
+++ b/frontend/src/utils/v1/index.ts
@@ -12,3 +12,5 @@ export * from "./user";
export * from "./instance";
export * from "./sqlEditor";
export * from "./sheet";
+export * from "./review";
+export * from "./changeHistory";
diff --git a/frontend/src/utils/v1/review.ts b/frontend/src/utils/v1/review.ts
new file mode 100644
index 0000000000..050c709a44
--- /dev/null
+++ b/frontend/src/utils/v1/review.ts
@@ -0,0 +1,5 @@
+export const extractReviewId = (name: string) => {
+ const pattern = /(?:^|\/)reviews\/(\d+)(?:$|\/)/;
+ const matches = name.match(pattern);
+ return matches?.[1] ?? "";
+};
diff --git a/frontend/src/views/MigrationHistoryDetail.vue b/frontend/src/views/ChangeHistoryDetail.vue
similarity index 58%
rename from frontend/src/views/MigrationHistoryDetail.vue
rename to frontend/src/views/ChangeHistoryDetail.vue
index 36d865dae5..676e4bbf81 100644
--- a/frontend/src/views/MigrationHistoryDetail.vue
+++ b/frontend/src/views/ChangeHistoryDetail.vue
@@ -1,6 +1,6 @@
<template>
<div class="flex-1 overflow-auto focus:outline-none" tabindex="0">
- <main class="flex-1 relative pb-8 overflow-y-auto">
+ <main v-if="changeHistory" class="flex-1 relative pb-8 overflow-y-auto">
<!-- Highlight Panel -->
<div
class="px-4 pb-4 border-b border-block-border md:flex md:items-center md:justify-between"
@@ -8,14 +8,15 @@
<div class="flex-1 min-w-0 space-y-3">
<!-- Summary -->
<div class="pt-2 flex items-center space-x-2">
- <MigrationHistoryStatusIcon :status="migrationHistory.status" />
+ <ChangeHistoryStatusIcon :status="changeHistory.status" />
<h1 class="text-xl font-bold leading-6 text-main truncate">
- {{ $t("common.version") }} {{ migrationHistory.version }}
+ {{ $t("common.version") }} {{ changeHistory.version }}
</h1>
</div>
<p class="text-control">
- {{ migrationHistory.source }} {{ migrationHistory.type }} -
- {{ migrationHistory.description }}
+ {{ changeHistory_SourceToJSON(changeHistory.source) }}
+ {{ changeHistory_TypeToJSON(changeHistory.type) }} -
+ {{ changeHistory.description }}
</p>
<dl
class="flex flex-col space-y-1 md:space-y-0 md:flex-row md:flex-wrap"
@@ -26,10 +27,10 @@
>{{ $t("common.issue") }}&nbsp;-&nbsp;</span
>
<router-link
- :to="`/issue/${migrationHistory.issueId}`"
+ :to="`/issue/${extractReviewId(changeHistory.review)}`"
class="normal-link"
>
- {{ migrationHistory.issueId }}
+ {{ extractReviewId(changeHistory.review) }}
</router-link>
</dd>
<dt class="sr-only">{{ $t("common.duration") }}</dt>
@@ -37,58 +38,58 @@
<span class="textlabel"
>{{ $t("common.duration") }}&nbsp;-&nbsp;</span
>
- {{ nanosecondsToString(migrationHistory.executionDurationNs) }}
+ {{ humanizeDurationV1(changeHistory.executionDuration) }}
</dd>
<dt class="sr-only">{{ $t("common.creator") }}</dt>
- <dd class="flex items-center text-sm md:mr-4">
+ <dd v-if="creator" class="flex items-center text-sm md:mr-4">
<span class="textlabel"
>{{ $t("common.creator") }}&nbsp;-&nbsp;</span
>
- {{ migrationHistory.creator }}
+ {{ creator.title }}
</dd>
<dt class="sr-only">{{ $t("common.created-at") }}</dt>
<dd class="flex items-center text-sm md:mr-4">
<span class="textlabel"
>{{ $t("common.created-at") }}&nbsp;-&nbsp;</span
>
- {{ humanizeTs(migrationHistory.createdTs) }} by
- {{ `version ${migrationHistory.releaseVersion}` }}
+ {{ humanizeDate(changeHistory.createTime) }} by
+ {{ `version ${changeHistory.releaseVersion}` }}
</dd>
</dl>
<div
v-if="pushEvent"
class="mt-1 text-sm text-control-light flex flex-row items-center space-x-1"
>
- <template v-if="pushEvent?.vcsType.startsWith('GITLAB')">
- <img class="h-4 w-auto" src="../assets/gitlab-logo.svg" />
+ <template
+ v-if="vcsTypeToJSON(pushEvent?.vcsType).startsWith('GITLAB')"
+ >
+ <img class="h-4 w-auto" src="@/assets/gitlab-logo.svg" />
</template>
- <template v-if="pushEvent?.vcsType.startsWith('GITHUB')">
- <img class="h-4 w-auto" src="../assets/github-logo.svg" />
+ <template
+ v-if="vcsTypeToJSON(pushEvent?.vcsType).startsWith('GITHUB')"
+ >
+ <img class="h-4 w-auto" src="@/assets/github-logo.svg" />
</template>
- <template v-if="pushEvent?.vcsType.startsWith('BITBUCKET')">
- <img class="h-4 w-auto" src="../assets/bitbucket-logo.svg" />
+ <template
+ v-if="vcsTypeToJSON(pushEvent?.vcsType).startsWith('BITBUCKET')"
+ >
+ <img class="h-4 w-auto" src="@/assets/bitbucket-logo.svg" />
</template>
<a :href="vcsBranchUrl" target="_blank" class="normal-link">
{{ `${vcsBranch}@${pushEvent.repositoryFullPath}` }}
</a>
- <span>
+ <span v-if="vcsCommit">
{{ $t("common.commit") }}
- <a
- :href="pushEvent.fileCommit.url"
- target="_blank"
- class="normal-link"
- >
- {{ pushEvent.fileCommit.id.substring(0, 7) }}:
+ <a :href="vcsCommit.url" target="_blank" class="normal-link">
+ {{ vcsCommit.id.substring(0, 7) }}:
</a>
- <span class="text-main">{{ pushEvent.fileCommit.title }}</span>
+ <span class="text-main mr-1">{{ vcsCommit.title }}</span>
<i18n-t keypath="change-history.commit-info">
<template #author>
{{ pushEvent.authorName }}
</template>
<template #time>
- {{
- dayjs(pushEvent.fileCommit.createdTs * 1000).format("LLL")
- }}
+ {{ humanizeDate(vcsCommit.createdTime) }}
</template>
</i18n-t>
</span>
@@ -113,7 +114,7 @@
</a>
<highlight-code-block
class="border px-2 whitespace-pre-wrap w-full"
- :code="migrationHistory.statement"
+ :code="changeHistory.statement"
/>
<a
id="schema"
@@ -182,16 +183,16 @@
<code-diff
v-if="state.showDiff"
class="mt-4 w-full"
- :old-string="migrationHistory.schemaPrev"
- :new-string="migrationHistory.schema"
+ :old-string="changeHistory.prevSchema"
+ :new-string="changeHistory.schema"
output-format="side-by-side"
data-label="bb-change-history-code-diff-block"
/>
<template v-else>
<highlight-code-block
- v-if="migrationHistory.schema"
+ v-if="changeHistory.schema"
class="border mt-2 px-2 whitespace-pre-wrap w-full"
- :code="migrationHistory.schema"
+ :code="changeHistory.schema"
data-label="bb-change-history-code-block"
/>
<div v-else class="mt-2">
@@ -202,7 +203,7 @@
</main>
<BBModal
- v-if="previousHistory && state.viewDrift"
+ v-if="changeHistory && previousHistory && state.viewDrift"
@close="state.viewDrift = false"
>
<template #title>
@@ -221,7 +222,7 @@
<code-diff
class="w-full"
:old-string="previousHistory.schema"
- :new-string="migrationHistory.schema"
+ :new-string="changeHistory.schema"
output-format="side-by-side"
/>
<div class="flex justify-end px-4">
@@ -239,117 +240,136 @@
</template>
<script lang="ts" setup>
-import { computed, reactive, onMounted } from "vue";
+import { computed, reactive, watch } from "vue";
import { toClipboard } from "@soerenmartius/vue3-clipboard";
import { CodeDiff } from "v-code-diff";
-import MigrationHistoryStatusIcon from "../components/MigrationHistoryStatusIcon.vue";
import {
- idFromSlug,
- nanosecondsToString,
- migrationHistorySlug,
- migrationHistoryIdFromSlug,
-} from "../utils";
-import {
- MigrationHistory,
- MigrationHistoryPayload,
- VCSPushEvent,
-} from "../types";
+ changeHistoryLink,
+ extractChangeHistoryUID,
+ extractReviewId,
+ extractUserResourceName,
+} from "@/utils";
import {
pushNotification,
- useDatabaseV1ByUID,
- useLegacyInstanceStore,
+ useChangeHistoryStore,
+ useDatabaseV1Store,
+ useUserStore,
} from "@/store";
+import {
+ ChangeHistory,
+ ChangeHistory_Type,
+ changeHistory_SourceToJSON,
+ changeHistory_TypeToJSON,
+} from "@/types/proto/v1/database_service";
+import { PushEvent, VcsType, vcsTypeToJSON } from "@/types/proto/v1/vcs";
+import ChangeHistoryStatusIcon from "@/components/ChangeHistory/ChangeHistoryStatusIcon.vue";
interface LocalState {
showDiff: boolean;
viewDrift: boolean;
}
-const props = defineProps({
- databaseSlug: {
- required: true,
- type: String,
- },
- migrationHistorySlug: {
- required: true,
- type: String,
- },
-});
+const props = defineProps<{
+ instance: string;
+ database: string;
+ changeHistorySlug: string;
+}>();
-const legacyInstanceStore = useLegacyInstanceStore();
+const changeHistoryStore = useChangeHistoryStore();
-const { database } = useDatabaseV1ByUID(
- computed(() => String(idFromSlug(props.databaseSlug)))
-);
-
-const migrationHistoryId = migrationHistoryIdFromSlug(
- props.migrationHistorySlug
-);
-
-onMounted(() => {
- legacyInstanceStore.fetchMigrationHistory({
- instanceId: Number(database.value.instanceEntity.uid),
- databaseName: database.value.databaseName,
- });
+const changeHistoryParent = computed(() => {
+ return `instances/${props.instance}/databases/${props.database}`;
+});
+const changeHistoryUID = computed(() => {
+ return extractChangeHistoryUID(props.changeHistorySlug);
+});
+const changeHistoryName = computed(() => {
+ return `${changeHistoryParent.value}/changeHistories/${changeHistoryUID.value}`;
});
-// get all migration histories before (include) the one of given id, ordered by descending version.
-const prevMigrationHistoryList = computed((): MigrationHistory[] => {
- const migrationHistoryList =
- legacyInstanceStore.getMigrationHistoryListByInstanceIdAndDatabaseName(
- Number(database.value.instanceEntity.uid),
- database.value.databaseName
- );
+watch(
+ changeHistoryParent,
+ (parent) => {
+ useDatabaseV1Store().getOrFetchDatabaseByName(parent);
+ changeHistoryStore.fetchChangeHistoryList({
+ parent,
+ });
+ },
+ { immediate: true }
+);
+watch(
+ changeHistoryName,
+ (name) => {
+ changeHistoryStore.fetchChangeHistory({
+ name,
+ });
+ },
+ { immediate: true }
+);
- // If migrationHistoryList does not contain current migration, it indicates cache stale.
- // Dispatch a fetch. When new data is returned, it will update computed value.
- if (migrationHistoryList.every((mh) => mh.id !== migrationHistoryId)) {
- legacyInstanceStore.fetchInstanceList();
- }
+// get all change histories before (include) the one of given id, ordered by descending version.
+const prevChangeHistoryList = computed(() => {
+ const changeHistoryList = changeHistoryStore.changeHistoryListByDatabase(
+ changeHistoryParent.value
+ );
- // The returned migration history list has been ordered by `id` DESC or (`namespace` ASC, `sequence` DESC) .
- // We can obtain prevMigrationHistoryList by cutting up the array by the `migrationHistoryId`.
- const idx = migrationHistoryList.findIndex(
- (mh) => mh.id === migrationHistoryId
+ // The returned change history list has been ordered by `id` DESC or (`namespace` ASC, `sequence` DESC) .
+ // We can obtain prevChangeHistoryList by cutting up the array by the `changeHistoryId`.
+ const idx = changeHistoryList.findIndex(
+ (history) => history.uid === changeHistoryUID.value
);
if (idx === -1) {
return [];
}
- return migrationHistoryList.slice(idx);
+ return changeHistoryList.slice(idx);
});
-// migrationHistory is the latest migration NOW.
-const migrationHistory = computed((): MigrationHistory => {
- if (prevMigrationHistoryList.value.length > 0) {
- return prevMigrationHistoryList.value[0];
+// changeHistory is the latest migration NOW.
+const changeHistory = computed((): ChangeHistory | undefined => {
+ if (prevChangeHistoryList.value.length > 0) {
+ return prevChangeHistoryList.value[0];
}
- return legacyInstanceStore.getMigrationHistoryById(migrationHistoryId)!;
+ return changeHistoryStore.getChangeHistoryByName(changeHistoryName.value)!;
});
-// previousHistory is the last migration history before the one of given id.
+// previousHistory is the last change history before the one of given id.
// Only referenced if hasDrift is true.
-const previousHistory = computed((): MigrationHistory | undefined => {
- return prevMigrationHistoryList.value[1];
+const previousHistory = computed((): ChangeHistory | undefined => {
+ return prevChangeHistoryList.value[1];
});
// "Show diff" feature is enabled when current migration has changed the schema.
const allowShowDiff = computed((): boolean => {
- return migrationHistory.value.schema !== migrationHistory.value.schemaPrev;
+ if (!changeHistory.value) {
+ return false;
+ }
+ return changeHistory.value.schema !== changeHistory.value.prevSchema;
});
// A schema drift is detected when the schema AFTER previousHistory has been
-// changed unexpectedly BEFORE current migrationHistory.
+// changed unexpectedly BEFORE current changeHistory.
const hasDrift = computed((): boolean => {
- if (migrationHistory.value.type === "BASELINE") {
+ if (!changeHistory.value) {
+ return false;
+ }
+ if (changeHistory.value.type === ChangeHistory_Type.BASELINE) {
return false;
}
return (
- prevMigrationHistoryList.value.length > 1 && // no drift if no previous migration history
- previousHistory.value?.schema !== migrationHistory.value.schemaPrev
+ prevChangeHistoryList.value.length > 1 && // no drift if no previous change history
+ previousHistory.value?.schema !== changeHistory.value.prevSchema
);
});
+const creator = computed(() => {
+ if (!changeHistory.value) {
+ return undefined;
+ }
+ const email = extractUserResourceName(changeHistory.value.creator);
+ return useUserStore().getUserByEmail(email);
+});
+
const state = reactive<LocalState>({
showDiff: allowShowDiff.value, // "Show diff" is turned on by default if available.
viewDrift: false,
@@ -358,22 +378,31 @@ const state = reactive<LocalState>({
const previousHistoryLink = computed(() => {
const previous = previousHistory.value;
if (!previous) return "";
- return `/db/${props.databaseSlug}/history/${migrationHistorySlug(
- previous.id,
- previous.version
- )}`;
+ return changeHistoryLink(previous);
});
-const pushEvent = computed((): VCSPushEvent | undefined => {
- return (migrationHistory.value.payload as MigrationHistoryPayload)?.pushEvent;
+const pushEvent = computed((): PushEvent | undefined => {
+ return changeHistory.value?.pushEvent;
+});
+
+const vcsCommit = computed(() => {
+ const fileCommit = pushEvent.value?.fileCommit;
+ if (fileCommit && fileCommit.id) {
+ return fileCommit;
+ }
+ const commit = pushEvent.value?.commits[0];
+ if (commit && commit.id) {
+ return commit;
+ }
+ return undefined;
});
const vcsBranch = computed((): string => {
if (pushEvent.value) {
if (
- pushEvent.value.vcsType == "GITLAB" ||
- pushEvent.value.vcsType == "GITHUB" ||
- pushEvent.value.vcsType == "BITBUCKET"
+ pushEvent.value.vcsType === VcsType.GITLAB ||
+ pushEvent.value.vcsType === VcsType.GITHUB ||
+ pushEvent.value.vcsType === VcsType.BITBUCKET
) {
const parts = pushEvent.value.ref.split("/");
return parts[parts.length - 1];
@@ -384,11 +413,11 @@ const vcsBranch = computed((): string => {
const vcsBranchUrl = computed((): string => {
if (pushEvent.value) {
- if (pushEvent.value.vcsType == "GITLAB") {
+ if (pushEvent.value.vcsType === VcsType.GITLAB) {
return `${pushEvent.value.repositoryUrl}/-/tree/${vcsBranch.value}`;
- } else if (pushEvent.value.vcsType == "GITHUB") {
+ } else if (pushEvent.value.vcsType === VcsType.GITHUB) {
return `${pushEvent.value.repositoryUrl}/tree/${vcsBranch.value}`;
- } else if (pushEvent.value.vcsType == "BITBUCKET") {
+ } else if (pushEvent.value.vcsType === VcsType.BITBUCKET) {
return `${pushEvent.value.repositoryUrl}/src/${vcsBranch.value}`;
}
}
@@ -396,7 +425,10 @@ const vcsBranchUrl = computed((): string => {
});
const copyStatement = () => {
- toClipboard(migrationHistory.value.statement).then(() => {
+ if (!changeHistory.value) {
+ return false;
+ }
+ toClipboard(changeHistory.value.statement).then(() => {
pushNotification({
module: "bytebase",
style: "INFO",
@@ -406,7 +438,10 @@ const copyStatement = () => {
};
const copySchema = () => {
- toClipboard(migrationHistory.value.schema).then(() => {
+ if (!changeHistory.value) {
+ return false;
+ }
+ toClipboard(changeHistory.value.schema).then(() => {
pushNotification({
module: "bytebase",
style: "INFO",
diff --git a/frontend/src/views/DatabaseDashboard.vue b/frontend/src/views/DatabaseDashboard.vue
index 5489fbff1f..79371e204a 100644
--- a/frontend/src/views/DatabaseDashboard.vue
+++ b/frontend/src/views/DatabaseDashboard.vue
@@ -89,7 +89,6 @@ import {
} from "../utils";
import {
useCurrentUserV1,
- useLegacyDatabaseStore,
useDBGroupStore,
useDatabaseV1Store,
useEnvironmentV1Store,
@@ -118,7 +117,6 @@ const state = reactive<LocalState>({
});
const currentUserV1 = useCurrentUserV1();
-const databaseStore = useLegacyDatabaseStore();
const databaseV1Store = useDatabaseV1Store();
const dbGroupStore = useDBGroupStore();
@@ -153,9 +151,6 @@ const prepareDatabaseList = async () => {
parent: "instances/-",
});
state.databaseV1List = sortDatabaseV1List(databaseV1List);
-
- // For legacy support
- await databaseStore.fetchDatabaseList();
state.loading = false;
}
};
diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vue
index c8222148e0..936dcf51c2 100644
--- a/frontend/src/views/DatabaseDetail.vue
+++ b/frontend/src/views/DatabaseDetail.vue
@@ -157,7 +157,7 @@
<DatabaseOverviewPanel :database="database" />
</template>
<template v-if="selectedTabItem?.hash === 'change-history'">
- <DatabaseMigrationHistoryPanel
+ <DatabaseChangeHistoryPanel
:database="database"
:allow-edit="allowEdit"
/>
@@ -250,7 +250,7 @@ import { useI18n } from "vue-i18n";
import { startCase } from "lodash-es";
import DatabaseBackupPanel from "@/components/DatabaseBackupPanel.vue";
-import DatabaseMigrationHistoryPanel from "@/components/DatabaseMigrationHistoryPanel.vue";
+import DatabaseChangeHistoryPanel from "@/components/DatabaseChangeHistoryPanel.vue";
import DatabaseOverviewPanel from "@/components/DatabaseOverviewPanel.vue";
import DatabaseSlowQueryPanel from "@/components/DatabaseSlowQueryPanel.vue";
import {
diff --git a/frontend/src/views/InstanceDetail.vue b/frontend/src/views/InstanceDetail.vue
index d1fe6af005..5eb64bbd52 100644
--- a/frontend/src/views/InstanceDetail.vue
+++ b/frontend/src/views/InstanceDetail.vue
@@ -130,7 +130,6 @@ import { SQLResultSet } from "@/types";
import {
featureToRef,
pushNotification,
- useLegacyInstanceStore,
useSubscriptionV1Store,
useSQLStore,
useDBSchemaStore,
@@ -155,7 +154,6 @@ const props = defineProps({
},
});
-const instanceStore = useLegacyInstanceStore();
const instanceV1Store = useInstanceV1Store();
const databaseStore = useDatabaseV1Store();
const subscriptionStore = useSubscriptionV1Store();
@@ -234,8 +232,6 @@ const allowArchiveOrRestore = computed(() => {
const doArchive = async () => {
await useGracefulRequest(async () => {
await instanceV1Store.archiveInstance(instance.value);
- // Legacy compatibility
- await instanceStore.fetchInstanceById(Number(instance.value.uid));
pushNotification({
module: "bytebase",
@@ -255,8 +251,6 @@ const doRestore = async () => {
}
await useGracefulRequest(async () => {
await instanceV1Store.restoreInstance(instance.value);
- // Legacy compatibility
- await instanceStore.fetchInstanceById(Number(instance.value.uid));
pushNotification({
module: "bytebase",
diff --git a/frontend/src/views/ProjectDetail.vue b/frontend/src/views/ProjectDetail.vue
index e0771c4e50..52eb0019c0 100644
--- a/frontend/src/views/ProjectDetail.vue
+++ b/frontend/src/views/ProjectDetail.vue
@@ -16,7 +16,7 @@
<ProjectDatabaseGroupPanel :project="projectV1" />
</template>
<template v-if="hash === 'change-history'">
- <ProjectMigrationHistoryPanel
+ <ProjectChangeHistoryPanel
id="change-history"
:database-list="databaseV1List"
/>
@@ -57,13 +57,13 @@
</template>
<script lang="ts" setup>
-import { computed, watchEffect } from "vue";
+import { computed } from "vue";
import { useRoute } from "vue-router";
import { DEFAULT_PROJECT_ID } from "@/types";
import { idFromSlug, sortDatabaseV1List } from "../utils";
import ProjectActivityPanel from "../components/ProjectActivityPanel.vue";
-import ProjectMigrationHistoryPanel from "../components/ProjectMigrationHistoryPanel.vue";
+import ProjectChangeHistoryPanel from "../components/ProjectChangeHistoryPanel.vue";
import ProjectSlowQueryPanel from "../components/ProjectSlowQueryPanel.vue";
import ProjectOverviewPanel from "../components/ProjectOverviewPanel.vue";
import ProjectDatabasesPanel from "../components/ProjectDatabasesPanel.vue";
@@ -72,7 +72,6 @@ import ProjectWebhookPanel from "../components/ProjectWebhookPanel.vue";
import ProjectSettingPanel from "../components/ProjectSettingPanel.vue";
import ProjectDeploymentConfigPanel from "../components/ProjectDeploymentConfigPanel.vue";
import {
- useLegacyDatabaseStore,
useSearchDatabaseV1List,
useDatabaseV1Store,
useLegacyProjectStore,
@@ -97,7 +96,6 @@ const props = defineProps({
});
const route = useRoute();
-const legacyDatabaseStore = useLegacyDatabaseStore();
const projectStore = useLegacyProjectStore();
const projectV1Store = useProjectV1Store();
@@ -110,12 +108,6 @@ const projectV1 = computed(() => {
return projectV1Store.getProjectByUID(String(idFromSlug(props.projectSlug)));
});
-const prepareLegacyDatabaseList = () => {
- legacyDatabaseStore.fetchDatabaseListByProjectId(String(project.value.id));
-};
-
-watchEffect(prepareLegacyDatabaseList);
-
useSearchDatabaseV1List(
computed(() => ({
parent: "instances/-",
diff --git a/frontend/src/views/SyncDatabaseSchema/SelectTargetDatabasesView.vue b/frontend/src/views/SyncDatabaseSchema/SelectTargetDatabasesView.vue
index fdf5d745fe..190d961b21 100644
--- a/frontend/src/views/SyncDatabaseSchema/SelectTargetDatabasesView.vue
+++ b/frontend/src/views/SyncDatabaseSchema/SelectTargetDatabasesView.vue
@@ -31,17 +31,12 @@
>{{ sourceDatabase.databaseName }}</a
>
</div>
- <div v-if="!isEqual(sourceSchema.migrationHistory.id, UNKNOWN_ID)">
+ <div v-if="sourceSchema.changeHistory.uid !== String(UNKNOWN_ID)">
<span>{{ $t("database.sync-schema.schema-version.self") }} - </span>
<a
class="normal-link inline-flex items-center"
- :href="`/db/${databaseV1Slug(
- sourceDatabase
- )}/history/${migrationHistorySlug(
- sourceSchema.migrationHistory.id,
- sourceSchema.migrationHistory.version
- )}`"
- >{{ sourceSchema.migrationHistory.version }}</a
+ :href="changeHistoryLink(sourceSchema.changeHistory)"
+ >{{ sourceSchema.changeHistory.version }}</a
>
</div>
</div>
@@ -198,7 +193,7 @@
<script lang="ts" setup>
import { toClipboard } from "@soerenmartius/vue3-clipboard";
import axios from "axios";
-import { head, isEqual } from "lodash-es";
+import { head } from "lodash-es";
import { NEllipsis } from "naive-ui";
import {
PropType,
@@ -216,17 +211,18 @@ import {
useEnvironmentV1Store,
useProjectV1ByUID,
} from "@/store";
-import { ComposedDatabase, MigrationHistory, UNKNOWN_ID } from "@/types";
-import { databaseV1Slug, migrationHistorySlug, projectV1Slug } from "@/utils";
+import { ComposedDatabase, UNKNOWN_ID } from "@/types";
+import { changeHistoryLink, databaseV1Slug, projectV1Slug } from "@/utils";
import TargetDatabasesSelectPanel from "./TargetDatabasesSelectPanel.vue";
import DiffViewPanel from "./DiffViewPanel.vue";
import { Engine, engineToJSON } from "@/types/proto/v1/common";
import { InstanceV1EngineIcon } from "@/components/v2";
+import { ChangeHistory } from "@/types/proto/v1/database_service";
interface SourceSchema {
environmentId: string;
databaseId: string;
- migrationHistory: MigrationHistory;
+ changeHistory: ChangeHistory;
}
interface LocalState {
@@ -280,7 +276,7 @@ const sourceDatabase = computed(() => {
return databaseStore.getDatabaseByUID(props.sourceSchema.databaseId);
});
const sourceDatabaseSchema = computed(() => {
- return props.sourceSchema.migrationHistory.schema || "";
+ return props.sourceSchema.changeHistory.schema || "";
});
const targetDatabaseList = computed(() => {
return state.selectedDatabaseIdList.map((id) => {
diff --git a/frontend/src/views/SyncDatabaseSchema/index.vue b/frontend/src/views/SyncDatabaseSchema/index.vue
index 7b528416a2..cdbea5fe48 100644
--- a/frontend/src/views/SyncDatabaseSchema/index.vue
+++ b/frontend/src/views/SyncDatabaseSchema/index.vue
@@ -76,13 +76,13 @@
>
<BBSelect
class="w-full"
- :selected-item="state.sourceSchema.migrationHistory"
+ :selected-item="state.sourceSchema.changeHistory"
:item-list="
- databaseMigrationHistoryList(state.sourceSchema.databaseId as string)
+ databaseChangeHistoryList(state.sourceSchema.databaseId as string)
"
:placeholder="$t('change-history.select')"
- :show-prefix-item="databaseMigrationHistoryList(state.sourceSchema.databaseId as string).length > 0"
- @select-item="(migrationHistory: MigrationHistory) => handleSchemaVersionSelect(migrationHistory)"
+ :show-prefix-item="databaseChangeHistoryList(state.sourceSchema.databaseId as string).length > 0"
+ @select-item="(changeHistory: ChangeHistory) => handleSchemaVersionSelect(changeHistory)"
>
<template #menuItem="{ item: migrationHistory }">
<div class="flex justify-between mr-2">
@@ -141,16 +141,20 @@ import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import {
hasFeature,
+ useChangeHistoryStore,
useDatabaseV1Store,
- useLegacyInstanceStore,
useProjectV1Store,
} from "@/store";
-import { MigrationHistory, MigrationType, UNKNOWN_ID } from "@/types";
+import { UNKNOWN_ID } from "@/types";
import DatabaseSelect from "@/components/DatabaseSelect.vue";
import SelectTargetDatabasesView from "./SelectTargetDatabasesView.vue";
import { Engine } from "@/types/proto/v1/common";
import { InstanceV1EngineIcon } from "@/components/v2";
import { instanceV1Name } from "@/utils";
+import {
+ ChangeHistory,
+ ChangeHistory_Type,
+} from "@/types/proto/v1/database_service";
const SELECT_SOURCE_DATABASE = 0;
const SELECT_TARGET_DATABASE_LIST = 1;
@@ -160,7 +164,7 @@ type Step = typeof SELECT_SOURCE_DATABASE | typeof SELECT_TARGET_DATABASE_LIST;
interface SourceSchema {
environmentId?: string;
databaseId?: string;
- migrationHistory?: MigrationHistory;
+ changeHistory?: ChangeHistory;
}
interface LocalState {
@@ -171,18 +175,18 @@ interface LocalState {
}
const allowedEngineTypeList: Engine[] = [Engine.MYSQL, Engine.POSTGRES];
-const allowedMigrationTypeList: MigrationType[] = [
- "BASELINE",
- "MIGRATE",
- "BRANCH",
+const allowedMigrationTypeList: ChangeHistory_Type[] = [
+ ChangeHistory_Type.BASELINE,
+ ChangeHistory_Type.MIGRATE,
+ ChangeHistory_Type.BRANCH,
];
const { t } = useI18n();
const router = useRouter();
const dialog = useDialog();
const projectStore = useProjectV1Store();
-const legacyInstanceStore = useLegacyInstanceStore();
const databaseStore = useDatabaseV1Store();
+const changeHistoryStore = useChangeHistoryStore();
const targetDatabaseViewRef =
ref<InstanceType<typeof SelectTargetDatabasesView>>();
const state = reactive<LocalState>({
@@ -198,8 +202,8 @@ const hasSyncSchemaFeature = computed(() => {
const shouldShowMoreVersionButton = computed(() => {
return (
!hasSyncSchemaFeature.value &&
- databaseMigrationHistoryList(state.sourceSchema.databaseId as string)
- .length > 0
+ databaseChangeHistoryList(state.sourceSchema.databaseId as string).length >
+ 0
);
});
@@ -215,7 +219,7 @@ const allowNext = computed(() => {
return (
isValidId(state.sourceSchema.environmentId) &&
isValidId(state.sourceSchema.databaseId) &&
- !isUndefined(state.sourceSchema.migrationHistory)
+ !isUndefined(state.sourceSchema.changeHistory)
);
} else {
if (!targetDatabaseViewRef.value) {
@@ -235,15 +239,12 @@ const allowNext = computed(() => {
}
});
-const databaseMigrationHistoryList = (databaseId: string) => {
+const databaseChangeHistoryList = (databaseId: string) => {
const database = databaseStore.getDatabaseByUID(databaseId);
- const list = legacyInstanceStore
- .getMigrationHistoryListByInstanceIdAndDatabaseName(
- Number(database.instanceEntity.uid),
- database.databaseName
- )
- .filter((migrationHistory) =>
- allowedMigrationTypeList.includes(migrationHistory.type)
+ const list = changeHistoryStore
+ .changeHistoryListByDatabase(database.name)
+ .filter((changeHistory) =>
+ allowedMigrationTypeList.includes(changeHistory.type)
);
if (!hasSyncSchemaFeature.value) {
@@ -278,8 +279,8 @@ const handleSourceDatabaseSelect = async (databaseId: string) => {
}
};
-const handleSchemaVersionSelect = (migrationHistory: MigrationHistory) => {
- state.sourceSchema.migrationHistory = migrationHistory;
+const handleSchemaVersionSelect = (changeHistory: ChangeHistory) => {
+ state.sourceSchema.changeHistory = changeHistory;
};
const isValidId = (id: any): id is string => {
@@ -386,39 +387,37 @@ watch(
async () => {
const databaseId = state.sourceSchema.databaseId;
if (!isValidId(databaseId)) {
- state.sourceSchema.migrationHistory = undefined;
+ state.sourceSchema.changeHistory = undefined;
return;
}
const database = databaseStore.getDatabaseByUID(databaseId);
if (database) {
- const migrationHistoryList = (
- await legacyInstanceStore.fetchMigrationHistory({
- instanceId: database.instanceEntity.uid,
- databaseName: database.databaseName,
+ const changeHistoryList = (
+ await changeHistoryStore.fetchChangeHistoryList({
+ parent: database.name,
})
- ).filter((migrationHistory) =>
- allowedMigrationTypeList.includes(migrationHistory.type)
+ ).filter((changeHistory) =>
+ allowedMigrationTypeList.includes(changeHistory.type)
);
- if (migrationHistoryList.length > 0) {
+ if (changeHistoryList.length > 0) {
// Default select the first migration history.
- state.sourceSchema.migrationHistory = head(migrationHistoryList);
+ state.sourceSchema.changeHistory = head(changeHistoryList);
} else {
// If database has no migration history, we will use its latest schema.
- const schema = await databaseStore.fetchDatabaseSchema(
- `${database.name}/schema`
- );
- state.sourceSchema.migrationHistory = {
- id: UNKNOWN_ID,
- updatedTs: Date.now() / 1000,
+ const schema = await databaseStore.fetchDatabaseSchema(database.name);
+ state.sourceSchema.changeHistory = {
+ name: `${database.name}/changeHistories/${UNKNOWN_ID}`,
+ uid: String(UNKNOWN_ID),
+ updateTime: new Date(),
schema: schema.schema,
version: "Latest version",
description: "the latest schema of database",
- } as any as MigrationHistory;
+ } as ChangeHistory;
}
} else {
- state.sourceSchema.migrationHistory = undefined;
+ state.sourceSchema.changeHistory = undefined;
}
}
);