Skip to content

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

feat(frontend): slow query for PG (#5690)

Liu Ji926e620eb3ee
diff --git a/frontend/src/bbkit/BBAttention.vue b/frontend/src/bbkit/BBAttention.vue
index 8f8f7eaf5c..7cffbe1d90 100644
--- a/frontend/src/bbkit/BBAttention.vue
+++ b/frontend/src/bbkit/BBAttention.vue
@@ -24,15 +24,17 @@
</div>
<div class="ml-3">
<h3 class="text-sm font-medium" :class="`text-${color}-800`">
- {{ $t(title) }}
+ {{ displayTitle }}
</h3>
- <div
- v-if="description"
- class="mt-2 text-sm"
- :class="`text-${color}-700`"
- >
- <p class="whitespace-pre-wrap">{{ $t(description) }}</p>
- </div>
+ <slot name="default">
+ <div
+ v-if="description"
+ class="mt-2 text-sm"
+ :class="`text-${color}-700`"
+ >
+ <p class="whitespace-pre-wrap">{{ $t(description) }}</p>
+ </div>
+ </slot>
</div>
</div>
<div
@@ -53,6 +55,7 @@
<script lang="ts" setup>
import { computed, withDefaults } from "vue";
import { BBAttentionSide, BBAttentionStyle } from "./types";
+import { useI18n } from "vue-i18n";
const props = withDefaults(
defineProps<{
@@ -75,6 +78,14 @@ defineEmits<{
(event: "click-action"): void;
}>();
+const { t, te } = useI18n();
+
+const displayTitle = computed(() => {
+ const { title } = props;
+ if (te(title)) return t(title);
+ return title;
+});
+
// eslint-disable-next-line vue/return-in-computed-property
const color = computed(() => {
switch (props.style) {
diff --git a/frontend/src/bbkit/BBGrid/BBGrid.vue b/frontend/src/bbkit/BBGrid/BBGrid.vue
index b83a7e194d..f0e694c5e4 100644
--- a/frontend/src/bbkit/BBGrid/BBGrid.vue
+++ b/frontend/src/bbkit/BBGrid/BBGrid.vue
@@ -14,8 +14,8 @@
class="bb-grid-row bb-grid-header-row group"
>
<div
- v-for="(column, row) in columnList"
- :key="row"
+ v-for="(column, i) in columnList"
+ :key="i"
role="table-cell"
class="bb-grid-header-cell"
:class="[headerClass, column.class]"
@@ -25,15 +25,12 @@
</div>
<template v-if="ready">
- <template
- v-for="(item, row) in dataSource"
- :key="rowKey ? item[rowKey] : row"
- >
+ <template v-for="(item, row) in dataSource" :key="rowKeyOf(item, row)">
<div
row="table-row"
class="bb-grid-row group"
:class="{
- clickable: rowClickable,
+ clickable: rowClickable && isRowClickable(item, row),
}"
@click="handleClick(item, 0, row, $event)"
>
@@ -46,6 +43,7 @@
>
<div
class="bb-grid-cell"
+ :class="expandedRowClass"
:style="{
gridColumnStart: 1,
gridColumnEnd: columnList.length + 1,
@@ -111,7 +109,7 @@ const props = withDefaults(
defineProps<{
columnList?: BBGridColumn[];
dataSource?: DataType[];
- rowKey?: string;
+ rowKey?: string | ((item: DataType, row: number) => any);
showHeader?: boolean;
customHeader?: boolean;
headerClass?: VueClass;
@@ -119,6 +117,8 @@ const props = withDefaults(
showPlaceholder?: boolean;
ready?: boolean;
isRowExpanded?: (item: DataType, row: number) => boolean;
+ isRowClickable?: (item: DataType, row: number) => boolean;
+ expandedRowClass?: VueClass;
}>(),
{
columnList: () => [],
@@ -131,6 +131,8 @@ const props = withDefaults(
showPlaceholder: false,
ready: true,
isRowExpanded: () => false,
+ isRowClickable: () => true,
+ expandedRowClass: undefined,
}
);
@@ -138,13 +140,24 @@ const gridClass = useResponsiveGridColumns(
computed(() => props.columnList.map((col) => col.width))
);
+const rowKeyOf = (item: DataType, row: number) => {
+ const { rowKey } = props;
+ if (typeof rowKey === "function") {
+ return rowKey(item, row);
+ }
+ if (typeof rowKey === "string") {
+ return item[rowKey];
+ }
+ return row;
+};
+
const handleClick = (
item: DataType,
section: number,
row: number,
e: MouseEvent
) => {
- if (props.rowClickable) {
+ if (props.rowClickable && props.isRowClickable(item, row)) {
emit("click-row", item, section, row, e);
}
};
diff --git a/frontend/src/components/SlowQuery/Panel/LogFilter.vue b/frontend/src/components/SlowQuery/Panel/LogFilter.vue
index 35f1449730..5fe90b9e32 100644
--- a/frontend/src/components/SlowQuery/Panel/LogFilter.vue
+++ b/frontend/src/components/SlowQuery/Panel/LogFilter.vue
@@ -7,15 +7,6 @@
class="flex items-center gap-x-4"
>
<div class="flex-1 flex items-center gap-x-4">
- <ProjectSelect
- v-if="filterTypes.includes('project')"
- :project="params.project?.id ?? UNKNOWN_ID"
- :include-default-project="canVisitDefaultProject"
- :include-all="true"
- :disabled="loading"
- @update:project="changeProjectId"
- />
-
<EnvironmentTabFilter
v-if="filterTypes.includes('environment')"
class="flex-1"
@@ -33,6 +24,14 @@
<div class="flex items-center gap-x-4">
<NInputGroup class="flex-1">
+ <ProjectSelect
+ v-if="filterTypes.includes('project')"
+ :project="params.project?.id ?? UNKNOWN_ID"
+ :include-default-project="canVisitDefaultProject"
+ :include-all="true"
+ :disabled="loading"
+ @update:project="changeProjectId"
+ />
<InstanceSelect
v-if="filterTypes.includes('instance')"
:instance="params.instance?.id ?? UNKNOWN_ID"
diff --git a/frontend/src/components/SlowQuery/Panel/LogTable.vue b/frontend/src/components/SlowQuery/Panel/LogTable.vue
index 699fa7fbae..306f749860 100644
--- a/frontend/src/components/SlowQuery/Panel/LogTable.vue
+++ b/frontend/src/components/SlowQuery/Panel/LogTable.vue
@@ -3,72 +3,107 @@
:column-list="columns"
:data-source="slowQueryLogList"
:show-placeholder="showPlaceholder"
+ :is-row-clickable="
+ (row) => instanceHasSlowQueryDetail(row.database.instance)
+ "
+ :is-row-expanded="isSelectedRow"
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">
+ <template #item="{ item }: SlowQueryLogRow">
+ <template v-if="item.log.statistics">
+ <div class="bb-grid-cell whitespace-nowrap !pl-1 !pr-1">
+ <NButton quaternary size="tiny" @click.stop="toggleExpandRow(item)">
+ <heroicons:chevron-right
+ class="w-4 h-4 transition-transform duration-150 cursor-pointer"
+ :class="[isSelectedRow(item) && 'rotate-90']"
+ />
+ </NButton>
+ </div>
<div class="bb-grid-cell text-xs font-mono">
<div class="truncate">
- {{ log.statistics.sqlFingerprint }}
+ {{ item.log.statistics.sqlFingerprint }}
</div>
</div>
<div class="bb-grid-cell">
- {{ log.statistics.count }}
+ {{ item.log.statistics.count }}
</div>
<div class="bb-grid-cell">
- {{
- log.statistics.nightyFifthPercentileQueryTime?.seconds.toFixed(6)
- }}
+ {{ durationText(item.log.statistics.maximumQueryTime) }}
</div>
<div class="bb-grid-cell">
- {{ log.statistics.averageQueryTime?.seconds.toFixed(6) }}
+ {{ durationText(item.log.statistics.averageQueryTime) }}
</div>
<div class="bb-grid-cell">
- {{ log.statistics.nightyFifthPercentileRowsExamined }}
+ {{
+ instanceHasSlowQueryDetail(item.database.instance)
+ ? item.log.statistics.maximumRowsExamined
+ : "-"
+ }}
</div>
<div class="bb-grid-cell">
- {{ log.statistics.averageRowsExamined }}
+ {{
+ instanceHasSlowQueryDetail(item.database.instance)
+ ? item.log.statistics.averageRowsExamined
+ : "-"
+ }}
</div>
<div class="bb-grid-cell">
- {{ log.statistics.nightyFifthPercentileRowsSent }}
+ {{
+ instanceHasSlowQueryDetail(item.database.instance)
+ ? item.log.statistics.maximumRowsSent
+ : "-"
+ }}
</div>
<div class="bb-grid-cell">
- {{ log.statistics.averageRowsSent }}
+ {{ item.log.statistics.averageRowsSent }}
</div>
<div v-if="showProjectColumn" class="bb-grid-cell">
- <ProjectName :project="database.project" :link="false" />
+ <ProjectName :project="item.database.project" :link="false" />
</div>
<div v-if="showEnvironmentColumn" class="bb-grid-cell">
<EnvironmentName
- :environment="database.instance.environment"
+ :environment="item.database.instance.environment"
:link="false"
/>
</div>
<div v-if="showInstanceColumn" class="bb-grid-cell">
- <InstanceName :instance="database.instance" :link="false" />
+ <InstanceName :instance="item.database.instance" :link="false" />
</div>
<div v-if="showDatabaseColumn" class="bb-grid-cell">
- <DatabaseName :database="database" :link="false" />
+ <DatabaseName :database="item.database" :link="false" />
</div>
<div class="bb-grid-cell whitespace-nowrap !pr-4">
{{
- dayjs(log.statistics.latestLogTime).format("YYYY-MM-DD HH:mm:ss")
+ dayjs(item.log.statistics.latestLogTime).format(
+ "YYYY-MM-DD HH:mm:ss"
+ )
}}
</div>
</template>
</template>
+
+ <template #expanded-item="{ item }: SlowQueryLogRow">
+ <div class="w-full max-h-[20rem] overflow-auto text-xs pl-2">
+ <HighlightCodeBlock
+ :code="item.log.statistics?.sqlFingerprint"
+ class="whitespace-pre-wrap"
+ />
+ </div>
+ </template>
</BBGrid>
</template>
<script lang="ts" setup>
-import { computed } from "vue";
+import { computed, shallowRef, watch } from "vue";
import { useI18n } from "vue-i18n";
+import type { Duration } from "@/types/proto/google/protobuf/duration";
import { type BBGridColumn, type BBGridRow, BBGrid } from "@/bbkit";
import type { ComposedSlowQueryLog } from "@/types";
import { DatabaseName, InstanceName, EnvironmentName } from "@/components/v2";
+import { instanceHasSlowQueryDetail } from "@/utils";
export type SlowQueryLogRow = BBGridRow<ComposedSlowQueryLog>;
@@ -96,9 +131,13 @@ defineEmits<{
}>();
const { t } = useI18n();
+const selectedSlowQueryLog = shallowRef<ComposedSlowQueryLog>();
const columns = computed(() => {
const columns = [
+ {
+ width: "auto",
+ },
{
title: t("slow-query.sql-statement"),
width: "minmax(20rem, 1fr)",
@@ -108,27 +147,27 @@ const columns = computed(() => {
width: "minmax(6rem, auto)",
},
{
- title: t("slow-query.query-time-95-percent"),
+ title: t("slow-query.max-query-time"),
width: "minmax(6rem, auto)",
},
{
- title: t("slow-query.query-time-avg"),
+ title: t("slow-query.avg-query-time"),
width: "minmax(6rem, auto)",
},
{
- title: t("slow-query.rows-examined-95-percent"),
+ title: t("slow-query.max-rows-examined"),
width: "minmax(6rem, auto)",
},
{
- title: t("slow-query.rows-examined-avg"),
+ title: t("slow-query.avg-rows-examined"),
width: "minmax(6rem, auto)",
},
{
- title: t("slow-query.rows-sent-95-percent"),
+ title: t("slow-query.max-rows-sent"),
width: "minmax(6rem, auto)",
},
{
- title: t("slow-query.rows-sent-avg"),
+ title: t("slow-query.avg-rows-sent"),
width: "minmax(6rem, auto)",
},
props.showProjectColumn && {
@@ -154,4 +193,31 @@ const columns = computed(() => {
].filter((col) => !!col) as BBGridColumn[];
return columns;
});
+
+const isSelectedRow = (item: ComposedSlowQueryLog) => {
+ return selectedSlowQueryLog.value === item;
+};
+
+const toggleExpandRow = (item: ComposedSlowQueryLog) => {
+ if (selectedSlowQueryLog.value === item) {
+ selectedSlowQueryLog.value = undefined;
+ } else {
+ selectedSlowQueryLog.value = item;
+ }
+};
+
+const durationText = (duration: Duration | undefined) => {
+ if (!duration) return "-";
+ const nanos = duration.nanos;
+ if (!nanos) return "0";
+ return (nanos / 1e9).toFixed(6);
+};
+
+watch(
+ () => props.slowQueryLogList,
+ () => {
+ selectedSlowQueryLog.value = undefined;
+ },
+ { immediate: true }
+);
</script>
diff --git a/frontend/src/components/SlowQuery/Panel/SlowQueryPanel.vue b/frontend/src/components/SlowQuery/Panel/SlowQueryPanel.vue
index 6c659cad2a..38dc332352 100644
--- a/frontend/src/components/SlowQuery/Panel/SlowQueryPanel.vue
+++ b/frontend/src/components/SlowQuery/Panel/SlowQueryPanel.vue
@@ -22,7 +22,7 @@
:show-environment-column="showEnvironmentColumn"
:show-instance-column="showInstanceColumn"
:show-database-column="showDatabaseColumn"
- @select="selectedSlowQueryLog = $event"
+ @select="selectSlowQueryLog"
/>
<div
v-if="loading"
@@ -60,6 +60,7 @@ import {
import LogFilter from "./LogFilter.vue";
import LogTable from "./LogTable.vue";
import DetailPanel from "./DetailPanel.vue";
+import { instanceHasSlowQueryDetail } from "@/utils";
const props = withDefaults(
defineProps<{
@@ -104,6 +105,14 @@ const fetchSlowQueryLogList = async () => {
}
};
+const selectSlowQueryLog = (log: ComposedSlowQueryLog) => {
+ if (instanceHasSlowQueryDetail(log.database.instance)) {
+ selectedSlowQueryLog.value = log;
+ } else {
+ selectedSlowQueryLog.value = undefined;
+ }
+};
+
const syncNow = async () => {
syncing.value = true;
try {
diff --git a/frontend/src/components/SlowQuery/Panel/types.ts b/frontend/src/components/SlowQuery/Panel/types.ts
index d14c69d187..18a388d118 100644
--- a/frontend/src/components/SlowQuery/Panel/types.ts
+++ b/frontend/src/components/SlowQuery/Panel/types.ts
@@ -62,6 +62,6 @@ export const buildListSlowQueriesRequest = (filter: SlowQueryFilterParams) => {
request.filter = query.join(" && ");
}
- request.orderBy = "nighty_fifth_percentile_query_time desc";
+ request.orderBy = "maximum_query_time desc";
return ListSlowQueriesRequest.fromJSON(request);
};
diff --git a/frontend/src/components/SlowQuery/Settings/SlowQuerySettings.vue b/frontend/src/components/SlowQuery/Settings/SlowQuerySettings.vue
index fc9b77ed59..a8b0a6ed2d 100644
--- a/frontend/src/components/SlowQuery/Settings/SlowQuerySettings.vue
+++ b/frontend/src/components/SlowQuery/Settings/SlowQuerySettings.vue
@@ -1,34 +1,49 @@
<template>
- <div class="space-y-4 pb-4 w-[48rem] max-w-full">
+ <div class="space-y-4 pb-4 w-[56rem] max-w-full">
<div>
- <BBAttention :style="'WARN'" :description="attentionDescription" />
+ <BBAttention :style="'WARN'" :title="$t('slow-query.report-slow-query')">
+ <i18n-t
+ keypath="slow-query.attention-description"
+ tag="div"
+ class="text-yellow-700 whitespace-pre-wrap mt-2 text-sm"
+ >
+ <template #slow_query>
+ <code>slow_query</code>
+ </template>
+ <template #pg_stat_statements>
+ <code>pg_stat_statements</code>
+ </template>
+ </i18n-t>
+ <div v-if="false" class="mt-2">
+ <!-- TODO: update docs link -->
+ <LearnMoreLink url="https://www.bytebase.com/404?source=console" />
+ </div>
+ </BBAttention>
</div>
- <div>
+ <div class="flex items-center justify-between">
<EnvironmentTabFilter
:environment="state.filter.environment?.id ?? UNKNOWN_ID"
:include-all="true"
@update:environment="changeEnvironment"
/>
+ <SearchBox v-model:value="state.filter.keyword" />
</div>
<div>
<SlowQueryPolicyTable
- :instance-list="state.ready ? filteredInstanceList : []"
+ :composed-slow-query-policy-list="filteredComposedSlowQueryPolicyList"
:policy-list="policyList"
:toggle-active="toggleActive"
- :show-placeholder="state.ready"
+ :ready="state.ready"
+ :show-placeholder="true"
/>
- <div
- v-if="!state.ready"
- class="relative flex flex-col h-[8rem] items-center justify-center"
- >
- <BBSpin />
- </div>
</div>
</div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive } from "vue";
+import { useI18n } from "vue-i18n";
+import { orderBy } from "lodash-es";
import { BBAttention } from "@/bbkit";
import {
@@ -39,22 +54,28 @@ import {
useSlowQueryStore,
} from "@/store";
import {
+ ComposedSlowQueryPolicy,
Environment,
EnvironmentId,
Instance,
SlowQueryPolicyPayload,
UNKNOWN_ID,
} from "@/types";
-import { EnvironmentTabFilter } from "@/components/v2";
+import { EnvironmentTabFilter, SearchBox } from "@/components/v2";
import { SlowQueryPolicyTable } from "./components";
-import { instanceSupportSlowQuery } from "@/utils";
-import { useI18n } from "vue-i18n";
+import {
+ extractSlowQueryPolicyPayload,
+ instanceSupportSlowQuery,
+} from "@/utils";
+import { useGracefulRequest } from "@/store/modules/utils";
+import LearnMoreLink from "@/components/LearnMoreLink.vue";
type LocalState = {
ready: boolean;
instanceList: Instance[];
filter: {
environment: Environment | undefined;
+ keyword: string;
};
};
@@ -63,6 +84,7 @@ const state = reactive<LocalState>({
instanceList: [],
filter: {
environment: undefined,
+ keyword: "",
},
});
@@ -79,14 +101,42 @@ const policyList = computed(() => {
);
});
-const filteredInstanceList = computed(() => {
- const list = state.instanceList;
+const composedSlowQueryPolicyList = computed(() => {
+ const list = state.instanceList.map<ComposedSlowQueryPolicy>((instance) => {
+ const policy = policyList.value.find((p) => p.resourceId === instance.id);
+ const payload = extractSlowQueryPolicyPayload(policy);
+ return {
+ instance,
+ active: payload.active,
+ };
+ });
+
+ return orderBy(
+ list,
+ [
+ (item) => item.instance.engine,
+ (item) => item.instance.environment.order,
+ (item) => item.instance.name,
+ ],
+ ["asc", "desc", "asc"]
+ );
+});
+
+const filteredComposedSlowQueryPolicyList = computed(() => {
+ let list = [...composedSlowQueryPolicyList.value];
const { environment } = state.filter;
if (environment && environment.id !== UNKNOWN_ID) {
- return list.filter(
- (instance) => instance.environment.id === environment.id
+ list = list.filter(
+ (item) => item.instance.environment.id === environment.id
);
}
+ const keyword = state.filter.keyword.trim().toLowerCase();
+ if (keyword) {
+ list = list.filter((item) =>
+ item.instance.name.toLowerCase().includes(keyword)
+ );
+ }
+
return list;
});
@@ -133,19 +183,15 @@ const toggleActive = async (instance: Instance, active: boolean) => {
// When turning ON an instance's slow query, call the corresponding
// API endpoint to sync slow queries from the instance immediately.
try {
- await slowQueryStore.syncSlowQueriesByInstance(instance);
+ await useGracefulRequest(() =>
+ slowQueryStore.syncSlowQueriesByInstance(instance)
+ );
pushNotification({
module: "bytebase",
style: "SUCCESS",
title: t("common.updated"),
});
- } catch (err: any) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: typeof err.message === "string" ? err.message : String(err),
- });
-
+ } catch {
await patchInstanceSlowQueryPolicy(instance, false);
}
}
@@ -155,12 +201,4 @@ const toggleActive = async (instance: Instance, active: boolean) => {
};
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/Settings/components/SlowQueryPolicyTable.vue b/frontend/src/components/SlowQuery/Settings/components/SlowQueryPolicyTable.vue
index f2518b6e67..4f84c18df5 100644
--- a/frontend/src/components/SlowQuery/Settings/components/SlowQueryPolicyTable.vue
+++ b/frontend/src/components/SlowQuery/Settings/components/SlowQueryPolicyTable.vue
@@ -1,24 +1,24 @@
<template>
<BBGrid
:column-list="COLUMNS"
- :data-source="instanceList"
+ :data-source="composedSlowQueryPolicyList"
:row-clickable="false"
- row-key="id"
+ :row-key="(item: ComposedSlowQueryPolicy) => item.instance.id"
class="border"
>
- <template #item="{ item: instance }: { item: Instance }">
+ <template #item="{ item }: { item: ComposedSlowQueryPolicy }">
<div class="bb-grid-cell">
- <InstanceName :instance="instance" />
+ <InstanceName :instance="item.instance" />
</div>
<div class="bb-grid-cell">
- <EnvironmentName :environment="instance.environment" />
+ <EnvironmentName :environment="item.instance.environment" />
</div>
<div class="bb-grid-cell">
<SpinnerSwitch
- :value="isActive(instance)"
+ :value="item.active"
:disabled="!allowAdmin"
- :on-toggle="(active) => toggleActive(instance, active)"
+ :on-toggle="(active) => toggleActive(item.instance, active)"
/>
</div>
</template>
@@ -30,14 +30,13 @@ import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { type BBGridColumn, BBGrid } from "@/bbkit";
-import type { Instance, Policy, SlowQueryPolicyPayload } from "@/types";
+import type { Instance, ComposedSlowQueryPolicy } from "@/types";
import { InstanceName, EnvironmentName, SpinnerSwitch } from "@/components/v2/";
import { useCurrentUser } from "@/store";
import { hasWorkspacePermission } from "@/utils";
-const props = defineProps<{
- instanceList: Instance[];
- policyList: Policy[];
+defineProps<{
+ composedSlowQueryPolicyList: ComposedSlowQueryPolicy[];
toggleActive: (instance: Instance, active: boolean) => Promise<void>;
}>();
@@ -55,7 +54,7 @@ const COLUMNS = computed((): BBGridColumn[] => {
width: "minmax(auto, 1fr)",
},
{
- title: t("common.active"),
+ title: t("slow-query.report"),
width: "minmax(auto, 6rem)",
},
];
@@ -67,13 +66,4 @@ const allowAdmin = computed(() => {
currentUser.value.role
);
});
-
-const isActive = (instance: Instance) => {
- const policy = props.policyList.find((policy) => {
- return policy.resourceId === instance.id;
- });
- if (!policy) return false;
- const payload = policy.payload as SlowQueryPolicyPayload;
- return payload.active;
-};
</script>
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index f4fb007750..98889d4666 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2307,22 +2307,25 @@
"slow-query": {
"self": "Slow query",
"slow-queries": "Slow queries",
+ "report-slow-query": "Report slow query",
+ "report": "Report",
"last-query-time": "Last query time",
"database-name": "Database name",
"sql-statement": "SQL statement",
"total-query-count": "Total query count",
- "query-time-95-percent": "Query time (95%)",
- "query-time-avg": "Query time avg.",
- "rows-examined-95-percent": "Rows examined (95%)",
- "rows-sent-95-percent": "Rows sent (95%)",
- "rows-examined-avg": "Rows examined avg.",
+ "max-query-time": "Max query time",
+ "avg-query-time": "Avg query time",
+ "max-rows-examined": "Max rows examined",
+ "avg-rows-examined": "Avg rows examined",
+ "max-rows-sent": "Max rows sent",
+ "avg-rows-sent": "Avg rows sent",
"rows-sent-avg": "Rows sent avg.",
"query-start-time": "Query start time",
"rows-examined": "Rows examined",
"rows-sent": "Rows sent",
"lock-time": "Lock time",
"query-time": "Query time",
- "attention-description": "Logging and analyzing slow queries for {versions}.\nBytebase will periodically sync slow query logs from instances.",
+ "attention-description": "Bytebase periodically syncs slow query logs from instances.\nFor MySQL instance, {slow_query} must be enabled first.\nFor PostgreSQL instance, {pg_stat_statements} must be enabled first in each database.",
"sync-job-started": "Sync jobs started. Please wait for the jobs to complete.",
"detail": "Slow Query Detail"
},
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 9be865cfe5..285d2e4a24 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2304,22 +2304,24 @@
"slow-query": {
"self": "慢查询",
"slow-queries": "慢查询",
+ "report-slow-query": "报告慢查询",
+ "report": "报告",
"last-query-time": "最近执行时间",
"database-name": "数据库名",
"sql-statement": "SQL 语句",
"total-query-count": "总执行次数",
- "query-time-95-percent": "执行时长(95%)",
- "query-time-avg": "平均执行时长",
- "rows-examined-95-percent": "扫描行数(95%)",
- "rows-sent-95-percent": "返回行数(95%)",
- "rows-examined-avg": "平均扫描行数",
- "rows-sent-avg": "平均返回行数",
+ "max-query-time": "最大执行时长",
+ "avg-query-time": "平均执行时长",
+ "max-rows-examined": "最大扫描行数",
+ "avg-rows-examined": "平均扫描行数",
+ "max-rows-sent": "最大返回行数",
+ "avg-rows-sent": "平均返回行数",
"query-start-time": "执行开始时间",
"rows-examined": "解析行数",
"rows-sent": "返回行数",
"lock-time": "持有锁时长",
"query-time": "执行时长",
- "attention-description": "为 {versions} 记录和分析慢查询。\nBytebase 会定期从实例上同步慢查询日志。",
+ "attention-description": "Bytebase 定期从实例上同步慢查询日志。\n对 MySQL 实例,需要先开启 {slow_query}。\n对 PostgreSQL 实例,需要先在各个数据库中开启 {pg_stat_statements}。",
"sync-job-started": "同步作业已启动。请等待同步完成。",
"detail": "慢查询详情"
},
diff --git a/frontend/src/types/slowQuery.ts b/frontend/src/types/slowQuery.ts
index e30cab5e4a..2f33c05ac0 100644
--- a/frontend/src/types/slowQuery.ts
+++ b/frontend/src/types/slowQuery.ts
@@ -1,7 +1,13 @@
-import { Database } from "./database";
+import type { Database } from "./database";
+import type { Instance } from "./instance";
import type { SlowQueryLog } from "./proto/v1/database_service";
export type ComposedSlowQueryLog = {
log: SlowQueryLog;
database: Database;
};
+
+export type ComposedSlowQueryPolicy = {
+ instance: Instance;
+ active: boolean;
+};
diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts
index e0ce9db6a8..f8ba269d55 100644
--- a/frontend/src/utils/index.ts
+++ b/frontend/src/utils/index.ts
@@ -28,3 +28,4 @@ export * from "./idp";
export * from "./id";
export * from "./workspaceApprovalSetting";
export * from "./projectIamPolicy";
+export * from "./slowQuery";
diff --git a/frontend/src/utils/instance.ts b/frontend/src/utils/instance.ts
index 36184a3810..7cdc951e52 100644
--- a/frontend/src/utils/instance.ts
+++ b/frontend/src/utils/instance.ts
@@ -7,7 +7,6 @@ import {
languageOfEngine,
MaybeRef,
} from "../types";
-import { semverCompare } from "./util";
export const supportedEngineList = () => {
const engines: EngineType[] = [
@@ -150,17 +149,6 @@ export const instanceHasCollationAndCharacterSet = (
return !excludedList.includes(engine);
};
-export const instanceSupportSlowQuery = (instance: Instance) => {
- const { engine } = instance;
- if (engine === "MYSQL") {
- return semverCompare(instance.engineVersion, "5.7", "gte");
- }
- if (engine === "POSTGRES") {
- return true;
- }
- return false;
-};
-
export const engineOfInstance = (instanceOrEngine: Instance | EngineType) => {
if (typeof instanceOrEngine === "string") {
return instanceOrEngine;
diff --git a/frontend/src/utils/slowQuery.ts b/frontend/src/utils/slowQuery.ts
new file mode 100644
index 0000000000..f186de5e5f
--- /dev/null
+++ b/frontend/src/utils/slowQuery.ts
@@ -0,0 +1,44 @@
+import type {
+ EngineType,
+ Instance,
+ Policy,
+ SlowQueryPolicyPayload,
+} from "@/types";
+import { semverCompare } from "./util";
+
+export const extractSlowQueryPolicyPayload = (
+ policy: Policy | undefined
+): SlowQueryPolicyPayload => {
+ if (!policy) return { active: false };
+ return policy.payload as SlowQueryPolicyPayload;
+};
+export const InstanceListSupportSlowQuery: [EngineType, string][] = [
+ ["MYSQL", "5.7"],
+ ["POSTGRES", "0"],
+];
+
+export const instanceSupportSlowQuery = (instance: Instance) => {
+ const { engine } = instance;
+ const item = InstanceListSupportSlowQuery.find((item) => item[0] === engine);
+ if (item) {
+ const [_, minVersion] = item;
+ if (minVersion === "0") return true;
+ return semverCompare(instance.engineVersion, minVersion, "gte");
+ }
+ return false;
+};
+
+export const slowQueryTypeOfInstance = (instance: Instance) => {
+ if (!instanceSupportSlowQuery(instance)) return undefined;
+ const { engine } = instance;
+ if (engine === "MYSQL") return "INSTANCE";
+ if (engine === "POSTGRES") return "DATABASE";
+ return undefined;
+};
+
+export const instanceHasSlowQueryDetail = (instance: Instance) => {
+ const { engine } = instance;
+ if (engine === "MYSQL") return true;
+
+ return false;
+};