Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(frontend): PITR create issue (#1299)
Liu Ji6df5c323604c
diff --git a/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue b/frontend/src/components/DatabaseDetail/PITRRestoreButton.vuenew file mode 100644index 0000000000..dce431d0a0--- /dev/null+++ b/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue@@ -0,0 +1,168 @@+<template>+ <BBTooltipButton+ type="normal"+ tooltip-mode="DISABLED-ONLY"+ :disabled="!allowAdmin || !pitrAvailable"+ @click="state.showDatabasePITRModal = true"+ >+ {{ $t("common.restore") }}+ <template v-if="allowAdmin && !pitrAvailable" #tooltip>+ {{ $t("database.pitr.no-available-backup") }}+ </template>+ </BBTooltipButton>++ <BBModal+ v-if="state.showDatabasePITRModal"+ :title="$t('database.pitr.restore')"+ @close="state.showDatabasePITRModal = false"+ >+ <div class="w-112 flex flex-col items-center gap-4">+ <div class="w-full textinfolabel">+ <i18n-t keypath="database.pitr.help-info" tag="p">+ <template #link>+ <a+ class="normal-link inline-flex items-center"+ href="https://github.com/bytebase/bytebase/blob/main/docs/design/pitr-mysql.md"+ >+ {{ $t("common.learn-more") }}+ </a>+ </template>+ </i18n-t>+ </div>++ <div class="w-64 space-y-2">+ <label class="textlabel w-full flex flex-col gap-1">+ <span>{{ $t("database.pitr.point-in-time") }}</span>+ <span class="text-gray-400 text-xs">{{ timezone }}</span>+ </label>+ <!--+ Displaying an input box and a popover date picker panel is somehow+ awkward here.+ But it's impossible to use NDatePicker only as a panel by now.+ I've sent the feature request to the author.+ -->+ <NDatePicker+ v-model:value="state.pitrTimestampMS"+ type="datetime"+ :is-date-disabled="isDateDisabled"+ :actions="['confirm']"+ />+ </div>++ <div+ class="w-full pt-6 mt-6 flex justify-end border-t border-block-border"+ >+ <button+ type="button"+ class="btn-normal py-2 px-4"+ @click.prevent="resetUI"+ >+ {{ $t("common.cancel") }}+ </button>+ <button+ type="button"+ class="btn-primary ml-3 inline-flex justify-center py-2 px-4"+ @click.prevent="onConfirm"+ >+ {{ $t("common.confirm") }}+ </button>+ </div>++ <div+ v-if="state.loading"+ class="absolute inset-0 z-10 bg-white/70 flex items-center justify-center"+ >+ <BBSpin />+ </div>+ </div>+ </BBModal>+</template>++<script lang="ts" setup>+import { computed, PropType, reactive } from "vue";+import { useRouter } from "vue-router";+import { NDatePicker } from "naive-ui";+import dayjs from "dayjs";+import { Database } from "@/types";+import { usePITRLogic } from "@/plugins";+import { issueSlug } from "@/utils";++interface LocalState {+ showDatabasePITRModal: boolean;+ pitrTimestampMS: number;+ loading: boolean;+}++const props = defineProps({+ allowAdmin: {+ type: Boolean,+ require: true,+ },+ database: {+ type: Object as PropType<Database>,+ required: true,+ },+});++const router = useRouter();++const state = reactive<LocalState>({+ showDatabasePITRModal: false,+ pitrTimestampMS: Date.now(),+ loading: false,+});++const timezone = computed(() => "UTC" + dayjs().format("ZZ"));++const { pitrAvailable, doneBackupList, createPITRIssue } = usePITRLogic(+ computed(() => props.database)+);++const earliest = computed(() => {+ if (!pitrAvailable.value) {+ return Infinity;+ }+ const timestamps = doneBackupList.value.map((backup) => backup.createdTs);+ const earliestAllowedRestoreTS = Math.min(...timestamps);+ return dayjs(earliestAllowedRestoreTS * 1000);+});++const isDateDisabled = (tsInMS: number) => {+ const date = dayjs(tsInMS);+ if (date.isBefore(earliest.value, "day")) {+ return true;+ }+ const now = dayjs();+ if (date.isAfter(now, "day")) {+ return true;+ }+ return false;+};++const resetUI = () => {+ state.loading = false;+ state.showDatabasePITRModal = false;+ state.pitrTimestampMS = Date.now();+};++const onConfirm = async () => {+ state.loading = true;++ try {+ const issue = await createPITRIssue(+ Math.floor(state.pitrTimestampMS / 1000),+ {+ name: `Restore database [${props.database.name}] to [${dayjs(+ state.pitrTimestampMS+ ).format("YYYY-MM-DD HH:mm:ss")} ${timezone.value}]`,+ }+ );+ const slug = issueSlug(issue.name, issue.id);+ router.push(`/issue/${slug}`);+ } catch (ex) {+ // TODO: error handling+ } finally {+ resetUI();+ }+};+</script>diff --git a/frontend/src/components/DatabaseDetail/index.ts b/frontend/src/components/DatabaseDetail/index.tsnew file mode 100644index 0000000000..dbfa16d166--- /dev/null+++ b/frontend/src/components/DatabaseDetail/index.ts@@ -0,0 +1,3 @@+import PITRRestoreButton from "./PITRRestoreButton.vue";++export { PITRRestoreButton };diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 22dd1bd014..547aa9c4a2 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -792,7 +792,13 @@"indexes": "Indexes","row-count-est": "Row count est.","incorrect-project-warning": "SQL editor can only query databases in projects available to the user. You should first transfer this database into a project.",- "go-to-transfer": "Go to transfer"+ "go-to-transfer": "Go to transfer",+ "pitr": {+ "restore": "@:common.restore @:common.database",+ "no-available-backup": "No available backup",+ "point-in-time": "Point in time",+ "help-info": "Restore the database state to a point in time. {link}."+ }},"repository": {"branch-observe-file-change": "The branch where Bytebase observes the file change.",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex b1066c62b0..4ec61d97a8 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -792,7 +792,13 @@"indexes": "索引","row-count-est": "估计行数","incorrect-project-warning": "SQL 编辑器只能查询用户可用的项目中的数据库。您应该首先将此数据库转移到一个可用的项目中。",- "go-to-transfer": "前去转移"+ "go-to-transfer": "前去转移",+ "pitr": {+ "restore": "@:common.restore@:common.database",+ "no-available-backup": "没有可用的备份",+ "point-in-time": "时间点",+ "help-info": "将数据库的状态恢复到一个时间点。{link}。"+ }},"repository": {"branch-observe-file-change": "Bytebase 跟踪文件变更的分支。",diff --git a/frontend/src/plugins/index.ts b/frontend/src/plugins/index.tsindex c86ac25fba..61b384d73c 100644--- a/frontend/src/plugins/index.ts+++ b/frontend/src/plugins/index.ts@@ -1,2 +1,3 @@export * from "./issue/template";export * from "./types";+export * from "./pitr";diff --git a/frontend/src/plugins/pitr/index.ts b/frontend/src/plugins/pitr/index.tsnew file mode 100644index 0000000000..b5abf600b7--- /dev/null+++ b/frontend/src/plugins/pitr/index.ts@@ -0,0 +1,48 @@+import { computed, Ref } from "vue";+import { Database, IssueCreate, PITRContext, SYSTEM_BOT_ID } from "@/types";+import { useBackupListByDatabaseId, useIssueStore } from "@/store";++export const usePITRLogic = (database: Ref<Database>) => {+ const backupList = useBackupListByDatabaseId(+ computed(() => database.value.id)+ );+ const doneBackupList = computed(() =>+ backupList.value.filter((backup) => backup.status === "DONE")+ );++ const pitrAvailable = computed(() => doneBackupList.value.length > 0);++ const createPITRIssue = async (+ pointTimeTs: number,+ params: Partial<IssueCreate> = {}+ ) => {+ const issueStore = useIssueStore();+ const createContext: PITRContext = {+ databaseId: database.value.id,+ pointInTimeTs: pointTimeTs,+ };+ const issueCreate: IssueCreate = {+ name: `Restore database [${database.value.name}]`,+ type: "bb.issue.database.pitr",+ description: "",+ assigneeId: SYSTEM_BOT_ID,+ projectId: database.value.project.id,+ payload: {},+ createContext,+ ...params,+ };++ await issueStore.validateIssue(issueCreate);++ const issue = await issueStore.createIssue(issueCreate);++ return issue;+ };++ return {+ backupList,+ doneBackupList,+ pitrAvailable,+ createPITRIssue,+ };+};diff --git a/frontend/src/store/modules/backup.ts b/frontend/src/store/modules/backup.tsindex 62a864a077..c60e9cf4c7 100644--- a/frontend/src/store/modules/backup.ts+++ b/frontend/src/store/modules/backup.ts@@ -1,3 +1,4 @@+import { computed, Ref, watchEffect } from "vue";import { defineStore } from "pinia";import axios from "axios";import {@@ -12,6 +13,7 @@ import {unknown,} from "@/types";import { getPrincipalFromIncludedList } from "./principal";+import { useAuthStore } from "./auth";export function convertBackup(backup: ResourceObject,@@ -193,3 +195,16 @@ export const useBackupStore = defineStore("backup", {},},});++export const useBackupListByDatabaseId = (databaseId: Ref<DatabaseId>) => {+ const store = useBackupStore();+ const authStore = useAuthStore();+ watchEffect(() => {+ if (!authStore.isLoggedIn()) {+ return;+ }+ store.fetchBackupListByDatabaseId(databaseId.value);+ });++ return computed(() => store.backupListByDatabaseId(databaseId.value));+};diff --git a/frontend/src/types/issue.ts b/frontend/src/types/issue.tsindex 1bfd5cb477..e30c7dee67 100644--- a/frontend/src/types/issue.ts+++ b/frontend/src/types/issue.ts@@ -18,7 +18,8 @@ type IssueTypeDatabase =| "bb.issue.database.grant"| "bb.issue.database.schema.update"| "bb.issue.database.data.update"- | "bb.issue.database.schema.update.ghost";+ | "bb.issue.database.schema.update.ghost"+ | "bb.issue.database.pitr";type IssueTypeDataSource = "bb.issue.data-source.request";@@ -60,6 +61,11 @@ export type UpdateSchemaGhostContext = {updateSchemaDetailList: UpdateSchemaGhostDetail[];};+export type PITRContext = {+ databaseId: DatabaseId;+ pointInTimeTs: number; // UNIX timestamp+};+// eslint-disable-next-line @typescript-eslint/ban-typesexport type EmptyContext = {};@@ -67,6 +73,7 @@ export type IssueCreateContext =| CreateDatabaseContext| UpdateSchemaContext| UpdateSchemaGhostContext+ | PITRContext| EmptyContext;export type IssuePayload = { [key: string]: any };diff --git a/frontend/src/types/pipeline/task.ts b/frontend/src/types/pipeline/task.tsindex bb3b149322..ed78a68442 100644--- a/frontend/src/types/pipeline/task.ts+++ b/frontend/src/types/pipeline/task.ts@@ -22,7 +22,10 @@ export type TaskType =| "bb.task.database.restore"| "bb.task.database.schema.update.ghost.sync"| "bb.task.database.schema.update.ghost.cutover"- | "bb.task.database.schema.update.ghost.drop-original-table";+ | "bb.task.database.schema.update.ghost.drop-original-table"+ | "bb.task.database.pitr.restore"+ | "bb.task.database.pitr.cutover"+ | "bb.task.database.pitr.delete";export type TaskStatus =| "PENDING"@@ -69,6 +72,21 @@ export type TaskDatabaseSchemaUpdateGhostDropOriginalTablePayload = {tableName: string;};+export type TaskDatabasePITRRestorePayload = {+ projectId: ProjectId;+ pointInTimeTs: number; // UNIX timestamp+};++export type TaskDatabasePITRCutoverPayload = {+ // empty by now+ // more input and output parameters in the future+};++export type TaskDatabasePITRDeletePayload = {+ // empty by now+ // more input and output parameters in the future+};+export type TaskDatabaseDataUpdatePayload = {statement: string;pushEvent?: VCSPushEvent;@@ -88,7 +106,10 @@ export type TaskPayload =| TaskDatabaseSchemaUpdateGhostDropOriginalTablePayload| TaskDatabaseDataUpdatePayload| TaskDatabaseRestorePayload- | TaskEarliestAllowedTimePayload;+ | TaskEarliestAllowedTimePayload+ | TaskDatabasePITRRestorePayload+ | TaskDatabasePITRCutoverPayload+ | TaskDatabasePITRDeletePayload;export type Task = {id: TaskId;diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vueindex 2f2b0a5121..3064ac20d6 100644--- a/frontend/src/views/DatabaseDetail.vue+++ b/frontend/src/views/DatabaseDetail.vue@@ -158,6 +158,12 @@</div></template></BBTooltipButton>++ <PITRRestoreButton+ v-if="isDev()"+ :database="database"+ :allow-admin="allowAdmin"+ /></div></div></main>@@ -284,23 +290,16 @@<GhostDialog ref="ghostDialog" /></template>-<script lang="ts">-import {- computed,- onMounted,- reactive,- watch,- defineComponent,- ref,-} from "vue";+<script lang="ts" setup>+import { computed, onMounted, reactive, watch, ref } from "vue";import { useRouter } from "vue-router";-import ProjectSelect from "../components/ProjectSelect.vue";-import DatabaseBackupPanel from "../components/DatabaseBackupPanel.vue";-import DatabaseMigrationHistoryPanel from "../components/DatabaseMigrationHistoryPanel.vue";-import DatabaseOverviewPanel from "../components/DatabaseOverviewPanel.vue";-import InstanceEngineIcon from "../components/InstanceEngineIcon.vue";-import { DatabaseLabelProps } from "../components/DatabaseLabels";-import { SelectDatabaseLabel } from "../components/TransferDatabaseForm";+import ProjectSelect from "@/components/ProjectSelect.vue";+import DatabaseBackupPanel from "@/components/DatabaseBackupPanel.vue";+import DatabaseMigrationHistoryPanel from "@/components/DatabaseMigrationHistoryPanel.vue";+import DatabaseOverviewPanel from "@/components/DatabaseOverviewPanel.vue";+import InstanceEngineIcon from "@/components/InstanceEngineIcon.vue";+import { DatabaseLabelProps } from "@/components/DatabaseLabels";+import { SelectDatabaseLabel } from "@/components/TransferDatabaseForm";import {idFromSlug,isDBAOrOwner,@@ -308,7 +307,7 @@ import {hidePrefix,isDev,allowGhostMigration,-} from "../utils";+} from "@/utils";import {ProjectId,UNKNOWN_ID,@@ -317,10 +316,11 @@ import {baseDirectoryWebUrl,Database,DatabaseLabel,-} from "../types";-import { BBTabFilterItem } from "../bbkit/types";+} from "@/types";+import { BBTabFilterItem } from "@/bbkit/types";import { useI18n } from "vue-i18n";import { GhostDialog } from "@/components/AlterSchemaPrepForm";+import { PITRRestoreButton } from "@/components/DatabaseDetail";import {pushNotification,useCurrentUser,@@ -344,352 +344,301 @@ interface LocalState {selectedIndex: number;}-export default defineComponent({- name: "DatabaseDetail",- components: {- ProjectSelect,- DatabaseOverviewPanel,- DatabaseMigrationHistoryPanel,- DatabaseBackupPanel,- InstanceEngineIcon,- DatabaseLabelProps,- SelectDatabaseLabel,- GhostDialog,+const props = defineProps({+ databaseSlug: {+ required: true,+ type: String,},- props: {- databaseSlug: {- required: true,- type: String,- },- },- setup(props) {- const databaseStore = useDatabaseStore();- const repositoryStore = useRepositoryStore();- const router = useRouter();- const { t } = useI18n();- const ghostDialog = ref<InstanceType<typeof GhostDialog>>();-- const databaseTabItemList: DatabaseTabItem[] = [- { name: t("common.overview"), hash: "overview" },- { name: t("migration-history.self"), hash: "migration-history" },- { name: t("common.backups"), hash: "backup" },- ];-- const state = reactive<LocalState>({- showTransferDatabaseModal: false,- showIncorrectProjectModal: false,- editingProjectId: UNKNOWN_ID,- selectedIndex: OVERVIEW_TAB,- });+});- const currentUser = useCurrentUser();+const databaseStore = useDatabaseStore();+const repositoryStore = useRepositoryStore();+const router = useRouter();+const { t } = useI18n();+const ghostDialog = ref<InstanceType<typeof GhostDialog>>();++const databaseTabItemList: DatabaseTabItem[] = [+ { name: t("common.overview"), hash: "overview" },+ { name: t("migration-history.self"), hash: "migration-history" },+ { name: t("common.backups"), hash: "backup" },+];++const state = reactive<LocalState>({+ showTransferDatabaseModal: false,+ showIncorrectProjectModal: false,+ editingProjectId: UNKNOWN_ID,+ selectedIndex: OVERVIEW_TAB,+});- const database = computed((): Database => {- return databaseStore.getDatabaseById(idFromSlug(props.databaseSlug));- });+const currentUser = useCurrentUser();- const isTenantProject = computed(() => {- return database.value.project.tenantMode === "TENANT";- });+const database = computed((): Database => {+ return databaseStore.getDatabaseById(idFromSlug(props.databaseSlug));+});- const isCurrentUserDBAOrOwner = computed((): boolean => {- return isDBAOrOwner(currentUser.value.role);- });+const isTenantProject = computed(() => {+ return database.value.project.tenantMode === "TENANT";+});- // Project can be transferred if meets either of the condition below:- // - Database is in default project- // - Workspace owner, dba- // - db's project owner- const allowChangeProject = computed(() => {- if (database.value.project.id == DEFAULT_PROJECT_ID) {- return true;- }+const isCurrentUserDBAOrOwner = computed((): boolean => {+ return isDBAOrOwner(currentUser.value.role);+});- if (isCurrentUserDBAOrOwner.value) {- return true;- }+// Project can be transferred if meets either of the condition below:+// - Database is in default project+// - Workspace owner, dba+// - db's project owner+const allowChangeProject = computed(() => {+ if (database.value.project.id == DEFAULT_PROJECT_ID) {+ return true;+ }++ if (isCurrentUserDBAOrOwner.value) {+ return true;+ }++ for (const member of database.value.project.memberList) {+ if (member.role == "OWNER" && member.principal.id == currentUser.value.id) {+ return true;+ }+ }++ return false;+});- for (const member of database.value.project.memberList) {- if (- member.role == "OWNER" &&- member.principal.id == currentUser.value.id- ) {- return true;- }- }+// Database can be admined if meets either of the condition below:+// - Workspace owner, dba+// - db's project owner+//+// The admin operation includes+// - Transfer project+// - Enable/disable backup+const allowAdmin = computed(() => {+ if (isCurrentUserDBAOrOwner.value) {+ return true;+ }++ for (const member of database.value.project.memberList) {+ if (member.role == "OWNER" && member.principal.id == currentUser.value.id) {+ return true;+ }+ }+ return false;+});- return false;- });+// Database can be edited if meets either of the condition below:+// - Workspace owner, dba+// - db's project member+//+// The edit operation includes+// - Take manual backup+const allowEdit = computed(() => {+ if (isCurrentUserDBAOrOwner.value) {+ return true;+ }++ for (const member of database.value.project.memberList) {+ if (member.principal.id == currentUser.value.id) {+ return true;+ }+ }+ return false;+});- // Database can be admined if meets either of the condition below:- // - Workspace owner, dba- // - db's project owner- //- // The admin operation includes- // - Transfer project- // - Enable/disable backup- const allowAdmin = computed(() => {- if (isCurrentUserDBAOrOwner.value) {- return true;- }+const allowMigrate = computed(() => {+ if (!allowEdit.value) return false;- for (const member of database.value.project.memberList) {- if (- member.role == "OWNER" &&- member.principal.id == currentUser.value.id- ) {- return true;- }- }- return false;- });+ // Migrating single database in tenant mode is not allowed+ // Since this will probably cause different migration version across a group of tenant databases+ return database.value.project.tenantMode === "DISABLED";+});- // Database can be edited if meets either of the condition below:- // - Workspace owner, dba- // - db's project member- //- // The edit operation includes- // - Take manual backup- const allowEdit = computed(() => {- if (isCurrentUserDBAOrOwner.value) {- return true;- }+const allowEditDatabaseLabels = computed((): boolean => {+ // only allowed to edit database labels when allowAdmin+ return allowAdmin.value;+});- for (const member of database.value.project.memberList) {- if (member.principal.id == currentUser.value.id) {- return true;- }- }- return false;- });+const alterSchemaText = computed(() => {+ if (database.value.project.workflowType == "VCS") {+ return t("database.alter-schema-in-vcs");+ }+ return t("database.alter-schema");+});- const allowMigrate = computed(() => {- if (!allowEdit.value) return false;+const changeDataText = computed(() => {+ if (database.value.project.workflowType == "VCS") {+ return t("database.change-data-in-vcs");+ }+ return t("database.change-data");+});- // Migrating single database in tenant mode is not allowed- // Since this will probably cause different migration version across a group of tenant databases- return database.value.project.tenantMode === "DISABLED";- });+const tabItemList = computed((): BBTabFilterItem[] => {+ return databaseTabItemList.map((item) => {+ return { title: item.name, alert: false };+ });+});- const allowEditDatabaseLabels = computed((): boolean => {- // only allowed to edit database labels when allowAdmin- return allowAdmin.value;- });+const tryTransferProject = () => {+ state.editingProjectId = database.value.project.id;+ state.showTransferDatabaseModal = true;+};- const alterSchemaText = computed(() => {- if (database.value.project.workflowType == "VCS") {- return t("database.alter-schema-in-vcs");- }- return t("database.alter-schema");- });+// 'normal' -> normal migration+// 'online' -> online migration+// false -> user clicked cancel button+const isUsingGhostMigration = async (databaseList: Database[]) => {+ if (!isDev()) {+ return "normal";+ }++ // check if all selected databases supports gh-ost+ if (allowGhostMigration(databaseList)) {+ // open the dialog to ask the user+ const { result, mode } = await ghostDialog.value!.open();+ if (!result) {+ return false; // return false when user clicked the cancel button+ }+ return mode;+ }++ // fallback to normal+ return "normal";+};- const changeDataText = computed(() => {- if (database.value.project.workflowType == "VCS") {- return t("database.change-data-in-vcs");- }- return t("database.change-data");+const alterSchema = async () => {+ if (database.value.project.workflowType == "UI") {+ const mode = await isUsingGhostMigration([database.value]);+ if (mode === false) return;+ const query: Record<string, any> = {+ template: "bb.issue.database.schema.update",+ name: `[${database.value.name}] Alter schema`,+ project: database.value.project.id,+ databaseList: database.value.id,+ };+ if (mode === "online") {+ query.ghost = "1";+ }+ router.push({+ name: "workspace.issue.detail",+ params: {+ issueSlug: "new",+ },+ query,});-- const tabItemList = computed((): BBTabFilterItem[] => {- return databaseTabItemList.map((item) => {- return { title: item.name, alert: false };+ } else if (database.value.project.workflowType == "VCS") {+ repositoryStore+ .fetchRepositoryByProjectId(database.value.project.id)+ .then((repository: Repository) => {+ window.open(baseDirectoryWebUrl(repository), "_blank");});- });-- const tryTransferProject = () => {- state.editingProjectId = database.value.project.id;- state.showTransferDatabaseModal = true;- };-- // 'normal' -> normal migration- // 'online' -> online migration- // false -> user clicked cancel button- const isUsingGhostMigration = async (databaseList: Database[]) => {- if (!isDev()) {- return "normal";- }-- // check if all selected databases supports gh-ost- if (allowGhostMigration(databaseList)) {- // open the dialog to ask the user- const { result, mode } = await ghostDialog.value!.open();- if (!result) {- return false; // return false when user clicked the cancel button- }- return mode;- }-- // fallback to normal- return "normal";- };-- const alterSchema = async () => {- if (database.value.project.workflowType == "UI") {- const mode = await isUsingGhostMigration([database.value]);- if (mode === false) return;- const query: Record<string, any> = {- template: "bb.issue.database.schema.update",- name: `[${database.value.name}] Alter schema`,- project: database.value.project.id,- databaseList: database.value.id,- };- if (mode === "online") {- query.ghost = "1";- }- router.push({- name: "workspace.issue.detail",- params: {- issueSlug: "new",- },- query,- });- } else if (database.value.project.workflowType == "VCS") {- repositoryStore- .fetchRepositoryByProjectId(database.value.project.id)- .then((repository: Repository) => {- window.open(baseDirectoryWebUrl(repository), "_blank");- });- }- };-- const changeData = () => {- if (database.value.project.workflowType == "UI") {- router.push({- name: "workspace.issue.detail",- params: {- issueSlug: "new",- },- query: {- template: "bb.issue.database.data.update",- name: `[${database.value.name}] Change data`,- project: database.value.project.id,- databaseList: database.value.id,- },- });- } else if (database.value.project.workflowType == "VCS") {- repositoryStore- .fetchRepositoryByProjectId(database.value.project.id)- .then((repository: Repository) => {- window.open(baseDirectoryWebUrl(repository), "_blank");- });- }- };-- const updateProject = (- newProjectId: ProjectId,- labels?: DatabaseLabel[]- ) => {- databaseStore- .transferProject({- databaseId: database.value.id,- projectId: newProjectId,- labels,- })- .then((updatedDatabase) => {- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t(- "database.successfully-transferred-updateddatabase-name-to-project-updateddatabase-project-name",- [updatedDatabase.name, updatedDatabase.project.name]- ),- });- });- };+ }+};- const updateLabels = (labels: DatabaseLabel[]) => {- databaseStore.patchDatabaseLabels({- databaseId: database.value.id,- labels,+const changeData = () => {+ if (database.value.project.workflowType == "UI") {+ router.push({+ name: "workspace.issue.detail",+ params: {+ issueSlug: "new",+ },+ query: {+ template: "bb.issue.database.data.update",+ name: `[${database.value.name}] Change data`,+ project: database.value.project.id,+ databaseList: database.value.id,+ },+ });+ } else if (database.value.project.workflowType == "VCS") {+ repositoryStore+ .fetchRepositoryByProjectId(database.value.project.id)+ .then((repository: Repository) => {+ window.open(baseDirectoryWebUrl(repository), "_blank");});- };+ }+};- const selectTab = (index: number) => {- state.selectedIndex = index;- router.replace({- name: "workspace.database.detail",- hash: "#" + databaseTabItemList[index].hash,+const updateProject = (newProjectId: ProjectId, labels?: DatabaseLabel[]) => {+ databaseStore+ .transferProject({+ databaseId: database.value.id,+ projectId: newProjectId,+ labels,+ })+ .then((updatedDatabase) => {+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t(+ "database.successfully-transferred-updateddatabase-name-to-project-updateddatabase-project-name",+ [updatedDatabase.name, updatedDatabase.project.name]+ ),});- };+ });+};- const selectDatabaseTabOnHash = () => {- if (router.currentRoute.value.hash) {- for (let i = 0; i < databaseTabItemList.length; i++) {- if (- databaseTabItemList[i].hash ==- router.currentRoute.value.hash.slice(1)- ) {- selectTab(i);- break;- }- }- } else {- selectTab(OVERVIEW_TAB);- }- };+const updateLabels = (labels: DatabaseLabel[]) => {+ databaseStore.patchDatabaseLabels({+ databaseId: database.value.id,+ labels,+ });+};++const selectTab = (index: number) => {+ state.selectedIndex = index;+ router.replace({+ name: "workspace.database.detail",+ hash: "#" + databaseTabItemList[index].hash,+ });+};- const gotoSQLEditor = () => {- // SQL editors can only query databases in the projects available to the user.+const selectDatabaseTabOnHash = () => {+ if (router.currentRoute.value.hash) {+ for (let i = 0; i < databaseTabItemList.length; i++) {if (- database.value.projectId === UNKNOWN_ID ||- database.value.projectId === DEFAULT_PROJECT_ID+ databaseTabItemList[i].hash == router.currentRoute.value.hash.slice(1)) {- state.editingProjectId = database.value.project.id;- state.showIncorrectProjectModal = true;- } else {- router.push({- name: "sql-editor.detail",- params: {- connectionSlug: connectionSlug(database.value),- },- });+ selectTab(i);+ break;}- };+ }+ } else {+ selectTab(OVERVIEW_TAB);+ }+};- onMounted(() => {- selectDatabaseTabOnHash();+const gotoSQLEditor = () => {+ // SQL editors can only query databases in the projects available to the user.+ if (+ database.value.projectId === UNKNOWN_ID ||+ database.value.projectId === DEFAULT_PROJECT_ID+ ) {+ state.editingProjectId = database.value.project.id;+ state.showIncorrectProjectModal = true;+ } else {+ router.push({+ name: "sql-editor.detail",+ params: {+ connectionSlug: connectionSlug(database.value),+ },});+ }+};- watch(- () => router.currentRoute.value.hash,- () => {- if (router.currentRoute.value.name == "workspace.database.detail") {- selectDatabaseTabOnHash();- }- }- );+onMounted(() => {+ selectDatabaseTabOnHash();+});- const doTransfer = (labels: DatabaseLabel[]) => {- updateProject(state.editingProjectId, labels);- state.showTransferDatabaseModal = false;- };+watch(+ () => router.currentRoute.value.hash,+ () => {+ if (router.currentRoute.value.name == "workspace.database.detail") {+ selectDatabaseTabOnHash();+ }+ }+);- return {- OVERVIEW_TAB,- MIGRATION_HISTORY_TAB,- BACKUP_TAB,- state,- ghostDialog,- isTenantProject,- database,- allowChangeProject,- allowAdmin,- allowEdit,- allowMigrate,- allowEditDatabaseLabels,- tabItemList,- tryTransferProject,- alterSchema,- changeData,- alterSchemaText,- changeDataText,- updateProject,- updateLabels,- selectTab,- gotoSQLEditor,- doTransfer,- hidePrefix,- };- },-});+const doTransfer = (labels: DatabaseLabel[]) => {+ updateProject(state.editingProjectId, labels);+ state.showTransferDatabaseModal = false;+};</script>