Skip to content

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

refactor: IssueDetail part.2 (#1267)

Liu Jic3bed597d2a0
diff --git a/frontend/src/plugins/issue/logic/common.ts b/frontend/src/plugins/issue/logic/common.ts
new file mode 100644
index 0000000000..0cce32d0d0
--- /dev/null
+++ b/frontend/src/plugins/issue/logic/common.ts
@@ -0,0 +1,55 @@
+import { Ref } from "vue";
+import { useRoute } from "vue-router";
+import { useDatabaseStore, useProjectStore } from "@/store";
+import { Database, Project, unknown, UNKNOWN_ID } from "@/types";
+import { IssueTemplate } from "@/plugins";
+
+// validateOnly: true doesn't support empty SQL
+// so we use a fake sql to validate and then set it back to empty if needed
+export const VALIDATE_ONLY_SQL = "/* YOUR_SQL_HERE */";
+
+export const ESTABLISH_BASELINE_SQL =
+ "/* Establish baseline using current schema */";
+
+export type BuildNewIssueContext = {
+ template: Ref<IssueTemplate>;
+ route: ReturnType<typeof useRoute>;
+};
+
+export const findProject = async (
+ context: BuildNewIssueContext
+): Promise<Project> => {
+ const { route } = context;
+
+ const projectId = route.query.project
+ ? parseInt(route.query.project as string)
+ : UNKNOWN_ID;
+ let project = unknown("PROJECT");
+
+ if (projectId !== UNKNOWN_ID) {
+ const projectStore = useProjectStore();
+ project = await projectStore.fetchProjectById(projectId);
+ }
+
+ return project;
+};
+
+export const findDatabaseListByQuery = (
+ context: BuildNewIssueContext
+): Database[] => {
+ // route.query.databaseList is comma-splitted databaseId list
+ // e.g. databaseList=7002,7006,7014
+ const { route } = context;
+ const idList = route.query.databaseList as string;
+ if (!idList) {
+ return [];
+ }
+
+ const databaseList: Database[] = [];
+ const databaseIdList = idList.split(",");
+ const databaseStore = useDatabaseStore();
+ for (const databaseId of databaseIdList) {
+ databaseList.push(databaseStore.getDatabaseById(parseInt(databaseId, 10)));
+ }
+ return databaseList;
+};
diff --git a/frontend/src/plugins/issue/logic/index.ts b/frontend/src/plugins/issue/logic/index.ts
new file mode 100644
index 0000000000..489d21258c
--- /dev/null
+++ b/frontend/src/plugins/issue/logic/index.ts
@@ -0,0 +1,2 @@
+export * from "./initialize";
+export * from "./poll";
diff --git a/frontend/src/plugins/issue/logic/initialize/ghost.ts b/frontend/src/plugins/issue/logic/initialize/ghost.ts
new file mode 100644
index 0000000000..6137a2a338
--- /dev/null
+++ b/frontend/src/plugins/issue/logic/initialize/ghost.ts
@@ -0,0 +1,50 @@
+import { IssueCreate, IssueType, UpdateSchemaGhostContext } from "@/types";
+import {
+ findDatabaseListByQuery,
+ BuildNewIssueContext,
+ VALIDATE_ONLY_SQL,
+} from "../common";
+import { IssueCreateHelper } from "./helper";
+
+export const maybeBuildGhostIssue = async (
+ context: BuildNewIssueContext
+): Promise<IssueCreate | undefined> => {
+ const { route } = context;
+
+ if (parseInt(route.query.ghost as string, 10) !== 1) {
+ return undefined;
+ }
+ const issueType = route.query.template as IssueType;
+ if (issueType !== "bb.issue.database.schema.update") {
+ // Only available for schema updates.
+ return undefined;
+ }
+ return buildNewGhostIssue(context);
+};
+
+const buildNewGhostIssue = async (
+ context: BuildNewIssueContext
+): Promise<IssueCreate> => {
+ const helper = new IssueCreateHelper(context);
+ await helper.prepare();
+
+ helper.issueCreate!.type = "bb.issue.database.schema.update.ghost";
+
+ const databaseList = findDatabaseListByQuery(context);
+ const createContext: UpdateSchemaGhostContext = {
+ updateSchemaDetailList: databaseList.map((db) => {
+ return {
+ databaseId: db.id,
+ databaseName: db.name,
+ statement: VALIDATE_ONLY_SQL,
+ earliestAllowedTs: 0,
+ };
+ }),
+ };
+
+ helper.issueCreate!.createContext = createContext;
+
+ await helper.validate();
+
+ return helper.generate();
+};
diff --git a/frontend/src/plugins/issue/logic/initialize/helper.ts b/frontend/src/plugins/issue/logic/initialize/helper.ts
new file mode 100644
index 0000000000..9ca9b25098
--- /dev/null
+++ b/frontend/src/plugins/issue/logic/initialize/helper.ts
@@ -0,0 +1,156 @@
+import { Ref } from "vue";
+import { TemplateType } from "@/plugins";
+import {
+ Issue,
+ IssueCreate,
+ Principal,
+ TaskDatabaseSchemaUpdatePayload,
+ UNKNOWN_ID,
+} from "@/types";
+import { isDBAOrOwner } from "@/utils";
+import {
+ useActuatorStore,
+ useCurrentUser,
+ useIssueStore,
+ usePrincipalStore,
+} from "@/store";
+import { BuildNewIssueContext, VALIDATE_ONLY_SQL } from "../common";
+
+export class IssueCreateHelper {
+ issueCreate: IssueCreate | null;
+ issue: Issue | null;
+ context: BuildNewIssueContext;
+ issueStore: ReturnType<typeof useIssueStore>;
+ currentUser: Ref<Principal>;
+
+ constructor(context: BuildNewIssueContext) {
+ this.issueCreate = null;
+ this.issue = null;
+ this.context = context;
+ this.issueStore = useIssueStore();
+ this.currentUser = useCurrentUser();
+ }
+
+ findDBAOrOwner(): Principal {
+ const currentUser = this.currentUser.value;
+ if (isDBAOrOwner(currentUser.role)) return currentUser;
+
+ const userList = usePrincipalStore().principalList;
+
+ // In bytebase, we always have at least 1 DBA or Owner, so it's safe here.
+ return userList.find((user) => isDBAOrOwner(user.role))!;
+ }
+
+ async prepare(): Promise<IssueCreate> {
+ const { context, currentUser } = this;
+ const { route } = context;
+ const actuatorStore = useActuatorStore();
+
+ const baseTemplate = context.template.value.buildIssue({
+ environmentList: [],
+ approvalPolicyList: [],
+ databaseList: [],
+ currentUser: currentUser.value,
+ });
+
+ const templateType = route.query.template as TemplateType;
+
+ const issueCreate: IssueCreate = {
+ projectId: parseInt(route.query.project as string) || UNKNOWN_ID,
+ name: (route.query.name as string) || baseTemplate.name,
+ type:
+ templateType === "bb.issue.database.schema.baseline"
+ ? "bb.issue.database.schema.update" // use schema.update to establish baseline
+ : templateType,
+ description: baseTemplate.description,
+ // validateOnly does not support assigneeId=-1
+ // so we need to specify here
+ // but will reset this to -1 if route.query.assignee is empty
+ assigneeId: this.findDBAOrOwner().id,
+ createContext: {},
+ payload: {},
+ };
+
+ // For demo mode, we assign the issue to the current user, so it can also experience the assignee user flow.
+ if (actuatorStore.isDemo) {
+ issueCreate.assigneeId = currentUser.value.id;
+ }
+ if (route.query.name) {
+ issueCreate.name = route.query.name as string;
+ }
+ if (route.query.description) {
+ issueCreate.description = route.query.description as string;
+ }
+ if (route.query.assignee) {
+ issueCreate.assigneeId = parseInt(route.query.assignee as string);
+ }
+
+ this.issueCreate = issueCreate;
+
+ return issueCreate;
+ }
+
+ async validate(): Promise<[IssueCreate, Issue]> {
+ const { issueStore } = this;
+ const issue = await issueStore.validateIssue(this.issueCreate!);
+
+ this.issue = issue;
+
+ return [this.issueCreate!, this.issue];
+ }
+
+ async generate(): Promise<IssueCreate> {
+ const { route, template } = this.context;
+ const issueCreate = this.issueCreate!;
+ const issue = this.issue!;
+
+ if (!route.query.assignee) {
+ issueCreate.assigneeId =
+ parseInt(route.query.assignee as string) || UNKNOWN_ID;
+ }
+
+ // copy the generated pipeline to issueCreate
+ // issueCreate is an editable object for the whole issue UI
+ issueCreate.pipeline = {
+ name: issue.pipeline.name,
+ stageList: issue.pipeline.stageList.map((stage) => ({
+ name: stage.name,
+ environmentId: stage.environment.id,
+ taskList: stage.taskList.map((task) => {
+ const payload = task.payload as TaskDatabaseSchemaUpdatePayload;
+ // if we are using VALIDATE_ONLY_SQL, set it back to empty
+ // otherwise keep it as-is
+ const statement =
+ payload.statement === VALIDATE_ONLY_SQL ? "" : payload.statement;
+ return {
+ name: task.name,
+ status: task.status,
+ type: task.type,
+ instanceId: task.instance.id,
+ databaseId: task.database?.id,
+ databaseName: task.database?.name,
+ migrationType: payload.migrationType,
+ statement,
+ earliestAllowedTs: task.earliestAllowedTs,
+ };
+ }),
+ })),
+ };
+
+ // cleanup input fields, not used yet.
+ for (const field of template.value.inputFieldList) {
+ const value = route.query[field.slug] as string;
+ if (value) {
+ if (field.type == "Boolean") {
+ // false if "0" or "false", true otherwise
+ const bool = value !== "0" && value.toLowerCase() !== "false";
+ issueCreate.payload[field.id] = bool;
+ } else {
+ issueCreate.payload[field.id] = value;
+ }
+ }
+ }
+
+ return issueCreate;
+ }
+}
diff --git a/frontend/src/plugins/issue/logic/initialize/index.ts b/frontend/src/plugins/issue/logic/initialize/index.ts
new file mode 100644
index 0000000000..be6ed16a5d
--- /dev/null
+++ b/frontend/src/plugins/issue/logic/initialize/index.ts
@@ -0,0 +1,68 @@
+import { computed, ref, Ref, watch } from "vue";
+import { useRoute } from "vue-router";
+import { Issue, IssueCreate, IssueType } from "@/types";
+import { pushNotification, useIssueStore } from "@/store";
+import { idFromSlug } from "@/utils";
+import { defaultTemplate, templateForType } from "@/plugins";
+import { BuildNewIssueContext } from "../common";
+import { maybeBuildTenantDeployIssue } from "./tenant";
+import { maybeBuildGhostIssue } from "./ghost";
+import { buildNewStandardIssue } from "./standard";
+
+export function useInitializeIssue(issueSlug: Ref<string>) {
+ const issueStore = useIssueStore();
+ const create = computed(() => issueSlug.value.toLowerCase() == "new");
+ const route = useRoute();
+ const issue = ref<Issue | IssueCreate | undefined>();
+ const template = computed(() => {
+ // Find proper IssueTemplate from route.query.template
+ const issueType = route.query.template as IssueType;
+ if (issueType) {
+ const tpl = templateForType(issueType);
+ if (tpl) {
+ return tpl;
+ }
+ pushNotification({
+ module: "bytebase",
+ style: "WARN",
+ title: `Unknown template '${issueType}'.`,
+ description: "Fallback to the default template",
+ });
+ }
+
+ // fallback
+ return defaultTemplate();
+ });
+
+ // initialize or re-initialize issue when issueSlug changes
+ watch(
+ issueSlug,
+ async () => {
+ issue.value = undefined;
+ if (create.value) {
+ issue.value = await buildNewIssue({ template, route });
+ } else {
+ issue.value = issueStore.getIssueById(idFromSlug(issueSlug.value));
+ }
+ },
+ { immediate: true }
+ );
+
+ return { create, issue };
+}
+
+const buildNewIssue = async (
+ context: BuildNewIssueContext
+): Promise<IssueCreate> => {
+ const tenant = await maybeBuildTenantDeployIssue(context);
+ if (tenant) {
+ return tenant;
+ }
+
+ const ghost = await maybeBuildGhostIssue(context);
+ if (ghost) {
+ return ghost;
+ }
+
+ return buildNewStandardIssue(context);
+};
diff --git a/frontend/src/plugins/issue/logic/initialize/standard.ts b/frontend/src/plugins/issue/logic/initialize/standard.ts
new file mode 100644
index 0000000000..7da2f6f9b9
--- /dev/null
+++ b/frontend/src/plugins/issue/logic/initialize/standard.ts
@@ -0,0 +1,48 @@
+import { TemplateType } from "@/plugins";
+import { IssueCreate, MigrationType } from "@/types";
+import {
+ findDatabaseListByQuery,
+ BuildNewIssueContext,
+ ESTABLISH_BASELINE_SQL,
+ VALIDATE_ONLY_SQL,
+} from "../common";
+import { IssueCreateHelper } from "./helper";
+
+export const buildNewStandardIssue = async (
+ context: BuildNewIssueContext
+): Promise<IssueCreate> => {
+ const helper = new IssueCreateHelper(context);
+
+ await helper.prepare();
+
+ // standard single-stage or multi-stage issue is generated by specifying
+ // databaseId for each stage
+ const databaseList = findDatabaseListByQuery(context);
+ const templateType = context.route.query.template as TemplateType;
+ let migrationType: MigrationType = "MIGRATE";
+ if (templateType === "bb.issue.database.data.update") {
+ migrationType = "DATA";
+ }
+ if (templateType === "bb.issue.database.schema.baseline") {
+ migrationType = "BASELINE";
+ }
+ const statement =
+ migrationType === "BASELINE" ? ESTABLISH_BASELINE_SQL : VALIDATE_ONLY_SQL;
+ helper.issueCreate!.createContext = {
+ migrationType,
+ updateSchemaDetailList: databaseList.map((db) => {
+ return {
+ databaseId: db.id,
+ databaseName: db.name,
+ statement,
+ };
+ }),
+ };
+
+ await helper.validate();
+
+ // clean up createContext for standard issues
+ helper.issueCreate!.createContext = {};
+
+ return helper.generate();
+};
diff --git a/frontend/src/plugins/issue/logic/initialize/tenant.ts b/frontend/src/plugins/issue/logic/initialize/tenant.ts
new file mode 100644
index 0000000000..26514578ed
--- /dev/null
+++ b/frontend/src/plugins/issue/logic/initialize/tenant.ts
@@ -0,0 +1,70 @@
+import { TemplateType } from "@/plugins";
+import {
+ IssueCreate,
+ IssueType,
+ MigrationType,
+ UpdateSchemaContext,
+} from "@/types";
+import {
+ findProject,
+ BuildNewIssueContext,
+ VALIDATE_ONLY_SQL,
+} from "../common";
+import { IssueCreateHelper } from "./helper";
+
+export const maybeBuildTenantDeployIssue = async (
+ context: BuildNewIssueContext
+): Promise<IssueCreate | undefined> => {
+ const { route } = context;
+ if (route.query.mode !== "tenant") {
+ return undefined;
+ }
+
+ const project = await findProject(context);
+ const issueType = route.query.template as IssueType;
+ const isMigrate =
+ issueType === "bb.issue.database.schema.update" ||
+ issueType === "bb.issue.database.data.update";
+ if (project.tenantMode === "TENANT" && isMigrate) {
+ // Only to build tenant issue when:
+ // 1. Project is tenant mode.
+ // 2. Is schema update or data update (no to establish baseline).
+ return buildNewTenantSchemaUpdateIssue(context);
+ }
+ return undefined;
+};
+
+const buildNewTenantSchemaUpdateIssue = async (
+ context: BuildNewIssueContext
+): Promise<IssueCreate> => {
+ const { route } = context;
+ const helper = new IssueCreateHelper(context);
+
+ await helper.prepare();
+ // tenant issue is generated by specifying databaseName
+ const templateType = route.query.template as TemplateType;
+ let migrationType: MigrationType = "MIGRATE";
+ if (templateType === "bb.issue.database.data.update") {
+ migrationType = "DATA";
+ }
+ helper.issueCreate!.createContext = {
+ migrationType,
+ updateSchemaDetailList: [
+ {
+ databaseName: route.query.databaseName,
+ statement: VALIDATE_ONLY_SQL,
+ },
+ ],
+ };
+ await helper.validate();
+
+ // we are setting SQL statement to "" because showing /* YOUR_SQL_HERE */
+ // is not that friendly to users
+ // setting it to empty can provide a placeholder to user, along with an
+ // exclamation mark indicating "No SQL statement"
+ const createContext = helper.issueCreate!
+ .createContext as UpdateSchemaContext;
+ createContext.updateSchemaDetailList[0].statement = "";
+
+ return helper.generate();
+};
diff --git a/frontend/src/plugins/issue/logic/poll/index.ts b/frontend/src/plugins/issue/logic/poll/index.ts
new file mode 100644
index 0000000000..b63e68df59
--- /dev/null
+++ b/frontend/src/plugins/issue/logic/poll/index.ts
@@ -0,0 +1,92 @@
+import { computed, onUnmounted, reactive, Ref, watch } from "vue";
+import { useIssueStore } from "@/store";
+import {
+ Issue,
+ IssueCreate,
+ IssueType,
+ NORMAL_POLL_INTERVAL,
+ POLL_JITTER,
+ POST_CHANGE_POLL_INTERVAL,
+} from "@/types";
+import { idFromSlug } from "@/utils";
+
+type LocalPollState = {
+ // Timer tracking the issue poller, we need this to cancel the outstanding one when needed.
+ timer: ReturnType<typeof setTimeout> | undefined;
+};
+
+export const usePollIssue = (
+ issueSlug: Ref<string>,
+ issue: Ref<Issue | IssueCreate | undefined>
+) => {
+ const state = reactive<LocalPollState>({
+ timer: undefined,
+ });
+ const create = computed(() => issueSlug.value.toLowerCase() == "new");
+ const issueStore = useIssueStore();
+
+ const stopPolling = () => {
+ if (!state.timer) {
+ return;
+ }
+ clearTimeout(state.timer);
+ };
+
+ // pollIssue invalidates the current timer and schedule a new timer in <<interval>> microseconds
+ const pollIssue = (interval: number) => {
+ stopPolling();
+
+ const int = Math.max(
+ 1000,
+ Math.min(interval, NORMAL_POLL_INTERVAL) +
+ (Math.random() * 2 - 1) * POLL_JITTER
+ );
+
+ state.timer = setTimeout(() => {
+ issueStore.fetchIssueById(idFromSlug(issueSlug.value));
+
+ pollIssue(Math.min(interval * 2, NORMAL_POLL_INTERVAL));
+ }, int);
+ };
+
+ const pollOnCreateStateChange = () => {
+ if (!issue.value) {
+ return;
+ }
+
+ let interval = NORMAL_POLL_INTERVAL;
+ // We will poll faster if meets either of the condition
+ // 1. Created the database create issue, expect creation result quickly.
+ // 2. Update the database schema, will do connection and syntax check.
+ const isNearNow =
+ Date.now() - (issue.value as Issue).updatedTs * 1000 < 5000;
+ const { type } = issue.value;
+ if (FASTER_TYPES.includes(type) && isNearNow) {
+ interval = POST_CHANGE_POLL_INTERVAL;
+ }
+ pollIssue(interval);
+ };
+
+ watch(
+ create,
+ () => {
+ if (create.value) {
+ stopPolling();
+ } else {
+ pollOnCreateStateChange();
+ }
+ },
+ { immediate: true }
+ );
+
+ onUnmounted(stopPolling);
+
+ return pollIssue;
+};
+
+const FASTER_TYPES: IssueType[] = [
+ "bb.issue.database.create",
+ "bb.issue.database.schema.update",
+ "bb.issue.database.data.update",
+ "bb.issue.database.schema.update.ghost",
+];
diff --git a/frontend/src/views/IssueDetail.vue b/frontend/src/views/IssueDetail.vue
index cfb7298a1e..646f71205f 100644
--- a/frontend/src/views/IssueDetail.vue
+++ b/frontend/src/views/IssueDetail.vue
@@ -2,7 +2,7 @@
<IssueDetailLayout
v-if="issue"
:issue="issue"
- :create="state.create"
+ :create="create"
@status-changed="onStatusChanged"
/>
<div v-else class="w-full h-full flex justify-center items-center">
@@ -15,537 +15,78 @@
/>
</template>
-<script lang="ts">
-import {
- computed,
- onMounted,
- onUnmounted,
- watch,
- watchEffect,
- reactive,
- ref,
- defineComponent,
- Ref,
-} from "vue";
+<script lang="ts" setup>
+import { computed, reactive, watch } from "vue";
import { useRoute, _RouteLocationBase } from "vue-router";
-import { idFromSlug, isDBAOrOwner } from "../utils";
-import { IssueDetailLayout } from "../components/Issue";
+import { NSpin } from "naive-ui";
+import { IssueDetailLayout } from "@/components/Issue";
import {
- UNKNOWN_ID,
- Issue,
- IssueCreate,
IssueType,
- Database,
NORMAL_POLL_INTERVAL,
- POLL_JITTER,
POST_CHANGE_POLL_INTERVAL,
Project,
unknown,
- MigrationType,
- TaskDatabaseSchemaUpdatePayload,
- Principal,
- UpdateSchemaContext,
- UpdateSchemaGhostContext,
-} from "../types";
-import {
- defaultTemplate,
- templateForType,
- IssueTemplate,
- TemplateType,
-} from "../plugins";
-import { NSpin } from "naive-ui";
-import {
- hasFeature,
- pushNotification,
- useActuatorStore,
- useCurrentUser,
- useDatabaseStore,
- useIssueStore,
- usePrincipalStore,
- useProjectStore,
-} from "@/store";
+ UNKNOWN_ID,
+} from "@/types";
+import { hasFeature, useProjectStore } from "@/store";
+import { useInitializeIssue, usePollIssue } from "@/plugins/issue/logic";
interface LocalState {
- // Needs to maintain this state and set it to false manually after creating the issue.
- // router.push won't trigger the reload because new and existing issue shares
- // the same component.
- create: boolean;
- newIssue?: IssueCreate;
- // Timer tracking the issue poller, we need this to cancel the outstanding one when needed.
- pollIssueTimer?: ReturnType<typeof setTimeout>;
showFeatureModal: boolean;
}
-// validateOnly: true doesn't support empty SQL
-// so we use a fake sql to validate and then set it back to empty if needed
-const VALIDATE_ONLY_SQL = "/* YOUR_SQL_HERE */";
-const ESTABLISH_BASELINE_SQL = "/* Establish baseline using current schema */";
-
-export default defineComponent({
- name: "IssueDetail",
- components: {
- IssueDetailLayout,
- NSpin,
- },
- props: {
- issueSlug: {
- required: true,
- type: String,
- },
- },
-
- setup(props) {
- const route = useRoute();
-
- const currentUser = useCurrentUser();
- const issueStore = useIssueStore();
- const projectStore = useProjectStore();
-
- let newIssueTemplate = ref<IssueTemplate>(defaultTemplate());
-
- const refreshTemplate = () => {
- const issueType = route.query.template as IssueType;
- if (issueType) {
- const template = templateForType(issueType);
- if (template) {
- newIssueTemplate.value = template;
- } else {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: `Unknown template '${issueType}'.`,
- description: "Fallback to the default template",
- });
- }
- }
-
- if (!newIssueTemplate.value) {
- newIssueTemplate.value = defaultTemplate();
- }
- };
-
- // Vue doesn't natively react to query parameter change
- // so we need to manually watch here.
- watch(
- () => route.query.template,
- () => {
- refreshTemplate();
- }
- );
-
- watchEffect(refreshTemplate);
-
- const state = reactive<LocalState>({
- create: props.issueSlug.toLowerCase() == "new",
- newIssue: undefined,
- showFeatureModal: false,
- });
-
- const issue = computed((): Issue | IssueCreate => {
- return state.create
- ? state.newIssue!
- : issueStore.getIssueById(idFromSlug(props.issueSlug));
- });
-
- const findProject = async (): Promise<Project> => {
- const projectId = route.query.project
- ? parseInt(route.query.project as string)
- : UNKNOWN_ID;
- let project = unknown("PROJECT") as Project;
- if (projectId !== UNKNOWN_ID) {
- project = await projectStore.fetchProjectById(projectId);
- }
-
- return project;
- };
-
- const findDatabaseListByQuery = (): Database[] => {
- // route.query.databaseList is comma-splitted databaseId list
- // e.g. databaseList=7002,7006,7014
- const databaseList: Database[] = [];
- if (route.query.databaseList) {
- const databaseIdList = (route.query.databaseList as string).split(",");
- const databaseStore = useDatabaseStore();
- for (const databaseId of databaseIdList) {
- databaseList.push(
- databaseStore.getDatabaseById(parseInt(databaseId, 10))
- );
- }
- }
- return databaseList;
- };
-
- const buildNewTenantSchemaUpdateIssue = async (): Promise<IssueCreate> => {
- const helper = new IssueCreateHelper({
- template: newIssueTemplate,
- currentUser,
- issueStore,
- route,
- });
- await helper.prepare();
- // tenant issue is generated by specifying databaseName
- const templateType = route.query.template as TemplateType;
- let migrationType: MigrationType = "MIGRATE";
- if (templateType === "bb.issue.database.data.update") {
- migrationType = "DATA";
- }
- helper.issueCreate!.createContext = {
- migrationType,
- updateSchemaDetailList: [
- {
- databaseName: route.query.databaseName,
- statement: VALIDATE_ONLY_SQL,
- },
- ],
- };
- await helper.validate();
-
- // we are setting SQL statement to "" because showing /* YOUR_SQL_HERE */
- // is not that friendly to users
- // setting it to empty can provide a placeholder to user, along with an
- // exclamation mark indicating "No SQL statement"
- const context = helper.issueCreate!.createContext as UpdateSchemaContext;
- context.updateSchemaDetailList[0].statement = "";
-
- return helper.generate();
- };
-
- const buildNewStandardIssue = async (): Promise<IssueCreate> => {
- const helper = new IssueCreateHelper({
- template: newIssueTemplate,
- currentUser,
- issueStore,
- route,
- });
- await helper.prepare();
-
- // standard single-stage or multi-stage issue is generated by specifying
- // databaseId for each stage
- const databaseList = findDatabaseListByQuery();
- const templateType = route.query.template as TemplateType;
- let migrationType: MigrationType = "MIGRATE";
- if (templateType === "bb.issue.database.data.update") {
- migrationType = "DATA";
- }
- if (templateType === "bb.issue.database.schema.baseline") {
- migrationType = "BASELINE";
- }
- const statement =
- migrationType === "BASELINE"
- ? ESTABLISH_BASELINE_SQL
- : VALIDATE_ONLY_SQL;
- helper.issueCreate!.createContext = {
- migrationType,
- updateSchemaDetailList: databaseList.map((db) => {
- return {
- databaseId: db.id,
- databaseName: db.name,
- statement,
- };
- }),
- };
-
- await helper.validate();
-
- // clean up createContext for standard issues
- helper.issueCreate!.createContext = {};
-
- return helper.generate();
- };
-
- const buildNewGhostIssue = async (): Promise<IssueCreate> => {
- const helper = new IssueCreateHelper({
- template: newIssueTemplate,
- currentUser,
- issueStore,
- route,
- });
- await helper.prepare();
-
- helper.issueCreate!.type = "bb.issue.database.schema.update.ghost";
-
- const databaseList = findDatabaseListByQuery();
- const createContext: UpdateSchemaGhostContext = {
- updateSchemaDetailList: databaseList.map((db) => {
- return {
- databaseId: db.id,
- databaseName: db.name,
- statement: VALIDATE_ONLY_SQL,
- earliestAllowedTs: 0,
- };
- }),
- };
-
- helper.issueCreate!.createContext = createContext;
-
- await helper.validate();
-
- return helper.generate();
- };
-
- const maybeBuildTenantDeployIssue = async (): Promise<
- IssueCreate | undefined
- > => {
- if (route.query.mode !== "tenant") {
- return undefined;
- }
-
- const project = await findProject();
- const issueType = route.query.template as IssueType;
- const isMigrate =
- issueType === "bb.issue.database.schema.update" ||
- issueType === "bb.issue.database.data.update";
- if (project.tenantMode === "TENANT" && isMigrate) {
- return buildNewTenantSchemaUpdateIssue();
- }
- return undefined;
- };
-
- const maybeBuildGhostIssue = async (): Promise<IssueCreate | undefined> => {
- if (parseInt(route.query.ghost as string, 10) !== 1) {
- return undefined;
- }
- const issueType = route.query.template as IssueType;
- if (issueType !== "bb.issue.database.schema.update") {
- return undefined;
- }
- return buildNewGhostIssue();
- };
-
- const buildNewIssue = async (): Promise<IssueCreate | undefined> => {
- const tenant = await maybeBuildTenantDeployIssue();
- if (tenant) {
- return tenant;
- }
-
- const ghost = await maybeBuildGhostIssue();
- if (ghost) {
- return ghost;
- }
-
- // Create issue from normal query parameter
- const newIssue = await buildNewStandardIssue();
-
- for (const field of newIssueTemplate.value.inputFieldList) {
- const value = route.query[field.slug] as string;
- if (value) {
- if (field.type == "Boolean") {
- newIssue.payload[field.id] =
- value != "0" && value.toLowerCase() != "false";
- } else {
- newIssue.payload[field.id] = value;
- }
- }
- }
-
- return newIssue;
- };
-
- // pollIssue invalidates the current timer and schedule a new timer in <<interval>> microseconds
- const pollIssue = (interval: number) => {
- if (state.pollIssueTimer) {
- clearInterval(state.pollIssueTimer);
- }
-
- state.pollIssueTimer = setTimeout(() => {
- issueStore.fetchIssueById(idFromSlug(props.issueSlug));
- pollIssue(Math.min(interval * 2, NORMAL_POLL_INTERVAL));
- }, Math.max(1000, Math.min(interval, NORMAL_POLL_INTERVAL) + (Math.random() * 2 - 1) * POLL_JITTER));
- };
-
- const pollOnCreateStateChange = () => {
- let interval = NORMAL_POLL_INTERVAL;
- // We will poll faster if meets either of the condition
- // 1. Created the database create issue, expect creation result quickly.
- // 2. Update the database schema, will do connection and syntax check.
- if (
- (issue.value.type == "bb.issue.database.create" ||
- issue.value.type == "bb.issue.database.schema.update" ||
- issue.value.type == "bb.issue.database.data.update") &&
- Date.now() - (issue.value as Issue).updatedTs * 1000 < 5000
- ) {
- interval = POST_CHANGE_POLL_INTERVAL;
- }
- pollIssue(interval);
- };
-
- onMounted(async () => {
- if (!state.create) {
- pollOnCreateStateChange();
- } else {
- state.newIssue = await buildNewIssue();
- }
- });
-
- onUnmounted(() => {
- if (state.pollIssueTimer) {
- clearInterval(state.pollIssueTimer);
- }
- });
-
- watch(
- () => props.issueSlug,
- async (cur) => {
- const oldCreate = state.create;
- state.create = cur.toLowerCase() == "new";
- if (!state.create && oldCreate) {
- pollOnCreateStateChange();
- } else if (state.create && !oldCreate) {
- clearInterval(state.pollIssueTimer as any);
- state.newIssue = await buildNewIssue();
- }
- }
- );
-
- watch(
- () => state.newIssue,
- async (issue) => {
- if (issue?.type === "bb.issue.database.schema.update") {
- const project = await findProject();
- if (
- project.tenantMode === "TENANT" &&
- !hasFeature("bb.feature.multi-tenancy")
- ) {
- state.showFeatureModal = true;
- }
- }
- }
- );
-
- const onStatusChanged = (eager: boolean) => {
- pollIssue(eager ? POST_CHANGE_POLL_INTERVAL : NORMAL_POLL_INTERVAL);
- };
-
- return {
- route,
- state,
- issue,
- onStatusChanged,
- };
+const props = defineProps({
+ issueSlug: {
+ required: true,
+ type: String,
},
});
-type IssueCreateHelperContext = {
- template: Ref<IssueTemplate>;
- currentUser: Ref<Principal>;
- issueStore: ReturnType<typeof useIssueStore>;
- route: _RouteLocationBase;
-};
-
-class IssueCreateHelper {
- context: IssueCreateHelperContext;
- issueCreate: IssueCreate | null;
- issue: Issue | null;
-
- constructor(context: IssueCreateHelperContext) {
- this.context = context;
- this.issueCreate = null;
- this.issue = null;
- }
-
- findDBAOrOwner(): Principal {
- const currentUser = this.context.currentUser.value;
- if (isDBAOrOwner(currentUser.role)) return currentUser;
+const route = useRoute();
- const userList = usePrincipalStore().principalList;
-
- // In bytebase, we always have at least 1 DBA or Owner, so it's safe here.
- return userList.find((user) => isDBAOrOwner(user.role))!;
- }
-
- async prepare(): Promise<IssueCreate> {
- const { template, currentUser, route } = this.context;
- const actuatorStore = useActuatorStore();
- const baseTemplate = template.value.buildIssue({
- environmentList: [],
- approvalPolicyList: [],
- databaseList: [],
- currentUser: currentUser.value,
- });
-
- const templateType = route.query.template as TemplateType;
- const issueCreate: IssueCreate = {
- projectId: parseInt(route.query.project as string) || UNKNOWN_ID,
- name: (route.query.name as string) || baseTemplate.name,
- type:
- templateType === "bb.issue.database.schema.baseline"
- ? "bb.issue.database.schema.update" // use schema.update to establish baseline
- : templateType,
- description: baseTemplate.description,
- // validateOnly does not support assigneeId=-1
- // so we need to specify here
- // but will reset this to -1 if route.query.assignee is empty
- assigneeId: this.findDBAOrOwner().id,
- createContext: {},
- payload: {},
- };
+const state = reactive<LocalState>({
+ showFeatureModal: false,
+});
- // For demo mode, we assign the issue to the current user, so it can also experience the assignee user flow.
- if (actuatorStore.isDemo) {
- issueCreate.assigneeId = currentUser.value.id;
+const issueSlug = computed(() => props.issueSlug);
+
+const { create, issue } = useInitializeIssue(issueSlug);
+
+const pollIssue = usePollIssue(issueSlug, issue);
+
+watch(issueSlug, async () => {
+ if (!create.value) return;
+ const type = route.query.template as IssueType;
+ const tenantIssueTypes: IssueType[] = [
+ "bb.issue.database.schema.update",
+ "bb.issue.database.data.update",
+ ];
+ if (tenantIssueTypes.includes(type)) {
+ const project = await findProject();
+ if (
+ project.tenantMode === "TENANT" &&
+ !hasFeature("bb.feature.multi-tenancy")
+ ) {
+ state.showFeatureModal = true;
}
- if (route.query.name) {
- issueCreate.name = route.query.name as string;
- }
- if (route.query.description) {
- issueCreate.description = route.query.description as string;
- }
- if (route.query.assignee) {
- issueCreate.assigneeId = parseInt(route.query.assignee as string);
- }
-
- this.issueCreate = issueCreate;
-
- return issueCreate;
}
+});
- async validate(): Promise<[IssueCreate, Issue]> {
- const { issueStore } = this.context;
- const issue = await issueStore.validateIssue(this.issueCreate!);
+const onStatusChanged = (eager: boolean) => {
+ pollIssue(eager ? POST_CHANGE_POLL_INTERVAL : NORMAL_POLL_INTERVAL);
+};
- this.issue = issue;
+const findProject = async (): Promise<Project> => {
+ const projectId = route.query.project
+ ? parseInt(route.query.project as string)
+ : UNKNOWN_ID;
+ let project = unknown("PROJECT");
- return [this.issueCreate!, this.issue];
+ if (projectId !== UNKNOWN_ID) {
+ const projectStore = useProjectStore();
+ project = await projectStore.fetchProjectById(projectId);
}
- async generate(): Promise<IssueCreate> {
- const { route } = this.context;
- const issueCreate = this.issueCreate!;
- const issue = this.issue!;
- if (!route.query.assignee) {
- issueCreate.assigneeId =
- parseInt(route.query.assignee as string) || UNKNOWN_ID;
- }
-
- // copy the generated pipeline to issueCreate
- // issueCreate is an editable object for the whole issue UI
- issueCreate.pipeline = {
- name: issue.pipeline.name,
- stageList: issue.pipeline.stageList.map((stage) => ({
- name: stage.name,
- environmentId: stage.environment.id,
- taskList: stage.taskList.map((task) => {
- const payload = task.payload as TaskDatabaseSchemaUpdatePayload;
- // if we are using VALIDATE_ONLY_SQL, set it back to empty
- // otherwise keep it as-is
- const statement =
- payload.statement === VALIDATE_ONLY_SQL ? "" : payload.statement;
- return {
- name: task.name,
- status: task.status,
- type: task.type,
- instanceId: task.instance.id,
- databaseId: task.database?.id,
- databaseName: task.database?.name,
- migrationType: payload.migrationType,
- statement,
- earliestAllowedTs: task.earliestAllowedTs,
- };
- }),
- })),
- };
-
- return issueCreate;
- }
-}
+ return project;
+};
</script>