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 first version (#273)
Yunwei Xiao6e55b0ec5d73
diff --git a/frontend/components.d.ts b/frontend/components.d.tsnew file mode 100644index 0000000000..83fb3f1cb5--- /dev/null+++ b/frontend/components.d.ts@@ -0,0 +1,191 @@+// generated by vite-plugin-components+// read more https://github.com/vuejs/vue-next/pull/3399++declare module 'vue' {+ export interface GlobalComponents {+ ActivityCommentLink: typeof import('./src/components/ActivityTable/ActivityCommentLink.vue')['default']+ ActivityTable: typeof import('./src/components/ActivityTable.vue')['default']+ ActivityTypeLink: typeof import('./src/components/ActivityTable/ActivityTypeLink.vue')['default']+ AlterSchemaPrepForm: typeof import('./src/components/AlterSchemaPrepForm.vue')['default']+ AnomalyTable: typeof import('./src/components/AnomalyTable.vue')['default']+ ArchiveBanner: typeof import('./src/components/ArchiveBanner.vue')['default']+ BackupTable: typeof import('./src/components/BackupTable.vue')['default']+ BBAlert: typeof import('./src/bbkit/BBAlert.vue')['default']+ BBAttention: typeof import('./src/bbkit/BBAttention.vue')['default']+ BBAvatar: typeof import('./src/bbkit/BBAvatar.vue')['default']+ BBButtonAdd: typeof import('./src/bbkit/BBButtonAdd.vue')['default']+ BBButtonConfirm: typeof import('./src/bbkit/BBButtonConfirm.vue')['default']+ BBCheckbox: typeof import('./src/bbkit/BBCheckbox.vue')['default']+ BBContextMenu: typeof import('./src/bbkit/BBContextMenu.vue')['default']+ BBModal: typeof import('./src/bbkit/BBModal.vue')['default']+ BBModalStack: typeof import('./src/bbkit/BBModalStack.vue')['default']+ BBNotification: typeof import('./src/bbkit/BBNotification.vue')['default']+ BBOutline: typeof import('./src/bbkit/BBOutline.vue')['default']+ BBSelect: typeof import('./src/bbkit/BBSelect.vue')['default']+ BBSpin: typeof import('./src/bbkit/BBSpin.vue')['default']+ BBStepBar: typeof import('./src/bbkit/BBStepBar.vue')['default']+ BBStepTab: typeof import('./src/bbkit/BBStepTab.vue')['default']+ BBSwitch: typeof import('./src/bbkit/BBSwitch.vue')['default']+ BBTab: typeof import('./src/bbkit/BBTab.vue')['default']+ BBTabFilter: typeof import('./src/bbkit/BBTabFilter.vue')['default']+ BBTable: typeof import('./src/bbkit/BBTable/BBTable.vue')['default']+ BBTableCell: typeof import('./src/bbkit/BBTable/BBTableCell.vue')['default']+ BBTableHeaderCell: typeof import('./src/bbkit/BBTable/BBTableHeaderCell.vue')['default']+ BBTableSearch: typeof import('./src/bbkit/BBTable/BBTableSearch.vue')['default']+ BBTabPanel: typeof import('./src/bbkit/BBTabPanel.vue')['default']+ BBTextField: typeof import('./src/bbkit/BBTextField.vue')['default']+ BookmarkListSidePanel: typeof import('./src/components/BookmarkListSidePanel.vue')['default']+ Breadcrumb: typeof import('./src/components/Breadcrumb.vue')['default']+ 'Carbon:save': typeof import('virtual:vite-icons/carbon/save')['default']+ 'Carbon:share': typeof import('virtual:vite-icons/carbon/share')['default']+ ColumnTable: typeof import('./src/components/ColumnTable.vue')['default']+ CreateDatabasePrepForm: typeof import('./src/components/CreateDatabasePrepForm.vue')['default']+ DatabaseBackupCreateForm: typeof import('./src/components/DatabaseBackupCreateForm.vue')['default']+ DatabaseBackupPanel: typeof import('./src/components/DatabaseBackupPanel.vue')['default']+ DatabaseListSidePanel: typeof import('./src/components/DatabaseListSidePanel.vue')['default']+ DatabaseMigrationHistoryPanel: typeof import('./src/components/DatabaseMigrationHistoryPanel.vue')['default']+ DatabaseOverviewPanel: typeof import('./src/components/DatabaseOverviewPanel.vue')['default']+ DatabaseSelect: typeof import('./src/components/DatabaseSelect.vue')['default']+ DatabaseTable: typeof import('./src/components/DatabaseTable.vue')['default']+ DataSourceConnectionPanel: typeof import('./src/components/DataSourceConnectionPanel.vue')['default']+ DataSourceCreateForm: typeof import('./src/components/DataSourceCreateForm.vue')['default']+ DataSourceMemberForm: typeof import('./src/components/DataSourceMemberForm.vue')['default']+ DataSourceMemberTable: typeof import('./src/components/DataSourceMemberTable.vue')['default']+ DataSourceSelect: typeof import('./src/components/DataSourceSelect.vue')['default']+ DataSourceTable: typeof import('./src/components/DataSourceTable.vue')['default']+ EnvironmentForm: typeof import('./src/components/EnvironmentForm.vue')['default']+ EnvironmentSelect: typeof import('./src/components/EnvironmentSelect.vue')['default']+ EnvironmentTabFilter: typeof import('./src/components/EnvironmentTabFilter.vue')['default']+ EnvironmentTable: typeof import('./src/components/EnvironmentTable.vue')['default']+ 'HeroiconsOutline:archive': typeof import('virtual:vite-icons/heroicons-outline/archive')['default']+ 'HeroiconsOutline:bell': typeof import('virtual:vite-icons/heroicons-outline/bell')['default']+ 'HeroiconsOutline:check': typeof import('virtual:vite-icons/heroicons-outline/check')['default']+ 'HeroiconsOutline:checkCircle': typeof import('virtual:vite-icons/heroicons-outline/check-circle')['default']+ 'HeroiconsOutline:chevronDoubleDown': typeof import('virtual:vite-icons/heroicons-outline/chevron-double-down')['default']+ 'HeroiconsOutline:clipboard': typeof import('virtual:vite-icons/heroicons-outline/clipboard')['default']+ 'HeroiconsOutline:collection': typeof import('virtual:vite-icons/heroicons-outline/collection')['default']+ 'HeroiconsOutline:cube': typeof import('virtual:vite-icons/heroicons-outline/cube')['default']+ 'HeroiconsOutline:database': typeof import('virtual:vite-icons/heroicons-outline/database')['default']+ 'HeroiconsOutline:duplicate': typeof import('virtual:vite-icons/heroicons-outline/duplicate')['default']+ 'HeroiconsOutline:exclamation': typeof import('virtual:vite-icons/heroicons-outline/exclamation')['default']+ 'HeroiconsOutline:exclamationCircle': typeof import('virtual:vite-icons/heroicons-outline/exclamation-circle')['default']+ 'HeroiconsOutline:externalLink': typeof import('virtual:vite-icons/heroicons-outline/external-link')['default']+ 'HeroiconsOutline:eye': typeof import('virtual:vite-icons/heroicons-outline/eye')['default']+ 'HeroiconsOutline:eyeOff': typeof import('virtual:vite-icons/heroicons-outline/eye-off')['default']+ 'HeroiconsOutline:hand': typeof import('virtual:vite-icons/heroicons-outline/hand')['default']+ 'HeroiconsOutline:home': typeof import('virtual:vite-icons/heroicons-outline/home')['default']+ 'HeroiconsOutline:informationCircle': typeof import('virtual:vite-icons/heroicons-outline/information-circle')['default']+ 'HeroiconsOutline:lightningBolt': typeof import('virtual:vite-icons/heroicons-outline/lightning-bolt')['default']+ 'HeroiconsOutline:menu': typeof import('virtual:vite-icons/heroicons-outline/menu')['default']+ 'HeroiconsOutline:minusCircle': typeof import('virtual:vite-icons/heroicons-outline/minus-circle')['default']+ 'HeroiconsOutline:pencil': typeof import('virtual:vite-icons/heroicons-outline/pencil')['default']+ 'HeroiconsOutline:pencilAlt': typeof import('virtual:vite-icons/heroicons-outline/pencil-alt')['default']+ 'HeroiconsOutline:plusSm': typeof import('virtual:vite-icons/heroicons-outline/plus-sm')['default']+ 'HeroiconsOutline:questionMarkCircle': typeof import('virtual:vite-icons/heroicons-outline/question-mark-circle')['default']+ 'HeroiconsOutline:reply': typeof import('virtual:vite-icons/heroicons-outline/reply')['default']+ 'HeroiconsOutline:search': typeof import('virtual:vite-icons/heroicons-outline/search')['default']+ 'HeroiconsOutline:selector': typeof import('virtual:vite-icons/heroicons-outline/selector')['default']+ 'HeroiconsOutline:shieldExclamation': typeof import('virtual:vite-icons/heroicons-outline/shield-exclamation')['default']+ 'HeroiconsOutline:switchHorizontal': typeof import('virtual:vite-icons/heroicons-outline/switch-horizontal')['default']+ 'HeroiconsOutline:template': typeof import('virtual:vite-icons/heroicons-outline/template')['default']+ 'HeroiconsOutline:translate': typeof import('virtual:vite-icons/heroicons-outline/translate')['default']+ 'HeroiconsOutline:trash': typeof import('virtual:vite-icons/heroicons-outline/trash')['default']+ 'HeroiconsOutline:user': typeof import('virtual:vite-icons/heroicons-outline/user')['default']+ 'HeroiconsOutline:users': typeof import('virtual:vite-icons/heroicons-outline/users')['default']+ 'HeroiconsOutline:x': typeof import('virtual:vite-icons/heroicons-outline/x')['default']+ 'HeroiconsSolid:check': typeof import('virtual:vite-icons/heroicons-solid/check')['default']+ 'HeroiconsSolid:checkCircle': typeof import('virtual:vite-icons/heroicons-solid/check-circle')['default']+ 'HeroiconsSolid:chevronRight': typeof import('virtual:vite-icons/heroicons-solid/chevron-right')['default']+ 'HeroiconsSolid:dotsVertical': typeof import('virtual:vite-icons/heroicons-solid/dots-vertical')['default']+ 'HeroiconsSolid:home': typeof import('virtual:vite-icons/heroicons-solid/home')['default']+ 'HeroiconsSolid:informationCircle': typeof import('virtual:vite-icons/heroicons-solid/information-circle')['default']+ 'HeroiconsSolid:minus': typeof import('virtual:vite-icons/heroicons-solid/minus')['default']+ 'HeroiconsSolid:pencil': typeof import('virtual:vite-icons/heroicons-solid/pencil')['default']+ 'HeroiconsSolid:plus': typeof import('virtual:vite-icons/heroicons-solid/plus')['default']+ 'HeroiconsSolid:save': typeof import('virtual:vite-icons/heroicons-solid/save')['default']+ 'HeroiconsSolid:search': typeof import('virtual:vite-icons/heroicons-solid/search')['default']+ 'HeroiconsSolid:selector': typeof import('virtual:vite-icons/heroicons-solid/selector')['default']+ 'HeroiconsSolid:star': typeof import('virtual:vite-icons/heroicons-solid/star')['default']+ 'HeroiconsSolid:x': typeof import('virtual:vite-icons/heroicons-solid/x')['default']+ InboxList: typeof import('./src/components/InboxList.vue')['default']+ IndexTable: typeof import('./src/components/IndexTable.vue')['default']+ InstanceEngineIcon: typeof import('./src/components/InstanceEngineIcon.vue')['default']+ InstanceForm: typeof import('./src/components/InstanceForm.vue')['default']+ InstanceSelect: typeof import('./src/components/InstanceSelect.vue')['default']+ InstanceTable: typeof import('./src/components/InstanceTable.vue')['default']+ InstanceUserTable: typeof import('./src/components/InstanceUserTable.vue')['default']+ IntroBanner: typeof import('./src/components/IntroBanner.vue')['default']+ IssueActivityPanel: typeof import('./src/components/IssueActivityPanel.vue')['default']+ IssueDescriptionPanel: typeof import('./src/components/IssueDescriptionPanel.vue')['default']+ IssueHighlightPanel: typeof import('./src/components/IssueHighlightPanel.vue')['default']+ IssueOutputPanel: typeof import('./src/components/IssueOutputPanel.vue')['default']+ IssueSidebar: typeof import('./src/components/IssueSidebar.vue')['default']+ IssueStagePanel: typeof import('./src/components/IssueStagePanel.vue')['default']+ IssueStatusIcon: typeof import('./src/components/IssueStatusIcon.vue')['default']+ IssueStatusSelect: typeof import('./src/components/IssueStatusSelect.vue')['default']+ IssueStatusTransitionButtonGroup: typeof import('./src/components/IssueStatusTransitionButtonGroup.vue')['default']+ IssueSubscriberPanel: typeof import('./src/components/IssueSubscriberPanel.vue')['default']+ IssueTable: typeof import('./src/components/IssueTable.vue')['default']+ IssueTaskStatementPanel: typeof import('./src/components/IssueTaskStatementPanel.vue')['default']+ KBarFooter: typeof import('./src/components/KBar/KBarFooter.vue')['default']+ KBarHelper: typeof import('./src/components/KBar/KBarHelper.vue')['default']+ KBarWrapper: typeof import('./src/components/KBar/KBarWrapper.vue')['default']+ 'Mdi:play': typeof import('virtual:vite-icons/mdi/play')['default']+ MemberAddOrInvite: typeof import('./src/components/MemberAddOrInvite.vue')['default']+ MemberSelect: typeof import('./src/components/MemberSelect.vue')['default']+ MemberTable: typeof import('./src/components/MemberTable.vue')['default']+ MigrationHistoryStatusIcon: typeof import('./src/components/MigrationHistoryStatusIcon.vue')['default']+ MigrationHistoryTable: typeof import('./src/components/MigrationHistoryTable.vue')['default']+ MonacoEditor: typeof import('./src/components/MonacoEditor/MonacoEditor.vue')['default']+ PricingTable: typeof import('./src/components/PricingTable.vue')['default']+ PrincipalAvatar: typeof import('./src/components/PrincipalAvatar.vue')['default']+ ProfileDropdown: typeof import('./src/components/ProfileDropdown.vue')['default']+ ProjectActivityPanel: typeof import('./src/components/ProjectActivityPanel.vue')['default']+ ProjectCreate: typeof import('./src/components/ProjectCreate.vue')['default']+ ProjectGeneralSettingPanel: typeof import('./src/components/ProjectGeneralSettingPanel.vue')['default']+ ProjectListSidePanel: typeof import('./src/components/ProjectListSidePanel.vue')['default']+ ProjectMemberPanel: typeof import('./src/components/ProjectMemberPanel.vue')['default']+ ProjectMemberTable: typeof import('./src/components/ProjectMemberTable.vue')['default']+ ProjectMigrationHistoryPanel: typeof import('./src/components/ProjectMigrationHistoryPanel.vue')['default']+ ProjectOverviewPanel: typeof import('./src/components/ProjectOverviewPanel.vue')['default']+ ProjectRoleSelect: typeof import('./src/components/ProjectRoleSelect.vue')['default']+ ProjectSelect: typeof import('./src/components/ProjectSelect.vue')['default']+ ProjectSettingPanel: typeof import('./src/components/ProjectSettingPanel.vue')['default']+ ProjectTable: typeof import('./src/components/ProjectTable.vue')['default']+ ProjectVersionControlPanel: typeof import('./src/components/ProjectVersionControlPanel.vue')['default']+ ProjectWebhookCard: typeof import('./src/components/ProjectWebhookCard.vue')['default']+ ProjectWebhookForm: typeof import('./src/components/ProjectWebhookForm.vue')['default']+ ProjectWebhookPanel: typeof import('./src/components/ProjectWebhookPanel.vue')['default']+ ProvideDashboardContext: typeof import('./src/components/ProvideDashboardContext.vue')['default']+ ProvideInstanceContext: typeof import('./src/components/ProvideInstanceContext.vue')['default']+ ProvideSqlEditorContext: typeof import('./src/components/ProvideSqlEditorContext.vue')['default']+ QuickActionPanel: typeof import('./src/components/QuickActionPanel.vue')['default']+ Quickstart: typeof import('./src/components/Quickstart.vue')['default']+ RenderResults: typeof import('./src/components/KBar/RenderResults.vue')['default']+ RepositoryConfigPanel: typeof import('./src/components/RepositoryConfigPanel.vue')['default']+ RepositoryForm: typeof import('./src/components/RepositoryForm.vue')['default']+ RepositoryPanel: typeof import('./src/components/RepositoryPanel.vue')['default']+ RepositorySelectionPanel: typeof import('./src/components/RepositorySelectionPanel.vue')['default']+ RepositorySetupWizard: typeof import('./src/components/RepositorySetupWizard.vue')['default']+ RepositoryTable: typeof import('./src/components/RepositoryTable.vue')['default']+ RepositoryVCSProviderPanel: typeof import('./src/components/RepositoryVCSProviderPanel.vue')['default']+ RequestDatabasePrepForm: typeof import('./src/components/RequestDatabasePrepForm.vue')['default']+ RoleSelect: typeof import('./src/components/RoleSelect.vue')['default']+ StageSelect: typeof import('./src/components/StageSelect.vue')['default']+ StatusTransitionForm: typeof import('./src/components/StatusTransitionForm.vue')['default']+ TableTable: typeof import('./src/components/TableTable.vue')['default']+ TaskCheckBadgeBar: typeof import('./src/components/TaskCheckBadgeBar.vue')['default']+ TaskCheckBar: typeof import('./src/components/TaskCheckBar.vue')['default']+ TaskCheckRunPanel: typeof import('./src/components/TaskCheckRunPanel.vue')['default']+ TaskRunTable: typeof import('./src/components/TaskRunTable.vue')['default']+ TransferDatabaseForm: typeof import('./src/components/TransferDatabaseForm.vue')['default']+ VCSCard: typeof import('./src/components/VCSCard.vue')['default']+ VCSProviderBasicInfoPanel: typeof import('./src/components/VCSProviderBasicInfoPanel.vue')['default']+ VCSProviderConfirmPanel: typeof import('./src/components/VCSProviderConfirmPanel.vue')['default']+ VCSProviderOAuthPanel: typeof import('./src/components/VCSProviderOAuthPanel.vue')['default']+ VCSSetupWizard: typeof import('./src/components/VCSSetupWizard.vue')['default']+ ViewTable: typeof import('./src/components/ViewTable.vue')['default']+ }+}++export { }diff --git a/frontend/package.json b/frontend/package.jsonindex f1d224a3fb..c812b581b6 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -22,16 +22,19 @@"inter-ui": "^3.15.0","lodash-es": "^4.17.21","moment": "^2.29.1",+ "monaco-editor": "^0.31.1","naive-ui": "^2.23.1","postcss": "^8.3.5","slug": "^4.0.2",+ "splitpanes": "^3.0.6","tailwindcss": "^2.2.2","uuid": "^8.3.2","v-code-diff": "^0.3.4","vue": "^3.2.13","vue-i18n": "^9.2.0-beta.20","vue-router": "^4.0.8",- "vuex": "^4.0.0"+ "vuex": "^4.0.0",+ "vuex-composition-helpers": "^2.0.1"},"devDependencies": {"@iconify/json": "^1.1.432",@@ -39,6 +42,7 @@"@types/lodash-es": "^4.17.4","@types/node": "^16.11.9","@types/slug": "^0.9.1",+ "@types/splitpanes": "^2.2.1","@types/uuid": "^8.3.0","@typescript-eslint/eslint-plugin": "^5.4.0","@typescript-eslint/parser": "^5.4.0",diff --git a/frontend/src/App.vue b/frontend/src/App.vueindex 347ceb71e8..877b0a7262 100644--- a/frontend/src/App.vue+++ b/frontend/src/App.vue@@ -1,6 +1,6 @@<template><!-- it is recommended by naive-ui that we leave the local to null when the language is en -->- <n-config-provider+ <NConfigProvider:locale="generalLang":date-locale="dateLang":theme-overrides="themeOverrides"@@ -17,18 +17,20 @@</template></KBarWrapper></BBModalStack>- </n-config-provider>+ </NConfigProvider></template><script lang="ts">import { reactive, watchEffect, onErrorCaptured } from "vue";import { useStore } from "vuex";import { useRouter } from "vue-router";+import { isDev } from "./utils";import { Notification } from "./types";import { BBNotificationItem } from "./bbkit/types";import KBarWrapper from "./components/KBar/KBarWrapper.vue";import BBModalStack from "./bbkit/BBModalStack.vue";+import { NConfigProvider } from "naive-ui";import { themeOverrides, dateLang, generalLang } from "../naive-ui.config";// Show at most 3 notifications to prevent excessive notification when shit hits the fan.diff --git a/frontend/src/bbkit/BBContextMenu.vue b/frontend/src/bbkit/BBContextMenu.vueindex fffba239e2..495c419f86 100644--- a/frontend/src/bbkit/BBContextMenu.vue+++ b/frontend/src/bbkit/BBContextMenu.vue@@ -47,10 +47,12 @@</div></template>-<script>+<script lang="ts">+import { defineComponent } from "vue";+import clickInsideOutside from "./directives/click-inside-outside";-export default {+export default defineComponent({name: "BBContextMenu",directives: {"click-inside-outside": clickInsideOutside,@@ -58,11 +60,11 @@ export default {data: function () {return {isOpen: false,- context: {},+ context: {} as any,};},methods: {- open(evt, context) {+ open(evt: any, context: any) {// This is a hack, upon intial click to bring up the context menu, it will// trigger both open and close. The latter is triggered because the click// is outside of the menu which hasn't brought up yet. So here, we use@@ -77,13 +79,13 @@ export default {this.isOpen = false;this.context = null;},- toggle(evt, context) {+ toggle(evt: any, context: any) {if (!this.isOpen) {this.open(evt, context);} else {- this.close(evt, false);+ this.close();}},},-};+});</script>diff --git a/frontend/src/components/MonacoEditor/AutoCompletion.ts b/frontend/src/components/MonacoEditor/AutoCompletion.tsnew file mode 100644index 0000000000..c82106ee41--- /dev/null+++ b/frontend/src/components/MonacoEditor/AutoCompletion.ts@@ -0,0 +1,156 @@+import * as monaco from "monaco-editor";++import {+ Instance,+ Database,+ Table,+ EditorModel,+ EditorPosition,+ SortText,+ CompletionItems,+} from "../../types";+import { keywords } from "./keywords";++export default class AutoCompletion {+ model: EditorModel;+ position: EditorPosition;+ instances: Instance[];+ databases: Database[];+ tables: Table[];++ constructor(+ model: EditorModel,+ position: EditorPosition,+ instances: Instance[],+ databases: Database[],+ tables: Table[]+ ) {+ this.model = model;+ this.position = position;+ this.instances = instances;+ this.databases = databases;+ this.tables = tables;+ }++ getWordRange() {+ const position = this.position;+ const word = this.model.getWordUntilPosition(position);+ const range = {+ startLineNumber: position.lineNumber,+ endLineNumber: position.lineNumber,+ startColumn: word.startColumn,+ endColumn: word.endColumn,+ };+ return range;+ }++ getCompletionItemsForKeywords() {+ const suggestions: CompletionItems = [];++ const range = this.getWordRange();++ keywords.forEach((keyword) => {+ suggestions.push({+ label: keyword,+ kind: monaco.languages.CompletionItemKind.Keyword,+ detail: "<Keyword>",+ documentation: keyword,+ sortText: SortText.KEYWORD,+ insertText: keyword,+ range,+ });+ });++ return suggestions;+ }++ getCompletionItemsForInstances(): CompletionItems {+ const suggestions: CompletionItems = [];++ const range = this.getWordRange();++ this.instances.forEach((instance) => {+ suggestions.push({+ label: instance.name,+ kind: monaco.languages.CompletionItemKind.Method,+ detail: "<Instance>",+ documentation: instance.name,+ sortText: SortText.INSTASNCE,+ insertText: instance.name,+ range,+ });+ });++ return suggestions;+ }++ getCompletionItemsForDatabases(): CompletionItems {+ const suggestions: CompletionItems = [];++ const range = this.getWordRange();++ this.databases.forEach((database) => {+ suggestions.push({+ label: database.name,+ kind: monaco.languages.CompletionItemKind.Struct,+ detail: "<Database>",+ documentation: database.name,+ sortText: SortText.DATABASE,+ insertText: database.name,+ range,+ });+ });++ return suggestions;+ }++ getCompletionItemsForTables(): CompletionItems {+ let suggestions: CompletionItems = [];++ const range = this.getWordRange();++ this.tables.forEach((table) => {+ suggestions.push({+ label: table.name,+ kind: monaco.languages.CompletionItemKind.Function,+ detail: "<Table>",+ documentation: table.name,+ sortText: SortText.TABLE,+ insertText: table.name,+ range,+ });+ const tableColumnSuggestions =+ this.getCompletionItemsForTableColumns(table);+ suggestions = suggestions.concat(tableColumnSuggestions);+ });++ return suggestions;+ }++ getCompletionItemsForTableColumns(+ table: Table,+ withTablePrefix: boolean = true+ ): CompletionItems {+ const suggestions: CompletionItems = [];++ const range = this.getWordRange();++ table.columnList.forEach((column) => {+ const label = withTablePrefix+ ? `${table.name}.${column.name}`+ : column.name;++ suggestions.push({+ label,+ kind: monaco.languages.CompletionItemKind.Field,+ detail: "<Field>",+ documentation: label,+ sortText: SortText.COLUMN,+ insertText: label,+ range,+ });+ });++ return suggestions;+ }+}diff --git a/frontend/src/components/MonacoEditor/MonacoEditor.vue b/frontend/src/components/MonacoEditor/MonacoEditor.vuenew file mode 100644index 0000000000..b7e63bd296--- /dev/null+++ b/frontend/src/components/MonacoEditor/MonacoEditor.vue@@ -0,0 +1,98 @@+<template>+ <div ref="editorRef" style="height: 100%; width: 100%"></div>+</template>++<script lang="ts" setup>+import { onMounted, ref, toRef, toRaw } from "vue";+import setupMonaco from "./setupMonaco";++const props = defineProps({+ modelValue: { type: String, default: "" },+ language: { type: String, default: "mysql" },+});++const emit = defineEmits<{+ (e: "update:modelValue", 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 language = toRef(props, "language");++// let editorInstance: Editor.IStandaloneCodeEditor++// const setContent = (content: string) => {+// if (editorInstance) editorInstance.setValue(content)+// }++// const formatContent = () => {+// if (editorInstance) editorInstance.getAction('editor.action.formatDocument').run()+// }++const init = async () => {+ const { monaco } = await setupMonaco(language.value);++ const model = monaco.editor.createModel(sqlCode.value, toRaw(language.value));++ const editorInstance = monaco.editor.create(editorRef.value, {+ model,+ tabSize: 2,+ insertSpaces: true,+ autoClosingQuotes: "always",+ detectIndentation: false,+ folding: false,+ automaticLayout: true,+ theme: "vs-light",+ minimap: {+ enabled: false,+ },+ wordWrap: "on",+ fixedOverflowWidgets: true,+ });++ // add the run query action in context menu+ editorInstance.addAction({+ id: "Bytebase",+ label: "Run Query",+ keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],+ contextMenuGroupId: "operation",+ contextMenuOrder: 0,+ run: async () => {+ console.log("run query");++ const typedValue = editorInstance.getValue();+ const selectedValue = editorInstance+ .getModel()+ // @ts-expect-error+ ?.getValueInRange(editorInstance.getSelection()) as string;++ const queryStatement = selectedValue || typedValue;++ emit("run-query", queryStatement);+ },+ });++ // typed something, change the text+ editorInstance.onDidChangeModelContent(() => {+ const value = editorInstance.getValue();+ emit("update:modelValue", value);+ emit("change", value);+ });++ // when editor change selection, emit change-selection event with selected text+ editorInstance.onDidChangeCursorSelection((e) => {+ const selectedText = editorInstance.getModel()?.getValueInRange({+ startLineNumber: e.selection.startLineNumber,+ startColumn: e.selection.startColumn,+ endLineNumber: e.selection.endLineNumber,+ endColumn: e.selection.endColumn,+ }) as string;+ emit("change-selection", selectedText);+ });+};++onMounted(init);+</script>diff --git a/frontend/src/components/MonacoEditor/keywords.ts b/frontend/src/components/MonacoEditor/keywords.tsnew file mode 100644index 0000000000..a3af9b9909--- /dev/null+++ b/frontend/src/components/MonacoEditor/keywords.ts@@ -0,0 +1,1075 @@+const keyword = [+ "ACCESSIBLE",+ "ACCOUNT",+ "ACTION",+ "ADD",+ "AFTER",+ "AGAINST",+ "AGGREGATE",+ "ALGORITHM",+ "ALL",+ "ALTER",+ "ALWAYS",+ "ANALYSE",+ "ANALYZE",+ "AND",+ "ANY",+ "AS",+ "ASC",+ "ASCII",+ "ASENSITIVE",+ "AT",+ "AUTOEXTEND_SIZE",+ "AUTO_INCREMENT",+ "AVG",+ "AVG_ROW_LENGTH",+ "BACKUP",+ "BEFORE",+ "BEGIN",+ "BETWEEN",+ "BIGINT",+ "BINARY",+ "BINLOG",+ "BIT",+ "BLOB",+ "BLOCK",+ "BOOL",+ "BOOLEAN",+ "BOTH",+ "BTREE",+ "BY",+ "BYTE",+ "CACHE",+ "CALL",+ "CASCADE",+ "CASCADED",+ "CASE",+ "CATALOG_NAME",+ "CHAIN",+ "CHANGE",+ "CHANGED",+ "CHANNEL",+ "CHAR",+ "CHARACTER",+ "CHARSET",+ "CHECK",+ "CHECKSUM",+ "CIPHER",+ "CLASS_ORIGIN",+ "CLIENT",+ "CLOSE",+ "COALESCE",+ "CODE",+ "COLLATE",+ "COLLATION",+ "COLUMN",+ "COLUMNS",+ "COLUMN_FORMAT",+ "COLUMN_NAME",+ "COMMENT",+ "COMMIT",+ "COMMITTED",+ "COMPACT",+ "COMPLETION",+ "COMPRESSED",+ "COMPRESSION",+ "CONCURRENT",+ "CONDITION",+ "CONNECTION",+ "CONSISTENT",+ "CONSTRAINT",+ "CONSTRAINT_CATALOG",+ "CONSTRAINT_NAME",+ "CONSTRAINT_SCHEMA",+ "CONTAINS",+ "CONTEXT",+ "CONTINUE",+ "CONVERT",+ "CPU",+ "CREATE",+ "CROSS",+ "CUBE",+ "CURRENT",+ "CURRENT_DATE",+ "CURRENT_TIME",+ "CURRENT_TIMESTAMP",+ "CURRENT_USER",+ "CURSOR",+ "CURSOR_NAME",+ "DATA",+ "DATABASE",+ "DATABASES",+ "DATAFILE",+ "DATE",+ "DATETIME",+ "DAY",+ "DAY_HOUR",+ "DAY_MICROSECOND",+ "DAY_MINUTE",+ "DAY_SECOND",+ "DEALLOCATE",+ "DEC",+ "DECIMAL",+ "DECLARE",+ "DEFAULT",+ "DEFAULT_AUTH",+ "DEFINER",+ "DELAYED",+ "DELAY_KEY_WRITE",+ "DELETE",+ "DESC",+ "DESCRIBE",+ "DES_KEY_FILE",+ "DETERMINISTIC",+ "DIAGNOSTICS",+ "DIRECTORY",+ "DISABLE",+ "DISCARD",+ "DISK",+ "DISTINCT",+ "DISTINCTROW",+ "DIV",+ "DO",+ "DOUBLE",+ "DROP",+ "DUAL",+ "DUMPFILE",+ "DUPLICATE",+ "DYNAMIC",+ "EACH",+ "ELSE",+ "ELSEIF",+ "ENABLE",+ "ENCLOSED",+ "ENCRYPTION",+ "END",+ "ENDS",+ "ENGINE",+ "ENGINES",+ "ENUM",+ "ERROR",+ "ERRORS",+ "ESCAPE",+ "ESCAPED",+ "EVENT",+ "EVENTS",+ "EVERY",+ "EXCHANGE",+ "EXECUTE",+ "EXISTS",+ "EXIT",+ "EXPANSION",+ "EXPIRE",+ "EXPLAIN",+ "EXPORT",+ "EXTENDED",+ "EXTENT_SIZE",+ "FALSE",+ "FAST",+ "FAULTS",+ "FETCH",+ "FIELDS",+ "FILE",+ "FILE_BLOCK_SIZE",+ "FILTER",+ "FIRST",+ "FIXED",+ "FLOAT",+ "FLOAT4",+ "FLOAT8",+ "FLUSH",+ "FOLLOWS",+ "FOR",+ "FORCE",+ "FOREIGN",+ "FORMAT",+ "FOUND",+ "FROM",+ "FULL",+ "FULLTEXT",+ "FUNCTION",+ "GENERAL",+ "GENERATED",+ "GEOMETRY",+ "GEOMETRYCOLLECTION",+ "GET",+ "GET_FORMAT",+ "GLOBAL",+ "GRANT",+ "GRANTS",+ "GROUP",+ "GROUP_REPLICATION",+ "HANDLER",+ "HASH",+ "HAVING",+ "HELP",+ "HIGH_PRIORITY",+ "HOST",+ "HOSTS",+ "HOUR",+ "HOUR_MICROSECOND",+ "HOUR_MINUTE",+ "HOUR_SECOND",+ "IDENTIFIED",+ "IF",+ "IGNORE",+ "IGNORE_SERVER_IDS",+ "IMPORT",+ "INDEX",+ "INDEXES",+ "INFILE",+ "INITIAL_SIZE",+ "INNER",+ "INOUT",+ "INSENSITIVE",+ "INSERT",+ "INSERT_METHOD",+ "INSTALL",+ "INSTANCE",+ "INT",+ "INT1",+ "INT2",+ "INT3",+ "INT4",+ "INT8",+ "INTEGER",+ "INTERVAL",+ "INTO",+ "INVOKER",+ "IO",+ "IO_AFTER_GTIDS",+ "IO_BEFORE_GTIDS",+ "IO_THREAD",+ "IPC",+ "ISOLATION",+ "ISSUER",+ "ITERATE",+ "JOIN",+ "JSON",+ "KEY",+ "KEYS",+ "KEY_BLOCK_SIZE",+ "KILL",+ "LANGUAGE",+ "LAST",+ "LEADING",+ "LEAVE",+ "LEAVES",+ "LEFT",+ "LESS",+ "LEVEL",+ "LIKE",+ "LIMIT",+ "LINEAR",+ "LINES",+ "LINESTRING",+ "LIST",+ "LOAD",+ "LOCAL",+ "LOCALTIME",+ "LOCALTIMESTAMP",+ "LOCK",+ "LOCKS",+ "LOGFILE",+ "LOGS",+ "LONG",+ "LONGBLOB",+ "LONGTEXT",+ "LOOP",+ "LOW_PRIORITY",+ "MASTER",+ "MASTER_AUTO_POSITION",+ "MASTER_BIND",+ "MASTER_CONNECT_RETRY",+ "MASTER_DELAY",+ "MASTER_HEARTBEAT_PERIOD",+ "MASTER_HOST",+ "MASTER_LOG_FILE",+ "MASTER_LOG_POS",+ "MASTER_PASSWORD",+ "MASTER_PORT",+ "MASTER_RETRY_COUNT",+ "MASTER_SERVER_ID",+ "MASTER_SSL",+ "MASTER_SSL_CA",+ "MASTER_SSL_CAPATH",+ "MASTER_SSL_CERT",+ "MASTER_SSL_CIPHER",+ "MASTER_SSL_CRL",+ "MASTER_SSL_CRLPATH",+ "MASTER_SSL_KEY",+ "MASTER_SSL_VERIFY_SERVER_CERT",+ "MASTER_TLS_VERSION",+ "MASTER_USER",+ "MATCH",+ "MAXVALUE",+ "MAX_CONNECTIONS_PER_HOUR",+ "MAX_QUERIES_PER_HOUR",+ "MAX_ROWS",+ "MAX_SIZE",+ "MAX_STATEMENT_TIME",+ "MAX_UPDATES_PER_HOUR",+ "MAX_USER_CONNECTIONS",+ "MEDIUM",+ "MEDIUMBLOB",+ "MEDIUMINT",+ "MEDIUMTEXT",+ "MEMORY",+ "MERGE",+ "MESSAGE_TEXT",+ "MICROSECOND",+ "MIDDLEINT",+ "MIGRATE",+ "MINUTE",+ "MINUTE_MICROSECOND",+ "MINUTE_SECOND",+ "MIN_ROWS",+ "MOD",+ "MODE",+ "MODIFIES",+ "MODIFY",+ "MONTH",+ "MULTILINESTRING",+ "MULTIPOINT",+ "MULTIPOLYGON",+ "MUTEX",+ "MYSQL_ERRNO",+ "NAME",+ "NAMES",+ "NATIONAL",+ "NATURAL",+ "NCHAR",+ "NDB",+ "NDBCLUSTER",+ "NEVER",+ "NEW",+ "NEXT",+ "NO",+ "NODEGROUP",+ "NONBLOCKING",+ "NONE",+ "NO_WAIT",+ "NO_WRITE_TO_BINLOG",+ "NUMBER",+ "NUMERIC",+ "NVARCHAR",+ "OFFSET",+ "OLD_PASSWORD",+ "ON",+ "ONE",+ "ONLY",+ "OPEN",+ "OPTIMIZE",+ "OPTIMIZER_COSTS",+ "OPTION",+ "OPTIONALLY",+ "OPTIONS",+ "OR",+ "ORDER",+ "OUT",+ "OUTER",+ "OUTFILE",+ "OWNER",+ "PACK_KEYS",+ "PAGE",+ "PARSER",+ "PARSE_GCOL_EXPR",+ "PARTIAL",+ "PARTITION",+ "PARTITIONING",+ "PARTITIONS",+ "PASSWORD",+ "PHASE",+ "PLUGIN",+ "PLUGINS",+ "PLUGIN_DIR",+ "POINT",+ "POLYGON",+ "PORT",+ "PRECEDES",+ "PRECISION",+ "PREPARE",+ "PRESERVE",+ "PREV",+ "PRIMARY",+ "PRIVILEGES",+ "PROCEDURE",+ "PROCESSLIST",+ "PROFILE",+ "PROFILES",+ "PROXY",+ "PURGE",+ "QUARTER",+ "QUERY",+ "QUICK",+ "RANGE",+ "READ",+ "READS",+ "READ_ONLY",+ "READ_WRITE",+ "REAL",+ "REBUILD",+ "RECOVER",+ "REDOFILE",+ "REDO_BUFFER_SIZE",+ "REDUNDANT",+ "REFERENCES",+ "REGEXP",+ "RELAY",+ "RELAYLOG",+ "RELAY_LOG_FILE",+ "RELAY_LOG_POS",+ "RELAY_THREAD",+ "RELEASE",+ "RELOAD",+ "REMOVE",+ "RENAME",+ "REORGANIZE",+ "REPAIR",+ "REPEAT",+ "REPEATABLE",+ "REPLACE",+ "REPLICATE_DO_DB",+ "REPLICATE_DO_TABLE",+ "REPLICATE_IGNORE_DB",+ "REPLICATE_IGNORE_TABLE",+ "REPLICATE_REWRITE_DB",+ "REPLICATE_WILD_DO_TABLE",+ "REPLICATE_WILD_IGNORE_TABLE",+ "REPLICATION",+ "REQUIRE",+ "RESET",+ "RESIGNAL",+ "RESTORE",+ "RESTRICT",+ "RESUME",+ "RETURN",+ "RETURNED_SQLSTATE",+ "RETURNS",+ "REVERSE",+ "REVOKE",+ "RIGHT",+ "RLIKE",+ "ROLLBACK",+ "ROLLUP",+ "ROTATE",+ "ROUTINE",+ "ROW",+ "ROWS",+ "ROW_COUNT",+ "ROW_FORMAT",+ "RTREE",+ "SAVEPOINT",+ "SCHEDULE",+ "SCHEMA",+ "SCHEMAS",+ "SCHEMA_NAME",+ "SECOND",+ "SECOND_MICROSECOND",+ "SECURITY",+ "SELECT",+ "SENSITIVE",+ "SEPARATOR",+ "SERIAL",+ "SERIALIZABLE",+ "SERVER",+ "SESSION",+ "SET",+ "SHARE",+ "SHOW",+ "SHUTDOWN",+ "SIGNAL",+ "SIGNED",+ "SIMPLE",+ "SLAVE",+ "SLOW",+ "SMALLINT",+ "SNAPSHOT",+ "SOCKET",+ "SOME",+ "SONAME",+ "SOUNDS",+ "SOURCE",+ "SPATIAL",+ "SPECIFIC",+ "SQL",+ "SQLEXCEPTION",+ "SQLSTATE",+ "SQLWARNING",+ "SQL_AFTER_GTIDS",+ "SQL_AFTER_MTS_GAPS",+ "SQL_BEFORE_GTIDS",+ "SQL_BIG_RESULT",+ "SQL_BUFFER_RESULT",+ "SQL_CACHE",+ "SQL_CALC_FOUND_ROWS",+ "SQL_NO_CACHE",+ "SQL_SMALL_RESULT",+ "SQL_THREAD",+ "SQL_TSI_DAY",+ "SQL_TSI_HOUR",+ "SQL_TSI_MINUTE",+ "SQL_TSI_MONTH",+ "SQL_TSI_QUARTER",+ "SQL_TSI_SECOND",+ "SQL_TSI_WEEK",+ "SQL_TSI_YEAR",+ "SSL",+ "STACKED",+ "START",+ "STARTING",+ "STARTS",+ "STATS_AUTO_RECALC",+ "STATS_PERSISTENT",+ "STATS_SAMPLE_PAGES",+ "STATUS",+ "STOP",+ "STORAGE",+ "STORED",+ "STRAIGHT_JOIN",+ "STRING",+ "SUBCLASS_ORIGIN",+ "SUBJECT",+ "SUBPARTITION",+ "SUBPARTITIONS",+ "SUPER",+ "SUSPEND",+ "SWAPS",+ "SWITCHES",+ "TABLE",+ "TABLES",+ "TABLESPACE",+ "TABLE_CHECKSUM",+ "TABLE_NAME",+ "TEMPORARY",+ "TEMPTABLE",+ "TERMINATED",+ "TEXT",+ "THAN",+ "THEN",+ "TIME",+ "TIMESTAMP",+ "TIMESTAMPADD",+ "TIMESTAMPDIFF",+ "TINYBLOB",+ "TINYINT",+ "TINYTEXT",+ "TO",+ "TRAILING",+ "TRANSACTION",+ "TRIGGER",+ "TRIGGERS",+ "TRUE",+ "TRUNCATE",+ "TYPE",+ "TYPES",+ "UNCOMMITTED",+ "UNDEFINED",+ "UNDO",+ "UNDOFILE",+ "UNDO_BUFFER_SIZE",+ "UNICODE",+ "UNINSTALL",+ "UNION",+ "UNIQUE",+ "UNKNOWN",+ "UNLOCK",+ "UNSIGNED",+ "UNTIL",+ "UPDATE",+ "UPGRADE",+ "USAGE",+ "USE",+ "USER",+ "USER_RESOURCES",+ "USE_FRM",+ "USING",+ "UTC_DATE",+ "UTC_TIME",+ "UTC_TIMESTAMP",+ "VALIDATION",+ "VALUE",+ "VALUES",+ "VARBINARY",+ "VARCHAR",+ "VARCHARACTER",+ "VARIABLES",+ "VARYING",+ "VIEW",+ "VIRTUAL",+ "WAIT",+ "WARNINGS",+ "WEEK",+ "WEIGHT_STRING",+ "WHEN",+ "WHERE",+ "WHILE",+ "WITH",+ "WITHOUT",+ "WORK",+ "WRAPPER",+ "WRITE",+ "X509",+ "XA",+ "XID",+ "XML",+ "XOR",+ "YEAR",+ "YEAR_MONTH",+ "ZEROFILL",+ "LEFT JOIN",+ "RIGHT JOIN",+ "GROUP BY",+ "ORDER BY",+];+const operators = [+ "AND",+ "BETWEEN",+ "IN",+ "LIKE",+ "NOT",+ "OR",+ "IS",+ "NULL",+ "INTERSECT",+ "UNION",+ "INNER",+ "JOIN",+ "LEFT",+ "OUTER",+ "RIGHT",+];++const builtinFunctions = [+ "ABS",+ "ACOS",+ "ADDDATE",+ "ADDTIME",+ "AES_DECRYPT",+ "AES_ENCRYPT",+ "ANY_VALUE",+ "Area",+ "AsBinary",+ "AsWKB",+ "ASCII",+ "ASIN",+ "AsText",+ "AsWKT",+ "ASYMMETRIC_DECRYPT",+ "ASYMMETRIC_DERIVE",+ "ASYMMETRIC_ENCRYPT",+ "ASYMMETRIC_SIGN",+ "ASYMMETRIC_VERIFY",+ "ATAN",+ "ATAN2",+ "ATAN",+ "AVG",+ "BENCHMARK",+ "BIN",+ "BIT_AND",+ "BIT_COUNT",+ "BIT_LENGTH",+ "BIT_OR",+ "BIT_XOR",+ "Buffer",+ "CAST",+ "CEIL",+ "CEILING",+ "Centroid",+ "CHAR",+ "CHAR_LENGTH",+ "CHARACTER_LENGTH",+ "CHARSET",+ "COALESCE",+ "COERCIBILITY",+ "COLLATION",+ "COMPRESS",+ "CONCAT",+ "CONCAT_WS",+ "CONNECTION_ID",+ "Contains",+ "CONV",+ "CONVERT",+ "CONVERT_TZ",+ "ConvexHull",+ "COS",+ "COT",+ "COUNT",+ "CRC32",+ "CREATE_ASYMMETRIC_PRIV_KEY",+ "CREATE_ASYMMETRIC_PUB_KEY",+ "CREATE_DH_PARAMETERS",+ "CREATE_DIGEST",+ "Crosses",+ "CURDATE",+ "CURRENT_DATE",+ "CURRENT_TIME",+ "CURRENT_TIMESTAMP",+ "CURRENT_USER",+ "CURTIME",+ "DATABASE",+ "DATE",+ "DATE_ADD",+ "DATE_FORMAT",+ "DATE_SUB",+ "DATEDIFF",+ "DAY",+ "DAYNAME",+ "DAYOFMONTH",+ "DAYOFWEEK",+ "DAYOFYEAR",+ "DECODE",+ "DEFAULT",+ "DEGREES",+ "DES_DECRYPT",+ "DES_ENCRYPT",+ "Dimension",+ "Disjoint",+ "Distance",+ "ELT",+ "ENCODE",+ "ENCRYPT",+ "EndPoint",+ "Envelope",+ "Equals",+ "EXP",+ "EXPORT_SET",+ "ExteriorRing",+ "EXTRACT",+ "ExtractValue",+ "FIELD",+ "FIND_IN_SET",+ "FLOOR",+ "FORMAT",+ "FOUND_ROWS",+ "FROM_BASE64",+ "FROM_DAYS",+ "FROM_UNIXTIME",+ "GeomCollFromText",+ "GeometryCollectionFromText",+ "GeomCollFromWKB",+ "GeometryCollectionFromWKB",+ "GeometryCollection",+ "GeometryN",+ "GeometryType",+ "GeomFromText",+ "GeometryFromText",+ "GeomFromWKB",+ "GeometryFromWKB",+ "GET_FORMAT",+ "GET_LOCK",+ "GLength",+ "GREATEST",+ "GROUP_CONCAT",+ "GTID_SUBSET",+ "GTID_SUBTRACT",+ "HEX",+ "HOUR",+ "IF",+ "IFNULL",+ "INET_ATON",+ "INET_NTOA",+ "INET6_ATON",+ "INET6_NTOA",+ "INSERT",+ "INSTR",+ "InteriorRingN",+ "Intersects",+ "INTERVAL",+ "IS_FREE_LOCK",+ "IS_IPV4",+ "IS_IPV4_COMPAT",+ "IS_IPV4_MAPPED",+ "IS_IPV6",+ "IS_USED_LOCK",+ "IsClosed",+ "IsEmpty",+ "ISNULL",+ "IsSimple",+ "JSON_APPEND",+ "JSON_ARRAY",+ "JSON_ARRAY_APPEND",+ "JSON_ARRAY_INSERT",+ "JSON_CONTAINS",+ "JSON_CONTAINS_PATH",+ "JSON_DEPTH",+ "JSON_EXTRACT",+ "JSON_INSERT",+ "JSON_KEYS",+ "JSON_LENGTH",+ "JSON_MERGE",+ "JSON_MERGE_PRESERVE",+ "JSON_OBJECT",+ "JSON_QUOTE",+ "JSON_REMOVE",+ "JSON_REPLACE",+ "JSON_SEARCH",+ "JSON_SET",+ "JSON_TYPE",+ "JSON_UNQUOTE",+ "JSON_VALID",+ "LAST_INSERT_ID",+ "LCASE",+ "LEAST",+ "LEFT",+ "LENGTH",+ "LineFromText",+ "LineStringFromText",+ "LineFromWKB",+ "LineStringFromWKB",+ "LineString",+ "LN",+ "LOAD_FILE",+ "LOCALTIME",+ "LOCALTIMESTAMP",+ "LOCATE",+ "LOG",+ "LOG10",+ "LOG2",+ "LOWER",+ "LPAD",+ "LTRIM",+ "MAKE_SET",+ "MAKEDATE",+ "MAKETIME",+ "MASTER_POS_WAIT",+ "MAX",+ "MBRContains",+ "MBRCoveredBy",+ "MBRCovers",+ "MBRDisjoint",+ "MBREqual",+ "MBREquals",+ "MBRIntersects",+ "MBROverlaps",+ "MBRTouches",+ "MBRWithin",+ "MD5",+ "MICROSECOND",+ "MID",+ "MIN",+ "MINUTE",+ "MLineFromText",+ "MultiLineStringFromText",+ "MLineFromWKB",+ "MultiLineStringFromWKB",+ "MOD",+ "MONTH",+ "MONTHNAME",+ "MPointFromText",+ "MultiPointFromText",+ "MPointFromWKB",+ "MultiPointFromWKB",+ "MPolyFromText",+ "MultiPolygonFromText",+ "MPolyFromWKB",+ "MultiPolygonFromWKB",+ "MultiLineString",+ "MultiPoint",+ "MultiPolygon",+ "NAME_CONST",+ "NOT IN",+ "NOW",+ "NULLIF",+ "NumGeometries",+ "NumInteriorRings",+ "NumPoints",+ "OCT",+ "OCTET_LENGTH",+ "OLD_PASSWORD",+ "ORD",+ "Overlaps",+ "PASSWORD",+ "PERIOD_ADD",+ "PERIOD_DIFF",+ "PI",+ "Point",+ "PointFromText",+ "PointFromWKB",+ "PointN",+ "PolyFromText",+ "PolygonFromText",+ "PolyFromWKB",+ "PolygonFromWKB",+ "Polygon",+ "POSITION",+ "POW",+ "POWER",+ "PROCEDURE ANALYSE",+ "QUARTER",+ "QUOTE",+ "RADIANS",+ "RAND",+ "RANDOM_BYTES",+ "RELEASE_ALL_LOCKS",+ "RELEASE_LOCK",+ "REPEAT",+ "REPLACE",+ "REVERSE",+ "RIGHT",+ "ROUND",+ "ROW_COUNT",+ "RPAD",+ "RTRIM",+ "SCHEMA",+ "SEC_TO_TIME",+ "SECOND",+ "SESSION_USER",+ "SHA1",+ "SHA",+ "SHA2",+ "SIGN",+ "SIN",+ "SLEEP",+ "SOUNDEX",+ "SPACE",+ "SQRT",+ "SRID",+ "ST_Area",+ "ST_AsBinary",+ "ST_AsWKB",+ "ST_AsGeoJSON",+ "ST_AsText",+ "ST_AsWKT",+ "ST_Buffer",+ "ST_Buffer_Strategy",+ "ST_Centroid",+ "ST_Contains",+ "ST_ConvexHull",+ "ST_Crosses",+ "ST_Difference",+ "ST_Dimension",+ "ST_Disjoint",+ "ST_Distance",+ "ST_Distance_Sphere",+ "ST_EndPoint",+ "ST_Envelope",+ "ST_Equals",+ "ST_ExteriorRing",+ "ST_GeoHash",+ "ST_GeomCollFromText",+ "ST_GeometryCollectionFromText",+ "ST_GeomCollFromTxt",+ "ST_GeomCollFromWKB",+ "ST_GeometryCollectionFromWKB",+ "ST_GeometryN",+ "ST_GeometryType",+ "ST_GeomFromGeoJSON",+ "ST_GeomFromText",+ "ST_GeometryFromText",+ "ST_GeomFromWKB",+ "ST_GeometryFromWKB",+ "ST_InteriorRingN",+ "ST_Intersection",+ "ST_Intersects",+ "ST_IsClosed",+ "ST_IsEmpty",+ "ST_IsSimple",+ "ST_IsValid",+ "ST_LatFromGeoHash",+ "ST_Length",+ "ST_LineFromText",+ "ST_LineStringFromText",+ "ST_LineFromWKB",+ "ST_LineStringFromWKB",+ "ST_LongFromGeoHash",+ "ST_MakeEnvelope",+ "ST_MLineFromText",+ "ST_MultiLineStringFromText",+ "ST_MLineFromWKB",+ "ST_MultiLineStringFromWKB",+ "ST_MPointFromText",+ "ST_MultiPointFromText",+ "ST_MPointFromWKB",+ "ST_MultiPointFromWKB",+ "ST_MPolyFromText",+ "ST_MultiPolygonFromText",+ "ST_MPolyFromWKB",+ "ST_MultiPolygonFromWKB",+ "ST_NumGeometries",+ "ST_NumInteriorRing",+ "ST_NumInteriorRings",+ "ST_NumPoints",+ "ST_Overlaps",+ "ST_PointFromGeoHash",+ "ST_PointFromText",+ "ST_PointFromWKB",+ "ST_PointN",+ "ST_PolyFromText",+ "ST_PolygonFromText",+ "ST_PolyFromWKB",+ "ST_PolygonFromWKB",+ "ST_Simplify",+ "ST_SRID",+ "ST_StartPoint",+ "ST_SymDifference",+ "ST_Touches",+ "ST_Union",+ "ST_Validate",+ "ST_Within",+ "ST_X",+ "ST_Y",+ "StartPoint",+ "STD",+ "STDDEV",+ "STDDEV_POP",+ "STDDEV_SAMP",+ "STR_TO_DATE",+ "STRCMP",+ "SUBDATE",+ "SUBSTR",+ "SUBSTRING",+ "SUBSTRING_INDEX",+ "SUBTIME",+ "SUM",+ "SYSDATE",+ "SYSTEM_USER",+ "TAN",+ "TIME",+ "TIME_FORMAT",+ "TIME_TO_SEC",+ "TIMEDIFF",+ "TIMESTAMP",+ "TIMESTAMPADD",+ "TIMESTAMPDIFF",+ "TO_BASE64",+ "TO_DAYS",+ "TO_SECONDS",+ "Touches",+ "TRIM",+ "TRUNCATE",+ "UCASE",+ "UNCOMPRESS",+ "UNCOMPRESSED_LENGTH",+ "UNHEX",+ "UNIX_TIMESTAMP",+ "UpdateXML",+ "UPPER",+ "USER",+ "UTC_DATE",+ "UTC_TIME",+ "UTC_TIMESTAMP",+ "UUID",+ "UUID_SHORT",+ "VALIDATE_PASSWORD_STRENGTH",+ "VALUES",+ "VAR_POP",+ "VAR_SAMP",+ "VARIANCE",+ "VERSION",+ "WAIT_FOR_EXECUTED_GTID_SET",+ "WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS",+ "WEEK",+ "WEEKDAY",+ "WEEKOFYEAR",+ "WEIGHT_STRING",+ "Within",+ "X",+ "Y",+ "YEAR",+ "YEARWEEK",+];++const keywords = [...keyword, ...operators, ...builtinFunctions];++export { keywords };diff --git a/frontend/src/components/MonacoEditor/setupMonaco.ts b/frontend/src/components/MonacoEditor/setupMonaco.tsnew file mode 100644index 0000000000..dd292ea33e--- /dev/null+++ b/frontend/src/components/MonacoEditor/setupMonaco.ts@@ -0,0 +1,143 @@+import * as monaco from "monaco-editor";+import { computed } from "vue";+import { useStore } from "vuex";++import AutoCompletion from "./AutoCompletion";+import {+ ConnectionAtom,+ Table,+ CompletionItems,+ InstanceGetters,+} from "../../types";++import { useNamespacedGetters } from "vuex-composition-helpers";++const setupMonaco = async (lang: string) => {+ const store = useStore();++ const { instanceList } = useNamespacedGetters<InstanceGetters>("instance", [+ "instanceList",+ ]);++ const instances = computed(() => instanceList.value());++ const databases = computed(() => {+ const currentInstanceId =+ store.state.sqlEditor.connectionContext.instanceId;+ return store.getters["database/databaseListByInstanceId"](+ currentInstanceId+ );+ });++ const tables = computed(() => {+ return databases.value+ .map((item: ConnectionAtom) =>+ store.getters["table/tableListByDatabaseId"](item.id)+ )+ .flat();+ });++ monaco.languages.typescript.typescriptDefaults.setCompilerOptions({+ ...monaco.languages.typescript.typescriptDefaults.getCompilerOptions(),+ noUnusedLocals: false,+ noUnusedParameters: false,+ allowUnreachableCode: true,+ allowUnusedLabels: true,+ strict: false,+ allowJs: true,+ });++ const completionItemProvider =+ monaco.languages.registerCompletionItemProvider(lang, {+ triggerCharacters: [" ", "."],+ provideCompletionItems: (model, position) => {+ let suggestions: CompletionItems = [];++ const { lineNumber, column } = position;+ // The text before the cursor pointer+ const textBeforePointer = model.getValueInRange({+ startLineNumber: lineNumber,+ startColumn: 0,+ endLineNumber: lineNumber,+ endColumn: column,+ });+ // The multi-text before the cursor pointer+ const textBeforePointerMulti = model.getValueInRange({+ startLineNumber: 1,+ startColumn: 0,+ endLineNumber: lineNumber,+ endColumn: column,+ });+ // The text after the cursor pointer+ const textAfterPointerMulti = model.getValueInRange({+ startLineNumber: lineNumber,+ startColumn: column,+ endLineNumber: model.getLineCount(),+ endColumn: model.getLineMaxColumn(model.getLineCount()),+ });+ const tokens = textBeforePointer.trim().split(/\s+/);+ const lastToken = tokens[tokens.length - 1].toLowerCase();++ // console.group("completionItemProvider");+ // console.log(textBeforePointer);+ // console.log(textBeforePointerMulti);+ // console.log(textAfterPointerMulti);+ // console.log(tokens);+ // console.log(lastToken);+ // console.groupEnd();++ const autoCompletion = new AutoCompletion(+ model,+ position,+ instances.value,+ databases.value,+ tables.value+ );++ const suggestionsForKeywords =+ autoCompletion.getCompletionItemsForKeywords();++ const suggestionsForTables =+ autoCompletion.getCompletionItemsForTables();++ // if enter a dot, show table columns+ if (lastToken.endsWith(".")) {+ const tableName = lastToken.replace(".", "");+ const idx = tables.value.findIndex(+ (item: Table) => item.name === tableName+ );+ if (idx !== -1) {+ suggestions = autoCompletion.getCompletionItemsForTableColumns(+ tables.value[idx],+ false+ );+ }+ } else {+ suggestions = [...suggestionsForKeywords, ...suggestionsForTables];+ }++ return { suggestions };+ },+ });++ await Promise.all([+ // load workers+ (async () => {+ const [{ default: EditorWorker }] = await Promise.all([+ // @ts-expect-error+ import("monaco-editor/esm/vs/editor/editor.worker.js?worker"),+ ]);++ // @ts-expect-error+ window.MonacoEnvironment = {+ getWorker(_: any, label: string) {+ return new EditorWorker();+ },+ };+ })(),+ ]);++ return { monaco, completionItemProvider };+};++export default setupMonaco;diff --git a/frontend/src/components/ProvideSqlEditorContext.vue b/frontend/src/components/ProvideSqlEditorContext.vuenew file mode 100644index 0000000000..9561a60a06--- /dev/null+++ b/frontend/src/components/ProvideSqlEditorContext.vue@@ -0,0 +1,58 @@+<template>+ <slot />+</template>++<script lang="ts" setup>+import { watchEffect } from "vue";+import { useStore } from "vuex";+import { Instance, Database, Table, ConnectionAtom } from "../types";+// import { idFromSlug } from "../utils";++const store = useStore();++const prepareSqlEdtiorContext = async function () {+ let connectionTree = [];++ const mapConnectionAtom = (item: Instance | Database | Table) => {+ const connectionAtom: ConnectionAtom = {+ id: item.id,+ key: item.id,+ label: item.name,+ };++ return connectionAtom;+ };++ const instanceList = await store.dispatch("instance/fetchInstanceList");+ connectionTree = instanceList.map(mapConnectionAtom);++ for (const instance of instanceList) {+ const databaseList = await store.dispatch(+ "database/fetchDatabaseListByInstanceId",+ instance.id+ );++ const instanceItem = connectionTree.find(+ (item: ConnectionAtom) => item.id === instance.id+ );+ instanceItem.children = databaseList.map(mapConnectionAtom);++ for (const db of databaseList) {+ const tableList = await store.dispatch(+ "table/fetchTableListByDatabaseId",+ db.id+ );++ const databaseItem = instanceItem.children.find(+ (item: ConnectionAtom) => item.id === db.id+ );++ databaseItem.children = tableList.map(mapConnectionAtom);+ }+ }++ store.dispatch("sqlEditor/setConnectionTree", connectionTree);+};++watchEffect(prepareSqlEdtiorContext);+</script>diff --git a/frontend/src/layouts/SqlEditorLayout.vue b/frontend/src/layouts/SqlEditorLayout.vuenew file mode 100644index 0000000000..cb7d790f98--- /dev/null+++ b/frontend/src/layouts/SqlEditorLayout.vue@@ -0,0 +1,58 @@+<template>+ <div class="relative h-screen overflow-hidden flex flex-col">+ <template v-if="isDemo">+ <BannerDemo />+ </template>++ <nav class="bg-white border-b border-block-border">+ <div class="max-w-full mx-auto px-4">+ <EditorHeader />+ </div>+ </nav>+ <!-- Suspense is experimental, be aware of the potential change -->+ <Suspense>+ <template #default>+ <ProvideSqlEditorContext>+ <router-view />+ </ProvideSqlEditorContext>+ </template>+ <template #fallback>+ <div class="flex flex-row justify-between p-4 space-x-2">+ <span class="items-center flex">Loading...</span>+ <button+ class="items-center flex justify-center btn-normal"+ @click.prevent="ping"+ >+ Ping+ </button>+ </div>+ </template>+ </Suspense>+ </div>+</template>++<script lang="ts" setup>+import { useStore } from "vuex";+import { computed } from "vue";++import ProvideSqlEditorContext from "@/components/ProvideSqlEditorContext.vue";+import EditorHeader from "@/views/SqlEditor/EditorHeader.vue";+import BannerDemo from "@/views/BannerDemo.vue";+import { ServerInfo } from "../types";++const store = useStore();++const ping = () => {+ store.dispatch("actuator/fetchInfo").then((info: ServerInfo) => {+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "SUCCESS",+ title: info,+ });+ });+};++const isDemo = computed(() => store.getters["actuator/isDemo"]());++const isReadonly = computed(() => store.getters["actuator/isReadonly"]());+</script>diff --git a/frontend/src/locales/en.yml b/frontend/src/locales/en.ymlindex 3c3818ccb5..0798e0b990 100644--- a/frontend/src/locales/en.yml+++ b/frontend/src/locales/en.yml@@ -150,6 +150,7 @@ common:billings: Billingsall: Allby: by+ share: Shareerror-page:go-back-home: Go back homeanomaly-center: Anomaly Center@@ -1023,3 +1024,6 @@ setting:free: Freeteam: Teamenterprise: Enterprise+sql-editor:+ select-connection: Select Connections+ sql-editor: SQL Editordiff --git a/frontend/src/locales/zh-CN.yml b/frontend/src/locales/zh-CN.ymlindex bcccb51876..1f820063d9 100644--- a/frontend/src/locales/zh-CN.yml+++ b/frontend/src/locales/zh-CN.yml@@ -150,6 +150,7 @@ common:billings: 计费all: 全部by: 由+ share: 分享error-page:go-back-home: 回到主页anomaly-center: 异常中心@@ -480,11 +481,9 @@ instance:successfully-connected-instance: 成功连接到实例。failed-to-connect-instance: 连接到实例失败。how-to-setup-instance: 如何设置「实例」?- how-to-setup-instance-description: >-+ how-to-setup-instance-description: |-每个 Bytebase 实例属于一个环境。一个实例通常映射到您的一个由 host:port 地址所代表的数据库实例。这可能是您在诸如 AWS 上的RDS 实例,也可能是您私有化部署的 MySQL 实例。--Bytebase 要求实例的读写权限(而不是 super 权限)以代表用户执行数据库操作。search-instance-name: 搜索实例名称grants: 权限@@ -893,3 +892,6 @@ setting:free: 免费版team: 团队版enterprise: 企业版+sql-editor:+ select-connection: 请选择数据连接+ sql-editor: SQL 编辑器diff --git a/frontend/src/main.ts b/frontend/src/main.tsindex e7678efdf3..931f9b5b52 100644--- a/frontend/src/main.ts+++ b/frontend/src/main.ts@@ -4,6 +4,8 @@ import moment from "moment";import { createApp } from "vue";import App from "./App.vue";import i18n from "./plugins/i18n";+import splitpanes from "./plugins/splitpanes";+import NaiveUI from "./plugins/naive-ui";import "./assets/css/inter.css";import "./assets/css/tailwind.css";@@ -21,6 +23,7 @@ import {humanizeTs,instanceName,instanceSlug,+ connectionSlug,isDev,isRelease,projectName,@@ -129,6 +132,7 @@ Promise.all([app.config.globalProperties.instanceSlug = instanceSlug;app.config.globalProperties.databaseSlug = databaseSlug;app.config.globalProperties.dataSourceSlug = dataSourceSlug;+ app.config.globalProperties.connectionSlug = connectionSlug;app// Need to use a directive on the element.@@ -139,5 +143,7 @@ Promise.all([.use(store).use(router).use(i18n)+ .use(splitpanes)+ .use(NaiveUI).mount("#app");});diff --git a/frontend/src/plugins/naive-ui.ts b/frontend/src/plugins/naive-ui.tsnew file mode 100644index 0000000000..7c335aa170--- /dev/null+++ b/frontend/src/plugins/naive-ui.ts@@ -0,0 +1,47 @@+import type { App } from "vue";+import {+ create,+ NButton,+ NButtonGroup,+ NCascader,+ NDataTable,+ NInput,+ NMessageProvider,+ NModal,+ NPopover,+ NPopconfirm,+ NSpace,+ NTabs,+ NTabPane,+ NTag,+ NTooltip,+ NTree,+ NUpload,+ NUploadDragger,+} from "naive-ui";++const naive = create({+ components: [+ NButton,+ NButtonGroup,+ NCascader,+ NDataTable,+ NInput,+ NMessageProvider,+ NModal,+ NPopover,+ NPopconfirm,+ NSpace,+ NTabs,+ NTabPane,+ NTag,+ NTooltip,+ NTree,+ NUpload,+ NUploadDragger,+ ],+});++const install = (app: App) => app.use(naive);++export default install;diff --git a/frontend/src/plugins/splitpanes.ts b/frontend/src/plugins/splitpanes.tsnew file mode 100644index 0000000000..34e1319ef0--- /dev/null+++ b/frontend/src/plugins/splitpanes.ts@@ -0,0 +1,9 @@+import { App } from "vue";++import { Splitpanes, Pane } from "splitpanes";+import "splitpanes/dist/splitpanes.css";++export default function install(app: App): void {+ app.component("Splitpanes", Splitpanes);+ app.component("Pane", Pane);+}diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.tsindex dfa90aec86..bd973f8a1a 100644--- a/frontend/src/router/index.ts+++ b/frontend/src/router/index.ts@@ -10,6 +10,7 @@ import DashboardLayout from "../layouts/DashboardLayout.vue";import DatabaseLayout from "../layouts/DatabaseLayout.vue";import InstanceLayout from "../layouts/InstanceLayout.vue";import SplashLayout from "../layouts/SplashLayout.vue";+import SqlEditorLayout from "../layouts/SqlEditorLayout.vue";import { t } from "../plugins/i18n";import { store } from "../store";import { Database, QuickActionType } from "../types";@@ -732,6 +733,27 @@ const routes: Array<RouteRecordRaw> = [},],},+ {+ path: "/sql-editor",+ name: "sql-editor",+ component: SqlEditorLayout,+ children: [+ {+ path: "",+ name: "sql-editor.home",+ meta: { title: () => "SQL Editor" },+ component: () => import("../views/SqlEditor/SqlEditor.vue"),+ props: true,+ },+ {+ path: "/sql-editor/:connectionSlug",+ name: "sql-editor.detail",+ meta: { title: () => "SQL Editor" },+ component: () => import("../views/SqlEditor/SqlEditor.vue"),+ props: true,+ },+ ],+ },];export const router = createRouter({@@ -862,6 +884,7 @@ router.beforeEach((to, from, next) => {to.name === "workspace.archive" ||to.name === "workspace.issue" ||to.name === "workspace.environment" ||+ to.name === "sql-editor.home" ||(to.name?.toString().startsWith("setting") &&to.name?.toString() != "setting.workspace.version-control.detail")) {@@ -888,6 +911,7 @@ router.beforeEach((to, from, next) => {const dataSourceSlug = routerSlug.dataSourceSlug;const migrationHistorySlug = routerSlug.migrationHistorySlug;const vcsSlug = routerSlug.vcsSlug;+ const connectionSlug = routerSlug.connectionSlug;if (principalId) {store@@ -1082,6 +1106,27 @@ router.beforeEach((to, from, next) => {return;}+ if (connectionSlug) {+ const [instanceSlug, instanceId, databaseSlug, databaseId] =+ connectionSlug.split("_");+ store+ .dispatch("sqlEditor/fetchConnectionByInstanceIdAndDatabaseId", {+ instanceId: Number(instanceId),+ databaseId: Number(databaseId),+ })+ .then(() => {+ next();+ })+ .catch((error) => {+ next({+ name: "error.404",+ replace: false,+ });+ throw error;+ });+ return;+ }+next({name: "error.404",replace: false,diff --git a/frontend/src/store/actions.ts b/frontend/src/store/actions.tsnew file mode 100644index 0000000000..a30751c62a--- /dev/null+++ b/frontend/src/store/actions.ts@@ -0,0 +1,19 @@+type StringRecord = Record<string, string>;++const makeAction = (type: string, namspace?: string) => {+ const mutationType = namspace ? `${namspace}/${type}` : type;+ return ({ commit }: any, ...args: any) => commit(mutationType, ...args);+};++export function makeActions<T>(types: StringRecord = {}): T {+ const actions = {};++ for (const type of Object.keys(types)) {+ const action = {+ [type]: makeAction(types[type]),+ };+ Object.assign(actions, action);+ }++ return actions as T;+};diff --git a/frontend/src/store/index.ts b/frontend/src/store/index.tsindex af1eb6318f..f530fd3888 100644--- a/frontend/src/store/index.ts+++ b/frontend/src/store/index.ts@@ -1,79 +1,23 @@import { createStore, Store } from "vuex";-// Following states are persisted in database-import activity from "./modules/activity";-// Actuator module-import actuator from "./modules/actuator";-import anomaly from "./modules/anomaly";-import auth from "./modules/auth";-import backup from "./modules/backup";-import bookmark from "./modules/bookmark";-import command from "./modules/command";-import database from "./modules/database";-import dataSource from "./modules/dataSource";-import environment from "./modules/environment";-import gitlab from "./modules/gitlab";-import inbox from "./modules/inbox";-import instance from "./modules/instance";-import issue from "./modules/issue";-import issueSubscriber from "./modules/issueSubscriber";-import member from "./modules/member";-import notification from "./modules/notification";-import pipeline from "./modules/pipeline";-import plan from "./modules/plan";-import policy from "./modules/policy";-import principal from "./modules/principal";-import project from "./modules/project";-import projectWebhook from "./modules/projectWebhook";-import repository from "./modules/repository";-// Following states are only stored in memory-import router from "./modules/router";-import setting from "./modules/setting";-import sql from "./modules/sql";-import stage from "./modules/stage";-import table from "./modules/table";-import task from "./modules/task";-// Following states are persisted in local storage-import uistate from "./modules/uistate";-import vcs from "./modules/vcs";-import view from "./modules/view";++/**+ * Following states are persisted in database+ * activity | actuator | anomlay | auth | backup | bookmark |+ * command | database | dataSource | environment | gitlab |+ * inbox |instance | issue | issueSubscriber | member | notification |+ * pipeline | plan | policy | principal | project | projectWebhook | repository |+ *+ * Following states are only stored in memory+ * router | setting | sql | stage | table | task | sqlEdtior+ *+ * Following states are persisted in local storage+ * uistate | vsc | view+ */+import modules from "./modules/index";const isProd = import.meta.env.NODE_ENV == "production";export const store: Store<any> = createStore({- modules: {- activity,- actuator,- auth,- bookmark,- command,- database,- dataSource,- environment,- gitlab,- instance,- issue,- issueSubscriber,- member,- inbox,- notification,- pipeline,- plan,- policy,- principal,- project,- projectWebhook,- repository,- router,- setting,- sql,- stage,- table,- backup,- task,- uistate,- vcs,- view,- anomaly,- },+ modules,strict: !isProd,});diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.tsnew file mode 100644index 0000000000..d359063041--- /dev/null+++ b/frontend/src/store/modules/index.ts@@ -0,0 +1,11 @@+// https://vitejs.dev/guide/features.html#glob-import+const modules = Object.fromEntries(+ Object.entries(import.meta.globEager("./*.ts")).map(+ ([key, value]) => {+ const moduleName = key.replace("./", "").replace(".ts", "");+ return [moduleName, value.default];+ }+ )+);++export default modules;diff --git a/frontend/src/store/modules/router.ts b/frontend/src/store/modules/router.tsindex a27dbf8792..aa41d7f0c4 100644--- a/frontend/src/store/modules/router.ts+++ b/frontend/src/store/modules/router.ts@@ -162,6 +162,21 @@ const getters = {}}+ {+ // /sql-editor/:connectionSlug+ const sqlEditorComponents = currentRoute.path.match(+ "/sql-editor/([0-9a-zA-Z_-]+)"+ ) || ["/", undefined];++ if (sqlEditorComponents[1]) {+ return {+ connectionSlug: sqlEditorComponents[1],+ };+ }+ }++ console.log(currentRoute);+return {};},};diff --git a/frontend/src/store/modules/sqlEditor.ts b/frontend/src/store/modules/sqlEditor.tsnew file mode 100644index 0000000000..2bec489fcc--- /dev/null+++ b/frontend/src/store/modules/sqlEditor.ts@@ -0,0 +1,153 @@+import { isEmpty } from "lodash-es";++import { SqlEditorState, ConnectionAtom, QueryInfo } from "../../types";+import * as types from "../mutation-types";+import { makeActions } from "../actions";++const state: () => SqlEditorState = () => ({+ connectionTree: [],+ connectionContext: {+ instanceId: 0,+ instanceName: "",+ databaseId: 0,+ databaseName: "",+ tableId: 0,+ tableName: "",+ },+ queryStatement: "",+ selectedStatement: "",+ queryResult: [],+});++const getters = {+ connectionTreeByInstanceId(state: SqlEditorState) {+ return state.connectionTree.find((item) => {+ return item.id === state.connectionContext.instanceId;+ });+ },+ connectionInfo(+ state: SqlEditorState,+ getter: any,+ rootState: any,+ rootGetters: any+ ) {+ return {+ allInstances: rootState.instance.instanceById,+ allDatabases: rootState.database.databaseListByInstanceId,+ allTables: rootState.table.tableListByDatabaseId,+ };+ },+ connectionInfoByInstanceId(+ state: SqlEditorState,+ getter: any,+ rootState: any,+ rootGetters: any+ ) {+ const instance = getter.connectionTreeByInstanceId;+ const databases = rootGetters["database/databaseListByInstanceId"](+ instance.id+ );++ const tables = instance.children+ .map((item: ConnectionAtom) =>+ rootGetters["table/tableListByDatabaseId"](item.id)+ )+ .flat();++ return {+ instance,+ databases,+ tables,+ };+ },+ currentSlug(state: SqlEditorState) {+ const connectionContext = state.connectionContext;+ return `${connectionContext.instanceId}/${connectionContext.databaseId}/${connectionContext.tableId}`;+ },+ isEmptyStatement(state: SqlEditorState) {+ return isEmpty(state.queryStatement);+ },+};++const mutations = {+ [types.SET_SQL_EDITOR_STATE](+ state: SqlEditorState,+ payload: Partial<SqlEditorState>+ ) {+ Object.assign(state, payload);+ },+ [types.SET_CONNECTION_TREE](+ state: SqlEditorState,+ payload: ConnectionAtom[]+ ) {+ state.connectionTree = payload;+ },+ [types.SET_QUERY_RESULT](state: SqlEditorState, payload: Array<any>) {+ state.queryResult = payload;+ },+};++type SqlEditorActionsMap = {+ setSqlEditorState: typeof mutations.SET_SQL_EDITOR_STATE;+ setConnectionTree: typeof mutations.SET_CONNECTION_TREE;+ setQueryResult: typeof mutations.SET_QUERY_RESULT;+};++const actions = {+ ...makeActions<SqlEditorActionsMap>({+ setSqlEditorState: types.SET_SQL_EDITOR_STATE,+ setConnectionTree: types.SET_CONNECTION_TREE,+ setQueryResult: types.SET_QUERY_RESULT,+ }),+ async executeQuery(+ { commit, dispatch, state }: any,+ payload: Partial<QueryInfo> = {}+ ) {+ const res = await dispatch(+ "sql/query",+ {+ instanceId: state.connectionContext.instanceId,+ databaseName: state.connectionContext.databaseName,+ statement: !isEmpty(state.selectedStatement)+ ? state.selectedStatement+ : state.queryStatement,+ ...payload,+ },+ { root: true }+ );+ commit(types.SET_QUERY_RESULT, res.data);+ return res.data;+ },+ async fetchConnectionByInstanceIdAndDatabaseId(+ { commit, dispatch }: any,+ { instanceId, databaseId }: Partial<SqlEditorState["connectionContext"]>+ ) {+ const instanceInfo = await dispatch(+ "instance/fetchInstanceById",+ instanceId,+ { root: true }+ );+ const databaseInfo = await dispatch(+ "database/fetchDatabaseById",+ { databaseId },+ { root: true }+ );+ commit(types.SET_SQL_EDITOR_STATE, {+ queryResult: [],+ connectionContext: {+ instanceId,+ instanceName: instanceInfo.name,+ databaseId,+ databaseName: databaseInfo.name,+ },+ });+ },+};++export default {+ namespaced: true,+ state,+ getters,+ actions,+ mutations,+};diff --git a/frontend/src/store/mutation-types.ts b/frontend/src/store/mutation-types.tsnew file mode 100644index 0000000000..ff290efaa8--- /dev/null+++ b/frontend/src/store/mutation-types.ts@@ -0,0 +1,4 @@+// SQL Editor mutation types+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";diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.tsindex 03fa9c69b3..10735d16a8 100644--- a/frontend/src/types/common.ts+++ b/frontend/src/types/common.ts@@ -63,6 +63,7 @@ export type RouterSlug = {dataSourceSlug?: string;migrationHistorySlug?: string;vcsSlug?: string;+ connectionSlug?: string;};// Quick Action Typediff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 72f0388f23..d539509171 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -33,3 +33,4 @@ export * from "./table";export * from "./tableIndex";export * from "./vcs";export * from "./view";+export * from "./sqlEditor";diff --git a/frontend/src/types/sqlEditor.ts b/frontend/src/types/sqlEditor.tsnew file mode 100644index 0000000000..40dbb215b3--- /dev/null+++ b/frontend/src/types/sqlEditor.ts@@ -0,0 +1,31 @@+import * as monaco from "monaco-editor";++import { InstanceId, DatabaseId, TableId, ViewId } from "../types";++export type EditorModel = monaco.editor.ITextModel;+export type EditorPosition = monaco.Position;+export type CompletionItems = monaco.languages.CompletionItem[];++export interface ConnectionAtom {+ id: InstanceId | DatabaseId | TableId | ViewId;+ key: InstanceId | DatabaseId | TableId | ViewId;+ label: string;+ children?: ConnectionAtom[];+}++export enum SortText {+ TABLE = "0",+ COLUMN = "1",+ KEYWORD = "2",+ DATABASE = "3",+ INSTASNCE = "4",+}++export type ConnectionContext = {+ instanceId: InstanceId;+ instanceName: string;+ databaseId?: DatabaseId;+ databaseName?: string;+ tableId?: TableId;+ tableName?: string;+};diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.tsindex 7d2e5bb04f..378470338a 100644--- a/frontend/src/types/store.ts+++ b/frontend/src/types/store.ts@@ -32,6 +32,10 @@ import { Repository } from "./repository";import { Setting, SettingName } from "./setting";import { Table } from "./table";import { VCS } from "./vcs";+import { ConnectionAtom, ConnectionContext } from "./sqlEditor";++import instanceStore from "../store/modules/instance";+import sqlEditorStore from "../store/modules/sqlEditor";export interface ActuatorState {serverInfo?: ServerInfo;@@ -111,6 +115,9 @@ export interface InstanceState {// The key is a concatenation of instance id and database namemigrationHistoryListByIdAndDatabaseName: Map<string, MigrationHistory[]>;}+export type InstanceGetters = typeof instanceStore.getters;+export type InstanceActions = typeof instanceStore.actions;+export type InstanceMutations = typeof instanceStore.mutations;export interface DataSourceState {dataSourceById: Map<DataSourceId, DataSource>;@@ -164,3 +171,15 @@ export interface NotificationState {export interface CommandState {commandListById: Map<CommandId, Command[]>;}++// type for vuex+export interface SqlEditorState {+ connectionTree: ConnectionAtom[];+ connectionContext: ConnectionContext;+ queryStatement: string;+ selectedStatement: string;+ queryResult: Array<Record<any, any>>;+}+export type SqlEditorGetters = typeof sqlEditorStore.getters;+export type SqlEditorActions = typeof sqlEditorStore.actions;+export type SqlEditorMutations = typeof sqlEditorStore.mutations;diff --git a/frontend/src/utils/slug.ts b/frontend/src/utils/slug.tsindex 667f630666..2302e121bb 100644--- a/frontend/src/utils/slug.ts+++ b/frontend/src/utils/slug.ts@@ -84,3 +84,12 @@ export function fullDataSourcePath(dataSource: DataSource): string {export function vcsSlug(vcs: VCS): string {return [slug(vcs.name), vcs.id].join("-");}++export function connectionSlug(database: Database): string {+ return [+ slug(database.instance.name),+ database.instance.id,+ slug(database.name),+ database.id,+ ].join("_");+}diff --git a/frontend/src/views/DashboardHeader.vue b/frontend/src/views/DashboardHeader.vueindex e3807a47d6..9489421430 100644--- a/frontend/src/views/DashboardHeader.vue+++ b/frontend/src/views/DashboardHeader.vue@@ -40,6 +40,12 @@class="bar-link px-2 py-2 rounded-md">{{ $t("common.settings") }}</router-link>+ <router-link+ v-if="isDevFeatures"+ to="/sql-editor"+ class="bar-link px-2 py-2 rounded-md"+ >SQL Editor</router-link+ ></div></div></div>diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vueindex 0651b0d4e7..013e5eed1c 100644--- a/frontend/src/views/DatabaseDetail.vue+++ b/frontend/src/views/DatabaseDetail.vue@@ -81,7 +81,7 @@</router-link></dd></template>- <dd+ <!-- <ddv-if="databaseConsoleLink.length > 0"class="flex items-center text-sm md:mr-4">@@ -94,6 +94,12 @@><heroicons-outline:external-link class="w-4 h-4" /></button>+ </dd> -->+ <dd class="flex items-center text-sm md:mr-4">+ <span class="textlabel">{{ $t("sql-editor.sql-editor") }}</span>+ <button class="ml-1 btn-icon" @click.prevent="gotoSqlEditor">+ <heroicons-outline:external-link class="w-4 h-4" />+ </button></dd></dl></div>@@ -202,7 +208,7 @@</template><script lang="ts">-import { computed, onMounted, reactive, watch } from "vue";+import { computed, onMounted, reactive, watch, defineComponent } from "vue";import { useStore } from "vuex";import { useRouter } from "vue-router";import ProjectSelect from "../components/ProjectSelect.vue";@@ -210,7 +216,12 @@ import DatabaseBackupPanel from "../components/DatabaseBackupPanel.vue";import DatabaseMigrationHistoryPanel from "../components/DatabaseMigrationHistoryPanel.vue";import DatabaseOverviewPanel from "../components/DatabaseOverviewPanel.vue";import InstanceEngineIcon from "../components/InstanceEngineIcon.vue";-import { consoleLink, idFromSlug, isDBAOrOwner } from "../utils";+import {+ consoleLink,+ idFromSlug,+ isDBAOrOwner,+ connectionSlug,+} from "../utils";import {ProjectId,UNKNOWN_ID,@@ -237,7 +248,7 @@ interface LocalState {selectedIndex: number;}-export default {+export default defineComponent({name: "DatabaseDetail",components: {ProjectSelect,@@ -277,14 +288,14 @@ export default {);});- const databaseConsoleLink = computed(() => {- const consoleUrl =- store.getters["setting/settingByName"]("bb.console.url").value;- if (!isEmpty(consoleUrl)) {- return consoleLink(consoleUrl, database.value.name);- }- return "";- });+ // const databaseConsoleLink = computed(() => {+ // const consoleUrl =+ // store.getters["setting/settingByName"]("bb.console.url").value;+ // if (!isEmpty(consoleUrl)) {+ // return consoleLink(consoleUrl, database.value.name);+ // }+ // return "";+ // });const isCurrentUserDBAOrOwner = computed((): boolean => {return isDBAOrOwner(currentUser.value.role);@@ -443,6 +454,15 @@ export default {}};+ const gotoSqlEditor = () => {+ router.replace({+ name: "sql-editor.detail",+ params: {+ connectionSlug: connectionSlug(database.value),+ },+ });+ };+onMounted(() => {selectDatabaseTabOnHash();});@@ -462,7 +482,7 @@ export default {BACKUP_TAB,state,database,- databaseConsoleLink,+ // databaseConsoleLink,allowChangeProject,allowAdmin,allowEdit,@@ -472,7 +492,8 @@ export default {alterSchemaText,updateProject,selectTab,+ gotoSqlEditor,};},-};+});</script>diff --git a/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue b/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vuenew file mode 100644index 0000000000..2fd560d86e--- /dev/null+++ b/frontend/src/views/SqlEditor/AsidePanel/AsidePanel.vue@@ -0,0 +1,27 @@+<template>+ <div class="aside-panel h-full">+ <n-tabs type="segment" default-value="databases" class="h-full">+ <n-tab-pane name="databases" tab="Databases">+ <Splitpanes horizontal class="default-theme">+ <Pane size="100"><DatabasesTree /></Pane>+ <Pane size="0" max-size="40"><TableSchema /></Pane>+ </Splitpanes>+ </n-tab-pane>+ <n-tab-pane name="queries" tab="Queries">+ Queries Page+ </n-tab-pane>+ </n-tabs>+ </div>+</template>++<script lang="ts" setup>+import DatabasesTree from "./DatabasesTree.vue";+import TableSchema from "./TableSchema.vue";+</script>++<style scoped>+.aside-panel .n-tab-pane {+ height: calc(100% - 40px);+ @apply pt-0;+}+</style>diff --git a/frontend/src/views/SqlEditor/AsidePanel/DatabasesTree.vue b/frontend/src/views/SqlEditor/AsidePanel/DatabasesTree.vuenew file mode 100644index 0000000000..2ce49fafca--- /dev/null+++ b/frontend/src/views/SqlEditor/AsidePanel/DatabasesTree.vue@@ -0,0 +1,17 @@+<template>+ <div class="databases-tree p-2">+ <NTree+ block-line+ :data="connectionTree"+ />+ </div>+</template>++<script lang="ts" setup>+import { computed } from "vue";+import { useStore } from "vuex";++const store = useStore();++const connectionTree = computed(() => store.state.sqlEditor.connectionTree);+</script>diff --git a/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vue b/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vuenew file mode 100644index 0000000000..24b6323d32--- /dev/null+++ b/frontend/src/views/SqlEditor/AsidePanel/TableSchema.vue@@ -0,0 +1 @@+<template>Table Schema</template>diff --git a/frontend/src/views/SqlEditor/EditorHeader.vue b/frontend/src/views/SqlEditor/EditorHeader.vuenew file mode 100644index 0000000000..ec684fcfb2--- /dev/null+++ b/frontend/src/views/SqlEditor/EditorHeader.vue@@ -0,0 +1,298 @@+<template>+ <div class="flex items-center justify-between h-16">+ <div class="flex items-center">+ <div class="flex-shrink-0 w-44">+ <router-link+ to="/"+ class="select-none"+ active-class=""+ exact-active-class=""+ ><img+ class="h-12 w-auto"+ src="../../assets/logo-full.svg"+ alt="Bytebase"+ /></router-link>+ </div>+ <div class="hidden sm:block">+ <div class="ml-6 flex items-baseline space-x-1">+ <router-link to="/sql-editor" class="bar-link px-2 py-2 rounded-md"+ >SQL Editor</router-link+ >+ </div>+ </div>+ </div>+ <div>+ <div class="flex items-center space-x-3">+ <router-link to="/inbox" exact-active-class="">+ <span+ v-if="inboxSummary.hasUnread"+ class="absolute rounded-full ml-4 -mt-1 h-2.5 w-2.5 bg-accent opacity-75"+ ></span>+ <heroicons-outline:bell class="w-6 h-6" />+ </router-link>+ <!-- TODO test for now, will delete -->+ <div+ v-if="showSwitchPlan"+ class="cursor-pointer"+ @click="toggleLocales"+ >+ <heroicons-outline:translate class="w-6 h-6" />+ </div>+ <div class="ml-2">+ <ProfileDropdown />+ </div>+ <div class="ml-2 -mr-2 flex sm:hidden">+ <!-- Mobile menu button -->+ <button+ class="icon-link inline-flex items-center justify-center rounded-md"+ @click.prevent="state.showMobileMenu = !state.showMobileMenu"+ >+ <span class="sr-only">Open main menu</span>+ <!--+ Heroicon name: menu++ Menu open: "hidden", Menu closed: "block"+ -->+ <heroicons-solid:dots-vertical class="w-6 h-6" />+ </button>+ </div>+ </div>+ </div>+ </div>++ <!--+ Mobile menu, toggle classes based on menu state.++ Open: "block", closed: "hidden"+ -->+ <div v-if="state.showMobileMenu" class="block md:hidden">+ <router-link to="/project" class="bar-link rounded-md block px-3 py-2"+ >Projects</router-link+ >++ <router-link to="/db" class="bar-link rounded-md block px-3 py-2"+ >Databases</router-link+ >++ <router-link+ v-if="showDBAItem"+ to="/instance"+ class="bar-link rounded-md block px-3 py-2"+ >Instances</router-link+ >++ <router-link to="/environment" class="bar-link rounded-md block px-3 py-2"+ >Environments</router-link+ >++ <router-link+ to="/setting/general"+ class="bar-link rounded-md block px-3 py-2"+ >{{ $t("common.settings") }}</router-link+ >+ </div>+</template>++<script lang="ts">+import { defineAction, useRegisterActions } from "@bytebase/vue-kbar";+import { computed, reactive, watchEffect } from "vue";+import { useRouter } from "vue-router";+import { useStore } from "vuex";+import { useI18n } from "vue-i18n";+import { useLocalStorage } from "@vueuse/core";++import ProfileDropdown from "../../components/ProfileDropdown.vue";+import { InboxSummary, PlanType, UNKNOWN_ID } from "../../types";+import { isDBAOrOwner, isDev } from "../../utils";++interface LocalState {+ showMobileMenu: boolean;+}++export default {+ name: "EditorHeader",+ components: { ProfileDropdown },+ setup() {+ const { t, availableLocales, locale } = useI18n();+ const store = useStore();+ const router = useRouter();++ const state = reactive<LocalState>({+ showMobileMenu: false,+ });++ const currentUser = computed(() => store.getters["auth/currentUser"]());++ const currentPlan = computed(() => store.getters["plan/currentPlan"]());++ const showDBAItem = computed((): boolean => {+ return (+ !store.getters["plan/feature"]("bb.dba-workflow") ||+ isDBAOrOwner(currentUser.value.role)+ );+ });++ const showSwitchPlan = computed((): boolean => {+ return isDev();+ });++ const prepareInboxSummary = () => {+ // It will also be called when user logout+ if (currentUser.value.id != UNKNOWN_ID) {+ store.dispatch("inbox/fetchInboxSummaryByUser", currentUser.value.id);+ }+ };++ watchEffect(prepareInboxSummary);++ const inboxSummary = computed((): InboxSummary => {+ return store.getters["inbox/inboxSummaryByUser"](currentUser.value.id);+ });++ const switchToOwner = () => {+ store.dispatch("auth/login", {+ email: "[email protected]",+ password: "1024",+ });+ };++ const switchToDBA = () => {+ store.dispatch("auth/login", {+ email: "[email protected]",+ password: "2048",+ });+ };++ const switchToDeveloper = () => {+ store.dispatch("auth/login", {+ email: "[email protected]",+ password: "4096",+ });+ };++ const switchToFree = () => {+ store.dispatch("plan/changePlan", PlanType.FREE);+ };++ const switchToTeam = () => {+ store.dispatch("plan/changePlan", PlanType.TEAM);+ };++ const switchToEnterprise = () => {+ store.dispatch("plan/changePlan", PlanType.ENTERPRISE);+ };++ const kbarActions = computed(() => [+ defineAction({+ id: "bb.navigation.projects",+ name: "Projects",+ shortcut: ["g", "p"],+ section: t("kbar.navigation"),+ keywords: "navigation",+ perform: () => router.push({ name: "workspace.project" }),+ }),+ defineAction({+ id: "bb.navigation.databases",+ name: "Databases",+ shortcut: ["g", "d"],+ section: t("kbar.navigation"),+ keywords: "navigation db",+ perform: () => router.push({ name: "workspace.database" }),+ }),+ defineAction({+ id: "bb.navigation.instances",+ name: "Instances",+ shortcut: ["g", "i"],+ section: t("kbar.navigation"),+ keywords: "navigation",+ perform: () => router.push({ name: "workspace.instance" }),+ }),+ defineAction({+ id: "bb.navigation.environments",+ name: "Environments",+ shortcut: ["g", "e"],+ section: t("kbar.navigation"),+ keywords: "navigation",+ perform: () => router.push({ name: "workspace.environment" }),+ }),+ defineAction({+ id: "bb.navigation.settings",+ name: "Settings",+ shortcut: ["g", "s"],+ section: t("kbar.navigation"),+ keywords: "navigation",+ perform: () => router.push({ name: "setting.workspace.general" }),+ }),+ defineAction({+ id: "bb.navigation.inbox",+ name: "Inbox",+ shortcut: ["g", "m"],+ section: t("kbar.navigation"),+ keywords: "navigation",+ perform: () => router.push({ name: "setting.inbox" }),+ }),+ ]);+ useRegisterActions(kbarActions);++ const storage = useLocalStorage("bytebase_options", {}) as any;++ const setLocale = (lang: string) => {+ locale.value = lang;+ storage.value = {+ appearance: {+ language: lang,+ },+ };+ };++ const toggleLocales = () => {+ // TODO change to some real logic+ const locales = availableLocales;+ const nextLocale =+ locales[(locales.indexOf(locale.value) + 1) % locales.length];+ setLocale(nextLocale);+ };++ const I18N_CHANGE_ACTION_ID_NAMESPACE = "bb.preferences.locale";+ const i18nChangeAction = computed(() =>+ defineAction({+ // here `id` is "bb.preferences.locale"+ id: I18N_CHANGE_ACTION_ID_NAMESPACE,+ section: t("kbar.preferences.common"),+ name: t("kbar.preferences.change-language"),+ keywords: "language lang locale",+ })+ );+ const i18nActions = computed(() => [+ i18nChangeAction.value,+ ...availableLocales.map((lang) => {+ return defineAction({+ // here `id` looks like "bb.preferences.locale.en"+ id: `${I18N_CHANGE_ACTION_ID_NAMESPACE}.${lang}`,+ name: lang,+ parent: I18N_CHANGE_ACTION_ID_NAMESPACE,+ keywords: `language lang locale ${lang}`,+ perform: () => setLocale(lang),+ });+ }),+ ]);+ useRegisterActions(i18nActions);++ return {+ state,+ currentUser,+ currentPlan,+ showDBAItem,+ showSwitchPlan,+ inboxSummary,+ switchToOwner,+ switchToDBA,+ switchToDeveloper,+ switchToFree,+ switchToTeam,+ switchToEnterprise,+ toggleLocales,+ };+ },+};+</script>diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorActions.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorActions.vuenew file mode 100644index 0000000000..427dd7b904--- /dev/null+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorActions.vue@@ -0,0 +1,137 @@+<template>+ <div class="sqleditor-editor-actions">+ <div class="actions-left w-3/5">+ <NButton+ type="primary"+ @click="handleExecuteQueries"+ :disabled="isEmptyStatement"+ >+ <mdi:play class="h-5 w-5" /> {{ $t("common.run") }} (⌘+⏎)+ </NButton>+ </div>+ <div class="actions-right space-x-2 flex w-2/5 justify-end">+ <NCascader+ v-model:value="selectedConnection"+ expand-trigger="hover"+ label-field="label"+ value-field="id"+ filterable+ :options="connectionTree"+ :placeholder="$t('sql-editor.select-connection')"+ :style="{ width: '400px' }"+ @update:value="handleConnectionChange"+ />+ <NButton secondary strong type="primary" :disabled="isEmptyStatement">+ <carbon:save class="h-5 w-5" /> {{ $t("common.save") }} (⌘+S)+ </NButton>+ <NButton :disabled="isEmptyStatement">+ <carbon:share class="h-5 w-5" /> {{ $t("common.share") }} (⌘+S)+ </NButton>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { ref, watch } from "vue";+import { CascaderOption } from "naive-ui";+import { useStore } from "vuex";++import {+ useNamespacedState,+ useNamespacedActions,+ useNamespacedGetters,+} from "vuex-composition-helpers";+import {+ SqlEditorState,+ SqlEditorGetters,+ SqlEditorActions,+ ConnectionContext,+} from "../../../types";++const { connectionTree, connectionContext } =+ useNamespacedState<SqlEditorState>("sqlEditor", [+ "connectionTree",+ "connectionContext",+ ]);+const { isEmptyStatement } = useNamespacedGetters<SqlEditorGetters>(+ "sqlEditor",+ ["isEmptyStatement", "connectionInfo"]+);+const { executeQuery, setSqlEditorState } =+ useNamespacedActions<SqlEditorActions>("sqlEditor", [+ "executeQuery",+ "setSqlEditorState",+ ]);++const selectedConnection = ref();+const isSeletedDatabase = ref(false);+const store = useStore();++const handleExecuteQueries = async () => {+ try {+ const res = await executeQuery();+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "SUCCESS",+ title: "Query executed successfully!",+ });+ } catch (error) {+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "CRITICAL",+ title: error,+ });+ }+};++watch(+ () => connectionTree.value,+ (newVal) => {+ if (newVal) {+ selectedConnection.value =+ connectionContext.value.tableId ||+ connectionContext.value.databaseId ||+ connectionContext.value.instanceId;+ }+ }+);++const handleConnectionChange = (+ value: number,+ option: CascaderOption,+ pathValues: Array<CascaderOption>+) => {+ isSeletedDatabase.value = pathValues.length >= 2;++ if (pathValues.length >= 1) {+ let connectionContext: ConnectionContext = {+ instanceId: 0,+ instanceName: "",+ };+ const [instanceInfo, databaseInfo, tableInfo] = pathValues;++ if (pathValues.length >= 1) {+ connectionContext.instanceId = instanceInfo.id as number;+ connectionContext.instanceName = instanceInfo.label as string;+ }+ if (pathValues.length >= 2) {+ connectionContext.databaseId = databaseInfo.id as number;+ connectionContext.databaseName = databaseInfo.label as string;+ }+ if (pathValues.length >= 3) {+ connectionContext.tableId = tableInfo.id as number;+ connectionContext.tableName = tableInfo.label as string;+ }++ setSqlEditorState({+ connectionContext,+ });+ }+};+</script>++<style scoped>+.sqleditor-editor-actions {+ @apply w-full flex justify-between items-center p-2;+}+</style>diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vuenew file mode 100644index 0000000000..825aea9436--- /dev/null+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue@@ -0,0 +1,10 @@+<template>+ <EditorActions />++ <QueryEditor />+</template>++<script lang="ts" setup>+import EditorActions from "./EditorActions.vue";+import QueryEditor from "./QueryEditor.vue";+</script>diff --git a/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue b/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vuenew file mode 100644index 0000000000..d839d45a34--- /dev/null+++ b/frontend/src/views/SqlEditor/EditorPanel/QueryEditor.vue@@ -0,0 +1,57 @@+<template>+ <MonacoEditor+ v-model="sqlCode"+ @change="handleChange"+ @change-selection="handleChangeSelection"+ @run-query="handleRunQuery"+ />+</template>++<script lang="ts" setup>+import { ref } from "vue";+import { debounce } from "lodash-es";+import { useNamespacedActions } from "vuex-composition-helpers";+import { useStore } from "vuex";++import { SqlEditorActions } from "../../../types";++const store = useStore();+const sqlCode = ref("");++const { setSqlEditorState, executeQuery } =+ useNamespacedActions<SqlEditorActions>("sqlEditor", [+ "setSqlEditorState",+ "executeQuery",+ ]);++const handleChange = debounce((value: string) => {+ setSqlEditorState({+ queryStatement: value,+ });+}, 300);++const handleChangeSelection = debounce((value: string) => {+ setSqlEditorState({+ selectedStatement: value,+ });+}, 300);++const handleRunQuery = async (statement: string) => {+ try {+ const res = await executeQuery({+ statement,+ });+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "SUCCESS",+ title: "Query executed successfully!",+ });+ } catch (error) {+ store.dispatch("notification/pushNotification", {+ module: "bytebase",+ style: "CRITICAL",+ title: error,+ });+ }+};+</script>diff --git a/frontend/src/views/SqlEditor/GettingStarted.vue b/frontend/src/views/SqlEditor/GettingStarted.vuenew file mode 100644index 0000000000..25999e5b0b--- /dev/null+++ b/frontend/src/views/SqlEditor/GettingStarted.vue@@ -0,0 +1 @@+<template>Empty Holder</template>diff --git a/frontend/src/views/SqlEditor/QuerySelector.vue b/frontend/src/views/SqlEditor/QuerySelector.vuenew file mode 100644index 0000000000..8c2aeb5470--- /dev/null+++ b/frontend/src/views/SqlEditor/QuerySelector.vue@@ -0,0 +1,11 @@+<template>+ <div class="query-selector border-b">query selector</div>+</template>++<script lang="ts" setup></script>++<style scoped>+.query-selector {+ height: var(--tab-height);+}+</style>diff --git a/frontend/src/views/SqlEditor/SqlEditor.vue b/frontend/src/views/SqlEditor/SqlEditor.vuenew file mode 100644index 0000000000..44f00e4ea6--- /dev/null+++ b/frontend/src/views/SqlEditor/SqlEditor.vue@@ -0,0 +1,87 @@+<template>+ <div class="sqleditor--wrapper">+ <QuerySelector />+ <Splitpanes class="default-theme splitpanes-wrap">+ <Pane size="20" min-size="0" max-size="30">+ <AsidePanel />+ </Pane>+ <Pane size="80">+ <template v-if="hasTabs">+ <Splitpanes :key="randomKey" horizontal class="default-theme">+ <Pane size="60">+ <EditorPanel />+ </Pane>+ <Pane size="40">+ <TablePanel />+ </Pane>+ </Splitpanes>+ </template>+ <template v-else>+ <GettingStarted />+ </template>+ </Pane>+ </Splitpanes>+ </div>+</template>++<script lang="ts" setup>+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();+</script>++<style>+/* splitpanes pane style */+.splitpanes.default-theme .splitpanes__pane {+ @apply bg-transparent;+}+.splitpanes.default-theme .splitpanes__splitter {+ @apply bg-gray-100;+ min-height: 16px;+ min-width: 16px;+}++.splitpanes.default-theme .splitpanes__splitter::before,+.splitpanes.default-theme .splitpanes__splitter::after {+ @apply bg-gray-700 opacity-50;+}++.splitpanes.default-theme .splitpanes__splitter:hover::before,+.splitpanes.default-theme .splitpanes__splitter:hover::after {+ @apply bg-transparent;+}++.default-theme.splitpanes--vertical > .splitpanes__splitter,+.default-theme .splitpanes--vertical > .splitpanes__splitter {+ @apply border-l border-r;+ border-color: var(--border-color);+}++.default-theme.splitpanes--horizontal > .splitpanes__splitter,+.default-theme .splitpanes--horizontal > .splitpanes__splitter {+ @apply border-t border-b;+ border-color: var(--border-color);+}+</style>++<style scoped>+.sqleditor--wrapper {+ color: var(--base);+ --base: #444;+ --nav-height: 64px;+ --tab-height: 48px;+ --font-code: "Source Code Pro", monospace;+ --color-branding: #4f46e5;+ --border-color: rgba(200, 200, 200, 0.2);+ height: calc(100vh - var(--nav-height));+}++.splitpanes.default-theme.splitpanes-wrap {+ height: calc(100% - var(--tab-height));+}+</style>diff --git a/frontend/src/views/SqlEditor/TablePanel/HistoryView.vue b/frontend/src/views/SqlEditor/TablePanel/HistoryView.vuenew file mode 100644index 0000000000..86fa7e9428--- /dev/null+++ b/frontend/src/views/SqlEditor/TablePanel/HistoryView.vue@@ -0,0 +1 @@+<template>History View</template>diff --git a/frontend/src/views/SqlEditor/TablePanel/TablePanel.vue b/frontend/src/views/SqlEditor/TablePanel/TablePanel.vuenew file mode 100644index 0000000000..26f35b110f--- /dev/null+++ b/frontend/src/views/SqlEditor/TablePanel/TablePanel.vue@@ -0,0 +1,15 @@+<template>+ <Splitpanes class="default-theme">+ <Pane size="100">+ <TableView />+ </Pane>+ <Pane size="0">+ <HistroyView />+ </Pane>+ </Splitpanes>+</template>++<script lang="ts" setup>+import TableView from "./TableView.vue";+import HistroyView from "./HistoryView.vue";+</script>diff --git a/frontend/src/views/SqlEditor/TablePanel/TableView.vue b/frontend/src/views/SqlEditor/TablePanel/TableView.vuenew file mode 100644index 0000000000..15fd68c6fe--- /dev/null+++ b/frontend/src/views/SqlEditor/TablePanel/TableView.vue@@ -0,0 +1,48 @@+<template>+ <div class="table-view h-full p-2" ref="tableViewRef">+ <NDataTable+ size="mini"+ :columns="columns"+ :data="data"+ :bordered="false"+ flex-height+ :style="{ height: `${tableMaxHeight}px` }"+ >+ <template #empty>+ <div class="p-20 h-full flex justify-center items-center">+ Click Run to execute the query.+ </div>+ </template>+ </NDataTable>+ </div>+</template>++<script lang="ts" setup>+import { computed, ref } from "vue";+import { useResizeObserver } from "@vueuse/core";+import { useNamespacedState } from "vuex-composition-helpers";++const { queryResult } = useNamespacedState("sqlEditor", ["queryResult"]);++const tableViewRef = ref<HTMLDivElement>();+const tableMaxHeight = ref(0);++const columns = computed(() => {+ return queryResult.value.length > 0+ ? Object.keys(queryResult.value[0]).map((item) => {+ return {+ title: item.toUpperCase(),+ key: item,+ };+ })+ : [];+});+const data = computed(() => queryResult.value);++// make sure the table view is always full of the pane+useResizeObserver(tableViewRef, (entries) => {+ const entry = entries[0];+ const { height } = entry.contentRect;+ tableMaxHeight.value = height;+});+</script>diff --git a/frontend/tsconfig.json b/frontend/tsconfig.jsonindex 891e00ec7f..17e78d417e 100644--- a/frontend/tsconfig.json+++ b/frontend/tsconfig.json@@ -5,7 +5,7 @@"target": "esnext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,"module": "esnext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,// "lib": [], /* Specify library files to be included in the compilation. */- // "allowJs": true, /* Allow javascript files to be compiled. */+ "allowJs": true, /* Allow javascript files to be compiled. */// "checkJs": true, /* Report errors in .js files. */"jsx": "preserve" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */,// "declaration": true, /* Generates corresponding '.d.ts' file. */diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex 791466c6c6..4e8dc06cf4 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -53,9 +53,9 @@ export default defineConfig(() => {},},resolve: {- // alias: {- // "/@/": path.resolve(__dirname, "./src"),- // },+ alias: {+ "@/": `${resolve(__dirname, "src")}/`,+ },},};});diff --git a/frontend/yarn.lock b/frontend/yarn.lockindex 767f3fb312..ce58169623 100644--- a/frontend/yarn.lock+++ b/frontend/yarn.lock@@ -401,6 +401,13 @@resolved "https://registry.yarnpkg.com/@types/slug/-/slug-0.9.1.tgz#16dbf8b77d73e0a09ce51a96400878f33806ab32"integrity sha512-zR/u8WFQ4/6uCIikjI00a5uB084XjgEGNRAvM4a1BL39Bw9yEiDQFiPS2DgJ8lPDkR2Qd/vZ26dCR9XqlKbDqQ==+"@types/splitpanes@^2.2.1":+ version "2.2.1"+ resolved "https://registry.yarnpkg.com/@types/splitpanes/-/splitpanes-2.2.1.tgz#7ff67e639b16eecfc3ad403269dff320cf96e866"+ integrity sha512-H5BgO6UdJRzz5ddRzuGvLBiPSPEuuHXb5ET+7avLLrEx1uc7f5Ut5oLMDQsfvGtHBBAFczt1QNYuDf27wHbvDQ==+ dependencies:+ vue "^2.0.0"+"@types/uuid@^8.3.0":version "8.3.3"resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-8.3.3.tgz#c6a60686d953dbd1b1d45e66f4ecdbd5d471b4d0"@@ -3090,6 +3097,11 @@ moment@^2.29.1:resolved "https://registry.yarnpkg.com/moment/-/moment-2.29.1.tgz#b2be769fa31940be9eeea6469c075e35006fa3d3"integrity sha512-kHmoybcPV8Sqy59DwNDY3Jefr64lK/by/da0ViFcuA4DH0vQg5Q6Ze5VimxkfQNSC+Mls/Kx53s7TjP1RhFEDQ==+monaco-editor@^0.31.1:+ version "0.31.1"+ resolved "https://registry.yarnpkg.com/monaco-editor/-/monaco-editor-0.31.1.tgz#67f597b3e45679d1f551237e12a3a42c4438b97b"+ integrity sha512-FYPwxGZAeP6mRRyrr5XTGHD9gRXVjy7GUzF4IPChnyt3fS5WrNxIkS8DNujWf6EQy0Zlzpxw8oTVE+mWI2/D1Q==+version "2.1.2"resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009"@@ -4133,6 +4145,11 @@ split@^1.0.1:dependencies:through "2"+splitpanes@^3.0.6:+ version "3.0.6"+ resolved "https://registry.yarnpkg.com/splitpanes/-/splitpanes-3.0.6.tgz#45636c36972d3391f837073807726a2dcc49af15"+ integrity sha512-Ogxc+e2te4Tp5IpMwjOPO1ZvXUf2PsuEoyZhF9H5Hp6XOB0mLg/OnEZFaK2MxT7Q3O+WSEKE7CeOoTC+4zsQ6A==+string-width@^1.0.1:version "1.0.2"resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3"@@ -4762,6 +4779,11 @@ vue-tsc@^0.29.6:"@volar/shared" "0.29.8"vscode-vue-languageservice "0.29.8"+vue@^2.0.0:+ version "2.6.14"+ resolved "https://registry.yarnpkg.com/vue/-/vue-2.6.14.tgz#e51aa5250250d569a3fbad3a8a5a687d6036e235"+ integrity sha512-x2284lgYvjOMj3Za7kqzRcUSxBboHqtgRE2zlos1qWaOye5yUmHn42LB1250NJBLRwEcdrB0JRwyPTEPhfQjiQ==+vue@^3.2.13:version "3.2.23"resolved "https://registry.yarnpkg.com/vue/-/vue-3.2.23.tgz#fe17e4a98bee1afe2aed351a0a80e052728f9ce2"@@ -4785,6 +4807,11 @@ vueuc@^0.4.18:vdirs "^0.1.4"vooks "^0.2.4"+vuex-composition-helpers@^2.0.1:+ version "2.0.1"+ resolved "https://registry.yarnpkg.com/vuex-composition-helpers/-/vuex-composition-helpers-2.0.1.tgz#8a1a2e5ac18e5e8e2c52f7ec717797f6261bcf6c"+ integrity sha512-i2Bg24AH9/AL5nDdh2lmP19Mcl86EJLV7EeVjrCtqY29wkzZa6PWaYYKcbwbYffYoAiTtz1n54VhIaZ1MxNAkw==+vuex@^4.0.0:version "4.0.2"resolved "https://registry.yarnpkg.com/vuex/-/vuex-4.0.2.tgz#f896dbd5bf2a0e963f00c67e9b610de749ccacc9"