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(sql-editor): add the query selector logic (#331)
Yunwei Xiao9518a7664388
diff --git a/frontend/package.json b/frontend/package.jsonindex fff513d263..af4e1d555c 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -18,6 +18,7 @@"@vueuse/core": "^7.0.1","autoprefixer": "^10.2.6","axios": "^0.21.2",+ "dayjs": "^1.10.7","highlight.js": "^10.6.0","inter-ui": "^3.15.0","lodash-es": "^4.17.21",diff --git a/frontend/src/components/MonacoEditor/AutoCompletion.ts b/frontend/src/components/MonacoEditor/AutoCompletion.tsindex c82106ee41..6e3a094733 100644--- a/frontend/src/components/MonacoEditor/AutoCompletion.ts+++ b/frontend/src/components/MonacoEditor/AutoCompletion.ts@@ -129,7 +129,7 @@ export default class AutoCompletion {getCompletionItemsForTableColumns(table: Table,- withTablePrefix: boolean = true+ withTablePrefix = true): CompletionItems {const suggestions: CompletionItems = [];diff --git a/frontend/src/components/MonacoEditor/MonacoEditor.vue b/frontend/src/components/MonacoEditor/MonacoEditor.vueindex 04f7e944f5..878460b7c4 100644--- a/frontend/src/components/MonacoEditor/MonacoEditor.vue+++ b/frontend/src/components/MonacoEditor/MonacoEditor.vue@@ -3,15 +3,24 @@</template><script lang="ts" setup>-import { onMounted, ref, toRef, toRaw, PropType, nextTick } from "vue";+import {+ onMounted,+ ref,+ toRef,+ toRaw,+ PropType,+ nextTick,+ defineProps,+ defineEmits,+ onUnmounted,+} from "vue";import type { editor as Editor } from "monaco-editor";-import setupMonaco from "./setupMonaco";-import sqlFormatter from "./sqlFormatter";+import { useMonaco } from "./useMonaco";import { SqlDialect } from "../../types";const props = defineProps({- modelValue: {+ value: {type: String,required: true,},@@ -22,33 +31,26 @@ const props = defineProps({});const emit = defineEmits<{- (e: "update:modelValue", content: string): void;+ (e: "update:value", content: string): void;(e: "change", content: string): void;(e: "change-selection", content: string): void;(e: "run-query", content: string): void;}>();const editorRef = ref();-const sqlCode = toRef(props, "modelValue");+const sqlCode = toRef(props, "value");const language = toRef(props, "language");let editorInstance: Editor.IStandaloneCodeEditor;-const setContent = (content: string) => {- if (editorInstance) editorInstance.setValue(content);-};--const formatContent = () => {- if (editorInstance) {- const sql = editorInstance.getValue();- const { data } = sqlFormatter(sql, language.value);- setContent(data);- }-};+const {+ monaco,+ setPositionAtEndOfLine,+ formatContent,+ completionItemProvider,+} = await useMonaco(language.value);const init = async () => {- const { monaco } = await setupMonaco(language.value);-const model = monaco.editor.createModel(sqlCode.value, toRaw(language.value));editorInstance = monaco.editor.create(editorRef.value, {@@ -88,6 +90,7 @@ const init = async () => {},});+ // add format sql action in context menueditorInstance.addAction({id: "FormatSQL",label: "Format SQL",@@ -97,23 +100,15 @@ const init = async () => {contextMenuGroupId: "operation",contextMenuOrder: 1,run: () => {- formatContent();- nextTick(() => {- // eslint-disable-next-line @typescript-eslint/ban-ts-comment- // @ts-expect-error- const range = editorInstance.getModel().getFullModelRange();- editorInstance.setPosition({- lineNumber: range?.endLineNumber,- column: range?.endColumn,- });- });+ formatContent(editorInstance, language.value);+ nextTick(() => setPositionAtEndOfLine(editorInstance));},});// typed something, change the texteditorInstance.onDidChangeModelContent(() => {const value = editorInstance.getValue();- emit("update:modelValue", value);+ // emit("update:value", value);emit("change", value);});@@ -130,4 +125,9 @@ const init = async () => {};onMounted(init);++onUnmounted(() => {+ completionItemProvider.dispose();+ editorInstance.dispose();+});</script>diff --git a/frontend/src/components/MonacoEditor/sqlParser.ts b/frontend/src/components/MonacoEditor/sqlParser.tsindex 3a62296328..fa6f08c46e 100644--- a/frontend/src/components/MonacoEditor/sqlParser.ts+++ b/frontend/src/components/MonacoEditor/sqlParser.ts@@ -16,6 +16,11 @@ const parseSQL = (sql: string): ParseResult => {}};+export const isValidStatement = (sql: string) => {+ const { data } = parseSQL(sql);+ return data !== null;+};+export const isSelectStatement = (sql: string) => {const { data } = parseSQL(sql);// eslint-disable-next-line @typescript-eslint/ban-ts-commentdiff --git a/frontend/src/components/MonacoEditor/setupMonaco.ts b/frontend/src/components/MonacoEditor/useMonaco.tssimilarity index 76%rename from frontend/src/components/MonacoEditor/setupMonaco.tsrename to frontend/src/components/MonacoEditor/useMonaco.tsindex dd292ea33e..165322eedc 100644--- a/frontend/src/components/MonacoEditor/setupMonaco.ts+++ b/frontend/src/components/MonacoEditor/useMonaco.ts@@ -1,6 +1,8 @@-import * as monaco from "monaco-editor";import { computed } from "vue";import { useStore } from "vuex";+import { useNamespacedGetters } from "vuex-composition-helpers";+import * as monaco from "monaco-editor";+import type { editor as Editor } from "monaco-editor";import AutoCompletion from "./AutoCompletion";import {@@ -8,11 +10,11 @@ import {Table,CompletionItems,InstanceGetters,+ SqlDialect,} from "../../types";+import sqlFormatter from "./sqlFormatter";-import { useNamespacedGetters } from "vuex-composition-helpers";--const setupMonaco = async (lang: string) => {+const useMonaco = async (lang: string) => {const store = useStore();const { instanceList } = useNamespacedGetters<InstanceGetters>("instance", [@@ -124,10 +126,12 @@ const setupMonaco = async (lang: string) => {// load workers(async () => {const [{ default: EditorWorker }] = await Promise.all([+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-expect-errorimport("monaco-editor/esm/vs/editor/editor.worker.js?worker"),]);+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-expect-errorwindow.MonacoEnvironment = {getWorker(_: any, label: string) {@@ -137,7 +141,45 @@ const setupMonaco = async (lang: string) => {})(),]);- return { monaco, completionItemProvider };+ const setContent = (+ editorInstance: Editor.IStandaloneCodeEditor,+ content: string+ ) => {+ if (editorInstance) editorInstance.setValue(content);+ };++ const formatContent = (+ editorInstance: Editor.IStandaloneCodeEditor,+ language: SqlDialect+ ) => {+ if (editorInstance) {+ const sql = editorInstance.getValue();+ const { data } = sqlFormatter(sql, language);+ setContent(editorInstance, data);+ }+ };++ const setPositionAtEndOfLine = (+ editorInstance: Editor.IStandaloneCodeEditor+ ) => {+ if (editorInstance) {+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ // @ts-expect-error+ const range = editorInstance.getModel().getFullModelRange();+ editorInstance.setPosition({+ lineNumber: range?.endLineNumber,+ column: range?.endColumn,+ });+ }+ };++ return {+ monaco,+ completionItemProvider,+ formatContent,+ setContent,+ setPositionAtEndOfLine,+ };};-export default setupMonaco;+export { useMonaco };diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.tsindex 61e99fda0a..ab8854d40f 100644--- a/frontend/src/composables/useExecuteSQL.ts+++ b/frontend/src/composables/useExecuteSQL.ts@@ -1,40 +1,75 @@+import { ref } from "vue";import { isEmpty } from "lodash-es";-import { isSelectStatement } from "../components/MonacoEditor/sqlParser";--const useExecuteSQL = async (store: any) => {- const queryStatement = store.state.sqlEditor.queryStatement;- const selectedStatement = store.state.sqlEditor.selectedStatement;- const sqlStatement = selectedStatement || queryStatement;-- if (!isEmpty(sqlStatement) && !isSelectStatement(sqlStatement)) {- store.dispatch("notification/pushNotification", {- module: "bytebase",- style: "CRITICAL",- title: "Only SELECT statements are allowed",- });- return;- }-- try {- const res = await store.dispatch("sqlEditor/executeQuery", {- statement: sqlStatement,- });-- if (res.error) {+import { useStore } from "vuex";+import {+ isSelectStatement,+ isValidStatement,+} from "../components/MonacoEditor/sqlParser";++const useExecuteSQL = () => {+ const store = useStore();+ const isLoadingData = ref(false);++ const execute = async () => {+ const queryStatement = store.state.sqlEditor.queryStatement;+ const selectedStatement = store.state.sqlEditor.selectedStatement;+ const sqlStatement = selectedStatement || queryStatement;++ if (isEmpty(sqlStatement)) {store.dispatch("notification/pushNotification", {module: "bytebase",style: "CRITICAL",- title: res.error,+ title: "Please input your SQL codes in the editor",});return;}- } catch (error) {- store.dispatch("notification/pushNotification", {- module: "bytebase",- style: "CRITICAL",- title: error,- });- }++ if (!isValidStatement(sqlStatement)) {+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "CRITICAL",+ title: "Please check if the statement is correct",+ });+ return;+ }++ if (!isSelectStatement(sqlStatement)) {+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "CRITICAL",+ title: "Only SELECT statements are allowed",+ });+ return;+ }+ try {+ isLoadingData.value = true;+ const res = await store.dispatch("sqlEditor/executeQuery", {+ statement: sqlStatement,+ });+ isLoadingData.value = false;++ if (res.error) {+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "CRITICAL",+ title: res.error,+ });+ return;+ }+ } catch (error) {+ isLoadingData.value = false;+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "CRITICAL",+ title: error,+ });+ }+ };++ return {+ isLoadingData,+ execute,+ };};export { useExecuteSQL };diff --git a/frontend/src/locales/en.yml b/frontend/src/locales/en.ymlindex 837939aff2..96eb12aa63 100644--- a/frontend/src/locales/en.yml+++ b/frontend/src/locales/en.yml@@ -1029,6 +1029,8 @@ sql-editor:search-databases: Search Databasesloading-databases: Loading Databases...close-pane: Close Pane+ loading-data: Loading Data...+ table-empty-placehoder: Click Run to execute the query.label:error:key-necessary: Key is requireddiff --git a/frontend/src/locales/zh-CN.yml b/frontend/src/locales/zh-CN.ymlindex 8912297a60..c36548d367 100644--- a/frontend/src/locales/zh-CN.yml+++ b/frontend/src/locales/zh-CN.yml@@ -900,6 +900,8 @@ sql-editor:search-databases: 搜索数据库loading-databases: 加载数据库信息...close-pane: 关闭面板+ loading-data: 加载数据中...+ table-empty-placehoder: 点击 ”运行“ 执行查询label:error:key-necessary: 需要指定 Keydiff --git a/frontend/src/store/modules/editorSelector.ts b/frontend/src/store/modules/editorSelector.tsnew file mode 100644index 0000000000..053a023d56--- /dev/null+++ b/frontend/src/store/modules/editorSelector.ts@@ -0,0 +1,121 @@+import dayjs from "dayjs";+import { v1 as uuidv1 } from "uuid";+import { TabInfo, AnyTabInfo, EditorSelectorState } from "../../types";+import * as types from "../mutation-types";+import { makeActions } from "../actions";++const state: () => EditorSelectorState = () => ({+ queryTabList: [],+ activeTab: {+ id: uuidv1(),+ idx: 0,+ label: "Untitled Queries",+ isSaved: true,+ savedAt: dayjs().format("YYYY-MM-DD HH:mm:ss"),+ queries: "",+ },+ activeTabIdx: 1,+});++const getters = {+ currentTab(state: EditorSelectorState) {+ const idx = state.queryTabList.findIndex(+ (tab: TabInfo) => tab.idx === state.activeTabIdx+ );+ return idx === -1 ? {} : state.queryTabList[idx];+ },+ hasTabs(state: EditorSelectorState) {+ return state.queryTabList.length > 0;+ },+};++const mutations = {+ [types.SET_EDITOR_SELECTOR_STATE](+ state: EditorSelectorState,+ payload: Partial<EditorSelectorState>+ ) {+ Object.assign(state, payload);+ },+ [types.ADD_TAB](state: EditorSelectorState, payload: TabInfo) {+ state.queryTabList.push(payload);+ },+ [types.REMOVE_TAB](state: EditorSelectorState, payload: TabInfo) {+ state.queryTabList.splice(state.queryTabList.indexOf(payload), 1);+ },+ [types.UPDATE_TAB](state: EditorSelectorState, payload: TabInfo) {+ const idx = state.queryTabList.findIndex(+ (tab: TabInfo) => tab.id === payload.id+ );+ Object.assign(state.queryTabList[idx], payload);+ },+};++type ActionsMap = {+ setEditorSelectorState: typeof mutations.SET_EDITOR_SELECTOR_STATE;+};++const actions = {+ ...makeActions<ActionsMap>({+ setEditorSelectorState: types.SET_EDITOR_SELECTOR_STATE,+ }),+ addTab({ commit, state }: any, payload: AnyTabInfo) {+ const id = uuidv1();+ const idx =+ state.queryTabList.length === 0+ ? 0+ : Math.max(...state.queryTabList.map((tab: TabInfo) => tab.idx)) + 1;+ const newTab = {+ id,+ idx,+ label: payload.label ? payload.label : `Untitled Queries`,+ isSaved: true,+ savedAt: dayjs().format("YYYY-MM-DD HH:mm:ss"),+ queries: payload.queries || "",+ };++ commit(types.SET_EDITOR_SELECTOR_STATE, {+ activeTab: newTab,+ activeTabIdx: idx,+ });+ commit(types.ADD_TAB, newTab);+ },+ removeTab({ commit, state, dispatch }: any, payload: TabInfo) {+ commit(types.REMOVE_TAB, payload);+ const tabsLength = state.queryTabList.length;++ if (tabsLength > 0) {+ dispatch("setActiveTab", state.queryTabList[tabsLength - 1]);+ }+ },+ updateTab({ commit, state }: any, payload: AnyTabInfo) {+ const { idx } = payload;+ const tab = state.queryTabList.find((tab: TabInfo) => tab.idx === idx);++ if (tab) {+ commit(types.SET_EDITOR_SELECTOR_STATE, {+ activeTab: tab,+ activeTabIdx: idx,+ });+ commit(types.UPDATE_TAB, payload);+ }+ },+ setActiveTab({ commit, state }: any, payload: TabInfo) {+ const { idx } = payload;+ const tab = state.queryTabList.find((tab: TabInfo) => tab.idx === idx);++ if (tab) {+ commit(types.SET_EDITOR_SELECTOR_STATE, {+ activeTab: tab,+ activeTabIdx: idx,+ });+ }+ },+};++export default {+ namespaced: true,+ state,+ getters,+ actions,+ mutations,+};diff --git a/frontend/src/store/mutation-types.ts b/frontend/src/store/mutation-types.tsindex 4f95d7d093..ef932d36ec 100644--- a/frontend/src/store/mutation-types.ts+++ b/frontend/src/store/mutation-types.ts@@ -3,3 +3,10 @@ export const SET_SQL_EDITOR_STATE = "SET_SQL_EDITOR_STATE";export const SET_CONNECTION_TREE = "SET_CONNECTION_TREE";export const SET_QUERY_RESULT = "SET_QUERY_RESULT";export const SET_CONNECTION_CONTEXT = "SET_CONNECTION_CONTEXT";++// Editor Selector mutation types+export const SET_EDITOR_SELECTOR_STATE = "SET_EDITOR_SELECTOR_STATE";+export const ADD_TAB = "ADD_TAB";+export const REMOVE_TAB = "REMOVE_TAB";+export const UPDATE_TAB = "UPDATE_TAB";+export const SET_ACTIVE_TAB = "SET_ACTIVE_TAB";diff --git a/frontend/src/types/editorSelector.ts b/frontend/src/types/editorSelector.tsnew file mode 100644index 0000000000..74b2712676--- /dev/null+++ b/frontend/src/types/editorSelector.ts@@ -0,0 +1,10 @@+export interface TabInfo {+ id: string;+ idx: number;+ label: string;+ isSaved: boolean;+ savedAt: string;+ queries: string;+}++export type AnyTabInfo = Partial<TabInfo>;diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 6cffa0b9a2..462db4fd76 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -35,3 +35,4 @@ export * from "./vcs";export * from "./view";export * from "./label";export * from "./sqlEditor";+export * from "./editorSelector";diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.tsindex 1d3bfae012..4e66593e1e 100644--- a/frontend/src/types/store.ts+++ b/frontend/src/types/store.ts@@ -34,8 +34,10 @@ import { Table } from "./table";import { VCS } from "./vcs";import { Label } from "./label";import { ConnectionAtom, ConnectionContext } from "./sqlEditor";+import { TabInfo, AnyTabInfo } from "./editorSelector";import instanceStore from "../store/modules/instance";import sqlEditorStore from "../store/modules/sqlEditor";+import editorSelectorStore from "../store/modules/editorSelector";export interface ActuatorState {serverInfo?: ServerInfo;@@ -187,3 +189,12 @@ export interface SqlEditorState {export type SqlEditorGetters = typeof sqlEditorStore.getters;export type SqlEditorActions = typeof sqlEditorStore.actions;export type SqlEditorMutations = typeof sqlEditorStore.mutations;++export interface EditorSelectorState {+ queryTabList: TabInfo[];+ activeTab: TabInfo;+ activeTabIdx: number;+}+export type EditorSelectorGetters = typeof editorSelectorStore.getters;+export type EditorSelectorActions = typeof editorSelectorStore.actions;+export type EditorSelectorMutations = typeof editorSelectorStore.mutations;diff --git a/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue b/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vueindex c9ded0d7db..745dbfd5aa 100644--- a/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue+++ b/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue@@ -1,7 +1,7 @@<template><div class="aside-panel h-full"><n-tabs type="segment" default-value="databases" class="h-full">- <n-tab-pane name="databases" tab="Databases">+ <n-tab-pane name="databases" :tab="$t('common.databases')"><Splitpaneshorizontalclass="default-theme"@@ -17,7 +17,9 @@</Pane></Splitpanes></n-tab-pane>- <n-tab-pane name="queries" tab="Queries"> Queries Page </n-tab-pane>+ <n-tab-pane v-if="isDev()" name="queries" tab="Queries">+ Queries Page+ </n-tab-pane></n-tabs></div></template>@@ -27,6 +29,7 @@ import { ref, watch } from "vue";import { useNamespacedState } from "vuex-composition-helpers";import type { SqlEditorState } from "../../../types";+import { isDev } from "../../../utils";import DatabaseTree from "./DatabaseTree.vue";import TableSchema from "./TableSchema.vue";diff --git a/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vue b/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vueindex 69c8283e68..97931ee30c 100644--- a/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vue+++ b/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vue@@ -8,7 +8,7 @@<divclass="table-schema--header-actions flex-1 flex justify-end space-x-2">- <div class="action-edit flex items-center">+ <div v-if="isDev()" class="action-edit flex items-center"><NTooltip trigger="hover"><template #trigger><NButton text @click="handleEditorSchema">@@ -64,13 +64,14 @@</template><script lang="ts" setup>-import { ref, watch } from "vue";+import { ref, watch, defineEmits } from "vue";import {useNamespacedState,useNamespacedActions,} from "vuex-composition-helpers";import type { SqlEditorState } from "../../../types";+import { isDev } from "../../../utils";const emit = defineEmits<{(e: "close-pane"): void;diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vueindex cd1c11d0a0..9753784668 100644--- a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue@@ -4,7 +4,7 @@<NButtontype="primary":disabled="isEmptyStatement"- @click="handleExecuteQueries"+ @click="handleRunQuery"><mdi:play class="h-5 w-5" /> {{ $t("common.run") }} (⌘+⏎)</NButton>@@ -21,10 +21,16 @@:style="{ width: '400px' }"@update:value="handleConnectionChange"/>- <NButton secondary strong type="primary" :disabled="isEmptyStatement">+ <NButton+ v-if="isDev()"+ secondary+ strong+ type="primary"+ :disabled="isEmptyStatement"+ ><carbon:save class="h-5 w-5" /> {{ $t("common.save") }} (⌘+S)</NButton>- <NButton :disabled="isEmptyStatement">+ <NButton v-if="isDev()" :disabled="isEmptyStatement"><carbon:share class="h-5 w-5" /> {{ $t("common.share") }} (⌘+S)</NButton></div>@@ -34,7 +40,6 @@<script lang="ts" setup>import { ref, watch } from "vue";import { CascaderOption } from "naive-ui";-import { useStore } from "vuex";import { cloneDeep } from "lodash-es";import {@@ -49,6 +54,7 @@ import {ConnectionContext,} from "../../../types";import { useExecuteSQL } from "../../../composables/useExecuteSQL";+import { isDev } from "../../../utils";const { connectionTree, connectionContext } =useNamespacedState<SqlEditorState>("sqlEditor", [@@ -66,9 +72,11 @@ const { setConnectionContext } = useNamespacedActions<SqlEditorActions>(const selectedConnection = ref();const isSeletedDatabase = ref(false);-const store = useStore();+const { execute } = useExecuteSQL();-const handleExecuteQueries = () => useExecuteSQL(store);+const handleRunQuery = () => {+ execute();+};watch(() => connectionTree.value,diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vueindex 4990a5f553..0151b56277 100644--- a/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue@@ -1,12 +1,12 @@<template><div class="editor-pane h-full">- <EditorActions />+ <EditorAction /><QueryEditor /></div></template><script lang="ts" setup>-import EditorActions from "./EditorAction.vue";+import EditorAction from "./EditorAction.vue";import QueryEditor from "./QueryEditor.vue";</script>diff --git a/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue b/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vueindex 5126018b61..648ca25d04 100644--- a/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue+++ b/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue@@ -1,6 +1,6 @@<template><MonacoEditor- v-model="sqlCode"+ v-model:value="sqlCode"@change="handleChange"@change-selection="handleChangeSelection"@run-query="handleRunQuery"@@ -8,22 +8,29 @@</template><script lang="ts" setup>-import { ref } from "vue";+import { computed } from "vue";import { debounce } from "lodash-es";-import { useNamespacedActions } from "vuex-composition-helpers";-import { useStore } from "vuex";+import {+ useNamespacedActions,+ useNamespacedState,+} from "vuex-composition-helpers";-import { SqlEditorActions } from "../../../types";+import { SqlEditorActions, EditorSelectorState } from "../../../types";import { useExecuteSQL } from "../../../composables/useExecuteSQL";-const store = useStore();-const sqlCode = ref("");-+const { activeTab } = useNamespacedState<EditorSelectorState>(+ "editorSelector",+ ["activeTab"]+);const { setSqlEditorState } = useNamespacedActions<SqlEditorActions>("sqlEditor",["setSqlEditorState"]);+const { execute } = useExecuteSQL();++const sqlCode = computed(() => activeTab.value.queries);+const handleChange = debounce((value: string) => {setSqlEditorState({queryStatement: value,@@ -36,5 +43,7 @@ const handleChangeSelection = debounce((value: string) => {});}, 300);-const handleRunQuery = () => useExecuteSQL(store);+const handleRunQuery = () => {+ execute();+};</script>diff --git a/frontend/src/views/SqlEditor/QuerySelector.vue b/frontend/src/views/SqlEditor/QuerySelector.vueindex 8c2aeb5470..aaf5904be0 100644--- a/frontend/src/views/SqlEditor/QuerySelector.vue+++ b/frontend/src/views/SqlEditor/QuerySelector.vue@@ -1,11 +1,158 @@<template>- <div class="query-selector border-b">query selector</div>+ <div class="query-selector border-b">+ <div+ v-for="tab in queryTabList"+ :key="tab.id"+ class="query-selector--tab"+ :class="{ active: tab.id === activeTab.id }"+ @click="handleSelectTab(tab)"+ @mouseover="enterTabIdx = tab.idx"+ @mouseleave="enterTabIdx = -1"+ >+ <span class="prefix">+ <carbon:code class="h-4 w-4" />+ </span>+ <span class="label">+ {{ tab.label }}+ </span>+ <template v-if="enterTabIdx === tab.idx && queryTabList.length > 1">+ <span+ class="suffix close hover:bg-gray-200 rounded-sm"+ @click.prevent="handleRemoveTab(tab)"+ >+ <heroicons-solid:x class="icon" />+ </span>+ </template>+ <template v-else>+ <!-- <template v-if="!tab.isSaved">+ <span class="editing text-gray-400">+ <carbon:dot-mark class="h-4 w-4" />+ </span>+ </template> -->+ <template v-if="tab.id === activeTab.id && queryTabList.length > 1">+ <span+ class="suffix close hover:bg-gray-200 rounded-sm"+ @click.prevent="handleRemoveTab(tab)"+ >+ <heroicons-solid:x class="icon" />+ </span>+ </template>+ <template v-else>+ <span class="suffix" />+ </template>+ </template>+ </div>+ <button+ v-if="isDev()"+ class="query-selector--added"+ @click="handleAddTab({})"+ >+ <heroicons-solid:plus class="h-4 w-4 hover:bg-gray-200 rounded-sm" />+ </button>+ </div></template>-<script lang="ts" setup></script>+<script lang="ts" setup>+import { ref } from "vue";+import {+ useNamespacedState,+ useNamespacedActions,+} from "vuex-composition-helpers";+import { debouncedWatch } from "@vueuse/core";++import {+ EditorSelectorState,+ TabInfo,+ AnyTabInfo,+ EditorSelectorActions,+ SqlEditorState,+} from "../../types";+import { isDev } from "../../utils";++const { queryTabList, activeTab } = useNamespacedState<EditorSelectorState>(+ "editorSelector",+ ["queryTabList", "activeTab"]+);+const { addTab, setActiveTab, removeTab, updateTab } =+ useNamespacedActions<EditorSelectorActions>("editorSelector", [+ "addTab",+ "setActiveTab",+ "removeTab",+ "updateTab",+ ]);+const { queryStatement } = useNamespacedState<SqlEditorState>("sqlEditor", [+ "queryStatement",+]);++const enterTabIdx = ref(-1);++if (queryTabList.value.length === 0) {+ addTab({});+}++const handleSelectTab = (tab: TabInfo) => {+ setActiveTab(tab);+};+const handleAddTab = (tab: AnyTabInfo) => {+ addTab(tab);+};+const handleRemoveTab = (tab: TabInfo) => {+ removeTab(tab);+};++debouncedWatch(+ () => queryStatement.value,+ (newVal, oldVal) => {+ if (newVal !== oldVal && newVal !== "") {+ updateTab({+ ...activeTab.value,+ queries: newVal,+ isSaved: false,+ });+ }+ },+ {+ deep: true,+ debounce: 333,+ }+);+</script><style scoped>.query-selector {height: var(--tab-height);+ @apply flex box-border;+ @apply text-gray-500;+ @apply text-sm;+}++.query-selector--tab {+ @apply inline-flex place-items-center;+ @apply cursor-pointer box-border;+ @apply px-2 border-r;+ @apply bg-gray-50;+}++.query-selector--tab.active {+ @apply cursor-text relative;+ @apply bg-white;+ @apply text-accent;+}++.query-selector--tab .label {+ @apply p-2;+}+.query-selector--tab .suffix {+ @apply flex justify-center items-center h-4 w-4;+}++.query-selector--tab .suffix.close {+ @apply cursor-pointer;+ @apply text-gray-500;+}++.query-selector--added {+ @apply cursor-pointer;+ @apply p-2;}</style>diff --git a/frontend/src/views/SqlEditor/SqlEditor.vue b/frontend/src/views/SqlEditor/SqlEditor.vueindex 748955e734..091c66fb30 100644--- a/frontend/src/views/SqlEditor/SqlEditor.vue+++ b/frontend/src/views/SqlEditor/SqlEditor.vue@@ -7,9 +7,9 @@</Pane><Pane size="80"><template v-if="hasTabs">- <Splitpanes :key="randomKey" horizontal class="default-theme">+ <Splitpanes horizontal class="default-theme"><Pane size="60">- <EditorPanel />+ <EditorPanel :key="paneKey" /></Pane><Pane size="40"><TablePanel />@@ -25,14 +25,18 @@</template><script lang="ts" setup>+import { computed } from "vue";+import { useStore } from "vuex";import AsidePanel from "./AsidePanel/AsidePanel.vue";import EditorPanel from "./EditorPanel/EditorPanel.vue";import QuerySelector from "./QuerySelector.vue";import TablePanel from "./TablePanel/TablePanel.vue";import GettingStarted from "./GettingStarted.vue";-const hasTabs = true;-const randomKey = Math.random();+const store = useStore();++const hasTabs = computed(() => store.getters["editorSelector/hasTabs"]);+const paneKey = computed(() => store.getters["editorSelector/currentTab"].id);</script><style>@@ -67,7 +71,7 @@ const randomKey = Math.random();color: var(--base);--base: #444;--nav-height: 64px;- --tab-height: 48px;+ --tab-height: 36px;--font-code: "Source Code Pro", monospace;--color-branding: #4f46e5;--border-color: rgba(200, 200, 200, 0.2);diff --git a/frontend/src/views/SqlEditor/TablePanel/TablePanel.vue b/frontend/src/views/SqlEditor/TablePanel/TablePanel.vueindex 26f35b110f..dd9e3d797e 100644--- a/frontend/src/views/SqlEditor/TablePanel/TablePanel.vue+++ b/frontend/src/views/SqlEditor/TablePanel/TablePanel.vue@@ -3,7 +3,7 @@<Pane size="100"><TableView /></Pane>- <Pane size="0">+ <Pane v-if="isDev()" size="0"><HistroyView /></Pane></Splitpanes>@@ -12,4 +12,6 @@<script lang="ts" setup>import TableView from "./TableView.vue";import HistroyView from "./HistoryView.vue";++import { isDev } from "../../../utils";</script>diff --git a/frontend/src/views/SqlEditor/TablePanel/TableView.vue b/frontend/src/views/SqlEditor/TablePanel/TableView.vueindex 15fd68c6fe..ac1a002ea9 100644--- a/frontend/src/views/SqlEditor/TablePanel/TableView.vue+++ b/frontend/src/views/SqlEditor/TablePanel/TableView.vue@@ -1,6 +1,7 @@<template>- <div class="table-view h-full p-2" ref="tableViewRef">+ <div ref="tableViewRef" class="table-view h-full p-2"><NDataTable+ v-if="!isLoadingData"size="mini":columns="columns":data="data"@@ -10,10 +11,13 @@><template #empty><div class="p-20 h-full flex justify-center items-center">- Click Run to execute the query.+ {{ $t("sql-editor.table-empty-placehoder") }}</div></template></NDataTable>+ <div v-else class="flex justify-center items-center h-full">+ <BBSpin :title="$t('sql-editor.loading-data')" />+ </div></div></template>@@ -22,6 +26,9 @@ import { computed, ref } from "vue";import { useResizeObserver } from "@vueuse/core";import { useNamespacedState } from "vuex-composition-helpers";+import { useExecuteSQL } from "../../../composables/useExecuteSQL";++const { isLoadingData } = useExecuteSQL();const { queryResult } = useNamespacedState("sqlEditor", ["queryResult"]);const tableViewRef = ref<HTMLDivElement>();diff --git a/frontend/yarn.lock b/frontend/yarn.lockindex b42f53ac4b..170aa3f8c5 100644--- a/frontend/yarn.lock+++ b/frontend/yarn.lock@@ -1326,6 +1326,11 @@ date-fns@^2.27.0:resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-2.27.0.tgz#e1ff3c3ddbbab8a2eaadbb6106be2929a5a2d92b"integrity sha512-sj+J0Mo2p2X1e306MHq282WS4/A8Pz/95GIFcsPNMPMZVI3EUrAdSv90al1k+p74WGLCruMXk23bfEDZa71X9Q==+dayjs@^1.10.7:+ version "1.10.7"+ resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.10.7.tgz#2cf5f91add28116748440866a0a1d26f3a6ce468"+ integrity sha512-P6twpd70BcPK34K26uJ1KT3wlhpuOAPoMwJzpsIWUxHZ7wpmbdZL/hQqBDfz7hGurYSa5PhzdhDHtt319hL3ig==+debug@^4.1.1, debug@^4.3.1, debug@^4.3.2:version "4.3.3"resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.3.tgz#04266e0b70a98d4462e6e288e38259213332b664"