Skip to content

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

feat: instance pagination in the frontend (#15687)

ecmadaoc2c481383e62
diff --git a/frontend/src/components/AdvancedSearch/useCommonSearchScopeOptions.ts b/frontend/src/components/AdvancedSearch/useCommonSearchScopeOptions.ts
index 9af604732d..be938cd023 100644
--- a/frontend/src/components/AdvancedSearch/useCommonSearchScopeOptions.ts
+++ b/frontend/src/components/AdvancedSearch/useCommonSearchScopeOptions.ts
@@ -10,10 +10,10 @@ import { t } from "@/plugins/i18n";
import {
useEnvironmentV1List,
useEnvironmentV1Store,
- useInstanceResourceList,
+ useInstanceV1Store,
useProjectV1Store,
} from "@/store";
-import type { MaybeRef, ComposedProject } from "@/types";
+import type { MaybeRef, ComposedProject, ComposedInstance } from "@/types";
import { engineToJSON } from "@/types/proto/v1/common";
import type { SearchScopeId } from "@/utils";
import {
@@ -30,9 +30,11 @@ export const useCommonSearchScopeOptions = (
supportOptionIdList: MaybeRef<SearchScopeId[]>
) => {
const projectStore = useProjectV1Store();
+ const instanceStore = useInstanceV1Store();
const environmentStore = useEnvironmentV1Store();
const environmentList = useEnvironmentV1List();
const projectList = ref<ComposedProject[]>([]);
+ const instanceList = ref<ComposedInstance[]>([]);
watchEffect(async () => {
try {
@@ -45,7 +47,16 @@ export const useCommonSearchScopeOptions = (
}
});
- const instanceList = computed(() => useInstanceResourceList().value);
+ watchEffect(async () => {
+ try {
+ const { instances } = await instanceStore.fetchInstanceList({
+ pageSize: getDefaultPagination(),
+ });
+ instanceList.value = instances;
+ } catch {
+ // do nothing
+ }
+ });
// fullScopeOptions provides full search scopes and options.
// we need this as the source of truth.
diff --git a/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepForm.vue b/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepForm.vue
index e710950cde..afddb567db 100644
--- a/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepForm.vue
+++ b/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepForm.vue
@@ -24,8 +24,9 @@
name="instance"
required
:disabled="!allowEditInstance"
+ :project-name="project.name"
:instance-name="state.instanceName"
- :filter="instanceV1HasCreateDatabase"
+ :allowed-engine-list="enginesSupportCreateDatabase()"
@update:instance-name="selectInstance"
/>
</div>
@@ -173,7 +174,6 @@ import {
experimentalCreateIssueByPlan,
useCurrentUserV1,
useInstanceResourceByName,
- useInstanceV1List,
useProjectByName,
} from "@/store";
import {
@@ -191,7 +191,7 @@ import type { Plan_CreateDatabaseConfig } from "@/types/proto/v1/plan_service";
import { Plan, Plan_Spec } from "@/types/proto/v1/plan_service";
import {
instanceV1HasCollationAndCharacterSet,
- instanceV1HasCreateDatabase,
+ enginesSupportCreateDatabase,
} from "@/utils";
import { FeatureModal } from "../FeatureGuard";
@@ -224,8 +224,6 @@ const emit = defineEmits<{
const { t } = useI18n();
const router = useRouter();
const currentUserV1 = useCurrentUserV1();
-// Prepare instance list.
-useInstanceV1List();
const state = reactive<LocalState>({
databaseName: "",
@@ -268,8 +266,8 @@ const allowEditInstance = computed(() => {
return !props.instanceName;
});
-const selectedInstance = computed(() =>
- useInstanceResourceByName(state.instanceName ?? "")
+const selectedInstance = computed(
+ () => useInstanceResourceByName(state.instanceName ?? "").instance.value
);
const showCollationAndCharacterSet = computed((): boolean => {
diff --git a/frontend/src/components/DatabaseGroup/utils.ts b/frontend/src/components/DatabaseGroup/utils.ts
index 5269dff71c..12a06d8691 100644
--- a/frontend/src/components/DatabaseGroup/utils.ts
+++ b/frontend/src/components/DatabaseGroup/utils.ts
@@ -1,11 +1,10 @@
import type { SelectOption } from "naive-ui";
+import { getRenderOptionFunc } from "@/components/CustomApproval/Settings/components/common";
import { type OptionConfig } from "@/components/ExprEditor/context";
+import { getInstanceIdOptions } from "@/components/SensitiveData/components/utils";
import type { Factor } from "@/plugins/cel";
import { useEnvironmentV1Store, useInstanceV1Store } from "@/store";
-import {
- extractEnvironmentResourceName,
- extractInstanceResourceName,
-} from "@/utils";
+import { extractEnvironmentResourceName, getDefaultPagination } from "@/utils";
export const FactorList: Factor[] = [
"resource.environment_name",
@@ -26,8 +25,22 @@ export const getDatabaseGroupOptionConfigMap = () => {
options = getEnvironmentOptions();
break;
case "resource.instance_id":
- options = getInstanceIdOptions();
- break;
+ const store = useInstanceV1Store();
+ map.set(factor, {
+ remote: true,
+ options: [],
+ search: async (keyword: string) => {
+ return store
+ .fetchInstanceList({
+ pageSize: getDefaultPagination(),
+ filter: {
+ query: keyword,
+ },
+ })
+ .then((resp) => getInstanceIdOptions(resp.instances));
+ },
+ });
+ return map;
}
map.set(factor, {
remote: false,
@@ -44,16 +57,7 @@ const getEnvironmentOptions = () => {
return {
label: environmentName,
value: env.name,
- };
- });
-};
-
-const getInstanceIdOptions = () => {
- return useInstanceV1Store().instanceList.map<SelectOption>((instance) => {
- const instanceId = extractInstanceResourceName(instance.name);
- return {
- label: instanceId,
- value: instanceId,
+ render: getRenderOptionFunc(env),
};
});
};
diff --git a/frontend/src/components/Instance/InstanceArchiveRestoreButton.vue b/frontend/src/components/Instance/InstanceArchiveRestoreButton.vue
index 4920117dfd..4644b45dc2 100644
--- a/frontend/src/components/Instance/InstanceArchiveRestoreButton.vue
+++ b/frontend/src/components/Instance/InstanceArchiveRestoreButton.vue
@@ -60,6 +60,7 @@ import { BBButtonConfirm } from "@/bbkit";
import {
useInstanceV1Store,
pushNotification,
+ useActuatorV1Store,
useSubscriptionV1Store,
} from "@/store";
import type { ComposedInstance } from "@/types";
@@ -81,6 +82,7 @@ const state = reactive<LocalState>({
const { t } = useI18n();
const instanceStore = useInstanceV1Store();
+const actuatorStore = useActuatorV1Store();
const subscriptionStore = useSubscriptionV1Store();
const force = ref(false);
@@ -104,7 +106,7 @@ const archiveOrRestoreInstance = async (archive: boolean) => {
});
} else {
if (
- subscriptionStore.instanceCountLimit <= instanceStore.instanceList.length
+ subscriptionStore.instanceCountLimit <= actuatorStore.totalInstanceCount
) {
state.showFeatureModal = true;
return;
diff --git a/frontend/src/components/InstanceAssignment.vue b/frontend/src/components/InstanceAssignment.vue
index 268f6c7e61..cb48dc0948 100644
--- a/frontend/src/components/InstanceAssignment.vue
+++ b/frontend/src/components/InstanceAssignment.vue
@@ -18,86 +18,34 @@
/>
</div>
<div class="mt-1 text-4xl flex items-center gap-x-2">
- <span>{{ assignedLicenseCount }}</span>
+ <span>
+ {{ actuatorStore.activatedInstanceCount }}
+ </span>
<span class="text-xl">/</span>
<span>{{ totalLicenseCount }}</span>
</div>
</div>
- <BBGrid
- class="border"
- :column-list="columnList"
- :data-source="instanceList"
- :show-header="true"
- :custom-header="true"
- :row-clickable="false"
- >
- <template #header>
- <div role="table-row" class="bb-grid-row bb-grid-header-row group">
- <div
- v-for="(column, index) in columnList"
- :key="index"
- role="table-cell"
- class="bb-grid-header-cell capitalize"
- :class="[column.class]"
- >
- <template v-if="index === 0 && canManageSubscription">
- <NCheckbox
- v-if="instanceList.length > 0"
- v-bind="allSelectionState"
- :disabled="
- !allSelectionState.checked &&
- instanceList.length > instanceLicenseCount
- "
- @update:checked="selectAllInstances($event)"
- />
- </template>
- <template v-else>{{ column.title }}</template>
- </div>
- </div>
- </template>
- <template #item="{ item: instance }: { item: InstanceResource }">
- <div
- v-if="canManageSubscription"
- class="bb-grid-cell"
- @click.stop.prevent
- >
- <NCheckbox
- :checked="isInstanceSelected(instance)"
- :disabled="
- !isInstanceSelected(instance) &&
- state.selectedInstance.size == instanceLicenseCount
- "
- @update:checked="toggleSelectInstance(instance, $event)"
- />
- </div>
- <div class="bb-grid-cell">
- <div class="flex items-center gap-x-1">
- <InstanceV1EngineIcon :instance="instance" />
- <router-link
- :to="`/${instance.name}`"
- class="hover:underline"
- active-class="link"
- exact-active-class="link"
- >
- {{ instanceV1Name(instance) }}
- </router-link>
- </div>
- </div>
- <div class="bb-grid-cell">
- <EnvironmentV1Name
- :environment="
- environmentStore.getEnvironmentByName(instance.environment)
- "
- :link="false"
- />
- </div>
- <div class="bb-grid-cell">
- <EllipsisText class="w-10">
- {{ hostPortOfInstanceV1(instance) }}
- </EllipsisText>
- </div>
- </template>
- </BBGrid>
+
+ <AdvancedSearch
+ v-model:params="state.params"
+ :autofocus="false"
+ :placeholder="$t('instance.filter-instance-name')"
+ :scope-options="scopeOptions"
+ />
+ <PagedInstanceTable
+ ref="pagedInstanceTableRef"
+ session-key="bb.instance-table"
+ :bordered="true"
+ :filter="filter"
+ :show-address="false"
+ :show-external-link="false"
+ :show-selection="canManageSubscription"
+ :selected-instance-names="Array.from(state.selectedInstance)"
+ :disabled-selected-instance-names="disabledSelectedInstanceNames"
+ @update:selected-instance-names="
+ (list) => (state.selectedInstance = new Set(list))
+ "
+ />
</div>
<template #footer>
@@ -126,32 +74,26 @@
</template>
<script lang="ts" setup>
-import { NButton, NCheckbox } from "naive-ui";
+import { NButton } from "naive-ui";
import { storeToRefs } from "pinia";
-import { reactive, computed, watchEffect } from "vue";
+import { reactive, computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
-import type { BBGridColumn } from "@/bbkit";
-import { BBGrid } from "@/bbkit";
-import EllipsisText from "@/components/EllipsisText.vue";
-import { EnvironmentV1Name, InstanceV1EngineIcon } from "@/components/v2";
+import AdvancedSearch from "@/components/AdvancedSearch";
+import { useCommonSearchScopeOptions } from "@/components/AdvancedSearch/useCommonSearchScopeOptions";
+import { PagedInstanceTable } from "@/components/v2";
import { Drawer, DrawerContent } from "@/components/v2";
import {
pushNotification,
useInstanceV1Store,
useSubscriptionV1Store,
useDatabaseV1Store,
- useInstanceResourceList,
- useEnvironmentV1Store,
+ useActuatorV1Store,
} from "@/store";
-import {
- Instance,
- type InstanceResource,
-} from "@/types/proto/v1/instance_service";
-import {
- instanceV1Name,
- hostPortOfInstanceV1,
- hasWorkspacePermissionV2,
-} from "@/utils";
+import { environmentNamePrefix } from "@/store/modules/v1/common";
+import { engineFromJSON } from "@/types/proto/v1/common";
+import { Instance } from "@/types/proto/v1/instance_service";
+import { PlanType } from "@/types/proto/v1/subscription_service";
+import { type SearchParams, hasWorkspacePermissionV2 } from "@/utils";
import LearnMoreLink from "./LearnMoreLink.vue";
const props = withDefaults(
@@ -166,6 +108,7 @@ const props = withDefaults(
);
interface LocalState {
+ params: SearchParams;
selectedInstance: Set<string>;
processing: boolean;
}
@@ -173,58 +116,85 @@ interface LocalState {
const emit = defineEmits(["dismiss"]);
const state = reactive<LocalState>({
+ params: {
+ query: "",
+ scopes: [],
+ },
selectedInstance: new Set(),
processing: false,
});
-const environmentStore = useEnvironmentV1Store();
+
const instanceV1Store = useInstanceV1Store();
const databaseV1Store = useDatabaseV1Store();
const subscriptionStore = useSubscriptionV1Store();
+const actuatorStore = useActuatorV1Store();
const { t } = useI18n();
-
-const instanceList = useInstanceResourceList();
+const pagedInstanceTableRef = ref<InstanceType<typeof PagedInstanceTable>>();
const { instanceLicenseCount } = storeToRefs(subscriptionStore);
-const columnList = computed(() => {
- const resp: BBGridColumn[] = [
- {
- title: t("common.name"),
- width: "minmax(min-content, auto)",
- },
- {
- title: t("common.environment"),
- width: "minmax(min-content, auto)",
- },
- {
- title: t("common.address"),
- width: "minmax(min-content, auto)",
- },
- ];
- if (canManageSubscription.value) {
- resp.unshift({
- // This column is for selection input.
- title: "",
- width: "minmax(auto, 3rem)",
- });
+const scopeOptions = computed(
+ () => useCommonSearchScopeOptions(["environment", "engine"]).value
+);
+
+const selectedEnvironment = computed(() => {
+ const environmentId = state.params.scopes.find(
+ (scope) => scope.id === "environment"
+ )?.value;
+ if (!environmentId) {
+ return;
}
- return resp;
+ return `${environmentNamePrefix}${environmentId}`;
+});
+
+const selectedEngines = computed(() => {
+ return state.params.scopes
+ .filter((scope) => scope.id === "engine")
+ .map((scope) => engineFromJSON(scope.value));
});
+const filter = computed(() => ({
+ environment: selectedEnvironment.value,
+ query: state.params.query,
+ engines: selectedEngines.value,
+}));
+
const canManageSubscription = computed((): boolean => {
- return hasWorkspacePermissionV2("bb.instances.update");
+ return (
+ hasWorkspacePermissionV2("bb.instances.update") &&
+ subscriptionStore.currentPlan !== PlanType.FREE
+ );
});
-watchEffect(() => {
- for (const instance of instanceList.value) {
- if (instance.activation) {
- state.selectedInstance.add(instance.name);
- }
- }
- for (const instance of props.selectedInstanceList) {
- state.selectedInstance.add(instance);
- }
+const disabledSelectedInstanceNames = computed(() => {
+ return new Set(
+ pagedInstanceTableRef.value?.dataList
+ ?.filter((ins) => ins.activation)
+ ?.map((ins) => ins.name) ?? []
+ );
});
+watch(
+ () => props.selectedInstanceList,
+ () => {
+ for (const instanceName of props.selectedInstanceList) {
+ state.selectedInstance.add(instanceName);
+ }
+ },
+ { immediate: true }
+);
+
+watch(
+ () => pagedInstanceTableRef.value?.dataList ?? [],
+ (dataList) => {
+ for (const instance of dataList) {
+ if (instance.activation) {
+ state.selectedInstance.add(instance.name);
+ }
+ }
+ },
+ { deep: true, immediate: true }
+);
+
const totalLicenseCount = computed((): string => {
if (instanceLicenseCount.value === Number.MAX_VALUE) {
return t("subscription.unlimited");
@@ -232,55 +202,10 @@ const totalLicenseCount = computed((): string => {
return `${instanceLicenseCount.value}`;
});
-const assignedLicenseCount = computed((): string => {
- return `${state.selectedInstance.size}`;
-});
-
-const isInstanceSelected = (instance: InstanceResource): boolean => {
- return state.selectedInstance.has(instance.name);
-};
-
-const allSelectionState = computed(() => {
- const checked =
- state.selectedInstance.size > 0 &&
- instanceList.value.every((instance) =>
- state.selectedInstance.has(instance.name)
- );
- const indeterminate =
- !checked &&
- instanceList.value.some((instance) =>
- state.selectedInstance.has(instance.name)
- );
-
- return {
- checked,
- indeterminate,
- };
-});
-
-const toggleSelectInstance = (
- instance: InstanceResource,
- selected: boolean
-) => {
- if (selected) {
- state.selectedInstance.add(instance.name);
- } else {
- state.selectedInstance.delete(instance.name);
- }
-};
-
-const selectAllInstances = (selected: boolean): void => {
- for (const instance of instanceList.value) {
- toggleSelectInstance(instance, selected);
- }
-};
-
const assignmentChanged = computed(() => {
- for (const instance of instanceList.value) {
- if (instance.activation && !state.selectedInstance.has(instance.name)) {
- return true;
- }
- if (!instance.activation && state.selectedInstance.has(instance.name)) {
+ for (const instanceName of state.selectedInstance) {
+ const instance = instanceV1Store.getInstanceByName(instanceName);
+ if (!instance.activation) {
return true;
}
}
@@ -297,27 +222,9 @@ const updateAssignment = async () => {
}
state.processing = true;
- const selectedInstanceName = new Set(state.selectedInstance);
- // deactivate instance first to avoid quota limitation.
- for (const instance of instanceList.value) {
- if (instance.activation && !selectedInstanceName.has(instance.name)) {
- // deactivate instance
- instance.activation = false;
- const composedInstance = await instanceV1Store.updateInstance(
- Instance.fromPartial(instance),
- ["activation"]
- );
- databaseV1Store.updateDatabaseInstance(composedInstance);
- }
- if (instance.activation && selectedInstanceName.has(instance.name)) {
- // remove unchanged
- selectedInstanceName.delete(instance.name);
- }
- }
-
- for (const instanceName of selectedInstanceName.values()) {
- const instance = instanceList.value.find((i) => i.name === instanceName);
- if (!instance) {
+ for (const instanceName of state.selectedInstance) {
+ const instance = instanceV1Store.getInstanceByName(instanceName);
+ if (instance.activation) {
continue;
}
// activate instance
@@ -329,6 +236,9 @@ const updateAssignment = async () => {
databaseV1Store.updateDatabaseInstance(composedInstance);
}
+ // refresh activatedInstanceCount
+ await actuatorStore.fetchServerInfo();
+
pushNotification({
module: "bytebase",
style: "SUCCESS",
diff --git a/frontend/src/components/IssueV1/logic/plan.ts b/frontend/src/components/IssueV1/logic/plan.ts
index 93e1dc71a2..3b602f91f1 100644
--- a/frontend/src/components/IssueV1/logic/plan.ts
+++ b/frontend/src/components/IssueV1/logic/plan.ts
@@ -28,7 +28,7 @@ export const databaseForSpec = (
if (createDatabaseConfig !== undefined) {
const instanceName = createDatabaseConfig.target;
const databaseName = createDatabaseConfig.database;
- const instance = useInstanceResourceByName(instanceName);
+ const { instance } = useInstanceResourceByName(instanceName);
return {
...unknownDatabase(),
name: `${instanceName}/databases/${databaseName}`,
@@ -36,11 +36,11 @@ export const databaseForSpec = (
instance: instanceName,
project: issue.project,
projectEntity: issue.projectEntity,
- effectiveEnvironment: instance.environment,
+ effectiveEnvironment: instance.value.environment,
effectiveEnvironmentEntity: environmentStore.getEnvironmentByName(
- instance.environment
+ instance.value.environment
),
- instanceResource: instance,
+ instanceResource: instance.value,
};
} else if (
changeDatabaseConfig !== undefined ||
diff --git a/frontend/src/components/IssueV1/logic/utils.ts b/frontend/src/components/IssueV1/logic/utils.ts
index b44e1da446..54f5ecf296 100644
--- a/frontend/src/components/IssueV1/logic/utils.ts
+++ b/frontend/src/components/IssueV1/logic/utils.ts
@@ -83,7 +83,7 @@ export const extractCoreDatabaseInfoFromDatabaseCreateTask = (
}
const environmentStore = useEnvironmentV1Store();
- const instance = useInstanceResourceByName(instanceName);
+ const { instance } = useInstanceResourceByName(instanceName);
return {
...unknownDatabase(),
name,
@@ -91,11 +91,11 @@ export const extractCoreDatabaseInfoFromDatabaseCreateTask = (
instance: instanceName,
project: project.name,
projectEntity: project,
- effectiveEnvironment: instance.environment,
+ effectiveEnvironment: instance.value.environment,
effectiveEnvironmentEntity: environmentStore.getEnvironmentByName(
- instance.environment
+ instance.value.environment
),
- instanceResource: instance,
+ instanceResource: instance.value,
};
};
diff --git a/frontend/src/components/ProjectDatabasesPanel.vue b/frontend/src/components/ProjectDatabasesPanel.vue
index e66a135e03..6ce15dedcc 100644
--- a/frontend/src/components/ProjectDatabasesPanel.vue
+++ b/frontend/src/components/ProjectDatabasesPanel.vue
@@ -70,6 +70,7 @@ import type { SearchParams, SearchScope } from "@/utils";
import {
CommonFilterScopeIdList,
extractProjectResourceName,
+ hasProjectPermissionV2,
hasWorkspacePermissionV2,
} from "@/utils";
import AdvancedSearch from "./AdvancedSearch";
@@ -120,7 +121,7 @@ const pagedDatabaseTableRef = ref<InstanceType<typeof PagedDatabaseTable>>();
const allowToCreateDB = computed(() => {
return (
hasWorkspacePermissionV2("bb.instances.list") &&
- hasWorkspacePermissionV2("bb.issues.create")
+ hasProjectPermissionV2(props.project, "bb.issues.create")
);
});
diff --git a/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vue b/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vue
index 4b2b36cf37..96e8919f84 100644
--- a/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vue
+++ b/frontend/src/components/SensitiveData/GlobalMaskingRulesView.vue
@@ -134,8 +134,8 @@ import {
featureToRef,
pushNotification,
usePolicyV1Store,
- useInstanceV1List,
useProjectV1Store,
+ useInstanceV1Store,
} from "@/store";
import type { Policy } from "@/types/proto/v1/org_policy_service";
import {
@@ -178,7 +178,6 @@ const state = reactive<LocalState>({
reorderRules: false,
});
-useInstanceV1List();
const policyStore = usePolicyV1Store();
const hasPermission = computed(() => {
return hasWorkspacePermissionV2("bb.policies.update");
@@ -357,8 +356,22 @@ const factorOptionsMap = computed((): Map<Factor, OptionConfig> => {
options = getEnvironmentIdOptions();
break;
case "instance_id":
- options = getInstanceIdOptions();
- break;
+ const store = useInstanceV1Store();
+ map.set(factor, {
+ remote: true,
+ options: [],
+ search: async (keyword: string) => {
+ return store
+ .fetchInstanceList({
+ pageSize: getDefaultPagination(),
+ filter: {
+ query: keyword,
+ },
+ })
+ .then((resp) => getInstanceIdOptions(resp.instances));
+ },
+ });
+ return map;
case "project_id":
const projectStore = useProjectV1Store();
map.set(factor, {
diff --git a/frontend/src/components/SensitiveData/components/utils.ts b/frontend/src/components/SensitiveData/components/utils.ts
index bfa17c902e..8d9556a1fa 100644
--- a/frontend/src/components/SensitiveData/components/utils.ts
+++ b/frontend/src/components/SensitiveData/components/utils.ts
@@ -3,7 +3,8 @@ import type { SelectOption } from "naive-ui";
import { getRenderOptionFunc } from "@/components/CustomApproval/Settings/components/common";
import type { Factor, Operator } from "@/plugins/cel";
import { EqualityOperatorList, CollectionOperatorList } from "@/plugins/cel";
-import { useInstanceResourceList, useSettingV1Store } from "@/store";
+import { useSettingV1Store } from "@/store";
+import type { ComposedInstance } from "@/types";
import type { Algorithm } from "@/types/proto/v1/setting_service";
import { extractInstanceResourceName } from "@/utils";
@@ -26,9 +27,8 @@ export const getClassificationLevelOptions = () => {
}));
};
-export const getInstanceIdOptions = () => {
- const instanceList = useInstanceResourceList();
- return instanceList.value.map<SelectOption>((ins) => {
+export const getInstanceIdOptions = (instanceList: ComposedInstance[]) => {
+ return instanceList.map<SelectOption>((ins) => {
const instanceId = extractInstanceResourceName(ins.name);
return {
label: `${ins.title} (${instanceId})`,
diff --git a/frontend/src/components/TransferDatabaseForm/TransferDatabaseForm.vue b/frontend/src/components/TransferDatabaseForm/TransferDatabaseForm.vue
index 806b6bebd6..07b3113545 100644
--- a/frontend/src/components/TransferDatabaseForm/TransferDatabaseForm.vue
+++ b/frontend/src/components/TransferDatabaseForm/TransferDatabaseForm.vue
@@ -6,14 +6,11 @@
<div class="space-y-4">
<TransferSourceSelector
v-model:transfer-source="state.transferSource"
- :project="project"
- :environment-filter="state.environmentFilter"
- :instance-filter="state.instanceFilter"
- :search-text="state.searchText"
+ v-model:search-text="state.searchText"
+ v-model:environment="state.environmentFilter"
+ v-model:instance="state.instanceFilter"
+ :source-project-name="sourceProject.name"
:has-permission-for-default-project="hasPermissionForDefaultProject"
- @select-environment="state.environmentFilter = $event"
- @select-instance="state.instanceFilter = $event"
- @search-text-change="state.searchText = $event"
/>
<ProjectSelect
v-if="state.transferSource == 'OTHER'"
@@ -32,7 +29,7 @@
<div v-else class="w-full relative">
<PagedDatabaseTable
mode="PROJECT"
- :parent="databaseParent"
+ :parent="sourceProjectName"
:filter="filter"
:show-selection="true"
:custom-click="true"
@@ -142,7 +139,7 @@ const state = reactive<LocalState>({
});
const { project } = useProjectByName(toRef(props, "projectName"));
-const databaseParent = computed(() => {
+const sourceProjectName = computed(() => {
if (state.transferSource === "DEFAULT") {
return DEFAULT_PROJECT_NAME;
}
@@ -152,6 +149,8 @@ const databaseParent = computed(() => {
return DEFAULT_PROJECT_NAME;
});
+const { project: sourceProject } = useProjectByName(sourceProjectName);
+
const filter = computed(() => ({
instance: state.instanceFilter?.name,
environment: state.environmentFilter?.name,
diff --git a/frontend/src/components/TransferDatabaseForm/TransferSourceSelector.vue b/frontend/src/components/TransferDatabaseForm/TransferSourceSelector.vue
index e2aefe5982..110a531693 100644
--- a/frontend/src/components/TransferDatabaseForm/TransferSourceSelector.vue
+++ b/frontend/src/components/TransferDatabaseForm/TransferSourceSelector.vue
@@ -3,7 +3,7 @@
<div
class="flex flex-col md:flex-row md:items-center gap-y-2 justify-between"
>
- <div v-if="project.name !== DEFAULT_PROJECT_NAME" class="radio-set-row">
+ <div class="radio-set-row">
<NRadioGroup
:value="transferSource"
class="space-x-4"
@@ -21,19 +21,20 @@
<NInputGroup style="width: auto">
<EnvironmentSelect
class="!w-40"
- :environment-name="environmentFilter?.name"
+ :environment-name="environment?.name"
@update:environment-name="changeEnvironmentFilter"
/>
<InstanceSelect
class="!w-40"
- :instance="instanceFilter?.name"
+ :project-name="sourceProjectName"
+ :instance="instance?.name"
@update:instance-name="changeInstanceFilter"
/>
<SearchBox
class="!w-40"
:value="searchText"
:placeholder="$t('database.filter-database')"
- @update:value="$emit('search-text-change', $event)"
+ @update:value="$emit('update:search-text', $event)"
/>
</NInputGroup>
</div>
@@ -47,54 +48,49 @@
import { NInputGroup, NRadio, NRadioGroup } from "naive-ui";
import { InstanceSelect, SearchBox } from "@/components/v2";
import { useEnvironmentV1Store, useInstanceResourceByName } from "@/store";
-import {
- DEFAULT_PROJECT_NAME,
- isValidEnvironmentName,
- isValidInstanceName,
-} from "@/types";
+import { isValidEnvironmentName, isValidInstanceName } from "@/types";
import type { Environment } from "@/types/proto/v1/environment_service";
import type { InstanceResource } from "@/types/proto/v1/instance_service";
-import type { Project } from "@/types/proto/v1/project_service";
import EnvironmentSelect from "../v2/Select/EnvironmentSelect.vue";
import type { TransferSource } from "./utils";
withDefaults(
defineProps<{
- project: Project;
+ sourceProjectName: string;
transferSource: TransferSource;
hasPermissionForDefaultProject: boolean;
- instanceFilter?: InstanceResource;
- environmentFilter?: Environment;
+ instance?: InstanceResource;
+ environment?: Environment;
searchText: string;
}>(),
{
- instanceFilter: undefined,
- environmentFilter: undefined,
+ instance: undefined,
+ environment: undefined,
searchText: "",
}
);
const emit = defineEmits<{
(event: "update:transferSource", src: TransferSource): void;
- (event: "select-instance", instance: InstanceResource | undefined): void;
- (event: "select-environment", env: Environment | undefined): void;
- (event: "search-text-change", searchText: string): void;
+ (event: "update:instance", instance: InstanceResource | undefined): void;
+ (event: "update:environment", env: Environment | undefined): void;
+ (event: "update:search-text", searchText: string): void;
}>();
const changeEnvironmentFilter = (name: string | undefined) => {
if (!isValidEnvironmentName(name)) {
- return emit("select-environment", undefined);
+ return emit("update:environment", undefined);
}
emit(
- "select-environment",
+ "update:environment",
useEnvironmentV1Store().getEnvironmentByName(name)
);
};
const changeInstanceFilter = (name: string | undefined) => {
if (!isValidInstanceName(name)) {
- return emit("select-instance", undefined);
+ return emit("update:instance", undefined);
}
- emit("select-instance", useInstanceResourceByName(name));
+ emit("update:instance", useInstanceResourceByName(name).instance.value);
};
</script>
diff --git a/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseOperations.vue b/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseOperations.vue
index 3bbf9a1d47..328a81af8d 100644
--- a/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseOperations.vue
+++ b/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseOperations.vue
@@ -473,7 +473,7 @@ const actions = computed((): DatabaseAction[] => {
});
break;
case "TRANSFER-IN": {
- if (operationsInProjectDetail.value) {
+ if (operationsInProjectDetail.value && !isInDefaultProject.value) {
resp.push({
icon: h(ChevronsDownIcon),
text: t("quick-action.transfer-in-db"),
diff --git a/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceOperations.vue b/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceOperations.vue
index ed9f8899c5..eebd8a003a 100644
--- a/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceOperations.vue
+++ b/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceOperations.vue
@@ -42,8 +42,13 @@ import { computed, h, reactive } from "vue";
import { useI18n } from "vue-i18n";
import InstanceSyncButton from "@/components/Instance/InstanceSyncButton.vue";
import InstanceAssignment from "@/components/InstanceAssignment.vue";
-import { useInstanceV1Store, pushNotification } from "@/store";
+import {
+ useInstanceV1Store,
+ useSubscriptionV1Store,
+ pushNotification,
+} from "@/store";
import type { ComposedInstance } from "@/types";
+import { PlanType } from "@/types/proto/v1/subscription_service";
import { hasWorkspacePermissionV2 } from "@/utils";
interface Action {
@@ -65,11 +70,16 @@ const props = defineProps<{
const { t } = useI18n();
const instanceStore = useInstanceV1Store();
+const subscriptionStore = useSubscriptionV1Store();
const state = reactive<LocalState>({
loading: false,
showAssignLicenseDrawer: false,
});
+const canAssignLicense = computed(() => {
+ return subscriptionStore.currentPlan !== PlanType.FREE;
+});
+
const actions = computed((): Action[] => {
const list: Action[] = [
// We'll always show the sync button, even if the user doesn't have the permission to sync.
@@ -88,7 +98,10 @@ const actions = computed((): Action[] => {
},
];
- if (hasWorkspacePermissionV2("bb.instances.update")) {
+ if (
+ hasWorkspacePermissionV2("bb.instances.update") &&
+ canAssignLicense.value
+ ) {
list.push({
icon: h(GraduationCapIcon),
text: t("subscription.instance-assignment.assign-license"),
diff --git a/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceV1Table.vue b/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceV1Table.vue
index 8f1fdc6354..89712a4985 100644
--- a/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceV1Table.vue
+++ b/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceV1Table.vue
@@ -1,28 +1,21 @@
<template>
- <div class="space-y-2">
- <InstanceOperations
- v-if="showOperation"
- :instance-list="selectedInstanceList"
- />
-
- <NDataTable
- key="instance-table"
- size="small"
- :columns="columnList"
- :data="instanceList"
- :striped="true"
- :bordered="bordered"
- :loading="loading"
- :row-key="(data: ComposedInstance) => data.name"
- :checked-row-keys="Array.from(state.selectedInstance)"
- :row-props="rowProps"
- :pagination="{ pageSize: 20 }"
- :paginate-single-page="false"
- @update:checked-row-keys="
- (val) => (state.selectedInstance = new Set(val as string[]))
+ <NDataTable
+ key="instance-table"
+ size="small"
+ :columns="columnList"
+ :data="instanceList"
+ :striped="true"
+ :bordered="bordered"
+ :loading="loading"
+ :row-key="(data: ComposedInstance) => data.name"
+ :checked-row-keys="selectedInstanceNames"
+ :row-props="rowProps"
+ :pagination="{ pageSize: 20 }"
+ :paginate-single-page="false"
+ @update:checked-row-keys="
+ (val) => $emit('update:selected-instance-names', val as string[])
"
- />
- </div>
+ />
</template>
<script setup lang="tsx">
@@ -39,14 +32,12 @@ import { InstanceV1Name } from "@/components/v2";
import type { ComposedInstance } from "@/types";
import { urlfy, hostPortOfInstanceV1, hostPortOfDataSource } from "@/utils";
import EnvironmentV1Name from "../../EnvironmentV1Name.vue";
-import InstanceOperations from "./InstanceOperations.vue";
type InstanceDataTableColumn = DataTableColumn<ComposedInstance> & {
hide?: boolean;
};
interface LocalState {
- selectedInstance: Set<string>;
dataSourceToggle: Set<string>;
processing: boolean;
}
@@ -57,25 +48,32 @@ const props = withDefaults(
bordered?: boolean;
loading?: boolean;
showSelection?: boolean;
- showOperation?: boolean;
- canAssignLicense?: boolean;
defaultExpandDataSource?: string[];
+ selectedInstanceNames?: string[];
+ disabledSelectedInstanceNames?: Set<string>;
+ showAddress?: boolean;
+ showExternalLink?: boolean;
onClick?: (instance: ComposedInstance, e: MouseEvent) => void;
}>(),
{
bordered: true,
showSelection: true,
- showOperation: true,
- canAssignLicense: true,
onClick: undefined,
+ showAddress: true,
+ showExternalLink: true,
+ disabledSelectedInstanceNames: () => new Set(),
defaultExpandDataSource: () => [],
+ selectedInstanceNames: () => [],
}
);
+defineEmits<{
+ (event: "update:selected-instance-names", val: string[]): void;
+}>();
+
const { t } = useI18n();
const router = useRouter();
const state = reactive<LocalState>({
- selectedInstance: new Set(),
dataSourceToggle: new Set(),
processing: false,
});
@@ -95,6 +93,8 @@ const columnList = computed((): InstanceDataTableColumn[] => {
const SELECTION: InstanceDataTableColumn = {
type: "selection",
hide: !props.showSelection,
+ disabled: (instance) =>
+ props.disabledSelectedInstanceNames.has(instance.name),
cellProps: () => {
return {
onClick: (e: MouseEvent) => {
@@ -127,6 +127,7 @@ const columnList = computed((): InstanceDataTableColumn[] => {
key: "address",
title: t("common.address"),
resizable: true,
+ hide: !props.showAddress,
render: (instance) => {
return (
<div class={"flex items-start gap-x-2"}>
@@ -159,6 +160,7 @@ const columnList = computed((): InstanceDataTableColumn[] => {
title: t("instance.external-link"),
resizable: true,
width: 150,
+ hide: !props.showExternalLink,
render: (instance) =>
instance.externalLink?.trim().length !== 0 && (
<NButton
@@ -209,10 +211,4 @@ const rowProps = (instance: ComposedInstance) => {
},
};
};
-
-const selectedInstanceList = computed(() => {
- return props.instanceList.filter((instance) =>
- state.selectedInstance.has(instance.name)
- );
-});
</script>
diff --git a/frontend/src/components/v2/Model/Instance/PagedInstanceTable.vue b/frontend/src/components/v2/Model/Instance/PagedInstanceTable.vue
new file mode 100644
index 0000000000..aabbca431e
--- /dev/null
+++ b/frontend/src/components/v2/Model/Instance/PagedInstanceTable.vue
@@ -0,0 +1,66 @@
+<template>
+ <PagedTable
+ ref="instancePagedTable"
+ :session-key="sessionKey"
+ :fetch-list="fetchInstances"
+ >
+ <template #table="{ list, loading }">
+ <InstanceV1Table
+ v-bind="$attrs"
+ :loading="loading"
+ :instance-list="list"
+ />
+ </template>
+ </PagedTable>
+</template>
+
+<script lang="tsx" setup>
+import { ref, watch, computed } from "vue";
+import type { ComponentExposed } from "vue-component-type-helpers";
+import PagedTable from "@/components/v2/Model/PagedTable.vue";
+import { useInstanceV1Store, type InstanceFilter } from "@/store";
+import { type ComposedInstance } from "@/types";
+import InstanceV1Table from "./InstanceV1Table";
+
+const props = defineProps<{
+ filter?: InstanceFilter;
+ sessionKey: string;
+}>();
+
+const instanceStore = useInstanceV1Store();
+
+const instancePagedTable =
+ ref<ComponentExposed<typeof PagedTable<ComposedInstance>>>();
+
+const fetchInstances = async ({
+ pageToken,
+ pageSize,
+}: {
+ pageToken: string;
+ pageSize: number;
+}) => {
+ const { nextPageToken, instances } = await instanceStore.fetchInstanceList({
+ pageToken,
+ pageSize,
+ filter: props.filter,
+ });
+ return {
+ nextPageToken: nextPageToken ?? "",
+ list: instances,
+ };
+};
+
+watch(
+ () => props.filter,
+ () => instancePagedTable.value?.refresh(),
+ { deep: true }
+);
+
+defineExpose({
+ updateCache: (instances: ComposedInstance[]) => {
+ instancePagedTable.value?.updateCache(instances);
+ },
+ refresh: () => instancePagedTable.value?.refresh(),
+ dataList: computed(() => instancePagedTable.value?.dataList),
+});
+</script>
diff --git a/frontend/src/components/v2/Model/Instance/index.ts b/frontend/src/components/v2/Model/Instance/index.ts
index aca1487586..0bc44ea71b 100644
--- a/frontend/src/components/v2/Model/Instance/index.ts
+++ b/frontend/src/components/v2/Model/Instance/index.ts
@@ -3,6 +3,8 @@ import InstanceRoleTable from "./InstanceRoleTable";
import InstanceV1EngineIcon from "./InstanceV1EngineIcon.vue";
import InstanceV1Name from "./InstanceV1Name.vue";
import InstanceV1Table from "./InstanceV1Table";
+import InstanceOperations from "./InstanceV1Table/InstanceOperations.vue";
+import PagedInstanceTable from "./PagedInstanceTable.vue";
import RichEngineName from "./RichEngineName.vue";
export {
@@ -12,4 +14,6 @@ export {
InstanceV1Table,
InstanceRoleTable,
RichEngineName,
+ PagedInstanceTable,
+ InstanceOperations,
};
diff --git a/frontend/src/components/v2/Select/InstanceSelect.vue b/frontend/src/components/v2/Select/InstanceSelect.vue
index b1b18729cf..253d25f6db 100644
--- a/frontend/src/components/v2/Select/InstanceSelect.vue
+++ b/frontend/src/components/v2/Select/InstanceSelect.vue
@@ -1,6 +1,8 @@
<template>
<ResourceSelect
v-bind="$attrs"
+ :remote="true"
+ :loading="state.loading"
:value="instanceName"
:options="options"
:placeholder="$t('instance.select')"
@@ -9,41 +11,46 @@
:fallback-option="false"
:consistent-menu-width="false"
class="bb-instance-select"
+ @search="handleSearch"
@update:value="(val) => $emit('update:instance-name', val)"
/>
</template>
<script lang="ts" setup>
-import { computed, h, watch } from "vue";
+import { useDebounceFn } from "@vueuse/core";
+import { computed, h, watch, reactive } from "vue";
import { useI18n } from "vue-i18n";
-import { useInstanceResourceList } from "@/store";
+import { useInstanceV1Store } from "@/store";
import {
UNKNOWN_INSTANCE_NAME,
- isValidEnvironmentName,
+ isValidInstanceName,
unknownInstance,
+ type ComposedInstance,
} from "@/types";
import { type Engine } from "@/types/proto/v1/common";
import type { InstanceResource } from "@/types/proto/v1/instance_service";
-import { supportedEngineV1List } from "@/utils";
+import { supportedEngineV1List, getDefaultPagination } from "@/utils";
import { InstanceV1EngineIcon } from "../Model/Instance";
import ResourceSelect from "./ResourceSelect.vue";
+interface LocalState {
+ loading: boolean;
+ rawInstanceList: ComposedInstance[];
+}
+
const props = withDefaults(
defineProps<{
instanceName?: string | undefined;
environmentName?: string;
- allowedEngineList?: readonly Engine[];
- includeAll?: boolean;
+ projectName?: string;
+ allowedEngineList?: Engine[];
autoReset?: boolean;
- filter?: (instance: InstanceResource, index: number) => boolean;
}>(),
{
instanceName: undefined,
environmentName: undefined,
allowedEngineList: () => supportedEngineV1List(),
- includeAll: false,
autoReset: true,
- filter: undefined,
}
);
@@ -52,39 +59,64 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
-const instanceList = useInstanceResourceList();
+const instanceStore = useInstanceV1Store();
+const state = reactive<LocalState>({
+ loading: true,
+ rawInstanceList: [],
+});
-const rawInstanceList = computed(() => {
- let list = [...instanceList.value];
- if (isValidEnvironmentName(props.environmentName)) {
- list = instanceList.value.filter(
- (instance) => instance.environment === props.environmentName
- );
+const initSelectedInstance = async (instanceName: string) => {
+ if (isValidInstanceName(instanceName)) {
+ const instance = await instanceStore.getOrFetchInstanceByName(instanceName);
+ if (!state.rawInstanceList.find((ins) => ins.name === instance.name)) {
+ state.rawInstanceList.unshift(instance);
+ }
}
- // Filter by engine type
- list = list.filter((instance) =>
- props.allowedEngineList.includes(instance.engine)
- );
- return list;
-});
+};
-const combinedInstanceList = computed(() => {
- let list = rawInstanceList.value;
+const searchInstances = async (name: string) => {
+ const { instances } = await instanceStore.fetchInstanceList({
+ pageSize: getDefaultPagination(),
+ filter: {
+ engines: props.allowedEngineList,
+ query: name,
+ environment: props.environmentName,
+ project: props.projectName,
+ },
+ });
+ return instances;
+};
- if (props.filter) {
- list = list.filter(props.filter);
+const handleSearch = useDebounceFn(async (search: string) => {
+ state.loading = true;
+ try {
+ const instances = await searchInstances(search);
+ state.rawInstanceList = instances;
+ if (!search) {
+ if (props.instanceName === UNKNOWN_INSTANCE_NAME) {
+ const dummyAll = {
+ ...unknownInstance(),
+ title: t("instance.all"),
+ };
+ state.rawInstanceList.unshift(dummyAll);
+ } else if (props.instanceName) {
+ await initSelectedInstance(props.instanceName);
+ }
+ }
+ } finally {
+ state.loading = false;
}
+}, 200);
- if (props.instanceName === UNKNOWN_INSTANCE_NAME || props.includeAll) {
- const dummyAll = {
- ...unknownInstance(),
- title: t("instance.all"),
- };
- list.unshift(dummyAll);
+watch(
+ () => [props.allowedEngineList, props.environmentName, props.projectName],
+ () => {
+ handleSearch("");
+ },
+ {
+ immediate: true,
}
-
- return list;
-});
+);
const renderLabel = (instance: InstanceResource) => {
if (instance.name === UNKNOWN_INSTANCE_NAME) {
@@ -105,7 +137,7 @@ const renderLabel = (instance: InstanceResource) => {
};
const options = computed(() => {
- return combinedInstanceList.value.map((instance) => {
+ return state.rawInstanceList.map((instance) => {
return {
resource: instance,
value: instance.name,
@@ -121,15 +153,19 @@ const resetInvalidSelection = () => {
if (!props.autoReset) return;
if (
props.instanceName &&
- !combinedInstanceList.value.find((item) => item.name === props.instanceName)
+ !state.rawInstanceList.find((item) => item.name === props.instanceName)
) {
emit("update:instance-name", undefined);
}
};
-watch([() => props.instanceName, combinedInstanceList], resetInvalidSelection, {
- immediate: true,
-});
+watch(
+ [() => props.instanceName, state.rawInstanceList, props.projectName],
+ resetInvalidSelection,
+ {
+ immediate: true,
+ }
+);
</script>
<style lang="postcss" scoped>
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index a09340a7a7..8c41beff7b 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1235,9 +1235,13 @@
},
"advanced-search": {
"scope": {
- "address": {
- "title": "Address",
- "description": "Filter by address"
+ "host": {
+ "title": "Host",
+ "description": "Filter by instance host. Please input the value then press the Enter."
+ },
+ "port": {
+ "title": "Port",
+ "description": "Filter by instance port. Please input the value then press the Enter."
}
}
},
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index bf1b739aa9..0278bfa88c 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1235,9 +1235,13 @@
},
"advanced-search": {
"scope": {
- "address": {
- "title": "DIRECCIÓN",
- "description": "Filtrar por dirección"
+ "host": {
+ "title": "Anfitrión",
+ "description": "Filtrar por host de instancia. Introduce el valor y pulsa Intro."
+ },
+ "port": {
+ "title": "Puerto",
+ "description": "Filtrar por puerto de instancia. Ingrese el valor y presione Enter."
}
}
},
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 7a167748d9..f0d11fdcf7 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1235,9 +1235,13 @@
},
"advanced-search": {
"scope": {
- "address": {
- "title": "住所",
- "description": "住所でフィルタリング"
+ "host": {
+ "title": "サーバーアドレス",
+ "description": "インスタンス サーバーのアドレスでフィルターします。値を入力してEnterキーを押してください。"
+ },
+ "port": {
+ "title": "ポート",
+ "description": "インスタンス ポートでフィルターします。値を入力してEnterキーを押してください。"
}
}
},
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 68a2f72945..bb75b07985 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1235,9 +1235,13 @@
},
"advanced-search": {
"scope": {
- "address": {
- "title": "Địa chỉ",
- "description": "Lọc theo địa chỉ"
+ "host": {
+ "title": "Chủ nhà",
+ "description": "Lọc theo máy chủ lưu trữ. Vui lòng nhập giá trị rồi nhấn Enter."
+ },
+ "port": {
+ "title": "Cảng",
+ "description": "Lọc theo cổng phiên bản. Vui lòng nhập giá trị rồi nhấn Enter."
}
}
},
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 4d2feec599..416aa0015f 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1235,9 +1235,13 @@
},
"advanced-search": {
"scope": {
- "address": {
- "title": "地址",
- "description": "按地址过滤"
+ "host": {
+ "title": "服务器地址",
+ "description": "按实例服务器地址过滤。请输入值然后按 Enter。"
+ },
+ "port": {
+ "title": "端口",
+ "description": "按实例端口过滤。请输入值然后按 Enter。"
}
}
},
diff --git a/frontend/src/store/modules/sqlEditor/tree.ts b/frontend/src/store/modules/sqlEditor/tree.ts
index 6cc234a593..60f1dbc07b 100644
--- a/frontend/src/store/modules/sqlEditor/tree.ts
+++ b/frontend/src/store/modules/sqlEditor/tree.ts
@@ -363,8 +363,8 @@ const mapGroupNode = (
return mapTreeNodeByType("environment", environment, parent);
}
if (factor === "instance") {
- const instance = useInstanceResourceByName(value);
- return mapTreeNodeByType("instance", instance, parent);
+ const { instance } = useInstanceResourceByName(value);
+ return mapTreeNodeByType("instance", instance.value, parent);
}
// factor is label
const key = extractLabelFactor(factor);
diff --git a/frontend/src/store/modules/v1/instance.ts b/frontend/src/store/modules/v1/instance.ts
index fcbfcf0530..7d826a5ef9 100644
--- a/frontend/src/store/modules/v1/instance.ts
+++ b/frontend/src/store/modules/v1/instance.ts
@@ -1,40 +1,71 @@
+import { defineStore } from "pinia";
+import { reactive } from "vue";
import { instanceServiceClient } from "@/grpcweb";
import type { ComposedInstance } from "@/types";
-import { unknownEnvironment, unknownInstance } from "@/types";
-import { State } from "@/types/proto/v1/common";
+import {
+ unknownEnvironment,
+ unknownInstance,
+ isValidProjectName,
+ isValidInstanceName,
+ isValidEnvironmentName,
+} from "@/types";
+import type { Engine } from "@/types/proto/v1/common";
+import { State, stateToJSON, engineToJSON } from "@/types/proto/v1/common";
import type { DataSource, Instance } from "@/types/proto/v1/instance_service";
import { extractInstanceResourceName, hasWorkspacePermissionV2 } from "@/utils";
-import { defineStore } from "pinia";
-import { computed, reactive, watchEffect } from "vue";
-import { useListCache } from "./cache";
import { useEnvironmentV1Store } from "./environment";
+export interface InstanceFilter {
+ environment?: string;
+ project?: string;
+ host?: string;
+ port?: string;
+ query?: string;
+ engines?: Engine[];
+ state?: State;
+}
+
+const getListInstanceFilter = (params: InstanceFilter) => {
+ const list = [];
+ const search = params.query?.trim().toLowerCase();
+ if (search) {
+ list.push(
+ `(name.matches("${search}") || resource_id.matches("${search}"))`
+ );
+ }
+ if (isValidProjectName(params.project)) {
+ list.push(`project == "${params.project}"`);
+ }
+ if (isValidEnvironmentName(params.environment)) {
+ list.push(`environment == "${params.environment}"`);
+ }
+ if (params.host) {
+ list.push(`host == "${params.host}"`);
+ }
+ if (params.port) {
+ list.push(`port == "${params.port}"`);
+ }
+ if (params.engines && params.engines.length > 0) {
+ // engine filter should be:
+ // engine in ["MYSQL", "POSTGRES"]
+ list.push(
+ `engine in [${params.engines.map((e) => `"${engineToJSON(e)}"`).join(", ")}]`
+ );
+ }
+ if (params.state === State.DELETED) {
+ list.push(`state == "${stateToJSON(params.state)}"`);
+ }
+ return list.join(" && ");
+};
+
export const useInstanceV1Store = defineStore("instance_v1", () => {
const instanceMapByName = reactive(new Map<string, ComposedInstance>());
+ const instanceRequestCache = new Map<string, Promise<ComposedInstance>>();
const reset = () => {
instanceMapByName.clear();
};
- // Getters
- const instanceListIncludingDeleted = computed(() => {
- return Array.from(instanceMapByName.values());
- });
- const instanceList = computed(() => {
- return instanceListIncludingDeleted.value.filter((instance) => {
- return instance.state === State.ACTIVE;
- });
- });
- const activateInstanceCount = computed(() => {
- let count = 0;
- for (const instance of instanceList.value) {
- if (instance.activation) {
- count++;
- }
- }
- return count;
- });
-
// Actions
const upsertInstances = async (list: Instance[]) => {
const composedInstances = await Promise.all(
@@ -115,12 +146,21 @@ export const useInstanceV1Store = defineStore("instance_v1", () => {
return instanceMapByName.get(name) ?? unknownInstance();
};
const getOrFetchInstanceByName = async (name: string, silent = false) => {
- const cached = instanceMapByName.get(name);
- if (cached) {
- return cached;
+ const cachedData = instanceMapByName.get(name);
+ if (cachedData) {
+ return cachedData;
+ }
+ if (
+ !isValidInstanceName(name) ||
+ !hasWorkspacePermissionV2("bb.instances.get")
+ ) {
+ return unknownInstance();
}
- await fetchInstanceByName(name, silent);
- return getInstanceByName(name);
+ const cached = instanceRequestCache.get(name);
+ if (cached) return cached;
+ const request = fetchInstanceByName(name, silent);
+ instanceRequestCache.set(name, request);
+ return request;
};
const createDataSource = async (
instance: Instance,
@@ -158,11 +198,34 @@ export const useInstanceV1Store = defineStore("instance_v1", () => {
return composed;
};
+ const fetchInstanceList = async (params: {
+ pageSize?: number;
+ pageToken?: string;
+ filter?: InstanceFilter;
+ }) => {
+ if (!hasWorkspacePermissionV2("bb.instances.list")) {
+ return {
+ instances: [],
+ nextPageToken: "",
+ };
+ }
+ const { instances, nextPageToken } =
+ await instanceServiceClient.listInstances({
+ pageSize: params.pageSize,
+ pageToken: params.pageToken,
+ filter: getListInstanceFilter(params.filter ?? {}),
+ showDeleted: params.filter?.state === State.DELETED ? true : false,
+ });
+
+ const composedInstances = await upsertInstances(instances);
+ return {
+ instances: composedInstances,
+ nextPageToken,
+ };
+ };
+
return {
reset,
- instanceListIncludingDeleted,
- instanceList,
- activateInstanceCount,
upsertInstances,
createInstance,
updateInstance,
@@ -176,51 +239,10 @@ export const useInstanceV1Store = defineStore("instance_v1", () => {
updateDataSource,
deleteDataSource,
listInstanceDatabases,
+ fetchInstanceList,
};
});
-export const useInstanceV1List = (showDeleted: boolean = false) => {
- const listCache = useListCache("instance");
- const store = useInstanceV1Store();
- const cacheKey = listCache.getCacheKey(showDeleted ? "" : "active");
-
- const cache = computed(() => listCache.getCache(cacheKey));
-
- watchEffect(async () => {
- if (!hasWorkspacePermissionV2("bb.instances.list")) {
- return;
- }
- // Skip if request is already in progress or cache is available.
- if (cache.value?.isFetching || cache.value) {
- return;
- }
-
- listCache.cacheMap.set(cacheKey, {
- timestamp: Date.now(),
- isFetching: true,
- });
- const { instances } = await instanceServiceClient.listInstances({
- showDeleted,
- });
- await store.upsertInstances(instances);
- listCache.cacheMap.set(cacheKey, {
- timestamp: Date.now(),
- isFetching: false,
- });
- });
-
- const instanceList = computed(() => {
- return showDeleted
- ? store.instanceListIncludingDeleted
- : store.instanceList;
- });
-
- return {
- instanceList,
- ready: computed(() => cache.value && !cache.value.isFetching),
- };
-};
-
const composeInstance = async (instance: Instance) => {
const composed = instance as ComposedInstance;
const environmentEntity =
diff --git a/frontend/src/store/modules/v1/instanceResource.ts b/frontend/src/store/modules/v1/instanceResource.ts
index b1765d2259..e00de68a25 100644
--- a/frontend/src/store/modules/v1/instanceResource.ts
+++ b/frontend/src/store/modules/v1/instanceResource.ts
@@ -1,34 +1,43 @@
import { uniqBy } from "lodash-es";
-import { computed } from "vue";
-import { unknownInstanceResource } from "@/types";
+import { ref, unref, watchEffect, computed, type MaybeRef } from "vue";
import type { InstanceResource } from "@/types/proto/v1/instance_service";
import { useDatabaseV1Store } from "./database";
-import { useInstanceV1List } from "./instance";
+import { useInstanceV1Store } from "./instance";
// Instance resource list is a list of all instance resources in the database list.
// Current user should have access to all instance resources in the list.
-export const useInstanceResourceList = () => {
- const { instanceList } = useInstanceV1List();
- const { databaseList } = useDatabaseV1Store();
- return computed(() => {
+export const useInstanceResourceByName = (
+ instanceName: MaybeRef<string> // Format: instances/{instance}
+) => {
+ const store = useInstanceV1Store();
+ const databaseStore = useDatabaseV1Store();
+ const ready = ref(false);
+
+ const instanceList = computed(() => {
return uniqBy(
- [
- ...databaseList.map((db) => db.instanceResource),
- // Merge possible instance resources from the instance store.
- ...instanceList.value,
- ],
+ [...databaseStore.databaseList.map((db) => db.instanceResource)],
(i) => i.name
) as InstanceResource[];
});
-};
-// Instance resource list is a list of all instance resources in the database list.
-// Current user should have access to all instance resources in the list.
-export const useInstanceResourceByName = (
- instanceName: string // Format: instances/{instance}
-) => {
- return (
- useInstanceResourceList().value.find((i) => i.name === instanceName) ||
- unknownInstanceResource()
- );
+ watchEffect(async () => {
+ ready.value = false;
+ await store.getOrFetchInstanceByName(
+ unref(instanceName),
+ /* silent */ true
+ );
+ ready.value = true;
+ });
+
+ const instance = computed(() => {
+ const instanceFromDb = instanceList.value.find(
+ (i) => i.name === unref(instanceName)
+ );
+ if (instanceFromDb) {
+ return instanceFromDb;
+ }
+ return store.getInstanceByName(unref(instanceName));
+ });
+
+ return { instance, ready };
};
diff --git a/frontend/src/utils/sqlEditor.ts b/frontend/src/utils/sqlEditor.ts
index 4630cda00a..100d4756e8 100644
--- a/frontend/src/utils/sqlEditor.ts
+++ b/frontend/src/utils/sqlEditor.ts
@@ -123,8 +123,8 @@ export const isDisconnectedSQLEditorTab = (tab: SQLEditorTab) => {
if (!connection.instance) {
return true;
}
- const instance = useInstanceResourceByName(connection.instance);
- if (instanceV1AllowsCrossDatabaseQuery(instance)) {
+ const { instance } = useInstanceResourceByName(connection.instance);
+ if (instanceV1AllowsCrossDatabaseQuery(instance.value)) {
// Connecting to instance directly.
return false;
}
diff --git a/frontend/src/utils/v1/advanced-search/common.ts b/frontend/src/utils/v1/advanced-search/common.ts
index 3edfa7b463..cb9369a3c8 100644
--- a/frontend/src/utils/v1/advanced-search/common.ts
+++ b/frontend/src/utils/v1/advanced-search/common.ts
@@ -36,7 +36,8 @@ export const AllSearchScopeIdList = [
"level",
"actor",
// instance related search scopes.
- "address",
+ "host",
+ "port",
// rollout related search scopes.
"stage",
] as const;
diff --git a/frontend/src/utils/v1/instance.ts b/frontend/src/utils/v1/instance.ts
index 6283cc9475..f5047b9ea7 100644
--- a/frontend/src/utils/v1/instance.ts
+++ b/frontend/src/utils/v1/instance.ts
@@ -1,16 +1,14 @@
-import { keyBy, orderBy } from "lodash-es";
import { computed, unref } from "vue";
import { t, locale } from "@/plugins/i18n";
-import { useEnvironmentV1Store, useSubscriptionV1Store } from "@/store";
-import type { ComposedInstance, MaybeRef } from "@/types";
+import { useSubscriptionV1Store } from "@/store";
+import type { MaybeRef } from "@/types";
import {
- emptyInstance,
isValidInstanceName,
languageOfEngineV1,
unknownInstance,
+ emptyInstance,
} from "@/types";
import { Engine, State } from "@/types/proto/v1/common";
-import type { Environment } from "@/types/proto/v1/environment_service";
import type {
Instance,
InstanceResource,
@@ -49,22 +47,6 @@ export const extractInstanceResourceName = (name: string) => {
return matches?.[1] ?? "";
};
-export const sortInstanceV1List = (
- instanceList: (ComposedInstance | InstanceResource)[]
-) => {
- return orderBy(
- instanceList,
- [
- (instance) =>
- useEnvironmentV1Store().getEnvironmentByName(instance.environment)
- .order,
- (instance) => instance.name,
- (instance) => instance.title,
- ],
- ["desc", "asc", "asc"]
- );
-};
-
export const readableDataSourceType = (type: DataSourceType): string => {
if (type === DataSourceType.ADMIN) {
return t("data-source.admin");
@@ -93,21 +75,6 @@ export const hostPortOfInstanceV1 = (instance: Instance | InstanceResource) => {
return hostPortOfDataSource(ds);
};
-// Sort the list to put prod items first.
-export const sortInstanceV1ListByEnvironmentV1 = <T extends Instance>(
- list: T[],
- environmentList: Environment[]
-): T[] => {
- const environmentMap = keyBy(environmentList, (env) => env.name);
-
- return list.sort((a, b) => {
- const aEnvOrder = environmentMap[a.environment]?.order ?? -1;
- const bEnvOrder = environmentMap[b.environment]?.order ?? -1;
-
- return -(aEnvOrder - bEnvOrder);
- });
-};
-
export const supportedEngineV1List = () => {
const engines: Engine[] = [
Engine.MYSQL,
@@ -156,12 +123,8 @@ export const instanceV1HasReadonlyMode = (
return true;
};
-export const instanceV1HasCreateDatabase = (
- instanceOrEngine: Instance | InstanceResource | Engine
-): boolean => {
- const engine = engineOfInstanceV1(instanceOrEngine);
-
- const excludedList: Engine[] = [
+export const enginesSupportCreateDatabase = () => {
+ const excludedList: Set<Engine> = new Set([
Engine.REDIS,
Engine.ORACLE,
Engine.DM,
@@ -171,9 +134,16 @@ export const instanceV1HasCreateDatabase = (
Engine.DYNAMODB,
Engine.DATABRICKS,
Engine.COSMOSDB,
- ];
+ ]);
- return !excludedList.includes(engine);
+ return supportedEngineV1List().filter((engine) => !excludedList.has(engine));
+};
+
+export const instanceV1HasCreateDatabase = (
+ instanceOrEngine: Instance | InstanceResource | Engine
+): boolean => {
+ const engine = engineOfInstanceV1(instanceOrEngine);
+ return enginesSupportCreateDatabase().includes(engine);
};
export const instanceV1HasStructuredQueryResult = (
diff --git a/frontend/src/views/Archive.vue b/frontend/src/views/Archive.vue
index 7b1a051d98..937a6d56f3 100644
--- a/frontend/src/views/Archive.vue
+++ b/frontend/src/views/Archive.vue
@@ -23,13 +23,15 @@
}"
:bordered="true"
/>
- <InstanceV1Table
+ <PagedInstanceTable
v-else-if="state.selectedTab == 'INSTANCE'"
- key="archived-instance-table"
- :instance-list="filteredInstanceList"
+ session-key="bb.instance-table.archived"
+ :bordered="true"
:show-selection="false"
- :can-assign-license="false"
- :show-operation="false"
+ :filter="{
+ query: state.searchText,
+ state: State.DELETED,
+ }"
/>
<EnvironmentV1Table
v-else-if="state.selectedTab == 'ENVIRONMENT'"
@@ -54,13 +56,9 @@ import {
SearchBox,
TabFilter,
PagedProjectTable,
- InstanceV1Table,
+ PagedInstanceTable,
} from "@/components/v2";
-import {
- useEnvironmentV1Store,
- useIdentityProviderStore,
- useInstanceV1List,
-} from "@/store";
+import { useEnvironmentV1Store, useIdentityProviderStore } from "@/store";
import { State } from "@/types/proto/v1/common";
import type { IdentityProvider } from "@/types/proto/v1/idp_service";
import { hasWorkspacePermissionV2 } from "@/utils";
@@ -95,12 +93,6 @@ const environmentList = computed(() => {
);
});
-const instanceList = computed(() => {
- return useInstanceV1List(true /** showDeleted */).instanceList.value.filter(
- (instance) => instance.state === State.DELETED
- );
-});
-
const deletedSSOList = computed(() => {
return useIdentityProviderStore().deletedIdentityProviderList;
});
@@ -125,18 +117,6 @@ const tabItemList = computed(() => {
return list;
});
-const filteredInstanceList = computed(() => {
- const keyword = state.searchText.trim();
- if (!keyword) {
- return instanceList.value;
- }
- return instanceList.value.filter((instance) => {
- return instance.title
- .toLowerCase()
- .includes(state.searchText.toLowerCase());
- });
-});
-
const filteredEnvironmentList = computed(() => {
const list = environmentList.value;
const keyword = state.searchText.trim().toLowerCase();
diff --git a/frontend/src/views/InstanceDashboard.vue b/frontend/src/views/InstanceDashboard.vue
index 71f9ecd458..b871369fe1 100644
--- a/frontend/src/views/InstanceDashboard.vue
+++ b/frontend/src/views/InstanceDashboard.vue
@@ -23,13 +23,19 @@
{{ $t("quick-action.add-instance") }}
</NButton>
</div>
- <InstanceV1Table
- :bordered="false"
- :loading="!ready"
- :instance-list="filteredInstanceV1List"
- :can-assign-license="subscriptionStore.currentPlan !== PlanType.FREE"
- :default-expand-data-source="state.dataSourceToggle"
- />
+ <div class="space-y-2">
+ <InstanceOperations :instance-list="selectedInstanceList" />
+ <PagedInstanceTable
+ session-key="bb.instance-table"
+ :bordered="false"
+ :filter="filter"
+ :footer-class="'mx-4'"
+ :selected-instance-names="Array.from(state.selectedInstance)"
+ @update:selected-instance-names="
+ (list) => (state.selectedInstance = new Set(list))
+ "
+ />
+ </div>
</div>
<Drawer
:auto-focus="true"
@@ -56,14 +62,11 @@
<script lang="tsx" setup>
import { PlusIcon } from "lucide-vue-next";
-import { NTag, NButton } from "naive-ui";
-import { computed, onMounted, reactive, watch } from "vue";
+import { NButton } from "naive-ui";
+import { computed, onMounted, reactive } from "vue";
import { useI18n } from "vue-i18n";
import AdvancedSearch from "@/components/AdvancedSearch";
-import type {
- ScopeOption,
- ValueOption,
-} from "@/components/AdvancedSearch/types";
+import type { ScopeOption } from "@/components/AdvancedSearch/types";
import { useCommonSearchScopeOptions } from "@/components/AdvancedSearch/useCommonSearchScopeOptions";
import { FeatureAttention, FeatureModal } from "@/components/FeatureGuard";
import {
@@ -71,39 +74,31 @@ import {
Form as InstanceFormBody,
Buttons as InstanceFormButtons,
} from "@/components/InstanceForm/";
-import { InstanceV1Table } from "@/components/v2";
+import { InstanceOperations, PagedInstanceTable } from "@/components/v2";
import { Drawer, DrawerContent } from "@/components/v2";
import {
useUIStateStore,
useSubscriptionV1Store,
- useEnvironmentV1List,
- useInstanceV1List,
useInstanceV1Store,
- useInstanceResourceList,
+ useActuatorV1Store,
} from "@/store";
-import { PlanType } from "@/types/proto/v1/subscription_service";
-import {
- type SearchParams,
- hostPortOfDataSource,
- readableDataSourceType,
- sortInstanceV1ListByEnvironmentV1,
- extractEnvironmentResourceName,
- hasWorkspacePermissionV2,
-} from "@/utils";
+import { environmentNamePrefix } from "@/store/modules/v1/common";
+import { isValidInstanceName } from "@/types";
+import { engineFromJSON } from "@/types/proto/v1/common";
+import { type SearchParams, hasWorkspacePermissionV2 } from "@/utils";
interface LocalState {
params: SearchParams;
showCreateDrawer: boolean;
showFeatureModal: boolean;
- dataSourceToggle: string[];
+ selectedInstance: Set<string>;
}
const { t } = useI18n();
const subscriptionStore = useSubscriptionV1Store();
const instanceV1Store = useInstanceV1Store();
const uiStateStore = useUIStateStore();
-const environmentList = useEnvironmentV1List();
-const { instanceList, ready } = useInstanceV1List();
+const actuatorStore = useActuatorV1Store();
const state = reactive<LocalState>({
params: {
@@ -112,97 +107,65 @@ const state = reactive<LocalState>({
},
showCreateDrawer: false,
showFeatureModal: false,
- dataSourceToggle: [],
+ selectedInstance: new Set(),
});
const selectedEnvironment = computed(() => {
- return (
- state.params.scopes.find((scope) => scope.id === "environment")?.value ?? ""
- );
+ const environmentId = state.params.scopes.find(
+ (scope) => scope.id === "environment"
+ )?.value;
+ if (!environmentId) {
+ return;
+ }
+ return `${environmentNamePrefix}${environmentId}`;
});
-const selectedAddress = computed(() => {
- return (
- state.params.scopes.find((scope) => scope.id === "address")?.value ?? ""
- );
+const selectedHost = computed(() => {
+ return state.params.scopes.find((scope) => scope.id === "host")?.value ?? "";
+});
+
+const selectedPort = computed(() => {
+ return state.params.scopes.find((scope) => scope.id === "port")?.value ?? "";
+});
+
+const selectedEngines = computed(() => {
+ return state.params.scopes
+ .filter((scope) => scope.id === "engine")
+ .map((scope) => engineFromJSON(scope.value));
});
+const filter = computed(() => ({
+ environment: selectedEnvironment.value,
+ host: selectedHost.value,
+ port: selectedPort.value,
+ query: state.params.query,
+ engines: selectedEngines.value,
+}));
+
const showCreateInstanceDrawer = () => {
- const instanceList = useInstanceResourceList();
- if (subscriptionStore.instanceCountLimit <= instanceList.value.length) {
+ if (
+ subscriptionStore.instanceCountLimit <= actuatorStore.activatedInstanceCount
+ ) {
state.showFeatureModal = true;
return;
}
state.showCreateDrawer = true;
};
-watch(
- () => selectedAddress.value,
- (selectedAddress) => {
- if (!selectedAddress) {
- state.dataSourceToggle = [];
- }
- }
-);
-
-const addressOptions = computed(() => {
- const addressMap: Map<
- string,
- {
- keywords: string[];
- types: Set<string>;
- }
- > = new Map();
-
- for (const instance of instanceList.value) {
- for (const ds of instance.dataSources) {
- const host = hostPortOfDataSource(ds);
- if (!host) {
- continue;
- }
- if (!addressMap.has(host)) {
- addressMap.set(host, {
- keywords: [ds.host, ds.port],
- types: new Set(),
- });
- }
- addressMap.get(host)?.types?.add(readableDataSourceType(ds.type));
- }
- }
-
- const options: ValueOption[] = [];
- for (const [host, item] of addressMap.entries()) {
- options.push({
- value: host,
- keywords: [...item.keywords, ...item.types],
- render: () => {
- return (
- <div class={"flex items-center gap-x-2"}>
- {host}
- <div class={"flex items-center gap-x-1"}>
- {[...item.types].map((type) => (
- <NTag size="small" round>
- {type}
- </NTag>
- ))}
- </div>
- </div>
- );
- },
- });
- }
-
- return options;
-});
-
const scopeOptions = computed((): ScopeOption[] => {
return [
- ...useCommonSearchScopeOptions(["environment"]).value,
+ ...useCommonSearchScopeOptions(["environment", "engine"]).value,
+ {
+ id: "host",
+ title: t("instance.advanced-search.scope.host.title"),
+ description: t("instance.advanced-search.scope.host.description"),
+ options: [],
+ },
{
- id: "address",
- title: t("instance.advanced-search.scope.address.title"),
- description: t("instance.advanced-search.scope.address.description"),
- options: addressOptions.value,
+ id: "port",
+ title: t("instance.advanced-search.scope.port.title"),
+ description: t("instance.advanced-search.scope.port.description"),
+ options: [],
},
];
});
@@ -216,41 +179,10 @@ onMounted(() => {
}
});
-const filteredInstanceV1List = computed(() => {
- const keyword = state.params.query.trim().toLowerCase();
- const list = instanceList.value.filter((instance) => {
- if (keyword) {
- if (!instance.title.toLowerCase().includes(keyword)) {
- return false;
- }
- }
- if (selectedEnvironment.value) {
- if (
- extractEnvironmentResourceName(instance.environment) !==
- selectedEnvironment.value
- ) {
- return false;
- }
- }
- if (selectedAddress.value) {
- const matched = instance.dataSources.some(
- (ds) => hostPortOfDataSource(ds) === selectedAddress.value
- );
- if (matched) {
- state.dataSourceToggle.push(instance.name);
- }
- return matched;
- }
- return true;
- });
-
- return sortInstanceV1ListByEnvironmentV1(list, environmentList.value);
-});
-
const remainingInstanceCount = computed((): number => {
return Math.max(
0,
- subscriptionStore.instanceCountLimit - instanceV1Store.instanceList.length
+ subscriptionStore.instanceCountLimit - actuatorStore.totalInstanceCount
);
});
@@ -279,4 +211,10 @@ const instanceCountAttention = computed((): string => {
return `${status} ${upgrade}`;
});
+
+const selectedInstanceList = computed(() => {
+ return [...state.selectedInstance]
+ .filter((instanceName) => isValidInstanceName(instanceName))
+ .map((instanceName) => instanceV1Store.getInstanceByName(instanceName));
+});
</script>
diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue
index cdb6038fd9..e933ab5d01 100644
--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue
+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue
@@ -163,8 +163,8 @@ const selectedKeys = computedAsync(async () => {
if (!node) return [];
return [node.key];
} else if (connection.instance) {
- const instance = useInstanceResourceByName(connection.instance);
- const nodes = treeStore.nodesByTarget("instance", instance);
+ const { instance } = useInstanceResourceByName(connection.instance);
+ const nodes = treeStore.nodesByTarget("instance", instance.value);
return nodes.map((node) => node.key);
}
return [];
diff --git a/frontend/src/views/sql-editor/Setting/Instance/Instance.vue b/frontend/src/views/sql-editor/Setting/Instance/Instance.vue
index 95ec4f12b0..ccee195685 100644
--- a/frontend/src/views/sql-editor/Setting/Instance/Instance.vue
+++ b/frontend/src/views/sql-editor/Setting/Instance/Instance.vue
@@ -21,13 +21,21 @@
</NEllipsis>
</NButton>
</div>
- <InstanceV1Table
- :bordered="false"
- :loading="!ready"
- :instance-list="filteredInstanceV1List"
- :can-assign-license="subscriptionStore.currentPlan !== PlanType.FREE"
- :on-click="showInstanceDetail"
- />
+
+ <div class="space-y-2">
+ <InstanceOperations :instance-list="selectedInstanceList" />
+ <PagedInstanceTable
+ session-key="bb.instance-table"
+ :bordered="false"
+ :filter="filter"
+ :footer-class="'mx-4'"
+ :selected-instance-names="Array.from(state.selectedInstance)"
+ :on-click="showInstanceDetail"
+ @update:selected-instance-names="
+ (list) => (state.selectedInstance = new Set(list))
+ "
+ />
+ </div>
<Drawer
v-model:show="state.detail.show"
@@ -100,22 +108,24 @@ import {
Form as InstanceFormBody,
Buttons as InstanceFormButtons,
} from "@/components/InstanceForm";
-import { Drawer, DrawerContent, InstanceV1Table } from "@/components/v2";
+import {
+ Drawer,
+ DrawerContent,
+ PagedInstanceTable,
+ InstanceOperations,
+} from "@/components/v2";
import {
useSubscriptionV1Store,
- useEnvironmentV1List,
- useInstanceV1List,
useInstanceV1Store,
useAppFeature,
+ useActuatorV1Store,
} from "@/store";
-import { UNKNOWN_ID } from "@/types";
+import { environmentNamePrefix } from "@/store/modules/v1/common";
+import { isValidInstanceName } from "@/types";
+import { engineFromJSON } from "@/types/proto/v1/common";
import type { Instance } from "@/types/proto/v1/instance_service";
-import { PlanType } from "@/types/proto/v1/subscription_service";
import {
type SearchParams,
- sortInstanceV1ListByEnvironmentV1,
- extractEnvironmentResourceName,
- wrapRefAsPromise,
extractInstanceResourceName,
instanceV1Name,
} from "@/utils";
@@ -127,16 +137,15 @@ interface LocalState {
show: boolean;
instance: Instance | undefined;
};
+ selectedInstance: Set<string>;
}
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
+const actuatorStore = useActuatorV1Store();
const subscriptionStore = useSubscriptionV1Store();
const instanceV1Store = useInstanceV1Store();
-const environmentList = useEnvironmentV1List();
-// Users are workspace admins in Bytebase Editor. So we don't need to check permission here.
-const { instanceList, ready } = useInstanceV1List();
const hideAdvancedFeatures = useAppFeature(
"bb.feature.sql-editor.hide-advance-instance-features"
);
@@ -150,70 +159,70 @@ const state = reactive<LocalState>({
show: false,
instance: undefined,
},
+ selectedInstance: new Set(),
});
-const scopeOptions = useCommonSearchScopeOptions(["environment"]);
+const scopeOptions = useCommonSearchScopeOptions(["environment", "engine"]);
const selectedEnvironment = computed(() => {
- return (
- state.params.scopes.find((scope) => scope.id === "environment")?.value ??
- `${UNKNOWN_ID}`
- );
+ const environmentId = state.params.scopes.find(
+ (scope) => scope.id === "environment"
+ )?.value;
+ if (!environmentId) {
+ return;
+ }
+ return `${environmentNamePrefix}${environmentId}`;
+});
+
+const selectedEngines = computed(() => {
+ return state.params.scopes
+ .filter((scope) => scope.id === "engine")
+ .map((scope) => engineFromJSON(scope.value));
});
-onMounted(() => {
+const filter = computed(() => ({
+ environment: selectedEnvironment.value,
+ query: state.params.query,
+ engines: selectedEngines.value,
+}));
+
+onMounted(async () => {
if (route.hash === "#add") {
state.detail.show = true;
state.detail.instance = undefined;
+ return;
}
- wrapRefAsPromise(ready, true).then(() => {
- const maybeInstanceName = route.hash.replace(/^#*/g, "");
- if (maybeInstanceName) {
- const instance = instanceList.value.find(
- (inst) => inst.name === maybeInstanceName
- );
+
+ const maybeInstanceName = route.hash.replace(/^#*/g, "");
+ if (isValidInstanceName(maybeInstanceName)) {
+ try {
+ const instance =
+ await instanceV1Store.getOrFetchInstanceByName(maybeInstanceName);
if (instance) {
state.detail.show = true;
state.detail.instance = instance;
}
+ } finally {
+ // ignore error
}
-
- watch(
- [() => state.detail.show, () => state.detail.instance?.name],
- ([show, instanceName]) => {
- if (show) {
- router.replace({ hash: instanceName ? `#${instanceName}` : "#add" });
- } else {
- router.replace({ hash: "" });
- }
- }
- );
- });
+ }
});
-const filteredInstanceV1List = computed(() => {
- let list = [...instanceList.value];
- if (selectedEnvironment.value !== `${UNKNOWN_ID}`) {
- list = list.filter(
- (instance) =>
- extractEnvironmentResourceName(instance.environment) ===
- selectedEnvironment.value
- );
- }
- const keyword = state.params.query.trim().toLowerCase();
- if (keyword) {
- list = list.filter((instance) =>
- instance.title.toLowerCase().includes(keyword)
- );
+watch(
+ [() => state.detail.show, () => state.detail.instance?.name],
+ ([show, instanceName]) => {
+ if (show) {
+ router.replace({ hash: instanceName ? `#${instanceName}` : "#add" });
+ } else {
+ router.replace({ hash: "" });
+ }
}
-
- return sortInstanceV1ListByEnvironmentV1(list, environmentList.value);
-});
+);
const remainingInstanceCount = computed((): number => {
return Math.max(
0,
- subscriptionStore.instanceCountLimit - instanceV1Store.instanceList.length
+ subscriptionStore.instanceCountLimit - actuatorStore.totalInstanceCount
);
});
@@ -258,6 +267,12 @@ const showInstanceDetail = (instance: Instance) => {
state.detail.show = true;
state.detail.instance = instance;
};
+
+const selectedInstanceList = computed(() => {
+ return [...state.selectedInstance]
+ .filter((instanceName) => isValidInstanceName(instanceName))
+ .map((instanceName) => instanceV1Store.getInstanceByName(instanceName));
+});
</script>
<style scoped lang="postcss">