Skip to content

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

refactor(frontend): migrate query readonly API to v1 (#6408)

Liu Jicc734f2731c9
diff --git a/frontend/src/components/Issue/action/ExportDataButton.vue b/frontend/src/components/Issue/action/ExportDataButton.vue
index 819807259d..20fa1fe18d 100644
--- a/frontend/src/components/Issue/action/ExportDataButton.vue
+++ b/frontend/src/components/Issue/action/ExportDataButton.vue
@@ -50,7 +50,11 @@ import {
PresetRoleType,
UNKNOWN_ID,
} from "@/types";
-import { pushNotification, useDatabaseV1Store, useSQLStore } from "@/store";
+import {
+ pushNotification,
+ useDatabaseV1Store,
+ useLegacySQLStore,
+} from "@/store";
import { BBSpin } from "@/bbkit";
import { convertFromCEL } from "@/utils/issue/cel";
@@ -124,7 +128,7 @@ const handleExport = async () => {
}
state.isRequesting = true;
- const queryResult = await useSQLStore().query(exportContext.value);
+ const queryResult = await useLegacySQLStore().query(exportContext.value);
if (queryResult.error) {
pushNotification({
module: "bytebase",
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index 0344cc41c8..adccc8cbab 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -5,14 +5,17 @@ import { useI18n } from "vue-i18n";
import {
parseSQL,
isSelectStatement,
- isMultipleStatements,
isDDLStatement,
isDMLStatement,
} from "../components/MonacoEditor/sqlParser";
import { pushNotification, useTabStore, useSQLEditorStore } from "@/store";
import { BBNotificationStyle } from "@/bbkit/types";
-import { ExecuteConfig, ExecuteOption, SQLResultSet, TabMode } from "@/types";
+import { ExecuteConfig, ExecuteOption } from "@/types";
import { useSilentRequest } from "@/plugins/silent-request";
+import {
+ Advice_Status,
+ advice_StatusToJSON,
+} from "@/types/proto/v1/sql_service";
const useExecuteSQL = () => {
const { t } = useI18n();
@@ -32,17 +35,48 @@ const useExecuteSQL = () => {
});
};
+ const preflight = (query: string) => {
+ const tab = tabStore.currentTab;
+
+ if (tab.isExecutingSQL) {
+ notify("INFO", t("common.tips"), t("sql-editor.can-not-execute-query"));
+ return false;
+ }
+
+ const isDisconnected = tabStore.isDisconnected;
+ if (isDisconnected) {
+ notify("CRITICAL", t("sql-editor.select-connection"));
+ return false;
+ }
+
+ if (isEmpty(query)) {
+ notify("CRITICAL", t("sql-editor.notify-empty-statement"));
+ return false;
+ }
+
+ tab.isExecutingSQL = true;
+ return true;
+ };
+ const cleanup = () => {
+ const tab = tabStore.currentTab;
+ tab.isExecutingSQL = false;
+ };
+
const executeReadonly = async (
query: string,
config: ExecuteConfig,
option?: Partial<ExecuteOption>
) => {
+ if (!preflight(query)) {
+ return cleanup();
+ }
+
const tab = tabStore.currentTab;
const { data } = parseSQL(query);
if (data === undefined) {
notify("CRITICAL", t("sql-editor.notify-invalid-sql-statement"));
- return;
+ return cleanup();
}
if (data !== null && !isSelectStatement(data)) {
@@ -51,48 +85,58 @@ const useExecuteSQL = () => {
sqlEditorStore.setSQLEditorState({
isShowExecutingHint: true,
});
- return;
- }
- if (isMultipleStatements(data)) {
- notify(
- "INFO",
- t("common.tips"),
- t("sql-editor.notify-multiple-statements")
- );
- return;
+ return cleanup();
}
}
- if (isMultipleStatements(data)) {
- notify(
- "INFO",
- t("common.tips"),
- t("sql-editor.notify-multiple-statements")
- );
- }
-
let selectStatement = query;
if (option?.explain) {
selectStatement = `EXPLAIN ${selectStatement}`;
}
+ const fail = (error: string) => {
+ Object.assign(tab, {
+ sqlResultSet: {
+ error,
+ results: [],
+ advices: [],
+ },
+ // Legacy compatibility
+ queryResult: {
+ error,
+ data: null,
+ adviceList: [],
+ },
+ executeParams: {
+ query,
+ config,
+ option,
+ },
+ });
+ cleanup();
+ };
+
try {
- const sqlResultSet = await useSilentRequest(() =>
- sqlEditorStore.executeQuery({
- statement: selectStatement,
- })
- );
+ const sqlResultSet = await sqlEditorStore.executeQuery({
+ statement: selectStatement,
+ });
// TODO(steven): use BBModel instead of notify to show the advice from SQL review.
- let adviceStatus = "SUCCESS";
+ let adviceStatus: "SUCCESS" | "ERROR" | "WARNING" = "SUCCESS";
let adviceNotifyMessage = "";
- for (const advice of sqlResultSet.adviceList) {
- if (advice.status === "ERROR") {
+ for (const advice of sqlResultSet.advices) {
+ if (advice.status === Advice_Status.SUCCESS) {
+ continue;
+ }
+
+ if (advice.status === Advice_Status.ERROR) {
adviceStatus = "ERROR";
} else if (adviceStatus !== "ERROR") {
- adviceStatus = advice.status;
+ adviceStatus = "WARNING";
}
- adviceNotifyMessage += `${advice.status}: ${advice.title}\n`;
+ adviceNotifyMessage += `${advice_StatusToJSON(advice.status)}: ${
+ advice.title
+ }\n`;
if (advice.content) {
adviceNotifyMessage += `${advice.content}\n`;
}
@@ -106,38 +150,24 @@ const useExecuteSQL = () => {
);
}
- // use `markRaw` to prevent vue from monitoring the object change deeply
- const queryResult = sqlResultSet ? markRaw(sqlResultSet) : undefined;
- Object.assign(tab, {
- queryResult,
- adviceList: sqlResultSet.adviceList,
- executeParams: {
- query,
- config,
- option,
- },
- });
- if (queryResult) {
- // Refresh the query history list when the query executed successfully
- // (with or without warnings).
- sqlEditorStore.fetchQueryHistoryList();
+ if (sqlResultSet.error) {
+ return fail(sqlResultSet.error);
}
- return sqlResultSet;
- } catch (error: any) {
Object.assign(tab, {
- queryResult: {
- data: null,
- error: error.response?.data?.message ?? String(error),
- adviceList: [],
- },
- adviceList: undefined,
+ sqlResultSet: markRaw(sqlResultSet),
executeParams: {
query,
config,
option,
},
});
+ // Refresh the query history list when the query executed successfully
+ // (with or without warnings).
+ sqlEditorStore.fetchQueryHistoryList();
+ cleanup();
+ } catch (error: any) {
+ fail(error.response?.data?.message ?? String(error));
}
};
@@ -146,6 +176,10 @@ const useExecuteSQL = () => {
config: ExecuteConfig,
option?: Partial<ExecuteOption>
) => {
+ if (!preflight(query)) {
+ return cleanup();
+ }
+
const tab = tabStore.currentTab;
let statement = query;
@@ -177,7 +211,8 @@ const useExecuteSQL = () => {
sqlEditorStore.fetchQueryHistoryList();
}
- return sqlResultSet;
+ cleanup();
+ return queryResult;
} catch (error: any) {
Object.assign(tab, {
queryResult: {
@@ -192,48 +227,14 @@ const useExecuteSQL = () => {
option,
},
});
- }
- };
-
- const execute = async (
- query: string,
- config: ExecuteConfig,
- option?: Partial<ExecuteOption>
- ) => {
- const tab = tabStore.currentTab;
- if (tab.isExecutingSQL) {
- notify("INFO", t("common.tips"), t("sql-editor.can-not-execute-query"));
- return;
+ cleanup();
}
-
- const isDisconnected = tabStore.isDisconnected;
- if (isDisconnected) {
- notify("CRITICAL", t("sql-editor.select-connection"));
- return;
- }
-
- if (isEmpty(query)) {
- notify("CRITICAL", t("sql-editor.notify-empty-statement"));
- return;
- }
-
- tab.isExecutingSQL = true;
-
- let result: SQLResultSet | undefined = undefined;
- if (tab.mode === TabMode.ReadOnly) {
- result = await executeReadonly(query, config, option);
- } else if (tab.mode === TabMode.Admin) {
- result = await executeAdmin(query, config, option);
- }
-
- tab.isExecutingSQL = false;
-
- return result;
};
return {
- execute,
+ executeReadonly,
+ executeAdmin,
};
};
diff --git a/frontend/src/store/modules/sql.ts b/frontend/src/store/modules/sql.ts
index 1d300163b7..4888990cd7 100644
--- a/frontend/src/store/modules/sql.ts
+++ b/frontend/src/store/modules/sql.ts
@@ -46,7 +46,7 @@ export function convert(resultSet: ResourceObject): SQLResultSet {
};
}
-export const useSQLStore = defineStore("sql", {
+export const useLegacySQLStore = defineStore("legacy_sql", {
actions: {
convert(resultSet: ResourceObject): SQLResultSet {
return convert(resultSet);
diff --git a/frontend/src/store/modules/sqlEditor.ts b/frontend/src/store/modules/sqlEditor.ts
index e1bac1affe..4db21c5c4b 100644
--- a/frontend/src/store/modules/sqlEditor.ts
+++ b/frontend/src/store/modules/sqlEditor.ts
@@ -9,9 +9,10 @@ import {
} from "@/types";
import { UNKNOWN_ID } from "@/types";
import { useActivityStore } from "./activity";
-import { useSQLStore } from "./sql";
+import { useLegacySQLStore } from "./sql";
import { useTabStore } from "./tab";
import { useDatabaseV1Store } from "./v1/database";
+import { useInstanceV1Store, useSQLStore } from "./v1";
// set the limit to 10000 temporarily to avoid the query timeout and page crash
export const RESULT_ROWS_LIMIT = 1000;
@@ -44,21 +45,22 @@ export const useSQLEditorStore = defineStore("sqlEditor", {
const database = useDatabaseV1Store().getDatabaseByUID(databaseId);
const databaseName =
database.uid === String(UNKNOWN_ID) ? "" : database.databaseName;
- const queryResult = await useSQLStore().query({
- instanceId: Number(instanceId),
- databaseName,
- statement: statement,
+ const instance = useInstanceV1Store().getInstanceByUID(instanceId);
+ const response = await useSQLStore().queryReadonly({
+ name: instance.name,
+ connectionDatabase: databaseName,
+ statement,
limit: RESULT_ROWS_LIMIT,
});
- return queryResult;
+ return response;
},
async executeAdminQuery({ statement }: Pick<QueryInfo, "statement">) {
const { instanceId, databaseId } = useTabStore().currentTab.connection;
const database = useDatabaseV1Store().getDatabaseByUID(databaseId);
const databaseName =
database.uid === String(UNKNOWN_ID) ? "" : database.databaseName;
- const queryResult = await useSQLStore().adminQuery({
+ const queryResult = await useLegacySQLStore().adminQuery({
instanceId: Number(instanceId),
databaseName,
statement: statement,
diff --git a/frontend/src/store/modules/v1/index.ts b/frontend/src/store/modules/v1/index.ts
index bc336b6836..6608ebdb93 100644
--- a/frontend/src/store/modules/v1/index.ts
+++ b/frontend/src/store/modules/v1/index.ts
@@ -12,6 +12,7 @@ export * from "./setting";
export * from "./instance";
export * from "./subscription";
export * from "./actuator";
+export * from "./sql";
export * from "./repository";
export * from "./vcs";
export * from "./changeHistory";
diff --git a/frontend/src/store/modules/v1/sql.ts b/frontend/src/store/modules/v1/sql.ts
new file mode 100644
index 0000000000..df73d4c9a6
--- /dev/null
+++ b/frontend/src/store/modules/v1/sql.ts
@@ -0,0 +1,28 @@
+import { sqlServiceClient } from "@/grpcweb";
+import { SQLResultSetV1 } from "@/types";
+import { QueryRequest } from "@/types/proto/v1/sql_service";
+import { extractGrpcErrorMessage } from "@/utils/grpcweb";
+import { defineStore } from "pinia";
+
+export const useSQLStore = defineStore("sql", () => {
+ const queryReadonly = async (
+ params: QueryRequest
+ ): Promise<SQLResultSetV1> => {
+ try {
+ const response = await sqlServiceClient.query(params);
+
+ return {
+ error: "",
+ ...response,
+ };
+ } catch (err) {
+ const error = extractGrpcErrorMessage(err);
+ return {
+ error,
+ results: [],
+ advices: [],
+ };
+ }
+ };
+ return { queryReadonly };
+});
diff --git a/frontend/src/types/tab.ts b/frontend/src/types/tab.ts
index e8ec7e0955..6d2c154721 100644
--- a/frontend/src/types/tab.ts
+++ b/frontend/src/types/tab.ts
@@ -1,4 +1,5 @@
-import { Advice, SQLResultSet } from "../types";
+import { SQLResultSet } from "../types";
+import { SQLResultSetV1 } from "./v1/sql";
export type ExecuteConfig = {
databaseType: string;
@@ -38,7 +39,7 @@ export interface TabInfo {
isExecutingSQL: boolean;
queryResult?: SQLResultSet;
sheetName?: string;
- adviceList?: Advice[];
+ sqlResultSet?: SQLResultSetV1;
}
export type CoreTabInfo = Pick<TabInfo, "connection" | "sheetName" | "mode">;
diff --git a/frontend/src/types/v1/index.ts b/frontend/src/types/v1/index.ts
index d6d18abebf..9f6c05f677 100644
--- a/frontend/src/types/v1/index.ts
+++ b/frontend/src/types/v1/index.ts
@@ -7,3 +7,4 @@ export * from "./projectWebhook";
export * from "./role";
export * from "./user";
export * from "./repository";
+export * from "./sql";
diff --git a/frontend/src/types/v1/sql.ts b/frontend/src/types/v1/sql.ts
new file mode 100644
index 0000000000..9edc552841
--- /dev/null
+++ b/frontend/src/types/v1/sql.ts
@@ -0,0 +1,7 @@
+import { Advice, QueryResult } from "../proto/v1/sql_service";
+
+export type SQLResultSetV1 = {
+ error: string; // empty if no error occurred
+ results: QueryResult[];
+ advices: Advice[];
+};
diff --git a/frontend/src/utils/v1/index.ts b/frontend/src/utils/v1/index.ts
index 80ba4a9194..aa9eabaf25 100644
--- a/frontend/src/utils/v1/index.ts
+++ b/frontend/src/utils/v1/index.ts
@@ -12,6 +12,7 @@ export * from "./role";
export * from "./user";
export * from "./instance";
export * from "./sqlEditor";
+export * from "./sql";
export * from "./sheet";
export * from "./vcs";
export * from "./review";
diff --git a/frontend/src/utils/v1/sql.ts b/frontend/src/utils/v1/sql.ts
new file mode 100644
index 0000000000..9c1d18b0dd
--- /dev/null
+++ b/frontend/src/utils/v1/sql.ts
@@ -0,0 +1,15 @@
+import { RowValue } from "@/types/proto/v1/sql_service";
+
+export const extractSQLRowValue = (value: RowValue) => {
+ const plainObject = RowValue.toJSON(value) as Record<string, any>;
+ const keys = Object.keys(plainObject);
+ if (keys.length === 0) {
+ console.debug("empty row value", value);
+ return null;
+ }
+ if (keys.length > 1) {
+ console.debug("mixed type in row value", value);
+ }
+ const key = keys[0];
+ return plainObject[key];
+};
diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vue
index 936dcf51c2..99422a3478 100644
--- a/frontend/src/views/DatabaseDetail.vue
+++ b/frontend/src/views/DatabaseDetail.vue
@@ -289,7 +289,7 @@ import {
useDatabaseV1Store,
useDBSchemaStore,
useGracefulRequest,
- useSQLStore,
+ useLegacySQLStore,
} from "@/store";
import { usePolicyByParentAndType } from "@/store/modules/v1/policy";
import { PolicyType } from "@/types/proto/v1/org_policy_service";
@@ -328,7 +328,7 @@ const { t } = useI18n();
const router = useRouter();
const databaseV1Store = useDatabaseV1Store();
const dbSchemaStore = useDBSchemaStore();
-const sqlStore = useSQLStore();
+const sqlStore = useLegacySQLStore();
const ghostDialog = ref<InstanceType<typeof GhostDialog>>();
const databaseTabItemList = computed((): DatabaseTabItem[] => {
diff --git a/frontend/src/views/InstanceDetail.vue b/frontend/src/views/InstanceDetail.vue
index 5eb64bbd52..354d097615 100644
--- a/frontend/src/views/InstanceDetail.vue
+++ b/frontend/src/views/InstanceDetail.vue
@@ -131,7 +131,7 @@ import {
featureToRef,
pushNotification,
useSubscriptionV1Store,
- useSQLStore,
+ useLegacySQLStore,
useDBSchemaStore,
useCurrentUserV1,
useInstanceV1Store,
@@ -160,7 +160,7 @@ const subscriptionStore = useSubscriptionV1Store();
const { t } = useI18n();
const currentUserV1 = useCurrentUserV1();
-const sqlStore = useSQLStore();
+const sqlStore = useLegacySQLStore();
const state = reactive<LocalState>({
showCreateDatabaseModal: false,
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
new file mode 100644
index 0000000000..4037d2b350
--- /dev/null
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
@@ -0,0 +1,122 @@
+<template>
+ <NConfigProvider
+ v-bind="naiveUIConfig"
+ class="relative flex flex-col justify-start items-start p-2"
+ :class="dark && 'dark bg-dark-bg'"
+ >
+ <template v-if="resultSet && !showPlaceholder">
+ <template v-if="viewMode === 'SINGLE-RESULT'">
+ <SingleResultViewV1 :result="resultSet.results[0]" />
+ </template>
+ <template v-else-if="viewMode === 'MULTI-RESULT'">
+ <NTabs
+ type="card"
+ size="small"
+ class="flex-1 flex flex-col overflow-hidden"
+ >
+ <NTabPane
+ v-for="(result, i) in resultSet.results"
+ :key="i"
+ :name="tabName(result, i)"
+ class="flex-1 flex flex-col overflow-hidden"
+ >
+ <SingleResultViewV1 :result="result" />
+ </NTabPane>
+ </NTabs>
+ </template>
+ <template v-else-if="viewMode === 'EMPTY'">
+ <EmptyView />
+ </template>
+ <template v-else-if="viewMode === 'ERROR'">
+ <ErrorView :error="resultSet.error" />
+ </template>
+ </template>
+
+ <div
+ v-if="showPlaceholder"
+ class="absolute inset-0 flex flex-col justify-center items-center z-10"
+ :class="loading && 'bg-white/80 dark:bg-black/80'"
+ >
+ <template v-if="loading">
+ <BBSpin />
+ {{ $t("sql-editor.loading-data") }}
+ </template>
+ <template v-else-if="!resultSet">
+ {{ $t("sql-editor.table-empty-placeholder") }}
+ </template>
+ </div>
+ </NConfigProvider>
+</template>
+
+<script lang="ts" setup>
+import { computed, PropType, toRef } from "vue";
+import { useI18n } from "vue-i18n";
+import { darkTheme, NConfigProvider, NTabs, NTabPane } from "naive-ui";
+
+import { darkThemeOverrides } from "@/../naive-ui.config";
+import SingleResultViewV1 from "./SingleResultViewV1.vue";
+import EmptyView from "./EmptyView.vue";
+import { SQLResultSetV1 } from "@/types";
+import { provideSQLResultViewContext } from "./context";
+import ErrorView from "./ErrorView.vue";
+import { QueryResult } from "@/types/proto/v1/sql_service";
+
+type ViewMode = "SINGLE-RESULT" | "MULTI-RESULT" | "EMPTY" | "ERROR";
+
+const props = defineProps({
+ resultSet: {
+ type: Object as PropType<SQLResultSetV1>,
+ default: undefined,
+ },
+ loading: {
+ type: Boolean,
+ default: false,
+ },
+ dark: {
+ type: Boolean,
+ default: false,
+ },
+});
+
+const { t } = useI18n();
+
+const viewMode = computed((): ViewMode => {
+ const { resultSet } = props;
+ if (!resultSet) {
+ return "EMPTY";
+ }
+ const { results, error } = resultSet;
+ if (error) {
+ return "ERROR";
+ }
+ if (results.length === 0) {
+ return "EMPTY";
+ }
+ if (results.length === 1) {
+ return "SINGLE-RESULT";
+ }
+ return "MULTI-RESULT";
+});
+
+const naiveUIConfig = computed(() => {
+ if (props.dark) {
+ return { theme: darkTheme, themeOverrides: darkThemeOverrides.value };
+ }
+ return {};
+});
+
+const showPlaceholder = computed(() => {
+ if (viewMode.value === "ERROR") return false;
+ if (!props.resultSet) return true;
+ if (props.loading) return true;
+ return false;
+});
+
+const tabName = (result: QueryResult, index: number) => {
+ return `${t("common.query")} #${index + 1}`;
+};
+
+provideSQLResultViewContext({
+ dark: toRef(props, "dark"),
+});
+</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
new file mode 100644
index 0000000000..aca570fe93
--- /dev/null
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
@@ -0,0 +1,348 @@
+<template>
+ <template v-if="viewMode === 'RESULT'">
+ <div
+ class="w-full shrink-0 flex flex-row justify-between items-center mb-2 overflow-x-auto"
+ >
+ <div class="flex flex-row justify-start items-center mr-2 shrink-0">
+ <NInput
+ v-if="showSearchFeature"
+ v-model:value="state.search"
+ class="!max-w-[8rem] sm:!max-w-xs"
+ type="text"
+ :placeholder="t('sql-editor.search-results')"
+ >
+ <template #prefix>
+ <heroicons-outline:search class="h-5 w-5 text-gray-300" />
+ </template>
+ </NInput>
+ <span class="ml-2 whitespace-nowrap text-sm text-gray-500">{{
+ `${data.length} ${t("sql-editor.rows", data.length)}`
+ }}</span>
+ <span
+ v-if="data.length === RESULT_ROWS_LIMIT"
+ class="ml-2 whitespace-nowrap text-sm text-gray-500"
+ >
+ <span>-</span>
+ <span class="ml-2">{{ $t("sql-editor.rows-upper-limit") }}</span>
+ </span>
+ </div>
+ <div class="flex justify-between items-center gap-x-3">
+ <NPagination
+ v-if="showPagination"
+ :item-count="table.getCoreRowModel().rows.length"
+ :page="table.getState().pagination.pageIndex + 1"
+ :page-size="table.getState().pagination.pageSize"
+ :show-quick-jumper="true"
+ :show-size-picker="true"
+ :page-sizes="[20, 50, 100]"
+ @update-page="handleChangePage"
+ @update-page-size="(ps) => table.setPageSize(ps)"
+ />
+ <NButton
+ v-if="showVisualizeButton"
+ text
+ type="primary"
+ @click="visualizeExplain"
+ >
+ {{ $t("sql-editor.visualize-explain") }}
+ </NButton>
+ <!-- In enterprise plan, we don't allow export data in SQL editor. -->
+ <NDropdown
+ v-if="showExportButton"
+ trigger="hover"
+ :options="exportDropdownOptions"
+ @select="handleExportBtnClick"
+ >
+ <NButton>
+ <template #icon>
+ <heroicons-outline:download class="h-5 w-5" />
+ </template>
+ {{ t("common.export") }}
+ </NButton>
+ </NDropdown>
+ </div>
+ </div>
+
+ <div class="flex-1 w-full flex flex-col overflow-y-auto">
+ <DataTable
+ ref="dataTable"
+ :table="table"
+ :columns="columns"
+ :data="data"
+ :sensitive="sensitive"
+ :keyword="state.search"
+ />
+ </div>
+ </template>
+ <template v-else-if="viewMode === 'AFFECTED-ROWS'">
+ <div
+ class="text-md font-normal flex items-center gap-x-1"
+ :class="[
+ dark ? 'text-[var(--color-matrix-green-hover)]' : 'text-control-light',
+ ]"
+ >
+ <span>{{ extractSQLRowValue(result.rows[0].values[0]) }}</span>
+ <span>rows affected</span>
+ </div>
+ </template>
+ <template v-else-if="viewMode === 'EMPTY'">
+ <EmptyView />
+ </template>
+ <template v-else-if="viewMode === 'ERROR'">
+ <ErrorView :error="result.error" />
+ </template>
+</template>
+
+<script lang="ts" setup>
+import { computed, reactive, ref } from "vue";
+import { NPagination } from "naive-ui";
+import { useI18n } from "vue-i18n";
+import { debouncedRef } from "@vueuse/core";
+import {
+ ColumnDef,
+ getCoreRowModel,
+ getPaginationRowModel,
+ useVueTable,
+} from "@tanstack/vue-table";
+import { isEmpty } from "lodash-es";
+import { unparse } from "papaparse";
+import dayjs from "dayjs";
+
+import {
+ createExplainToken,
+ extractSQLRowValue,
+ instanceV1HasStructuredQueryResult,
+} from "@/utils";
+import {
+ useInstanceV1Store,
+ useTabStore,
+ RESULT_ROWS_LIMIT,
+ featureToRef,
+ useCurrentUserIamPolicy,
+ pushNotification,
+ useDatabaseV1Store,
+} from "@/store";
+import DataTable from "./DataTable";
+import EmptyView from "./EmptyView.vue";
+import ErrorView from "./ErrorView.vue";
+import { useSQLResultViewContext } from "./context";
+import { Engine } from "@/types/proto/v1/common";
+import { QueryResult } from "@/types/proto/v1/sql_service";
+import { SQLResultSetV1 } from "@/types";
+
+type LocalState = {
+ search: string;
+};
+type ViewMode = "RESULT" | "EMPTY" | "AFFECTED-ROWS" | "ERROR";
+
+const PAGE_SIZES = [20, 50, 100];
+const DEFAULT_PAGE_SIZE = 50;
+
+const props = defineProps<{
+ result: QueryResult;
+}>();
+
+const state = reactive<LocalState>({
+ search: "",
+});
+
+const { dark } = useSQLResultViewContext();
+
+const { t } = useI18n();
+const tabStore = useTabStore();
+const instanceStore = useInstanceV1Store();
+const databaseStore = useDatabaseV1Store();
+const dataTable = ref<InstanceType<typeof DataTable>>();
+
+const viewMode = computed((): ViewMode => {
+ const { result } = props;
+ if (result.error) {
+ return "ERROR";
+ }
+ const columnNames = result.columnNames;
+ if (columnNames?.length === 0) {
+ return "EMPTY";
+ }
+ if (columnNames?.length === 1 && columnNames[0] === "Affected Rows") {
+ return "AFFECTED-ROWS";
+ }
+ return "RESULT";
+});
+
+const showSearchFeature = computed(() => {
+ const instance = instanceStore.getInstanceByUID(
+ tabStore.currentTab.connection.instanceId
+ );
+ return instanceV1HasStructuredQueryResult(instance);
+});
+
+// show export button only when the subscription is not enterprise.
+// In enterprise plan, all users need to fill in the export data request issue.
+const showExportButton = computed(() => {
+ return !featureToRef("bb.feature.custom-role").value;
+});
+
+const allowToExportData = computed(() => {
+ const database = databaseStore.getDatabaseByUID(
+ tabStore.currentTab.connection.databaseId
+ );
+ return useCurrentUserIamPolicy().allowToExportDatabaseV1(database);
+});
+
+// use a debounced value to improve performance when typing rapidly
+const keyword = debouncedRef(
+ computed(() => state.search),
+ 200
+);
+
+const columns = computed(() => {
+ const columns = props.result.columnNames;
+ return columns.map<ColumnDef<string[]>>((col, index) => ({
+ id: `${col}@${index}`,
+ accessorFn: (item) => item[index],
+ header: col,
+ }));
+});
+
+const convertedData = computed(() => {
+ const rows = props.result.rows;
+ return rows.map((row) => {
+ return row.values.map((value) => extractSQLRowValue(value));
+ });
+});
+
+const data = computed(() => {
+ const data = convertedData.value;
+ const search = keyword.value.trim().toLowerCase();
+ let temp = data;
+ if (search) {
+ temp = data.filter((item) => {
+ return item.some((col) => String(col).toLowerCase().includes(search));
+ });
+ }
+ return temp;
+});
+
+const sensitive = computed(() => {
+ return props.result.masked;
+});
+
+const table = useVueTable<string[]>({
+ get data() {
+ return data.value;
+ },
+ get columns() {
+ return columns.value;
+ },
+ getCoreRowModel: getCoreRowModel(),
+ getPaginationRowModel: getPaginationRowModel(),
+});
+
+table.setPageSize(DEFAULT_PAGE_SIZE);
+
+const exportDropdownOptions = computed(() => [
+ {
+ label: t("sql-editor.download-as-csv"),
+ key: "csv",
+ disabled: props.result === null || isEmpty(props.result),
+ },
+ {
+ label: t("sql-editor.download-as-json"),
+ key: "json",
+ disabled: props.result === null || isEmpty(props.result),
+ },
+]);
+
+const handleExportBtnClick = (format: "csv" | "json") => {
+ if (!allowToExportData.value) {
+ pushNotification({
+ module: "bytebase",
+ style: "INFO",
+ title: "You don't have permission to export data.",
+ });
+ return;
+ }
+
+ let rawText = "";
+
+ if (format === "csv") {
+ const csvFields = columns.value.map((col) => col.header as string);
+ const csvData = data.value.map((d) => {
+ const temp: any[] = [];
+ for (const k in d) {
+ temp.push(d[k]);
+ }
+ return temp;
+ });
+
+ rawText = unparse({
+ fields: csvFields,
+ data: csvData,
+ });
+ } else {
+ const objects = [];
+ for (const item of data.value) {
+ const object = {} as any;
+ for (let i = 0; i < columns.value.length; i++) {
+ object[columns.value[i].header as string] = item[i];
+ }
+ objects.push(object);
+ }
+ rawText = JSON.stringify(objects);
+ }
+
+ const encodedUri = encodeURI(`data:text/${format};charset=utf-8,${rawText}`);
+ const formattedDateString = dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss");
+ // Example filename: `mysheet-2022-03-23T09-54-21.json`
+ const filename = `${tabStore.currentTab.name}-${formattedDateString}`;
+ const link = document.createElement("a");
+
+ link.download = `${filename}.${format}`;
+ link.href = encodedUri;
+ link.click();
+};
+
+const showVisualizeButton = computed((): boolean => {
+ const instance = instanceStore.getInstanceByUID(
+ tabStore.currentTab.connection.instanceId
+ );
+ const databaseType = instance.engine;
+ const { executeParams } = tabStore.currentTab;
+ return databaseType === Engine.POSTGRES && !!executeParams?.option?.explain;
+});
+
+const visualizeExplain = () => {
+ try {
+ const { executeParams, sqlResultSet } = tabStore.currentTab;
+ if (!executeParams || !sqlResultSet) return;
+
+ const statement = executeParams.query || "";
+ if (!statement) return;
+
+ const explain = explainFromSQLResultSetV1(sqlResultSet);
+ if (!explain) return;
+
+ const token = createExplainToken(statement, explain);
+
+ window.open(`/explain-visualizer.html?token=${token}`, "_blank");
+ } catch {
+ // nothing
+ }
+};
+
+const showPagination = computed(() => data.value.length > PAGE_SIZES[0]);
+
+const handleChangePage = (page: number) => {
+ table.setPageIndex(page - 1);
+ dataTable.value?.scrollTo(0, 0);
+};
+
+const explainFromSQLResultSetV1 = (resultSet: SQLResultSetV1 | undefined) => {
+ if (!resultSet) return "";
+ const lines = resultSet.results[0].rows.map((row) =>
+ row.values.map((value) => String(extractSQLRowValue(value)))
+ );
+ const explain = lines.map((line) => line[0]).join("\n");
+ return explain;
+};
+</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/index.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/index.ts
index 55dd2e66af..f80de16e82 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/index.ts
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/index.ts
@@ -1,3 +1,4 @@
import ResultView from "./ResultView.vue";
+import ResultViewV1 from "./ResultViewV1.vue";
-export default ResultView;
+export { ResultView, ResultViewV1 };
diff --git a/frontend/src/views/sql-editor/EditorCommon/index.ts b/frontend/src/views/sql-editor/EditorCommon/index.ts
index 49a23ac3b5..2e8543fad0 100644
--- a/frontend/src/views/sql-editor/EditorCommon/index.ts
+++ b/frontend/src/views/sql-editor/EditorCommon/index.ts
@@ -4,7 +4,7 @@ import EditorAction from "./EditorAction.vue";
import ExecutingHintModal from "./ExecutingHintModal.vue";
import SaveSheetModal from "./SaveSheetModal.vue";
import SharePopover from "./SharePopover.vue";
-import ResultView from "./ResultView";
+import { ResultView, ResultViewV1 } from "./ResultView";
export {
ConnectionHolder,
@@ -14,4 +14,5 @@ export {
SaveSheetModal,
SharePopover,
ResultView,
+ ResultViewV1,
};
diff --git a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue b/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
index 75e87e563d..6b245dffe8 100644
--- a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
@@ -62,14 +62,14 @@ const sheetBacktracePayload = computed(() => {
return getSheetIssueBacktracePayloadV1(sheet);
});
-const { execute } = useExecuteSQL();
+const { executeReadonly } = useExecuteSQL();
const handleExecute = (
query: string,
config: ExecuteConfig,
option?: ExecuteOption
) => {
- execute(query, config, option);
+ executeReadonly(query, config, option);
};
const trySaveSheet = (sheetName?: string) => {
diff --git a/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue b/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue
index 87c1768f77..3b85996eca 100644
--- a/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue
+++ b/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue
@@ -1,7 +1,7 @@
<template>
- <ResultView
+ <ResultViewV1
class="w-full h-full"
- :result-set="queryResult"
+ :result-set="resultSet"
:loading="loading"
/>
</template>
@@ -9,11 +9,11 @@
<script lang="ts" setup>
import { computed } from "vue";
-import { ResultView } from "../EditorCommon/";
+import { ResultViewV1 } from "../EditorCommon/";
import { useTabStore } from "@/store";
const tabStore = useTabStore();
-const queryResult = computed(() => tabStore.currentTab.queryResult);
+const resultSet = computed(() => tabStore.currentTab.sqlResultSet);
const loading = computed(() => tabStore.currentTab.isExecutingSQL);
</script>
diff --git a/frontend/src/views/sql-editor/TerminalPanel/TerminalPanel.vue b/frontend/src/views/sql-editor/TerminalPanel/TerminalPanel.vue
index 502b9a46ae..4e42531285 100644
--- a/frontend/src/views/sql-editor/TerminalPanel/TerminalPanel.vue
+++ b/frontend/src/views/sql-editor/TerminalPanel/TerminalPanel.vue
@@ -106,7 +106,7 @@ const currentQuery = computed(
() => queryList.value[queryList.value.length - 1]
);
-const { execute } = useExecuteSQL();
+const { executeAdmin } = useExecuteSQL();
const { move: moveHistory } = useHistory();
@@ -146,13 +146,13 @@ const handleExecute = async (
queryItem.executeParams = { query, config, option };
queryItem.status = "RUNNING";
- const sqlResultSet = await execute(query, config, option);
+ const queryResult = await executeAdmin(query, config, option);
// If the queryItem is still the currentQuery
// which means it hasn't been cancelled.
- if (queryItem === currentQuery.value) {
+ if (queryResult && queryItem === currentQuery.value) {
// If the result is empty, mock it as "Affected rows: 0"
- const resultList = sqlResultSet?.resultList ?? [];
+ const resultList = queryResult?.resultList ?? [];
resultList.forEach((result) => {
if (
!Array.isArray(result.data) ||
@@ -162,7 +162,7 @@ const handleExecute = async (
result.data = mockAffectedRows0().data;
}
});
- queryItem.queryResult = sqlResultSet;
+ queryItem.queryResult = queryResult;
pushQueryItem();
// Clear the tab's statement and keep it sync with the latest query
tabStore.currentTab.statement = "";