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): slow query displaying (#5508)
Liu Ji5d81602bbe8e
diff --git a/frontend/src/assets/css/tailwind.css b/frontend/src/assets/css/tailwind.cssindex 30a378ebb0..e15c000296 100644--- a/frontend/src/assets/css/tailwind.css+++ b/frontend/src/assets/css/tailwind.css@@ -88,13 +88,27 @@@apply contents;}.bb-grid-header-cell {- @apply flex items-center bg-gray-50 p-2 text-left text-xs font-medium text-gray-500 tracking-wider;+ @apply flex items-center bg-gray-50 text-left text-xs font-medium text-gray-500 tracking-wider;+ }+ .bb-grid:not(.compact) .bb-grid-header-cell {+ @apply px-2 py-2;@apply first:pl-4 last:pr-4;}+ .bb-grid.compact .bb-grid-header-cell {+ @apply px-1 py-2;+ @apply first:pl-2 last:pr-2;+ }.bb-grid-cell {- @apply border-t border-block-border flex items-center text-sm leading-5 p-2 whitespace-pre-wrap break-all;+ @apply border-t border-block-border flex items-center text-sm leading-5 whitespace-pre-wrap break-all;+ }+ .bb-grid:not(.compact) .bb-grid-cell {+ @apply px-2 py-2;@apply first:pl-4 last:pr-4;}+ .bb-grid.compact .bb-grid-cell {+ @apply px-1 py-2;+ @apply first:pl-2 last:pr-2;+ }.bb-grid-row.clickable:hover > .bb-grid-cell {@apply cursor-pointer bg-gray-100;}diff --git a/frontend/src/bbkit/types.ts b/frontend/src/bbkit/types.tsindex 23c6e7b183..2e13bc2758 100644--- a/frontend/src/bbkit/types.ts+++ b/frontend/src/bbkit/types.ts@@ -29,6 +29,11 @@ export type BBGridColumn = {class?: VueClass;};+export type BBGridRow<T = any> = {+ item: T;+ row: number;+};+export type BBTableSectionDataSource<T> = {title: string;link?: string;diff --git a/frontend/src/components/DatabaseSlowQueryPanel.vue b/frontend/src/components/DatabaseSlowQueryPanel.vuenew file mode 100644index 0000000000..cf3cf4e2c2--- /dev/null+++ b/frontend/src/components/DatabaseSlowQueryPanel.vue@@ -0,0 +1,40 @@+<template>+ <div>+ <SlowQueryPanel+ v-if="database"+ v-model:filter="filter"+ :filter-types="['time-range']"+ />+ </div>+</template>++<script lang="ts" setup>+import { shallowRef, watch } from "vue";++import type { Database } from "@/types";+import {+ type SlowQueryFilterParams,+ SlowQueryPanel,+ defaultSlowQueryFilterParams,+} from "@/components/SlowQuery";++const props = defineProps<{+ database: Database;+}>();++const filter = shallowRef<SlowQueryFilterParams>({+ ...defaultSlowQueryFilterParams(),+ environment: props.database.instance.environment,+ instance: props.database.instance,+ database: props.database,+});++watch(+ () => props.database.id,+ () => {+ filter.value.environment = props.database.instance.environment;+ filter.value.instance = props.database.instance;+ filter.value.database = props.database;+ }+);+</script>diff --git a/frontend/src/components/ProjectDatabasesPanel.vue b/frontend/src/components/ProjectDatabasesPanel.vueindex 4ee3610dcb..8e5b24fa4b 100644--- a/frontend/src/components/ProjectDatabasesPanel.vue+++ b/frontend/src/components/ProjectDatabasesPanel.vue@@ -48,6 +48,8 @@<script lang="ts" setup>import { reactive, PropType, computed } from "vue";+import { NInputGroup } from "naive-ui";+import { uniqBy } from "lodash-es";import {Database,@@ -59,10 +61,7 @@ import {} from "../types";import { filterDatabaseByKeyword } from "@/utils";import DatabaseTable from "../components/DatabaseTable.vue";-import { NInputGroup } from "naive-ui";import { EnvironmentTabFilter, InstanceSelect, SearchBox } from "./v2";-import { uniqBy } from "lodash-es";-import { useInstanceList } from "@/store";interface LocalState {environment: EnvironmentId;@@ -86,7 +85,6 @@ const state = reactive<LocalState>({instance: UNKNOWN_ID,keyword: "",});-useInstanceList(["NORMAL"]);const filteredDatabaseList = computed(() => {return props.databaseListdiff --git a/frontend/src/components/ProjectSlowQueryPanel.vue b/frontend/src/components/ProjectSlowQueryPanel.vuenew file mode 100644index 0000000000..58d1c4c90f--- /dev/null+++ b/frontend/src/components/ProjectSlowQueryPanel.vue@@ -0,0 +1,35 @@+<template>+ <div>+ <SlowQueryPanel+ v-model:filter="filter"+ :filter-types="['environment', 'database', 'time-range']"+ />+ </div>+</template>++<script lang="ts" setup>+import { shallowRef, watch } from "vue";++import {+ SlowQueryPanel,+ SlowQueryFilterParams,+ defaultSlowQueryFilterParams,+} from "@/components/SlowQuery";+import { Project } from "@/types";++const props = defineProps<{+ project: Project;+}>();++const filter = shallowRef<SlowQueryFilterParams>({+ ...defaultSlowQueryFilterParams(),+ project: props.project,+});++watch(+ () => props.project.id,+ () => {+ filter.value.project = props.project;+ }+);+</script>diff --git a/frontend/src/components/SlowQuery/Panel/DetailDialog.vue b/frontend/src/components/SlowQuery/Panel/DetailDialog.vuenew file mode 100644index 0000000000..7db6d1a314--- /dev/null+++ b/frontend/src/components/SlowQuery/Panel/DetailDialog.vue@@ -0,0 +1,116 @@+<template>+ <BBModal :title="$t('common.detail')" @close="$emit('close')">+ <div+ class="max-h-[calc(100vh-12rem)] w-[calc(100vw-8rem)] lg:max-w-[56rem] flex flex-col gap-y-4 text-sm"+ >+ <div+ class="grid grid-cols-[minmax(auto,7rem)_1fr] md:grid-cols-[minmax(auto,7rem)_1fr_minmax(auto,7rem)_1fr] gap-x-2 gap-y-4"+ >+ <div class="contents">+ <label class="font-medium">{{ $t("common.instance") }}</label>++ <InstanceName :instance="database.instance" />+ </div>++ <div class="contents">+ <label class="font-medium">{{ $t("common.database") }}</label>++ <DatabaseName :database="database" />+ </div>++ <div class="contents">+ <label class="font-medium whitespace-nowrap">+ {{ $t("common.sql-statement") }}+ </label>++ <div+ class="col-start-2 md:col-span-3 max-h-[8rem] overflow-auto border p-1 text-xs"+ >+ <HighlightCodeBlock+ :code="log.statistics?.sqlFingerprint ?? ''"+ class="whitespace-pre-wrap"+ />+ </div>+ </div>+ </div>+ <div class="flex-1 overflow-auto border">+ <BBGrid+ :column-list="columns"+ :data-source="log.statistics?.samples"+ :row-clickable="false"+ class="compact"+ header-class="capitalize"+ >+ <template #item="{ item: detail }: SlowQueryDetailsRow">+ <div class="bb-grid-cell">+ {{ dayjs(detail.startTime).format("YYYY-MM-DD HH:mm:ss") }}+ </div>+ <div class="bb-grid-cell">+ {{ detail.queryTime?.seconds.toFixed(6) }}+ </div>+ <div class="bb-grid-cell">+ {{ detail.lockTime?.seconds.toFixed(6) }}+ </div>+ <div class="bb-grid-cell">+ {{ detail.rowsExamined }}+ </div>+ <div class="bb-grid-cell">+ {{ detail.rowsSent }}+ </div>+ </template>+ </BBGrid>+ </div>+ </div>+ </BBModal>+</template>++<script lang="ts" setup>+import { computed } from "vue";+import { useI18n } from "vue-i18n";++import { type BBGridColumn, type BBGridRow, BBModal, BBGrid } from "@/bbkit";+import type { ComposedSlowQueryLog } from "@/types";+import type { SlowQueryDetails } from "@/types/proto/v1/database_service";+import { DatabaseName, InstanceName } from "@/components/v2";+import HighlightCodeBlock from "@/components/HighlightCodeBlock";++export type SlowQueryDetailsRow = BBGridRow<SlowQueryDetails>;++const props = defineProps<{+ slowQueryLog: ComposedSlowQueryLog;+}>();++defineEmits<{+ (event: "close"): void;+}>();++const { t } = useI18n();++const columns = computed(() => {+ const columns: BBGridColumn[] = [+ {+ title: t("slow-query.query-start-time"),+ width: "minmax(auto, 2fr)",+ },+ {+ title: t("slow-query.query-time"),+ width: "minmax(auto, 1fr)",+ },+ {+ title: t("slow-query.lock-time"),+ width: "minmax(auto, 1fr)",+ },+ {+ title: t("slow-query.rows-examined"),+ width: "minmax(auto, 1fr)",+ },+ {+ title: t("slow-query.rows-sent"),+ width: "minmax(auto, 1fr)",+ },+ ];+ return columns;+});+const log = computed(() => props.slowQueryLog.log);+const database = computed(() => props.slowQueryLog.database);+</script>diff --git a/frontend/src/components/SlowQuery/Panel/LogFilter.vue b/frontend/src/components/SlowQuery/Panel/LogFilter.vuenew file mode 100644index 0000000000..4d6eb76309--- /dev/null+++ b/frontend/src/components/SlowQuery/Panel/LogFilter.vue@@ -0,0 +1,196 @@+<template>+ <div class="mb-2 space-y-2">+ <div class="flex items-center gap-x-4 h-[34px]">+ <NRadioGroup+ v-if="allowFilterByEnvironment"+ v-model:value="mode"+ :disabled="loading"+ class="ml-1"+ >+ <NRadio value="environment">{{ $t("common.environment") }}</NRadio>+ <NRadio value="project">{{ $t("common.project") }}</NRadio>+ </NRadioGroup>++ <NInputGroup style="width: auto">+ <ProjectSelect+ v-if="mode === 'project' && filterTypes.includes('project')"+ :project="params.project?.id ?? UNKNOWN_ID"+ :include-default-project="false"+ :include-all="true"+ :disabled="loading"+ @update:project="changeProjectId"+ />+ <InstanceSelect+ v-if="mode === 'environment' && filterTypes.includes('instance')"+ :instance="params.instance?.id ?? UNKNOWN_ID"+ :environment="params.environment?.id"+ :include-all="true"+ :filter="instanceSupportSlowQuery"+ :disabled="loading"+ @update:instance="changeInstanceId"+ />+ <DatabaseSelect+ v-if="filterTypes.includes('database')"+ :database="params.database?.id ?? UNKNOWN_ID"+ :environment="params.environment?.id"+ :instance="params.instance?.id"+ :project="params.project?.id"+ :include-all="true"+ :filter="(db) => instanceSupportSlowQuery(db.instance)"+ :disabled="loading"+ @update:database="changeDatabaseId"+ />+ <NDatePicker+ v-if="filterTypes.includes('time-range')"+ :value="params.timeRange"+ :disabled="loading"+ :is-date-disabled="isDateDisabled"+ type="daterange"+ clearable+ style="width: 16rem"+ @update:value="changeTimeRange"+ />+ </NInputGroup>+ </div>++ <div v-if="filterTypes.includes('environment')">+ <EnvironmentTabFilter+ :environment="params.environment?.id ?? UNKNOWN_ID"+ :include-all="true"+ :disabled="loading"+ @update:environment="changeEnvironmentId"+ />+ </div>+ </div>+</template>+<script lang="ts" setup>+import { computed, shallowRef, watch } from "vue";+import { NDatePicker, NInputGroup, NRadio, NRadioGroup } from "naive-ui";+import dayjs from "dayjs";++import {+ type DatabaseId,+ type EnvironmentId,+ type InstanceId,+ type ProjectId,+ UNKNOWN_ID,+} from "@/types";+import {+ useCurrentUser,+ useDatabaseStore,+ useEnvironmentStore,+ useInstanceStore,+ useProjectStore,+} from "@/store";+import { hasWorkspacePermission, instanceSupportSlowQuery } from "@/utils";+import type { FilterType, SlowQueryFilterParams } from "./types";+import {+ ProjectSelect,+ InstanceSelect,+ EnvironmentTabFilter,+ DatabaseSelect,+} from "@/components/v2";++type FilterMode = "environment" | "project";++const props = defineProps<{+ params: SlowQueryFilterParams;+ filterTypes: readonly FilterType[];+ loading?: boolean;+}>();++const emit = defineEmits<{+ (event: "update:params", params: SlowQueryFilterParams): void;+}>();++const currentUser = useCurrentUser();+const mode = shallowRef<FilterMode>("environment");++const allowFilterByEnvironment = computed(() => {+ if (!props.filterTypes.includes("mode")) {+ return false;+ }+ return hasWorkspacePermission(+ "bb.permission.workspace.manage-database",+ currentUser.value.role+ );+});++const changeEnvironmentId = (id: EnvironmentId) => {+ const environment = useEnvironmentStore().getEnvironmentById(id);+ update({ environment });+};+const changeInstanceId = (id: InstanceId | undefined) => {+ if (id && id !== UNKNOWN_ID) {+ const instance = useInstanceStore().getInstanceById(id ?? UNKNOWN_ID);+ update({ instance });+ return;+ }+ update({ instance: undefined });+};+const changeDatabaseId = (id: DatabaseId | undefined) => {+ if (id && id !== UNKNOWN_ID) {+ const database = useDatabaseStore().getDatabaseById(id ?? UNKNOWN_ID);+ update({ database });+ return;+ }+ update({ database: undefined });+};+const changeProjectId = (id: ProjectId | undefined) => {+ if (id && id !== UNKNOWN_ID) {+ const project = useProjectStore().getProjectById(id);+ update({ project });+ return;+ }+ update({ project: undefined });+};+const changeTimeRange = (timeRange: [number, number] | null) => {+ if (!timeRange) {+ update({ timeRange: undefined });+ return;+ }+ update({ timeRange });+};++const update = (params: Partial<SlowQueryFilterParams>) => {+ emit("update:params", {+ ...props.params,+ ...params,+ });+};++// Clear unused filter params when mode changed+watch(mode, (mode) => {+ if (!props.filterTypes.includes("mode")) {+ return;+ }++ if (mode === "environment") {+ if (props.params.project) {+ update({ project: undefined, instance: undefined, database: undefined });+ }+ } else if (mode === "project") {+ if (props.params.environment) {+ update({+ environment: undefined,+ instance: undefined,+ database: undefined,+ });+ }+ }+});++watch(+ allowFilterByEnvironment,+ (allowed) => {+ if (!allowed) {+ mode.value = "project";+ }+ },+ { immediate: true }+);++const isDateDisabled = (date: number) => {+ return date > dayjs().endOf("day").valueOf();+};+</script>diff --git a/frontend/src/components/SlowQuery/Panel/LogTable.vue b/frontend/src/components/SlowQuery/Panel/LogTable.vuenew file mode 100644index 0000000000..7820f6219b--- /dev/null+++ b/frontend/src/components/SlowQuery/Panel/LogTable.vue@@ -0,0 +1,129 @@+<template>+ <BBGrid+ :column-list="columns"+ :data-source="slowQueryLogList"+ :show-placeholder="showPlaceholder"+ class="border compact w-auto overflow-x-auto"+ header-class="capitalize"+ @click-row="(log: ComposedSlowQueryLog) => $emit('select', log)"+ >+ <template #item="{ item: { log, database } }: SlowQueryLogRow">+ <template v-if="log.statistics">+ <div class="bb-grid-cell">+ <HumanizeTs :ts="dateToTS(log.statistics.latestLogTime)" />+ </div>+ <div class="bb-grid-cell">+ <DatabaseName :database="database" />+ </div>+ <div class="bb-grid-cell text-xs font-mono">+ <div class="truncate">+ {{ log.statistics.sqlFingerprint }}+ </div>+ </div>+ <div class="bb-grid-cell">+ {{ log.statistics.count }}+ </div>+ <div class="bb-grid-cell">+ {{+ log.statistics.nightyFifthPercentileQueryTime?.seconds.toFixed(6)+ }}+ </div>+ <div class="bb-grid-cell">+ {{ log.statistics.averageQueryTime?.seconds.toFixed(6) }}+ </div>+ <div class="bb-grid-cell">+ {{ log.statistics.nightyFifthPercentileRowsExamined }}+ </div>+ <div class="bb-grid-cell">+ {{ log.statistics.averageRowsExamined }}+ </div>+ <div class="bb-grid-cell">+ {{ log.statistics.nightyFifthPercentileRowsSent }}+ </div>+ <div class="bb-grid-cell">+ {{ log.statistics.averageRowsSent }}+ </div>+ </template>+ </template>+ </BBGrid>+</template>++<script lang="ts" setup>+import { computed } from "vue";+import { useI18n } from "vue-i18n";++import { type BBGridColumn, type BBGridRow, BBGrid } from "@/bbkit";+import type { ComposedSlowQueryLog } from "@/types";+import HumanizeTs from "@/components/misc/HumanizeTs.vue";+import { DatabaseName } from "@/components/v2";++export type SlowQueryLogRow = BBGridRow<ComposedSlowQueryLog>;++withDefaults(+ defineProps<{+ slowQueryLogList?: ComposedSlowQueryLog[];+ showPlaceholder?: boolean;+ }>(),+ {+ slowQueryLogList: () => [],+ showPlaceholder: true,+ }+);++defineEmits<{+ (event: "select", log: ComposedSlowQueryLog): void;+}>();++const { t } = useI18n();++const columns = computed(() => {+ const columns: BBGridColumn[] = [+ {+ title: t("slow-query.last-query-time"),+ width: "minmax(8rem, auto)",+ },+ {+ title: t("slow-query.database-name"),+ width: "minmax(12rem, 18rem)",+ },+ {+ title: t("slow-query.sql-statement"),+ width: "minmax(20rem, 1fr)",+ },+ {+ title: t("slow-query.total-query-count"),+ width: "minmax(6rem, auto)",+ },+ {+ title: t("slow-query.query-time-95-percent"),+ width: "minmax(6rem, auto)",+ },+ {+ title: t("slow-query.query-time-avg"),+ width: "minmax(6rem, auto)",+ },+ {+ title: t("slow-query.rows-examined-95-percent"),+ width: "minmax(6rem, auto)",+ },+ {+ title: t("slow-query.rows-sent-95-percent"),+ width: "minmax(6rem, auto)",+ },+ {+ title: t("slow-query.rows-examined-avg"),+ width: "minmax(6rem, auto)",+ },+ {+ title: t("slow-query.rows-sent-avg"),+ width: "minmax(6rem, auto)",+ },+ ];+ return columns;+});++const dateToTS = (date: Date | undefined) => {+ if (!date) return 0;+ return Math.floor(date.getTime() / 1000);+};+</script>diff --git a/frontend/src/components/SlowQuery/Panel/SlowQueryPanel.vue b/frontend/src/components/SlowQuery/Panel/SlowQueryPanel.vuenew file mode 100644index 0000000000..ecace98bba--- /dev/null+++ b/frontend/src/components/SlowQuery/Panel/SlowQueryPanel.vue@@ -0,0 +1,85 @@+<template>+ <div>+ <div v-if="filterTypes.length > 0">+ <LogFilter+ :params="filter"+ :filter-types="filterTypes"+ :loading="loading"+ @update:params="$emit('update:filter', $event)"+ />+ </div>+ <div class="relative min-h-[8rem]">+ <LogTable+ :slow-query-log-list="slowQueryLogList"+ :show-placeholder="!loading"+ @select="selectedSlowQueryLog = $event"+ />+ <div+ v-if="loading"+ class="absolute inset-0 bg-white/50 flex flex-col items-center pt-[6rem]"+ >+ <BBSpin />+ </div>+ </div>++ <DetailDialog+ v-if="selectedSlowQueryLog"+ :slow-query-log="selectedSlowQueryLog"+ @close="selectedSlowQueryLog = undefined"+ />+ </div>+</template>++<script lang="ts" setup>+import { computed, shallowRef, watch } from "vue";++import type { ComposedSlowQueryLog } from "@/types";+import { useSlowQueryStore } from "@/store";+import {+ type FilterType,+ type SlowQueryFilterParams,+ FilterTypeList,+ buildListSlowQueriesRequest,+} from "./types";+import LogFilter from "./LogFilter.vue";+import LogTable from "./LogTable.vue";+import DetailDialog from "./DetailDialog.vue";++const props = withDefaults(+ defineProps<{+ filter: SlowQueryFilterParams;+ filterTypes?: readonly FilterType[];+ }>(),+ {+ filterTypes: () => FilterTypeList,+ }+);++defineEmits<{+ (event: "update:filter", filter: SlowQueryFilterParams): void;+}>();++const slowQueryStore = useSlowQueryStore();+const loading = shallowRef(false);+const slowQueryLogList = shallowRef<ComposedSlowQueryLog[]>([]);+const selectedSlowQueryLog = shallowRef<ComposedSlowQueryLog>();++const params = computed(() => {+ return buildListSlowQueriesRequest(props.filter);+});++const fetchSlowQueryLogList = async () => {+ loading.value = true;+ try {+ const list = await slowQueryStore.fetchSlowQueryLogList(params.value);+ slowQueryLogList.value = list;+ } finally {+ loading.value = false;+ }+};++// Fetch the list while params changed.+watch(() => JSON.stringify(params.value), fetchSlowQueryLogList, {+ immediate: true,+});+</script>diff --git a/frontend/src/components/SlowQuery/Panel/index.ts b/frontend/src/components/SlowQuery/Panel/index.tsnew file mode 100644index 0000000000..7a80007fc7--- /dev/null+++ b/frontend/src/components/SlowQuery/Panel/index.ts@@ -0,0 +1,4 @@+import SlowQueryPanel from "./SlowQueryPanel.vue";++export * from "./types";+export { SlowQueryPanel };diff --git a/frontend/src/components/SlowQuery/Panel/types.ts b/frontend/src/components/SlowQuery/Panel/types.tsnew file mode 100644index 0000000000..dcd86b331f--- /dev/null+++ b/frontend/src/components/SlowQuery/Panel/types.ts@@ -0,0 +1,68 @@+import dayjs from "dayjs";+import { Environment, Instance, Database, Project, UNKNOWN_ID } from "@/types";+import { ListSlowQueriesRequest } from "@/types/proto/v1/database_service";++export type SlowQueryFilterParams = {+ project: Project | undefined; // undefined to "All"+ environment: Environment | undefined; // undefined to "All"+ instance: Instance | undefined; // undefined to "All"+ database: Database | undefined; // undefined to "All"+ timeRange: [number, number] | undefined;+};++export const FilterTypeList = [+ "mode",+ "project",+ "environment",+ "instance",+ "database",+ "time-range",+] as const;++export type FilterType = typeof FilterTypeList[number];++export const defaultSlowQueryFilterParams = (): SlowQueryFilterParams => {+ const now = dayjs();+ const recentWeek: [number, number] = [+ now.subtract(7, "days").startOf("day").valueOf(),+ now.endOf("day").valueOf(),+ ];+ return {+ project: undefined,+ environment: undefined,+ instance: undefined,+ database: undefined,+ timeRange: recentWeek,+ };+};++export const buildListSlowQueriesRequest = (filter: SlowQueryFilterParams) => {+ const request = {} as Partial<ListSlowQueriesRequest>;+ const { project, environment, instance, database, timeRange } = filter;++ request.parent = "environments/-/instances/-/databases/-";+ if (database && database.id !== UNKNOWN_ID) {+ request.parent = `environments/${database.instance.environment.resourceId}/instances/${database.instance.resourceId}/databases/${database.name}`;+ } else if (instance && instance.id !== UNKNOWN_ID) {+ request.parent = `environments/${instance.environment.resourceId}/instances/${instance.resourceId}/databases/-`;+ } else if (environment && environment.id !== UNKNOWN_ID) {+ request.parent = `environments/${environment.resourceId}/instances/-/databases/-`;+ }++ const query: string[] = [];+ if (project) {+ query.push(`project = "projects/${project.resourceId}"`);+ }+ if (timeRange) {+ const start = dayjs(timeRange[0]).startOf("day").toISOString();+ const end = dayjs(timeRange[1]).endOf("day").toISOString();+ query.push(`start_time >= "${start}"`);+ query.push(`start_time <= "${end}"`);+ }+ if (query.length > 0) {+ request.filter = query.join(" && ");+ }++ request.orderBy = "count desc";+ return ListSlowQueriesRequest.fromJSON(request);+};diff --git a/frontend/src/components/SlowQuery/Settings/SlowQuerySettings.vue b/frontend/src/components/SlowQuery/Settings/SlowQuerySettings.vueindex 2996c5b162..30836e842f 100644--- a/frontend/src/components/SlowQuery/Settings/SlowQuerySettings.vue+++ b/frontend/src/components/SlowQuery/Settings/SlowQuerySettings.vue@@ -1,5 +1,8 @@<template>- <div class="space-y-4 pb-4">+ <div class="space-y-4 pb-4 w-[48rem] max-w-full">+ <div>+ <BBAttention :style="'WARN'" :description="attentionDescription" />+ </div><div><EnvironmentTabFilter:environment="state.filter.environment?.id ?? UNKNOWN_ID"@@ -7,7 +10,7 @@@update:environment="changeEnvironment"/></div>- <div class="w-[48rem] max-w-full">+ <div><SlowQueryPolicyTable:instance-list="state.ready ? filteredInstanceList : []":policy-list="policyList"@@ -27,11 +30,14 @@<script lang="ts" setup>import { computed, onMounted, reactive } from "vue";+import { BBAttention } from "@/bbkit";import {featureToRef,+ pushNotification,useEnvironmentList,useInstanceStore,useSlowQueryPolicyStore,+ useSlowQueryStore,} from "@/store";import {Environment,@@ -43,6 +49,7 @@ import {import { EnvironmentTabFilter } from "@/components/v2";import { SlowQueryPolicyTable } from "./components";import { instanceSupportSlowQuery } from "@/utils";+import { useI18n } from "vue-i18n";const emit = defineEmits<{(event: "show-feature-modal"): void;@@ -64,7 +71,9 @@ const state = reactive<LocalState>({},});+const { t } = useI18n();const policyStore = useSlowQueryPolicyStore();+const slowQueryStore = useSlowQueryStore();const instanceStore = useInstanceStore();const environmentList = useEnvironmentList(["NORMAL"]);const hasSlowQueryFeature = featureToRef("bb.feature.slow-query");@@ -127,10 +136,28 @@ const toggleActive = async (instance: Instance, active: boolean) => {payload,});+ if (active) {+ // When turning ON an instance's slow query, call the corresponding+ // API endpoint to sync slow queries from the instance immediately.+ await slowQueryStore.syncSlowQueriesByInstance(instance);+ }+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });} catch {// nothing}};onMounted(prepare);++const attentionDescription = computed(() => {+ const versions = `MySQL >= 5.7`;++ return t("slow-query.attention-description", {+ versions,+ });+});</script>diff --git a/frontend/src/components/SlowQuery/index.ts b/frontend/src/components/SlowQuery/index.tsindex abda3bc7b5..1b257b334e 100644--- a/frontend/src/components/SlowQuery/index.ts+++ b/frontend/src/components/SlowQuery/index.ts@@ -1 +1,2 @@export * from "./Settings";+export * from "./Panel";diff --git a/frontend/src/components/TransferDatabaseForm/TransferSourceSelector.vue b/frontend/src/components/TransferDatabaseForm/TransferSourceSelector.vueindex bf4d06fed0..0c0c41cdb2 100644--- a/frontend/src/components/TransferDatabaseForm/TransferSourceSelector.vue+++ b/frontend/src/components/TransferDatabaseForm/TransferSourceSelector.vue@@ -49,7 +49,7 @@</template><script lang="ts" setup>-import { PropType, reactive, watch, watchEffect } from "vue";+import { PropType, reactive, watch } from "vue";import { NInputGroup } from "naive-ui";import { TransferSource } from "./utils";@@ -96,10 +96,6 @@ const state = reactive<LocalState>({transferSource: props.transferSource,});-const prepare = () => {- useInstanceStore().fetchInstanceList();-};-const changeInstanceFilter = (instanceId: InstanceId | undefined) => {if (!instanceId || instanceId === UNKNOWN_ID) {return emit("select-instance", undefined);@@ -120,6 +116,4 @@ watch(}});--watchEffect(prepare);</script>diff --git a/frontend/src/components/v2/Model/DatabaseName.vue b/frontend/src/components/v2/Model/DatabaseName.vuenew file mode 100644index 0000000000..34235ff59c--- /dev/null+++ b/frontend/src/components/v2/Model/DatabaseName.vue@@ -0,0 +1,51 @@+<template>+ <component+ :is="link ? 'router-link' : tag"+ v-bind="bindings"+ class="inline-flex items-center gap-x-1"+ >+ <span v-if="prefix" class="ml-1 text-gray-400">{{ prefix }}</span>+ <span>{{ database.name }}</span>+ </component>+</template>++<script lang="ts" setup>+import { computed } from "vue";++import type { Database } from "@/types";+import { databaseSlug } from "@/utils";++const props = withDefaults(+ defineProps<{+ database: Database;+ tag?: string;+ link?: boolean;+ }>(),+ {+ tag: "span",+ link: true,+ }+);++const bindings = computed(() => {+ if (props.link) {+ return {+ to: `/db/${databaseSlug(props.database)}`,+ activeClass: "",+ exactActiveClass: "",+ onClick: (e: MouseEvent) => {+ e.stopPropagation();+ },+ };+ }+ return {};+});++const prefix = computed(() => {+ const { database } = props;+ if (database.instance.engine === "REDIS") {+ return database.instance.name;+ }+ return "";+});+</script>diff --git a/frontend/src/components/v2/Model/EnvironmentName.vue b/frontend/src/components/v2/Model/EnvironmentName.vueindex fe0b35152e..fbf9840edc 100644--- a/frontend/src/components/v2/Model/EnvironmentName.vue+++ b/frontend/src/components/v2/Model/EnvironmentName.vue@@ -13,10 +13,11 @@</template><script lang="ts" setup>+import { computed } from "vue";+import type { Environment } from "@/types";import { environmentName, environmentSlug } from "@/utils";import ProductionEnvironmentIcon from "@/components/Environment/ProductionEnvironmentIcon.vue";-import { computed } from "vue";const props = withDefaults(defineProps<{@@ -34,6 +35,8 @@ const bindings = computed(() => {if (props.link) {return {to: `/environment/${environmentSlug(props.environment)}`,+ activeClass: "",+ exactActiveClass: "",onClick: (e: MouseEvent) => {e.stopPropagation();},diff --git a/frontend/src/components/v2/Model/InstanceName.vue b/frontend/src/components/v2/Model/InstanceName.vueindex febdc478ef..b4a3a13b52 100644--- a/frontend/src/components/v2/Model/InstanceName.vue+++ b/frontend/src/components/v2/Model/InstanceName.vue@@ -1,6 +1,7 @@<template><component:is="link ? 'router-link' : tag"+ v-bind="bindings":to="link && `/instance/${instance.id}`"class="inline-flex items-center gap-x-1"@click.stop=""@@ -20,11 +21,13 @@</template><script lang="ts" setup>+import { computed } from "vue";+import type { Instance } from "@/types";import InstanceEngineIcon from "@/components/InstanceEngineIcon.vue";-import { instanceName } from "@/utils";+import { instanceName, instanceSlug } from "@/utils";-withDefaults(+const props = withDefaults(defineProps<{instance: Instance;tag?: string;@@ -39,4 +42,18 @@ withDefaults(iconPosition: "prefix",});++const bindings = computed(() => {+ if (props.link) {+ return {+ to: `/instance/${instanceSlug(props.instance)}`,+ activeClass: "",+ exactActiveClass: "",+ onClick: (e: MouseEvent) => {+ e.stopPropagation();+ },+ };+ }+ return {};+});</script>diff --git a/frontend/src/components/v2/Model/index.ts b/frontend/src/components/v2/Model/index.tsindex e7ed32b35f..e8647d29eb 100644--- a/frontend/src/components/v2/Model/index.ts+++ b/frontend/src/components/v2/Model/index.ts@@ -1,4 +1,5 @@+import DatabaseName from "./DatabaseName.vue";import InstanceName from "./InstanceName.vue";import EnvironmentName from "./EnvironmentName.vue";-export { InstanceName, EnvironmentName };+export { DatabaseName, InstanceName, EnvironmentName };diff --git a/frontend/src/components/v2/Select/DatabaseSelect.vue b/frontend/src/components/v2/Select/DatabaseSelect.vuenew file mode 100644index 0000000000..6f4f0543fe--- /dev/null+++ b/frontend/src/components/v2/Select/DatabaseSelect.vue@@ -0,0 +1,129 @@+<template>+ <NSelect+ :value="database"+ :options="options"+ :placeholder="$t('database.select')"+ :virtual-scroll="true"+ style="width: 12rem"+ @update:value="$emit('update:database', $event)"+ />+</template>++<script lang="ts" setup>+import { computed, watch, watchEffect } from "vue";+import { NSelect, SelectOption } from "naive-ui";+import { useI18n } from "vue-i18n";++import { useCurrentUser, useDatabaseStore } from "@/store";+import {+ Database,+ DatabaseId,+ DatabaseSyncStatus,+ EngineType,+ EngineTypeList,+ EnvironmentId,+ InstanceId,+ ProjectId,+ UNKNOWN_ID,+ unknown,+} from "@/types";++const props = withDefaults(+ defineProps<{+ database: DatabaseId | undefined;+ environment?: EnvironmentId;+ instance?: InstanceId;+ project?: ProjectId;+ allowedEngineTypeList?: readonly EngineType[];+ allowedSyncStatusList?: DatabaseSyncStatus[];+ includeAll?: boolean;+ autoReset?: boolean;+ filter?: (database: Database, index: number) => boolean;+ }>(),+ {+ environment: undefined,+ instance: undefined,+ project: undefined,+ allowedEngineTypeList: () => EngineTypeList,+ allowedSyncStatusList: () => ["OK", "NOT_FOUND"],+ includeAll: false,+ autoReset: true,+ filter: undefined,+ }+);++const emit = defineEmits<{+ (event: "update:database", value: DatabaseId | undefined): void;+}>();++const { t } = useI18n();+const currentUser = useCurrentUser();+const databaseStore = useDatabaseStore();++const prepare = () => {+ databaseStore.fetchDatabaseList();+};+watchEffect(prepare);++const rawDatabaseList = computed(() => {+ const list = databaseStore.getDatabaseListByPrincipalId(currentUser.value.id);++ return list.filter((db) => {+ if (props.environment && props.environment !== UNKNOWN_ID) {+ if (db.instance.environment.id !== props.environment) return false;+ }+ if (props.instance && props.instance !== UNKNOWN_ID) {+ if (db.instance.id !== props.instance) return false;+ }+ if (props.project && props.project !== UNKNOWN_ID) {+ if (db.project.id !== props.project) return false;+ }+ if (!props.allowedEngineTypeList.includes(db.instance.engine)) return false;+ if (!props.allowedSyncStatusList.includes(db.syncStatus)) return false;++ return true;+ });+});++const combinedDatabaseList = computed(() => {+ let list = [...rawDatabaseList.value];++ if (props.filter) {+ list = list.filter(props.filter);+ }++ if (props.database === UNKNOWN_ID || props.includeAll) {+ const dummyAll = unknown("DATABASE");+ dummyAll.name = t("database.all");+ list.unshift(dummyAll);+ }++ return list;+});++const options = computed(() => {+ return combinedDatabaseList.value.map<SelectOption>((database) => {+ return {+ value: database.id,+ label: database.name,+ };+ });+});++// The database list might change if environment changes, and the previous selected id+// might not exist in the new list. In such case, we need to invalidate the selection+// and emit the event.+const resetInvalidSelection = () => {+ if (!props.autoReset) return;+ if (+ props.database &&+ !combinedDatabaseList.value.find((item) => item.id === props.database)+ ) {+ emit("update:database", undefined);+ }+};++watch([() => props.database, combinedDatabaseList], resetInvalidSelection, {+ immediate: true,+});+</script>diff --git a/frontend/src/components/v2/Select/InstanceSelect.vue b/frontend/src/components/v2/Select/InstanceSelect.vueindex 7676afbffe..7a6748fa33 100644--- a/frontend/src/components/v2/Select/InstanceSelect.vue+++ b/frontend/src/components/v2/Select/InstanceSelect.vue@@ -13,7 +13,7 @@ import { computed, watch, h } from "vue";import { NSelect, SelectOption } from "naive-ui";import { useI18n } from "vue-i18n";-import { useInstanceStore } from "@/store";+import { useInstanceList, useInstanceStore } from "@/store";import {InstanceId,EnvironmentId,@@ -51,6 +51,7 @@ const emit = defineEmits<{const { t } = useI18n();const instanceStore = useInstanceStore();+useInstanceList();const rawInstanceList = computed(() => {let list: Instance[] = [];diff --git a/frontend/src/components/v2/Select/ProjectSelect.vue b/frontend/src/components/v2/Select/ProjectSelect.vuenew file mode 100644index 0000000000..3ba4655ba2--- /dev/null+++ b/frontend/src/components/v2/Select/ProjectSelect.vue@@ -0,0 +1,144 @@+<template>+ <NSelect+ :value="project"+ :options="options"+ :placeholder="$t('project.select')"+ style="width: 12rem"+ @update:value="$emit('update:project', $event)"+ />+</template>++<script lang="ts" setup>+import { computed, watchEffect } from "vue";+import { useI18n } from "vue-i18n";+import { NSelect, SelectOption } from "naive-ui";++import { useCurrentUser, useProjectStore } from "@/store";+import {+ DEFAULT_PROJECT_ID,+ ProjectId,+ ProjectRoleType,+ ProjectTenantMode,+ ProjectWorkflowType,+ UNKNOWN_ID,+ unknown,+} from "@/types";+import { memberInProject } from "@/utils";++const props = withDefaults(+ defineProps<{+ project: ProjectId | undefined; // UNKNOWN_ID(-1) to "ALL"+ allowedProjectRoleList?: ProjectRoleType[];+ allowedProjectTenantModeList?: ProjectTenantMode[];+ allowedProjectWorkflowTypeList?: ProjectWorkflowType[];+ includeAll?: boolean;+ includeDefaultProject?: boolean;+ includeArchived?: boolean;+ }>(),+ {+ allowedProjectRoleList: () => ["OWNER", "DEVELOPER"],+ allowedProjectTenantModeList: () => ["DISABLED", "TENANT"],+ allowedProjectWorkflowTypeList: () => ["UI", "VCS"],+ includeAll: false,+ includeDefaultProject: false,+ includeArchived: false,+ }+);++defineEmits<{+ (event: "update:project", id: ProjectId | undefined): void;+}>();++const { t } = useI18n();+const currentUser = useCurrentUser();+const projectStore = useProjectStore();++const prepare = () => {+ projectStore.fetchProjectListByUser({+ userId: currentUser.value.id,+ rowStatusList: ["NORMAL", "ARCHIVED"],+ });+};++const rawProjectList = computed(() => {+ let list = projectStore.getProjectListByUser(currentUser.value.id, [+ "NORMAL",+ "ARCHIVED",+ ]);+ // Filter by role+ list = list.filter((project) => {+ const member = memberInProject(project, currentUser.value);+ if (!member) return false;+ return props.allowedProjectRoleList.includes(member.role);+ });+ // Filter by project tenant mode+ list = list.filter((project) => {+ return props.allowedProjectTenantModeList.includes(project.tenantMode);+ });+ // Filter by project workflow type+ list = list.filter((project) => {+ return props.allowedProjectWorkflowTypeList.includes(project.workflowType);+ });++ return list;+});++const isOrphanValue = computed(() => {+ if (props.project === undefined) return false;++ return !rawProjectList.value.find((proj) => proj.id === props.project);+});++const combinedProjectList = computed(() => {+ const list = rawProjectList.value.filter((project) => {+ if (props.includeArchived) return true;+ if (project.rowStatus === "NORMAL") return true;+ // ARCHIVED+ if (project.id === props.project) return true;+ return false;+ });++ if (props.includeDefaultProject) {+ list.unshift(projectStore.getProjectById(DEFAULT_PROJECT_ID));+ }+ if (+ props.project &&+ props.project !== DEFAULT_PROJECT_ID &&+ props.project !== UNKNOWN_ID &&+ isOrphanValue.value+ ) {+ // It may happen the selected id might not be in the project list.+ // e.g. the selected project is deleted after the selection and we+ // are unable to cleanup properly. In such case, the selected project id+ // is orphaned and we just display the id+ const dummyProject = unknown("PROJECT");+ dummyProject.id = props.project;+ dummyProject.name = props.project.toString();+ list.unshift(dummyProject);+ }++ if (props.project === UNKNOWN_ID || props.includeAll) {+ const dummyAll = unknown("PROJECT");+ dummyAll.name = t("project.all");+ list.unshift(dummyAll);+ }++ return list;+});++const options = computed(() => {+ return combinedProjectList.value.map<SelectOption>((project) => {+ return {+ value: project.id,+ label:+ project.id === DEFAULT_PROJECT_ID+ ? t("common.unassigned")+ : project.id === UNKNOWN_ID+ ? t("project.all")+ : project.name,+ };+ });+});++watchEffect(prepare);+</script>diff --git a/frontend/src/components/v2/Select/index.ts b/frontend/src/components/v2/Select/index.tsindex 24fb471c76..6e664ec6e4 100644--- a/frontend/src/components/v2/Select/index.ts+++ b/frontend/src/components/v2/Select/index.ts@@ -1,3 +1,5 @@import InstanceSelect from "./InstanceSelect.vue";+import DatabaseSelect from "./DatabaseSelect.vue";+import ProjectSelect from "./ProjectSelect.vue";-export { InstanceSelect };+export { InstanceSelect, DatabaseSelect, ProjectSelect };diff --git a/frontend/src/components/v2/index.ts b/frontend/src/components/v2/index.tsindex cb6f25f5ac..897fd18554 100644--- a/frontend/src/components/v2/index.ts+++ b/frontend/src/components/v2/index.ts@@ -1,3 +1,4 @@+export * from "./Select";export * from "./TabFilter";export * from "./Model";export * from "./Form";diff --git a/frontend/src/grpcweb/index.ts b/frontend/src/grpcweb/index.tsindex 7ba4d8ec67..ff80aa7f83 100644--- a/frontend/src/grpcweb/index.ts+++ b/frontend/src/grpcweb/index.ts@@ -12,6 +12,7 @@ import { SQLServiceDefinition } from "@/types/proto/v1/sql_service";import { RiskServiceDefinition } from "@/types/proto/v1/risk_service";import { SettingServiceDefinition } from "@/types/proto/v1/setting_service";import { ReviewServiceDefinition } from "@/types/proto/v1/review_service";+import { DatabaseServiceDefinition } from "@/types/proto/v1/database_service";// Create each grpc service client.// Reference: https://github.com/deeplay-io/nice-grpc/blob/master/packages/nice-grpc-web/README.md@@ -49,6 +50,11 @@ export const projectServiceClient = clientFactory.create(channel);+export const databaseServiceClient = clientFactory.create(+ DatabaseServiceDefinition,+ channel+);+export const identityProviderClient = clientFactory.create(IdentityProviderServiceDefinition,channeldiff --git a/frontend/src/layouts/ProjectLayout.vue b/frontend/src/layouts/ProjectLayout.vueindex a87a376b31..e7dd6ef488 100644--- a/frontend/src/layouts/ProjectLayout.vue+++ b/frontend/src/layouts/ProjectLayout.vue@@ -27,11 +27,7 @@:responsive="false":tab-item-list="tabItemList":selected-index="state.selectedIndex"- @select-index="- (index: number) => {- selectTab(index);- }- "+ @select-index="selectTab"/><div class="py-6 px-6">@@ -46,6 +42,8 @@<script lang="ts">import { computed, defineComponent, reactive, watch } from "vue";import { useRouter } from "vue-router";+import { startCase } from "lodash-es";+import {idFromSlug,hasProjectPermission,@@ -105,6 +103,8 @@ export default defineComponent({? null // Hide "Change History" tab for tenant projects: { name: t("common.change-history"), hash: "change-history" },+ { name: startCase(t("slow-query.slow-queries")), hash: "slow-query" },+{ name: t("common.activities"), hash: "activity" },{ name: t("common.gitops"), hash: "gitops" },{ name: t("common.webhooks"), hash: "webhook" },diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 09696fc649..47a3b08b1c 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1142,7 +1142,8 @@"n-selected-m-in-total": "({selected} selected, {total} in total)","doesnt-match-database-name-template": "Doesn't match tenant database name template","doesnt-match-tenant-value": "Doesn't match label value",- "should-follow-database-name-template": "Should follow tenant database name template"+ "should-follow-database-name-template": "Should follow tenant database name template",+ "all": "All databases"},"repository": {"branch-observe-file-change": "The branch where Bytebase observes the file change.",@@ -1349,7 +1350,8 @@"project-member": "Require LGTM from project members","project-owner": "Require LGTM from project owner"},- "successfully-updated-db-name-template": "Successfully updated database name template."+ "successfully-updated-db-name-template": "Successfully updated database name template.",+ "all": "All projects"},"inbox": {"mark-all-as-read": "Mark all as read",@@ -2275,6 +2277,7 @@"rows-examined": "Rows examined","rows-sent": "Rows sent","lock-time": "Lock time",- "query-time": "Query time"+ "query-time": "Query time",+ "attention-description": "Logging and analyzing slow queires for {versions}.\nBytebase will periodically sync slow query logs from instances."}}diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 60005754a8..520f5557eb 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1140,7 +1140,8 @@"n-selected-m-in-total": "(已选择 {selected},共计 {total})","doesnt-match-database-name-template": "不符合租户数据库名称模板","doesnt-match-tenant-value": "与租户标签值不匹配",- "should-follow-database-name-template": "需要遵循租户数据库名称模板"+ "should-follow-database-name-template": "需要遵循租户数据库名称模板",+ "all": "所有数据库"},"repository": {"branch-observe-file-change": "Bytebase 跟踪文件变更的分支。",@@ -1347,7 +1348,8 @@"project-member": "需要来自项目成员的 LGTM","project-owner": "需要来自项目所有者的 LGTM"},- "successfully-updated-db-name-template": "成功更新数据库名称模板。"+ "successfully-updated-db-name-template": "成功更新数据库名称模板。",+ "all": "所有项目"},"inbox": {"mark-all-as-read": "全部标记为已读",@@ -2272,6 +2274,7 @@"rows-examined": "解析行数","rows-sent": "返回行数","lock-time": "持有锁时长",- "query-time": "执行时长"+ "query-time": "执行时长",+ "attention-description": "为 {versions} 记录和分析慢查询。\nBytebase 会定期从实例上同步慢查询日志。"}}diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.tsindex eb8b222dd0..a080f7a86e 100644--- a/frontend/src/router/index.ts+++ b/frontend/src/router/index.ts@@ -252,6 +252,20 @@ const routes: Array<RouteRecordRaw> = [leftSidebar: true,},},+ {+ path: "slow-query",+ name: "workspace.slow-query",+ meta: { title: () => startCase(t("slow-query.slow-queries")) },+ components: {+ content: () =>+ import("../views/SlowQuery/SlowQueryDashboard.vue"),+ leftSidebar: DashboardSidebar,+ },+ props: {+ content: true,+ leftSidebar: true,+ },+ },{path: "anomaly-center",name: "workspace.anomaly-center",@@ -1288,6 +1302,7 @@ router.beforeEach((to, from, next) => {to.name === "error.500" ||to.name === "workspace.home" ||to.name === "workspace.inbox" ||+ to.name === "workspace.slow-query" ||to.name === "workspace.anomaly-center" ||to.name === "workspace.project" ||to.name === "workspace.instance" ||diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.tsindex c926bc1abe..836aee67ff 100644--- a/frontend/src/store/modules/index.ts+++ b/frontend/src/store/modules/index.ts@@ -50,3 +50,4 @@ export * from "./user";export * from "./risk";export * from "./workspaceApprovalSetting";export * from "./review";+export * from "./slowQuery";diff --git a/frontend/src/store/modules/slowQuery.ts b/frontend/src/store/modules/slowQuery.tsnew file mode 100644index 0000000000..a4e0452ab6--- /dev/null+++ b/frontend/src/store/modules/slowQuery.ts@@ -0,0 +1,73 @@+import { defineStore } from "pinia";+import { uniq } from "lodash-es";++import { databaseServiceClient, instanceServiceClient } from "@/grpcweb";+import {+ ListSlowQueriesRequest,+ SlowQueryLog,+} from "@/types/proto/v1/database_service";+import {+ ComposedSlowQueryLog,+ Database,+ Instance,+ unknown,+ UNKNOWN_ID,+} from "@/types";+import { useDatabaseStore } from "./database";++export const useSlowQueryStore = defineStore("slow-query", () => {+ const fetchSlowQueryLogList = async (+ request: Partial<ListSlowQueriesRequest> = {}+ ) => {+ try {+ const response = await databaseServiceClient.listSlowQueries(request);+ const composedLogList = await composeSlowQueryLogDatabase(+ response.slowQueryLogs+ );+ return composedLogList;+ } catch (ex) {+ return [];+ }+ };++ const syncSlowQueriesByInstance = async (instance: Instance) => {+ const name = `environments/${instance.environment.resourceId}/instances/${instance.resourceId}`;+ await instanceServiceClient.syncSlowQueries({+ instance: name,+ });+ };++ return { fetchSlowQueryLogList, syncSlowQueriesByInstance };+});++const composeSlowQueryLogDatabase = async (+ slowQueryLogList: SlowQueryLog[]+) => {+ const databaseNameList = uniq(slowQueryLogList.map((log) => log.resource));+ const databaseIdList = await Promise.all(+ databaseNameList.map((name) => {+ return databaseServiceClient.getDatabase({ name }).then(+ (db) => parseInt(db.uid, 10),+ () => UNKNOWN_ID // fallback for robustness+ );+ })+ );+ const databaseList = await Promise.all(+ databaseIdList.map((id) => {+ if (id === UNKNOWN_ID) return unknown("DATABASE");+ return useDatabaseStore().getOrFetchDatabaseById(id);+ })+ );+ const databaseMap = databaseList.reduce((map, db) => {+ if (db.id !== UNKNOWN_ID) {+ const resource = `environments/${db.instance.environment.resourceId}/instances/${db.instance.resourceId}/databases/${db.name}`;+ map.set(resource, db);+ }+ return map;+ }, new Map<string, Database>());++ return slowQueryLogList.map<ComposedSlowQueryLog>((log) => ({+ log,+ database: databaseMap.get(log.resource) ?? unknown("DATABASE"), // databaseMap.get(log.resource)!,+ }));+};diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex e9c7b9902b..644678fa59 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -52,3 +52,4 @@ export * from "./mfa";export * from "./risk";export * from "./workspaceApprovalSetting";export * from "./review";+export * from "./slowQuery";diff --git a/frontend/src/types/slowQuery.ts b/frontend/src/types/slowQuery.tsnew file mode 100644index 0000000000..e30cab5e4a--- /dev/null+++ b/frontend/src/types/slowQuery.ts@@ -0,0 +1,7 @@+import { Database } from "./database";+import type { SlowQueryLog } from "./proto/v1/database_service";++export type ComposedSlowQueryLog = {+ log: SlowQueryLog;+ database: Database;+};diff --git a/frontend/src/utils/database.ts b/frontend/src/utils/database.tsindex 619afd00c8..50badb6614 100644--- a/frontend/src/utils/database.ts+++ b/frontend/src/utils/database.ts@@ -144,3 +144,28 @@ export function isArchivedDatabase(db: Database): boolean {}return false;}++export const extractDatabaseResourceName = (+ resource: string+): {+ environment?: string;+ instance?: string;+ database?: string;+} => {+ const pattern =+ /^environments\/([^/]+)\/instances\/([^/]+)\/databases\/([^/]+)$/;+ const matches = resource.match(pattern);+ if (matches) {+ const [_, environment, instance, database] = matches;+ return {+ environment,+ instance,+ database,+ };+ }+ return {+ environment: undefined,+ instance: undefined,+ database: undefined,+ };+};diff --git a/frontend/src/utils/project.ts b/frontend/src/utils/project.tsindex a2ae15e810..5dd353a616 100644--- a/frontend/src/utils/project.ts+++ b/frontend/src/utils/project.ts@@ -1,4 +1,4 @@-import { DEFAULT_PROJECT_ID, type Project } from "../types";+import { DEFAULT_PROJECT_ID, Principal, type Project } from "../types";export function projectName(project: Project) {if (project.id === DEFAULT_PROJECT_ID) {@@ -11,3 +11,7 @@ export function projectName(project: Project) {}return name;}++export const memberInProject = (project: Project, user: Principal) => {+ return project.memberList.find((member) => member.principal.id === user.id);+};diff --git a/frontend/src/views/DashboardSidebar.vue b/frontend/src/views/DashboardSidebar.vueindex 742032de4d..e8a7a8e3bb 100644--- a/frontend/src/views/DashboardSidebar.vue+++ b/frontend/src/views/DashboardSidebar.vue@@ -39,6 +39,14 @@<heroicons-solid:terminal class="w-5 h-5 mr-2" />{{ $t("sql-editor.self") }}</a>+ <router-link+ to="/slow-query"+ class="outline-item group flex items-center px-2 py-2 capitalize"+ >+ <heroicons:rocket-launch class="w-5 h-5 mr-2" />+ {{ $t("slow-query.slow-queries") }}+ </router-link>+<router-linkto="/anomaly-center"class="outline-item group flex items-center px-2 py-2"diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vueindex ca55077738..30e4c3fd75 100644--- a/frontend/src/views/DatabaseDetail.vue+++ b/frontend/src/views/DatabaseDetail.vue@@ -162,22 +162,25 @@"/><div class="py-6 px-6">- <template v-if="state.selectedIndex == OVERVIEW_TAB">+ <template v-if="selectedTabItem?.hash === 'overview'"><DatabaseOverviewPanel :database="database" /></template>- <template v-if="state.selectedIndex == MIGRATION_HISTORY_TAB">+ <template v-if="selectedTabItem?.hash === 'change-history'"><DatabaseMigrationHistoryPanel:database="database":allow-edit="allowEdit"/></template>- <template v-if="state.selectedIndex == BACKUP_TAB">+ <template v-if="selectedTabItem?.hash === 'backup-and-restore'"><DatabaseBackupPanel:database="database":allow-admin="allowAdmin":allow-edit="allowEdit"/></template>+ <template v-if="selectedTabItem?.hash === 'slow-query'">+ <DatabaseSlowQueryPanel :database="database" />+ </template></div><BBModal@@ -298,10 +301,15 @@<script lang="ts" setup>import { computed, onMounted, reactive, watch, ref } from "vue";import { useRouter } from "vue-router";+import dayjs from "dayjs";+import { useI18n } from "vue-i18n";+import { startCase } from "lodash-es";+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 DatabaseSlowQueryPanel from "@/components/DatabaseSlowQueryPanel.vue";import InstanceEngineIcon from "@/components/InstanceEngineIcon.vue";import { DatabaseLabelProps } from "@/components/DatabaseLabels";import { SelectDatabaseLabel } from "@/components/TransferDatabaseForm";@@ -317,6 +325,7 @@ import {isArchivedDatabase,instanceHasBackupRestore,instanceHasAlterSchema,+ instanceSupportSlowQuery,} from "@/utils";import {ProjectId,@@ -327,7 +336,6 @@ import {SQLResultSet,} from "@/types";import { BBTabFilterItem } from "@/bbkit/types";-import { useI18n } from "vue-i18n";import { GhostDialog } from "@/components/AlterSchemaPrepForm";import { SchemaDiagram, SchemaDiagramIcon } from "@/components/SchemaDiagram";import { SQLEditorButton } from "@/components/DatabaseDetail";@@ -339,11 +347,6 @@ import {usePolicyByDatabaseAndType,useSQLStore,} from "@/store";-import dayjs from "dayjs";--const OVERVIEW_TAB = 0;-const MIGRATION_HISTORY_TAB = 1;-const BACKUP_TAB = 2;type DatabaseTabItem = {name: string;@@ -374,18 +377,21 @@ const dbSchemaStore = useDBSchemaStore();const sqlStore = useSQLStore();const ghostDialog = ref<InstanceType<typeof GhostDialog>>();-const databaseTabItemList: DatabaseTabItem[] = [- { name: t("common.overview"), hash: "overview" },- { name: t("change-history.self"), hash: "change-history" },- { name: t("common.backup-and-restore"), hash: "backup-and-restore" },-];+const databaseTabItemList = computed((): DatabaseTabItem[] => {+ return [+ { name: t("common.overview"), hash: "overview" },+ { name: t("change-history.self"), hash: "change-history" },+ { name: t("common.backup-and-restore"), hash: "backup-and-restore" },+ { name: startCase(t("slow-query.slow-queries")), hash: "slow-query" },+ ];+});const state = reactive<LocalState>({showTransferDatabaseModal: false,showIncorrectProjectModal: false,showSchemaEditorModal: false,editingProjectId: UNKNOWN_ID,- selectedIndex: OVERVIEW_TAB,+ selectedIndex: 0,syncingSchema: false,showSchemaDiagram: false,});@@ -545,15 +551,21 @@ const allowEditDatabaseLabels = computed((): boolean => {return allowAdmin.value;});+const availableDatabaseTabItemList = computed(() => {+ const db = database.value;+ return databaseTabItemList.value.filter((item) => {+ if (item.hash === "backup-and-restore") {+ return instanceHasBackupRestore(db.instance);+ }+ if (item.hash === "slow-query") {+ return instanceSupportSlowQuery(db.instance);+ }+ return true;+ });+});+const tabItemList = computed((): BBTabFilterItem[] => {- if (!instanceHasBackupRestore(database.value.instance)) {- return databaseTabItemList- .filter((item) => item.hash !== "backup-and-restore")- .map((item) => {- return { title: item.name, alert: false };- });- }- return databaseTabItemList.map((item) => {+ return availableDatabaseTabItemList.value.map((item) => {return { title: item.name, alert: false };});});@@ -666,26 +678,32 @@ const updateLabels = (labels: DatabaseLabel[]) => {});};+const selectedTabItem = computed(() => {+ return availableDatabaseTabItemList.value[state.selectedIndex];+});+const selectTab = (index: number) => {+ const item = availableDatabaseTabItemList.value[index];state.selectedIndex = index;router.replace({name: "workspace.database.detail",- hash: "#" + databaseTabItemList[index].hash,+ hash: "#" + item.hash,});};const selectDatabaseTabOnHash = () => {if (router.currentRoute.value.hash) {- for (let i = 0; i < databaseTabItemList.length; i++) {+ for (let i = 0; i < availableDatabaseTabItemList.value.length; i++) {if (- databaseTabItemList[i].hash == router.currentRoute.value.hash.slice(1)+ availableDatabaseTabItemList.value[i].hash ==+ router.currentRoute.value.hash.slice(1)) {selectTab(i);break;}}} else {- selectTab(OVERVIEW_TAB);+ selectTab(0);}};diff --git a/frontend/src/views/ProjectDetail.vue b/frontend/src/views/ProjectDetail.vueindex bef6c3791b..cab1b0ee06 100644--- a/frontend/src/views/ProjectDetail.vue+++ b/frontend/src/views/ProjectDetail.vue@@ -6,7 +6,7 @@:database-list="databaseList"/></template>- <template v-else-if="hash === 'databases'">+ <template v-if="hash === 'databases'"><ProjectDeploymentConfigPanelv-if="isTenantProject"id="deployment-config"@@ -27,24 +27,27 @@:database-list="databaseList"/></template>+ <template v-if="hash === 'slow-query'">+ <ProjectSlowQueryPanel :project="project" />+ </template><template v-if="hash === 'activity'"><ProjectActivityPanel id="activity" :project="project" /></template>- <template v-else-if="hash === 'gitops'">+ <template v-if="hash === 'gitops'"><ProjectVersionControlPanelid="gitops":project="project":allow-edit="allowEdit"/></template>- <template v-else-if="hash === 'webhook'">+ <template v-if="hash === 'webhook'"><ProjectWebhookPanelid="webhook":project="project":allow-edit="allowEdit"/></template>- <template v-else-if="hash === 'setting'">+ <template v-if="hash === 'setting'"><ProjectSettingPanelid="setting":project="project"@@ -58,6 +61,7 @@ import { computed, defineComponent, watchEffect } from "vue";import { idFromSlug, sortDatabaseList } from "../utils";import ProjectActivityPanel from "../components/ProjectActivityPanel.vue";import ProjectMigrationHistoryPanel from "../components/ProjectMigrationHistoryPanel.vue";+import ProjectSlowQueryPanel from "../components/ProjectSlowQueryPanel.vue";import ProjectOverviewPanel from "../components/ProjectOverviewPanel.vue";import ProjectDatabasesPanel from "../components/ProjectDatabasesPanel.vue";import ProjectVersionControlPanel from "../components/ProjectVersionControlPanel.vue";@@ -73,6 +77,7 @@ export default defineComponent({components: {ProjectActivityPanel,ProjectMigrationHistoryPanel,+ ProjectSlowQueryPanel,ProjectOverviewPanel,ProjectVersionControlPanel,ProjectWebhookPanel,diff --git a/frontend/src/views/SlowQuery/SlowQueryDashboard.vue b/frontend/src/views/SlowQuery/SlowQueryDashboard.vuenew file mode 100644index 0000000000..391a198b52--- /dev/null+++ b/frontend/src/views/SlowQuery/SlowQueryDashboard.vue@@ -0,0 +1,19 @@+<template>+ <div class="p-2">+ <SlowQueryPanel v-model:filter="filter" />+ </div>+</template>++<script lang="ts" setup>+import { shallowRef } from "vue";++import {+ SlowQueryPanel,+ SlowQueryFilterParams,+ defaultSlowQueryFilterParams,+} from "@/components/SlowQuery";++const filter = shallowRef<SlowQueryFilterParams>({+ ...defaultSlowQueryFilterParams(),+});+</script>