Skip to content

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

refactor: migrate sheet store to pinia (#1102)

Yunwei Xiaoc59b54bf0470
diff --git a/frontend/package.json b/frontend/package.json
index fa7b7a15cd..f81c5089f0 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -35,9 +35,7 @@
"vue-i18n": "^9.2.0-beta.20",
"vue-router": "^4.0.8",
"vueuc": "^0.4.27",
- "vuex": "^4.0.0",
- "vuex-composition-helpers": "^2.0.1",
- "vuex-persistedstate": "^4.1.0"
+ "vuex": "^4.0.0"
},
"devDependencies": {
"@iconify/json": "^1.1.432",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index db1d50e563..b2420af276 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -56,8 +56,6 @@ specifiers:
vue-tsc: ^0.29.6
vueuc: ^0.4.27
vuex: ^4.0.0
- vuex-composition-helpers: ^2.0.1
- vuex-persistedstate: ^4.1.0
dependencies:
'@bytebase/vue-kbar': [email protected]
@@ -84,8 +82,6 @@ dependencies:
vue-router: [email protected]
- vuex-composition-helpers: [email protected][email protected]
- vuex-persistedstate: [email protected]
devDependencies:
'@iconify/json': 1.1.461
@@ -288,8 +284,8 @@ packages:
- supports-color
dev: true
- /@intlify/bundle-utils/[email protected]:
- resolution: {integrity: sha512-8n8zhYEKypS+KP22KUAC6BnQifJDDWUGcn3OVPqsThqMMucU22MShGvOuiKqQ4AeT7XQ5O4pudlJmxv3L91JrQ==}
+ /@intlify/bundle-utils/[email protected]:
+ resolution: {integrity: sha512-y43Z5Q3ZJvxqtD8xUH6U3yrlZeay7ZTqkzv1GQ4b0mGQtk5uptOT9Ra4qvGuUv8QyPQsortrA/OHWUD5ax5ZNQ==}
engines: {node: '>= 12'}
peerDependencies:
petite-vue-i18n: '*'
@@ -300,8 +296,8 @@ packages:
vue-i18n:
optional: true
dependencies:
- '@intlify/message-compiler': 9.2.0-beta.33
- '@intlify/shared': 9.2.0-beta.33
+ '@intlify/message-compiler': 9.2.0-beta.35
+ '@intlify/shared': 9.2.0-beta.35
jsonc-eslint-parser: 1.4.1
source-map: 0.6.1
@@ -333,11 +329,11 @@ packages:
source-map: 0.6.1
dev: false
- /@intlify/message-compiler/9.2.0-beta.33:
- resolution: {integrity: sha512-+SICjFlnHSbRLZT+sNdBvOAQfcNX+fESyMmgPxC8HHWu4GLN2CoVQS4ACXb3QBZDKLVJBFhFGMnl+UXyJrno6g==}
+ /@intlify/message-compiler/9.2.0-beta.35:
+ resolution: {integrity: sha512-wYQCgnRtyJ40HK3bJTrszHDaxqDXZH+9Ps7RsXNuNwZ9hIb1cVkLiUNIbuJS/XSJ1kATJXA6K+4if6ZLb0Ozxw==}
engines: {node: '>= 12'}
dependencies:
- '@intlify/shared': 9.2.0-beta.33
+ '@intlify/shared': 9.2.0-beta.35
source-map: 0.6.1
dev: true
@@ -346,8 +342,8 @@ packages:
engines: {node: '>= 12'}
dev: false
- /@intlify/shared/9.2.0-beta.33:
- resolution: {integrity: sha512-HldlkV66vMt1vQsuUz4zjQ202C5KW6aHeIQhx7RxBO11i3E8V84dp5MG9epr9GZXVsrCAR56Ekj0HaTqksIRJA==}
+ /@intlify/shared/9.2.0-beta.35:
+ resolution: {integrity: sha512-DXf7xrwf08GKhr93XPQ8EgaEN0CIELl+mAS6SlRhi/aLtZv5HSGSMkz4M/ICwoWzFLSgOx/ZdBSasex19MMogg==}
engines: {node: '>= 12'}
dev: true
@@ -364,8 +360,8 @@ packages:
vue-i18n:
optional: true
dependencies:
- '@intlify/bundle-utils': [email protected]
- '@intlify/shared': 9.2.0-beta.33
+ '@intlify/bundle-utils': [email protected]
+ '@intlify/shared': 9.2.0-beta.35
'@rollup/pluginutils': 4.2.0
debug: 4.3.3
fast-glob: 3.2.11
@@ -1218,11 +1214,6 @@ packages:
resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==}
dev: true
- /deepmerge/4.2.2:
- resolution: {integrity: sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==}
- engines: {node: '>=0.10.0'}
- dev: false
-
/defined/1.0.0:
resolution: {integrity: sha1-yY2bzvdWdBiOEQlpFRGZ45sfppM=}
dev: true
@@ -2796,10 +2787,6 @@ packages:
engines: {node: '>=8'}
dev: true
- /shvl/2.0.3:
- resolution: {integrity: sha512-V7C6S9Hlol6SzOJPnQ7qzOVEWUQImt3BNmmzh40wObhla3XOYMe4gGiYzLrJd5TFa+cI2f9LKIRJTTKZSTbWgw==}
- dev: false
-
/signal-exit/3.0.7:
resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}
dev: true
@@ -3454,27 +3441,6 @@ packages:
vue: 3.2.31
dev: false
- /vuex-composition-helpers/[email protected][email protected]:
- resolution: {integrity: sha512-i2Bg24AH9/AL5nDdh2lmP19Mcl86EJLV7EeVjrCtqY29wkzZa6PWaYYKcbwbYffYoAiTtz1n54VhIaZ1MxNAkw==}
- peerDependencies:
- vue: '>= 3.0.5'
- vuex: '>= 4.0.0'
- dependencies:
- vue: 3.2.31
- dev: false
-
- /vuex-persistedstate/[email protected]:
- resolution: {integrity: sha512-3SkEj4NqwM69ikJdFVw6gObeB0NHyspRYMYkR/EbhR0hbvAKyR5gksVhtAfY1UYuWUOCCA0QNGwv9pOwdj+XUQ==}
- deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
- peerDependencies:
- vuex: ^3.0 || ^4.0.0-rc
- dependencies:
- deepmerge: 4.2.2
- shvl: 2.0.3
- dev: false
-
resolution: {integrity: sha512-M6r8uxELjZIK8kTKDGgZTYX/ahzblnzC4isU1tpmEuOIIKmV+TRdc+H4s8ds2NuZ7wpUTdGRzJRtoj+lI+pc0Q==}
peerDependencies:
diff --git a/frontend/src/components/MonacoEditor/MonacoEditor.vue b/frontend/src/components/MonacoEditor/MonacoEditor.vue
index 1d9e5dd308..6a063675c9 100644
--- a/frontend/src/components/MonacoEditor/MonacoEditor.vue
+++ b/frontend/src/components/MonacoEditor/MonacoEditor.vue
@@ -17,14 +17,14 @@ import { useI18n } from "vue-i18n";
import { editor as Editor } from "monaco-editor";
import { useMonaco } from "./useMonaco";
-import {
- useNamespacedActions,
- useNamespacedGetters,
- useNamespacedState,
-} from "vuex-composition-helpers";
-import { pushNotification, useTabStore, useSQLEditorStore } from "@/store";
-import { SheetGetters, SqlDialect } from "../../types";
+import {
+ pushNotification,
+ useTabStore,
+ useSQLEditorStore,
+ useSheetStore,
+} from "@/store";
+import { SqlDialect } from "../../types";
import { useLineDecorations } from "./lineDecorations";
const props = defineProps({
@@ -58,13 +58,10 @@ const language = toRef(props, "language");
const tabStore = useTabStore();
const sqlEditorStore = useSQLEditorStore();
+const sheetStore = useSheetStore();
const { t } = useI18n();
-const { isReadOnly } = useNamespacedGetters<SheetGetters>("sheet", [
- "isReadOnly",
-]);
-
-const readonly = computed(() => isReadOnly.value(tabStore.currentTab));
+const readonly = computed(() => sheetStore.isReadOnly);
let editorInstance: Editor.IStandaloneCodeEditor;
diff --git a/frontend/src/components/ProvideSqlEditorContext.vue b/frontend/src/components/ProvideSqlEditorContext.vue
index 2f43c7af7c..b108c55d86 100644
--- a/frontend/src/components/ProvideSqlEditorContext.vue
+++ b/frontend/src/components/ProvideSqlEditorContext.vue
@@ -10,6 +10,7 @@ import {
useProjectStore,
useTableStore,
useSQLEditorStore,
+ useSheetStore,
} from "@/store";
import { reactive, onMounted } from "vue";
import { useStore } from "vuex";
@@ -27,6 +28,8 @@ import {
const store = useStore();
const databaseStore = useDatabaseStore();
+const sheetStore = useSheetStore();
+
const state = reactive<{
projectList: Project[];
instanceIdList: Map<InstanceId, Instance["name"]>;
@@ -119,7 +122,7 @@ const prepareSqlEditorContext = async () => {
sqlEditorStore.setConnectionTree(connectionTree);
sqlEditorStore.setConnectionContext({ isLoadingTree: false });
sqlEditorStore.fetchQueryHistoryList();
- store.dispatch("sheet/fetchSheetList");
+ sheetStore.fetchSheetList();
};
onMounted(async () => {
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index 707c4bc8ef..65cb2a00b0 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -11,7 +11,6 @@ import {
isDMLStatement,
} from "../components/MonacoEditor/sqlParser";
import { pushNotification, useTabStore, useSQLEditorStore } from "@/store";
-import { TabInfo } from "@/types";
type ExecuteConfig = {
databaseType: string;
diff --git a/frontend/src/composables/useSQLEditorConnection.ts b/frontend/src/composables/useSQLEditorConnection.ts
index a8f9cc9ccf..42e251d0bb 100644
--- a/frontend/src/composables/useSQLEditorConnection.ts
+++ b/frontend/src/composables/useSQLEditorConnection.ts
@@ -1,16 +1,20 @@
import { useRouter } from "vue-router";
-import { useStore } from "vuex";
import { DEFAULT_PROJECT_ID, SheetState, UNKNOWN_ID } from "../types";
import { connectionSlug } from "../utils";
import { getDefaultConnectionContext } from "@/store/pinia-modules/sqlEditor";
-import { useDatabaseStore, useTabStore, useSQLEditorStore } from "@/store";
+import {
+ useDatabaseStore,
+ useTabStore,
+ useSQLEditorStore,
+ useSheetStore,
+} from "@/store";
const useSQLEditorConnection = () => {
const router = useRouter();
- const store = useStore();
const tabStore = useTabStore();
const sqlEditorStore = useSQLEditorStore();
+ const sheetStore = useSheetStore();
/**
* Set the connection by tab info
@@ -19,7 +23,7 @@ const useSQLEditorConnection = () => {
*/
const setConnectionContextFromCurrentTab = () => {
const currentTab = tabStore.currentTab;
- const sheetById = store.state.sheet.sheetById as SheetState["sheetById"];
+ const sheetById = sheetStore.sheetById as SheetState["sheetById"];
if (currentTab.sheetId && sheetById.has(currentTab.sheetId)) {
const sheet = sheetById.get(currentTab.sheetId);
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 4f00e38c52..78723c454a 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -22,7 +22,13 @@ import {
usePrincipalStore,
useRouterStore,
} from "../store";
-import { Database, QuickActionType, Sheet, UNKNOWN_ID } from "../types";
+import {
+ Database,
+ QuickActionType,
+ Sheet,
+ UNKNOWN_ID,
+ SheetId,
+} from "../types";
import { idFromSlug, isDBAOrOwner, isOwner } from "../utils";
// import PasswordReset from "../views/auth/PasswordReset.vue";
import Signin from "../views/auth/Signin.vue";
@@ -38,6 +44,7 @@ import {
useProjectStore,
useTableStore,
useSQLEditorStore,
+ useSheetStore,
} from "@/store";
const HOME_MODULE = "workspace.home";
@@ -1175,8 +1182,8 @@ router.beforeEach((to, from, next) => {
// for sharing the sheet to others
if (sheetSlug) {
const [_, sheetId] = sheetSlug.split("_");
- store
- .dispatch("sheet/fetchSheetById", sheetId)
+ useSheetStore()
+ .fetchSheetById(Number(sheetId))
.then((sheet: Sheet) => {
tabStore.addTab({
name: sheet.name,
diff --git a/frontend/src/store/modules/sheet.ts b/frontend/src/store/modules/sheet.ts
deleted file mode 100644
index 1a66da73b0..0000000000
--- a/frontend/src/store/modules/sheet.ts
+++ /dev/null
@@ -1,313 +0,0 @@
-import axios from "axios";
-import { isEmpty } from "lodash-es";
-
-import * as types from "../mutation-types";
-import { makeActions } from "../actions";
-import type {
- Sheet,
- SheetId,
- SheetState,
- SheetPatch,
- Principal,
- ResourceObject,
- ConnectionContext,
- TabInfo,
- Database,
- Project,
- ProjectMember,
-} from "@/types";
-import { unknown, UNKNOWN_ID } from "@/types";
-import { getPrincipalFromIncludedList } from "../pinia";
-import {
- useAuthStore,
- useDatabaseStore,
- useProjectStore,
- useSQLEditorStore,
-} from "../pinia-modules";
-
-function convertSheet(
- sheet: ResourceObject,
- includedList: ResourceObject[],
- rootGetters: any
-): Sheet {
- let project = unknown("PROJECT") as Project;
- let database = unknown("DATABASE") as Database;
-
- const projectId = sheet.attributes.projectId;
- const databaseId = sheet.attributes.databaseId || UNKNOWN_ID;
-
- const databaseStore = useDatabaseStore();
- const projectStore = useProjectStore();
- for (const item of includedList || []) {
- if (item.type == "project" && Number(item.id) === Number(projectId)) {
- project = projectStore.convert(item, includedList);
- }
- if (item.type == "database" && Number(item.id) == Number(databaseId)) {
- database = databaseStore.convert(item, includedList);
- }
- }
-
- return {
- ...(sheet.attributes as Omit<Sheet, "id" | "creator" | "updater">),
- id: parseInt(sheet.id),
- creator: getPrincipalFromIncludedList(
- sheet.relationships!.creator.data,
- includedList
- ) as Principal,
- updater: getPrincipalFromIncludedList(
- sheet.relationships!.updater.data,
- includedList
- ) as Principal,
- project,
- database,
- };
-}
-
-const state: () => SheetState = () => {
- return {
- sheetList: [],
- sheetById: new Map(),
- };
-};
-
-const getters = {
- currentSheet:
- (state: SheetState) =>
- (currentTab: TabInfo): Sheet => {
- if (!currentTab || isEmpty(currentTab)) return unknown("SHEET") as Sheet;
-
- const sheetId = currentTab.sheetId || UNKNOWN_ID;
-
- return state.sheetById.get(sheetId) || (unknown("SHEET") as Sheet);
- },
- isCreator:
- (state: SheetState, getters: any, rootState: any, rootGetters: any) =>
- (currentTab: TabInfo): boolean => {
- const { currentUser } = useAuthStore();
- const currentSheet = getters.currentSheet(currentTab);
-
- if (!currentSheet) return false;
-
- return currentUser.id === currentSheet!.creator.id;
- },
- /**
- * Check the sheet whether is read-only.
- * 1、If the sheet is not created yet, it can not be edited.
- * 2、If the sheet is created by the current user, it can be edited.
- * 3、If the sheet is created by other user, will be checked the visibility of the sheet.
- * a) If the sheet's visibility is private or public, it can be edited only if the current user is the creator of the sheet.
- * b) If the sheet's visibility is project, will be checked whether the current user is the `OWNER` of the project, only the current user is the `OWNER` of the project, it can be edited.
- */
- isReadOnly:
- (state: SheetState, getters: any, rootState: any, rootGetters: any) =>
- (currentTab: TabInfo): boolean => {
- const { currentUser } = useAuthStore();
- const sqlEditorStore = useSQLEditorStore();
- const sharedSheet = sqlEditorStore.sharedSheet;
- const currentSheet = getters.currentSheet(currentTab);
- const isSharedByOthers = sharedSheet.id !== UNKNOWN_ID;
-
- if (!currentSheet) return true;
- // normal sheet can be edit by anyone
- if (!isSharedByOthers) return false;
-
- // if the sheet is shared by others, will be checked the visibility of the sheet.
- // creator always can edit
- if (getters.isCreator(currentTab)) return false;
- const isPrivate = currentSheet?.visibility === "PRIVATE" ?? false;
- const isProject = currentSheet?.visibility === "PROJECT" ?? false;
- const isPublic = currentSheet?.visibility === "PUBLIC" ?? false;
-
- const isCurrentUserProjectOwner = () => {
- const projectMemberList = currentSheet?.project.memberList;
-
- if (projectMemberList && projectMemberList.length > 0) {
- const currentMemberByProjectMember = projectMemberList?.find(
- (member: ProjectMember) => {
- return member.principal.id === currentUser.id;
- }
- );
-
- return currentMemberByProjectMember.role !== "OWNER";
- }
-
- return false;
- };
-
- // if current user is not creator, check the link access level by project relationship
- return (
- isPrivate || isPublic || (isProject && isCurrentUserProjectOwner())
- );
- },
-};
-
-const mutations = {
- [types.SET_SHEET_STATE](state: SheetState, payload: Partial<SheetState>) {
- Object.assign(state, payload);
- },
- [types.SET_SHEET_LIST](state: SheetState, payload: Sheet[]) {
- state.sheetList = payload;
- },
- [types.SET_SHEET_BY_ID](
- state: SheetState,
- { sheetId, sheet }: { sheetId: SheetId; sheet: Sheet }
- ) {
- const item = state.sheetList.find((sheet) => sheet.id === sheetId);
- if (item !== undefined) {
- Object.assign(item, sheet);
- }
- state.sheetById.set(sheetId, sheet);
- },
- [types.DELETE_SHEET](state: SheetState, sheetId: SheetId) {
- const idx = state.sheetList.findIndex((sheet) => sheet.id === sheetId);
- if (idx !== -1) state.sheetList.splice(idx, 1);
-
- if (state.sheetById.has(sheetId)) {
- state.sheetById.delete(sheetId);
- }
- },
-};
-
-type ActionsMap = {
- setSheetState: typeof mutations.SET_SHEET_STATE;
- setSheetList: typeof mutations.SET_SHEET_LIST;
-};
-
-const actions = {
- ...makeActions<ActionsMap>({
- setSheetState: types.SET_SHEET_STATE,
- setSheetList: types.SET_SHEET_LIST,
- }),
- // create
- async createSheet(
- { commit, state, rootState, rootGetters }: any,
- currentTab: TabInfo
- ): Promise<Sheet> {
- const sqlEditorStore = useSQLEditorStore();
- const ctx = sqlEditorStore.connectionContext as ConnectionContext;
-
- const result = (
- await axios.post(`/api/sheet`, {
- data: {
- type: "createSheet",
- attributes: {
- projectId: ctx.projectId,
- databaseId: ctx.databaseId,
- name: currentTab.name,
- statement: currentTab.statement,
- visibility: "PRIVATE",
- },
- },
- })
- ).data;
- const sheet = convertSheet(result.data, result.included, rootGetters);
-
- commit(
- types.SET_SHEET_LIST,
- (state.sheetList as Sheet[])
- .concat(sheet)
- .sort((a, b) => b.createdTs - a.createdTs)
- );
-
- commit(types.SET_SHEET_BY_ID, {
- sheetId: sheet.id,
- sheet: sheet,
- });
-
- return sheet;
- },
- // retrieve
- async fetchSheetList({ commit, dispatch, state, rootGetters }: any) {
- useSQLEditorStore().setSqlEditorState({ isFetchingSheet: true });
- const data = (await axios.get(`/api/sheet`)).data;
- const sheetList: Sheet[] = data.data.map((rawData: ResourceObject) => {
- const sheet = convertSheet(rawData, data.included, rootGetters);
- commit(types.SET_SHEET_BY_ID, {
- sheetId: sheet.id,
- sheet: sheet,
- });
- return sheet;
- });
-
- commit(
- types.SET_SHEET_LIST,
- sheetList.sort((a, b) => b.createdTs - a.createdTs)
- );
- useSQLEditorStore().setSqlEditorState({ isFetchingSheet: false });
- },
- async fetchSheetById(
- { commit, dispatch, state, rootGetters }: any,
- sheetId: SheetId
- ) {
- const data = (await axios.get(`/api/sheet/${sheetId}`)).data;
- const sheet = convertSheet(data.data, data.included, rootGetters);
- commit(types.SET_SHEET_BY_ID, {
- sheetId: sheet.id,
- sheet: sheet,
- });
-
- return sheet;
- },
- // update
- async patchSheetById(
- { commit, dispatch, rootGetters }: any,
- { id, name, statement, visibility }: SheetPatch
- ): Promise<Sheet> {
- const attributes: Omit<SheetPatch, "id"> = {};
- if (name) {
- attributes.name = name;
- }
- if (statement) {
- attributes.statement = statement;
- }
- if (visibility) {
- attributes.visibility = visibility;
- }
-
- const result = (
- await axios.patch(`/api/sheet/${id}`, {
- data: {
- type: "sheetPatch",
- attributes,
- },
- })
- ).data;
-
- const sheet = convertSheet(result.data, result.included, rootGetters);
-
- commit(types.SET_SHEET_BY_ID, {
- sheetId: sheet.id,
- sheet: sheet,
- });
-
- return sheet;
- },
- // delete
- async deleteSheet({ commit, state }: any, id: number) {
- await axios.delete(`/api/sheet/${id}`);
-
- commit(types.DELETE_SHEET, id);
- },
- // upsert
- async upsertSheet(
- { commit, dispatch, state }: any,
- payload: { sheet: Partial<Sheet>; currentTab: TabInfo }
- ): Promise<Sheet> {
- const { sheet, currentTab } = payload;
- const hasSheet = state.sheetById.has(sheet.id);
-
- if (hasSheet) {
- return dispatch("patchSheetById", sheet);
- } else {
- return dispatch("createSheet", currentTab);
- }
- },
-};
-
-export default {
- namespaced: true,
- state,
- getters,
- actions,
- mutations,
-};
diff --git a/frontend/src/store/pinia-modules/index.ts b/frontend/src/store/pinia-modules/index.ts
index 5e0c74631f..8c05ed07d1 100644
--- a/frontend/src/store/pinia-modules/index.ts
+++ b/frontend/src/store/pinia-modules/index.ts
@@ -26,6 +26,7 @@ export * from "./project";
export * from "./projectWebhook";
export * from "./router";
export * from "./setting";
+export * from "./sheet";
export * from "./stage";
export * from "./sql";
export * from "./sqlEditor";
diff --git a/frontend/src/store/pinia-modules/sheet.ts b/frontend/src/store/pinia-modules/sheet.ts
new file mode 100644
index 0000000000..42c7f93058
--- /dev/null
+++ b/frontend/src/store/pinia-modules/sheet.ts
@@ -0,0 +1,275 @@
+import axios from "axios";
+import { isEmpty } from "lodash-es";
+import { defineStore } from "pinia";
+
+import type {
+ Sheet,
+ SheetId,
+ SheetState,
+ SheetPatch,
+ Principal,
+ ResourceObject,
+ TabInfo,
+ Database,
+ Project,
+ ProjectMember,
+} from "@/types";
+import { unknown, UNKNOWN_ID } from "@/types";
+import { getPrincipalFromIncludedList } from "../pinia";
+import {
+ useAuthStore,
+ useDatabaseStore,
+ useProjectStore,
+ useSQLEditorStore,
+ useTabStore,
+} from ".";
+
+function convertSheet(
+ sheet: ResourceObject,
+ includedList: ResourceObject[]
+): Sheet {
+ let project = unknown("PROJECT") as Project;
+ let database = unknown("DATABASE") as Database;
+
+ const projectId = sheet.attributes.projectId;
+ const databaseId = sheet.attributes.databaseId || UNKNOWN_ID;
+
+ const databaseStore = useDatabaseStore();
+ const projectStore = useProjectStore();
+ for (const item of includedList || []) {
+ if (item.type == "project" && Number(item.id) === Number(projectId)) {
+ project = projectStore.convert(item, includedList);
+ }
+ if (item.type == "database" && Number(item.id) == Number(databaseId)) {
+ database = databaseStore.convert(item, includedList);
+ }
+ }
+
+ return {
+ ...(sheet.attributes as Omit<Sheet, "id" | "creator" | "updater">),
+ id: parseInt(sheet.id),
+ creator: getPrincipalFromIncludedList(
+ sheet.relationships!.creator.data,
+ includedList
+ ) as Principal,
+ updater: getPrincipalFromIncludedList(
+ sheet.relationships!.updater.data,
+ includedList
+ ) as Principal,
+ project,
+ database,
+ };
+}
+
+export const useSheetStore = defineStore("sheet", {
+ state: (): SheetState => ({
+ sheetList: [],
+ sheetById: new Map(),
+ }),
+
+ getters: {
+ currentSheet(state) {
+ const currentTab = useTabStore().currentTab;
+
+ if (!currentTab || isEmpty(currentTab)) return unknown("SHEET") as Sheet;
+
+ const sheetId = currentTab.sheetId || UNKNOWN_ID;
+
+ return state.sheetById.get(sheetId) || (unknown("SHEET") as Sheet);
+ },
+ isCreator() {
+ const { currentUser } = useAuthStore();
+ const currentSheet = this.currentSheet as Sheet;
+
+ if (!currentSheet) return false;
+
+ return currentUser.id === currentSheet!.creator.id;
+ },
+ /**
+ * Check the sheet whether is read-only.
+ * 1、If the sheet is not created yet, it can not be edited.
+ * 2、If the sheet is created by the current user, it can be edited.
+ * 3、If the sheet is created by other user, will be checked the visibility of the sheet.
+ * a) If the sheet's visibility is private or public, it can be edited only if the current user is the creator of the sheet.
+ * b) If the sheet's visibility is project, will be checked whether the current user is the `OWNER` of the project, only the current user is the `OWNER` of the project, it can be edited.
+ */
+ isReadOnly() {
+ const sqlEdtiorStore = useSQLEditorStore();
+ const { currentUser } = useAuthStore();
+ const sharedSheet = sqlEdtiorStore.sharedSheet;
+ const currentSheet = this.currentSheet as Sheet;
+ const isSharedByOthers = sharedSheet.id !== UNKNOWN_ID;
+
+ if (!currentSheet) return true;
+ // normal sheet can be edit by anyone
+ if (!isSharedByOthers) return false;
+
+ // if the sheet is shared by others, will be checked the visibility of the sheet.
+ // creator always can edit
+ if (this.isCreator) return false;
+ const isPrivate = currentSheet?.visibility === "PRIVATE" ?? false;
+ const isProject = currentSheet?.visibility === "PROJECT" ?? false;
+ const isPublic = currentSheet?.visibility === "PUBLIC" ?? false;
+
+ const isCurrentUserProjectOwner = () => {
+ const projectMemberList = currentSheet?.project.memberList;
+
+ if (projectMemberList && projectMemberList.length > 0) {
+ const currentMemberByProjectMember = projectMemberList?.find(
+ (member: ProjectMember) => {
+ return member.principal.id === currentUser.id;
+ }
+ ) as ProjectMember;
+
+ return currentMemberByProjectMember.role !== "OWNER";
+ }
+
+ return false;
+ };
+
+ // if current user is not creator, check the link access level by project relationship
+ return (
+ isPrivate || isPublic || (isProject && isCurrentUserProjectOwner())
+ );
+ },
+ },
+
+ actions: {
+ setSheetState(payload: Partial<SheetState>) {
+ Object.assign(this, payload);
+ },
+ setSheetList(payload: Sheet[]) {
+ this.sheetList = payload;
+ },
+ setSheetById({ sheetId, sheet }: { sheetId: SheetId; sheet: Sheet }) {
+ const item = this.sheetList.find((sheet) => sheet.id === sheetId);
+ if (item !== undefined) {
+ Object.assign(item, sheet);
+ }
+ this.sheetById.set(sheetId, sheet);
+ },
+ deleteSheetById(sheetId: SheetId) {
+ const idx = this.sheetList.findIndex((sheet) => sheet.id === sheetId);
+ if (idx !== -1) this.sheetList.splice(idx, 1);
+
+ if (this.sheetById.has(sheetId)) {
+ this.sheetById.delete(sheetId);
+ }
+ },
+ // create
+ async createSheet(currentTab: TabInfo): Promise<Sheet> {
+ const sqlEditorStore = useSQLEditorStore();
+ const ctx = sqlEditorStore.connectionContext;
+
+ const result = (
+ await axios.post(`/api/sheet`, {
+ data: {
+ type: "createSheet",
+ attributes: {
+ projectId: ctx.projectId,
+ databaseId: ctx.databaseId,
+ name: currentTab.name,
+ statement: currentTab.statement,
+ visibility: "PRIVATE",
+ },
+ },
+ })
+ ).data;
+ const sheet = convertSheet(result.data, result.included);
+
+ this.setSheetList(
+ this.sheetList.concat(sheet).sort((a, b) => b.createdTs - a.createdTs)
+ );
+
+ this.setSheetById({
+ sheetId: sheet.id,
+ sheet: sheet,
+ });
+
+ return sheet;
+ },
+ // retrieve
+ async fetchSheetList() {
+ const sqlEditorStore = useSQLEditorStore();
+ sqlEditorStore.setSqlEditorState({ isFetchingSheet: true });
+ const data = (await axios.get(`/api/sheet`)).data;
+ const sheetList: Sheet[] = data.data.map((rawData: ResourceObject) => {
+ const sheet = convertSheet(rawData, data.included);
+ this.setSheetById({
+ sheetId: sheet.id,
+ sheet: sheet,
+ });
+ return sheet;
+ });
+
+ this.setSheetList(sheetList.sort((a, b) => b.createdTs - a.createdTs));
+ sqlEditorStore.setSqlEditorState({ isFetchingSheet: false });
+ },
+ async fetchSheetById(sheetId: SheetId) {
+ const data = (await axios.get(`/api/sheet/${sheetId}`)).data;
+ const sheet = convertSheet(data.data, data.included);
+ this.setSheetById({
+ sheetId: sheet.id,
+ sheet: sheet,
+ });
+
+ return sheet;
+ },
+ // update
+ async patchSheetById({
+ id,
+ name,
+ statement,
+ visibility,
+ }: SheetPatch): Promise<Sheet> {
+ const attributes: Omit<SheetPatch, "id"> = {};
+ if (name) {
+ attributes.name = name;
+ }
+ if (statement) {
+ attributes.statement = statement;
+ }
+ if (visibility) {
+ attributes.visibility = visibility;
+ }
+
+ const result = (
+ await axios.patch(`/api/sheet/${id}`, {
+ data: {
+ type: "sheetPatch",
+ attributes,
+ },
+ })
+ ).data;
+
+ const sheet = convertSheet(result.data, result.included);
+
+ this.setSheetById({
+ sheetId: sheet.id,
+ sheet: sheet,
+ });
+
+ return sheet;
+ },
+ // delete
+ async deleteSheet(id: number) {
+ await axios.delete(`/api/sheet/${id}`);
+
+ this.deleteSheetById(id);
+ },
+ // upsert
+ async upsertSheet(payload: {
+ sheet: Pick<Sheet, "id" | "name" | "statement">;
+ currentTab: TabInfo;
+ }): Promise<Sheet> {
+ const { sheet, currentTab } = payload;
+ const hasSheet = this.sheetById.has(sheet.id);
+
+ if (hasSheet) {
+ return this.patchSheetById(sheet);
+ } else {
+ return this.createSheet(currentTab);
+ }
+ },
+ },
+});
diff --git a/frontend/src/store/pinia-modules/tab.ts b/frontend/src/store/pinia-modules/tab.ts
index 3274358f50..01080af92a 100644
--- a/frontend/src/store/pinia-modules/tab.ts
+++ b/frontend/src/store/pinia-modules/tab.ts
@@ -4,11 +4,6 @@ import { TabInfo, AnyTabInfo, TabState } from "@/types";
import { getDefaultTab } from "@/utils/tab";
export const useTabStore = defineStore("tab", {
- persist: {
- enabled: true,
- strategy: "localStorage",
- },
-
state: (): TabState => ({
tabList: [],
currentTabId: "",
diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.ts
index 794560f7db..130a8fd3be 100644
--- a/frontend/src/types/store.ts
+++ b/frontend/src/types/store.ts
@@ -46,7 +46,6 @@ import { VCS } from "./vcs";
import { Label } from "./label";
import { ConnectionAtom, ConnectionContext } from "./sqlEditor";
import { TabInfo } from "./tab";
-import sheetStore from "../store/modules/sheet";
export interface ActuatorState {
serverInfo?: ServerInfo;
@@ -212,9 +211,6 @@ export interface SheetState {
sheetList: Sheet[];
sheetById: Map<SheetId, Sheet>;
}
-export type SheetGetters = typeof sheetStore.getters;
-export type SheetActions = typeof sheetStore.actions;
-export type SheetMutations = typeof sheetStore.mutations;
export interface DebugState {
isDebug: boolean;
diff --git a/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue b/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue
index 77917a9d55..73d0e1b86b 100644
--- a/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue
+++ b/frontend/src/views/SqlEditor/AsidePanel/SheetContainer.vue
@@ -84,14 +84,10 @@
import { escape } from "lodash-es";
import { computed, reactive, ref, nextTick } from "vue";
import { useI18n } from "vue-i18n";
-import {
- useNamespacedActions,
- useNamespacedState,
-} from "vuex-composition-helpers";
import { useDialog } from "naive-ui";
-import { useTabStore, useSQLEditorStore } from "@/store";
-import { SheetActions, SheetState, Sheet, UNKNOWN_ID } from "@/types";
+import { useTabStore, useSQLEditorStore, useSheetStore } from "@/store";
+import { Sheet, UNKNOWN_ID } from "@/types";
import { getHighlightHTMLByKeyWords } from "@/utils";
import { useSQLEditorConnection } from "@/composables/useSQLEditorConnection";
@@ -107,16 +103,10 @@ const { setConnectionContextFromCurrentTab } = useSQLEditorConnection();
const dialog = useDialog();
const tabStore = useTabStore();
const sqlEditorStore = useSQLEditorStore();
+const sheetStore = useSheetStore();
const isLoading = computed(() => sqlEditorStore.isFetchingSheet);
-const { sheetList } = useNamespacedState<SheetState>("sheet", ["sheetList"]);
-
-const { deleteSheet, patchSheetById } = useNamespacedActions<SheetActions>(
- "sheet",
- ["deleteSheet", "patchSheetById"]
-);
-
const state = reactive<State>({
search: "",
currentSheetName: "",
@@ -129,8 +119,8 @@ const queryNameInputerRef = ref<HTMLInputElement>();
const data = computed(() => {
const filterSheetList =
sqlEditorStore.sharedSheet.id !== UNKNOWN_ID
- ? [...sheetList.value, sqlEditorStore.sharedSheet]
- : sheetList.value;
+ ? [...sheetStore.sheetList, sqlEditorStore.sharedSheet]
+ : sheetStore.sheetList;
const tempData =
filterSheetList && filterSheetList.length > 0
? filterSheetList.filter((sheet) => {
@@ -167,7 +157,7 @@ const notifyMessage = computed(() => {
if (isLoading.value) {
return "";
}
- if (sheetList.value.length === null) {
+ if (sheetStore.sheetList.length === null) {
return t("sql-editor.no-sheet-found");
}
@@ -196,7 +186,7 @@ const handleCancelEdit = () => {
const handleSheetNameChanged = () => {
if (state.editingSheetId) {
- patchSheetById({
+ sheetStore.patchSheetById({
id: state.editingSheetId,
name: state.currentSheetName,
});
@@ -212,7 +202,7 @@ const handleSheetNameChanged = () => {
const handleDeleteSheet = () => {
if (state.currentActionSheet) {
- deleteSheet(state.currentActionSheet.id);
+ sheetStore.deleteSheet(state.currentActionSheet.id);
if (tabStore.currentTab.sheetId === state.currentActionSheet.id) {
tabStore.updateCurrentTab({
diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue
index c264be7de1..8264e90b2b 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorPanel.vue
@@ -28,10 +28,8 @@
<script lang="ts" setup>
import { ref } from "vue";
-import { useNamespacedActions } from "vuex-composition-helpers";
-import { useTabStore, useSQLEditorStore } from "@/store";
-import { SheetActions } from "@/types";
+import { useTabStore, useSQLEditorStore, useSheetStore } from "@/store";
import EditorAction from "./EditorAction.vue";
import QueryEditor from "./QueryEditor.vue";
import ExecuteHint from "./ExecuteHint.vue";
@@ -41,11 +39,7 @@ import { defaultTabName } from "../../../utils/tab";
const tabStore = useTabStore();
const sqlEditorStore = useSQLEditorStore();
-
-// actions
-const { upsertSheet } = useNamespacedActions<SheetActions>("sheet", [
- "upsertSheet",
-]);
+const sheetStore = useSheetStore();
const isShowSaveSheetModal = ref(false);
@@ -64,9 +58,9 @@ const handleSaveSheet = async (sheetName?: string) => {
const { name, statement, sheetId } = tabStore.currentTab;
- const sheet = await upsertSheet({
+ const sheet = await sheetStore.upsertSheet({
sheet: {
- id: sheetId,
+ id: sheetId as number,
name: sheetName ? sheetName : name,
statement,
},
diff --git a/frontend/src/views/SqlEditor/EditorPanel/SharePopover.vue b/frontend/src/views/SqlEditor/EditorPanel/SharePopover.vue
index e9aed97983..73ea7da58e 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/SharePopover.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/SharePopover.vue
@@ -79,14 +79,15 @@
import { ref, computed, onMounted } from "vue";
import { useClipboard } from "@vueuse/core";
import { useI18n } from "vue-i18n";
-import {
- useNamespacedGetters,
- useNamespacedActions,
-} from "vuex-composition-helpers";
import slug from "slug";
-import { pushNotification, useTabStore, useSQLEditorStore } from "@/store";
-import { SheetGetters, SheetActions, AccessOption } from "@/types";
+import {
+ pushNotification,
+ useTabStore,
+ useSQLEditorStore,
+ useSheetStore,
+} from "@/store";
+import { AccessOption } from "@/types";
const emit = defineEmits<{
(e: "close"): void;
@@ -95,6 +96,7 @@ const emit = defineEmits<{
const { t } = useI18n();
const tabStore = useTabStore();
const sqlEditorStore = useSQLEditorStore();
+const sheetStore = useSheetStore();
const accessOptions = computed<AccessOption[]>(() => {
return [
@@ -116,18 +118,10 @@ const accessOptions = computed<AccessOption[]>(() => {
];
});
-const { currentSheet, isCreator } = useNamespacedGetters<SheetGetters>(
- "sheet",
- ["currentSheet", "isCreator"]
-);
-const { patchSheetById } = useNamespacedActions<SheetActions>("sheet", [
- "patchSheetById",
-]);
-
const ctx = computed(() => sqlEditorStore.connectionContext);
-const sheet = computed(() => currentSheet.value(tabStore.currentTab));
-const creator = computed(() => isCreator.value(tabStore.currentTab));
+const sheet = computed(() => sheetStore.currentSheet);
+const creator = computed(() => sheetStore.isCreator);
const host = window.location.host;
const connectionSlug = [
@@ -151,7 +145,7 @@ const creatorAccessDescStyle = computed(() => {
const updateSheet = () => {
if (tabStore.currentTab.sheetId) {
- patchSheetById({
+ sheetStore.patchSheetById({
id: tabStore.currentTab.sheetId,
visibility: currentAccess.value.value,
});
diff --git a/frontend/src/views/SqlEditor/TabListContainer.vue b/frontend/src/views/SqlEditor/TabListContainer.vue
index 2acf5019cd..376cccbccd 100644
--- a/frontend/src/views/SqlEditor/TabListContainer.vue
+++ b/frontend/src/views/SqlEditor/TabListContainer.vue
@@ -119,28 +119,16 @@
import { ref, reactive, nextTick, computed, onMounted, onUnmounted } from "vue";
import { debounce } from "lodash-es";
import { useI18n } from "vue-i18n";
-import {
- useNamespacedGetters,
- useNamespacedActions,
-} from "vuex-composition-helpers";
import { useDialog } from "naive-ui";
-import { pushNotification, useTabStore } from "@/store";
-import { TabInfo, SheetGetters, SheetActions } from "@/types";
+import { pushNotification, useTabStore, useSheetStore } from "@/store";
+import { TabInfo } from "@/types";
import { useSQLEditorConnection } from "@/composables/useSQLEditorConnection";
const tabStore = useTabStore();
+const sheetStore = useSheetStore();
-const { currentSheet } = useNamespacedGetters<SheetGetters>("sheet", [
- "currentSheet",
-]);
-
-const sheet = computed(() => currentSheet.value(tabStore.currentTab));
-
-// actions map
-const { patchSheetById } = useNamespacedActions<SheetActions>("sheet", [
- "patchSheetById",
-]);
+const sheet = computed(() => sheetStore.currentSheet);
const { t } = useI18n();
const { setConnectionContextFromCurrentTab } = useSQLEditorConnection();
@@ -184,7 +172,7 @@ const recalculateScrollWidth = () => {
const updateSheetName = () => {
if (tabStore.currentTab.sheetId) {
- patchSheetById({
+ sheetStore.patchSheetById({
id: tabStore.currentTab.sheetId,
name: labelState.currentLabelName,
});