Skip to content

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

fix(instance): scope connection settings to Admin and Read-only tabs (#21451)

p0ny3eaaba6e337f
diff --git a/frontend/src/components/instance/CreateDataSourceExample.test.tsx b/frontend/src/components/instance/CreateDataSourceExample.test.tsx
new file mode 100644
index 0000000000..0bf5eee009
--- /dev/null
+++ b/frontend/src/components/instance/CreateDataSourceExample.test.tsx
@@ -0,0 +1,27 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, expect, test, vi } from "vitest";
+import enUS from "@/locales/en-US.json";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import { DataSource_AuthenticationType, DataSourceType } from "@/types/proto-es/v1/instance_service_pb";
+import { CreateDataSourceExample } from "./CreateDataSourceExample";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key.split(".").reduce<unknown>((value, part) => (value as Record<string, unknown>)[part], enUS) }),
+}));
+vi.mock("@/types", () => ({
+ DATASOURCE_ADMIN_USER_NAME: "bytebase",
+ DATASOURCE_READONLY_USER_NAME: "bytebase_readonly",
+ languageOfEngineV1: () => "sql",
+}));
+vi.mock("@/lib/clipboard", () => ({ writeTextToClipboard: vi.fn() }));
+afterEach(cleanup);
+
+test.each([
+ [Engine.TIDB, true],
+ [Engine.COCKROACHDB, false],
+ [Engine.BIGQUERY, false],
+])("shows the read-only description independently of setup examples for engine %s", (engine, hasExample) => {
+ render(<CreateDataSourceExample engine={engine as Engine} dataSourceType={DataSourceType.READ_ONLY} authenticationType={DataSource_AuthenticationType.PASSWORD} createInstanceFlag={false} />);
+ expect(screen.getByText("This is the connection used by Bytebase to perform read-only operations such as SELECT query.")).toBeTruthy();
+ expect(screen.queryByText("Show how to create") !== null).toBe(hasExample);
+});
diff --git a/frontend/src/components/instance/CreateDataSourceExample.tsx b/frontend/src/components/instance/CreateDataSourceExample.tsx
index d7de59f237..ab412ac703 100644
--- a/frontend/src/components/instance/CreateDataSourceExample.tsx
+++ b/frontend/src/components/instance/CreateDataSourceExample.tsx
@@ -476,10 +476,6 @@ export function CreateDataSourceExample({
setShowExample((prev) => !prev);
}, []);
- if (!grantStatement) {
- return null;
- }
-
const descriptionText = isEngineUsingSQL
? dataSourceType === DataSourceType.ADMIN
? t("instance.sentence.create-admin-user")
@@ -492,7 +488,7 @@ export function CreateDataSourceExample({
<div className={`w-full flex flex-col justify-start ${className ?? ""}`}>
<p className="w-full text-sm text-gray-500">
{descriptionText}
- {!createInstanceFlag && (
+ {!createInstanceFlag && grantStatement && (
<span
className="normal-link select-none ml-1 cursor-pointer"
onClick={toggleExample}
@@ -501,7 +497,7 @@ export function CreateDataSourceExample({
</span>
)}
</p>
- {showExample && (
+ {showExample && grantStatement && (
<div className="text-sm text-main">
<EngineSpecificDescription
engine={engine}
diff --git a/frontend/src/components/instance/DataSourceForm.tsx b/frontend/src/components/instance/DataSourceForm.tsx
index c033c71d90..3e68bc4a04 100644
--- a/frontend/src/components/instance/DataSourceForm.tsx
+++ b/frontend/src/components/instance/DataSourceForm.tsx
@@ -30,16 +30,11 @@ import {
DataSourceExternalSecret_SecretType,
DataSourceExternalSecret_TokenType,
DataSourceExternalSecretSchema,
- DataSourceType,
KerberosConfigSchema,
SASLConfigSchema,
} from "@/types/proto-es/v1/instance_service_pb";
-import {
- PlanFeature,
- PlanType,
-} from "@/types/proto-es/v1/subscription_service_pb";
+import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";
import { onlyAllowNumber } from "@/utils";
-import { CreateDataSourceExample } from "./CreateDataSourceExample";
import { CredentialSourceForm } from "./CredentialSourceForm";
import {
type EditDataSource,
@@ -189,9 +184,6 @@ export function DataSourceForm({
isCreating,
allowEdit,
basicInfo,
- adminDataSource,
- hasReadonlyReplicaFeature,
- setMissingFeature,
hideAdvancedFeatures,
needsKeytabResupply,
dataSourceResetEvent,
@@ -203,8 +195,6 @@ export function DataSourceForm({
showSSH,
allowUsingEmptyPassword,
showAuthenticationDatabase,
- hasReadonlyReplicaHost,
- hasReadonlyReplicaPort,
hasExtraParameters,
} = specs;
@@ -512,38 +502,6 @@ export function DataSourceForm({
onDataSourceChange(ds);
};
- const handleHostInput = (value: string) => {
- if (dataSource.type === DataSourceType.READ_ONLY) {
- if (!hasReadonlyReplicaFeature) {
- if (dataSource.host || dataSource.port) {
- update({
- host: adminDataSource.host,
- port: adminDataSource.port,
- });
- setMissingFeature(PlanFeature.FEATURE_INSTANCE_READ_ONLY_CONNECTION);
- return;
- }
- }
- }
- update({ host: value.trim() });
- };
-
- const handlePortInput = (value: string) => {
- if (dataSource.type === DataSourceType.READ_ONLY) {
- if (!hasReadonlyReplicaFeature) {
- if (dataSource.host || dataSource.port) {
- update({
- host: adminDataSource.host,
- port: adminDataSource.port,
- });
- setMissingFeature(PlanFeature.FEATURE_INSTANCE_READ_ONLY_CONNECTION);
- return;
- }
- }
- }
- update({ port: value.trim() });
- };
-
const handleSSHChange = (
value: Partial<{
sshHost: string;
@@ -848,17 +806,6 @@ export function DataSourceForm({
<>
{!hideAuthentication && authenticationTypeControl}
- {/* Create data source example (edit mode only) */}
- {!isCreating && (
- <CreateDataSourceExample
- className="sm:col-span-3 border-none"
- createInstanceFlag={false}
- engine={basicInfo.engine}
- dataSourceType={dataSource.type}
- authenticationType={dataSource.authenticationType}
- />
- )}
-
{/* Hive authentication */}
{basicInfo.engine === Engine.HIVE && (
<div className="sm:col-span-3 sm:col-start-1">
@@ -2089,49 +2036,6 @@ export function DataSourceForm({
</FormField>
)}
- {/* Read-only replica host/port */}
- {dataSource.type === DataSourceType.READ_ONLY &&
- (hasReadonlyReplicaHost || hasReadonlyReplicaPort) && (
- <>
- {hasReadonlyReplicaHost && (
- <FormField
- validationField="host"
- className="sm:col-span-3 sm:col-start-1"
- title={<>{t("data-source.read-replica-host")}</>}
- >
- <Input
- className="w-full"
- autoComplete="off"
- value={dataSource.host}
- disabled={!allowEdit}
- onChange={(e) => handleHostInput(e.target.value)}
- />
- </FormField>
- )}
- {hasReadonlyReplicaPort && (
- <FormField
- className="sm:col-span-3 sm:col-start-1"
- title={<>{t("data-source.read-replica-port")}</>}
- >
- <Input
- className="w-full"
- autoComplete="off"
- value={dataSource.port}
- disabled={!allowEdit}
- onChange={(e) => {
- if (
- e.target.value &&
- !onlyAllowNumber(e.target.value)
- )
- return;
- handlePortInput(e.target.value);
- }}
- />
- </FormField>
- )}
- </>
- )}
-
{/* Database field */}
{showDatabase && (
<FormField
diff --git a/frontend/src/components/instance/DataSourceSection.test.tsx b/frontend/src/components/instance/DataSourceSection.test.tsx
index 2cc0bdfdcb..bfd21640e3 100644
--- a/frontend/src/components/instance/DataSourceSection.test.tsx
+++ b/frontend/src/components/instance/DataSourceSection.test.tsx
@@ -33,6 +33,8 @@ vi.mock("./InstanceFormContext", () => ({
useInstanceFormContext: () => mocks.context,
}));
+vi.mock("./CreateDataSourceExample", () => ({ CreateDataSourceExample: () => null }));
+
vi.mock("./DataSourceForm", () => ({
DataSourceForm: ({ dataSource }: { dataSource: EditDataSource }) => (
<div data-testid="data-source-form" data-id={dataSource.id} />
diff --git a/frontend/src/components/instance/DataSourceSection.tsx b/frontend/src/components/instance/DataSourceSection.tsx
index 8df2596425..6ff8c4c1d6 100644
--- a/frontend/src/components/instance/DataSourceSection.tsx
+++ b/frontend/src/components/instance/DataSourceSection.tsx
@@ -1,5 +1,5 @@
import { Plus } from "lucide-react";
-import { useCallback } from "react";
+import { type ReactNode, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
@@ -7,6 +7,7 @@ import { useAppStore } from "@/stores/app";
import { DATASOURCE_READONLY_USER_NAME } from "@/types";
import { Engine } from "@/types/proto-es/v1/common_pb";
import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";
+import { CreateDataSourceExample } from "./CreateDataSourceExample";
import type { EditDataSource } from "./common";
import { wrapEditDataSource } from "./common";
import { DataSourceForm } from "./DataSourceForm";
@@ -14,14 +15,16 @@ import { useInstanceFormContext } from "./InstanceFormContext";
import type { InfoSection } from "./info-content";
interface DataSourceSectionProps {
+ children?: ReactNode;
hideOptions?: boolean;
- hideAdminAuthentication?: boolean;
+ hideAuthentication?: boolean;
onOpenInfoPanel?: (section: InfoSection) => void;
}
export function DataSourceSection({
+ children,
hideOptions = false,
- hideAdminAuthentication = false,
+ hideAuthentication = false,
onOpenInfoPanel,
}: DataSourceSectionProps) {
const { t } = useTranslation();
@@ -121,17 +124,84 @@ export function DataSourceSection({
);
// DynamoDB normally has a single admin data source, so the read-only
- // tabs/tips are hidden — unless a read-only data source already exists
+ // tabs are hidden unless a read-only data source already exists
// (creatable via the API), which must stay reachable.
const showDataSourceTabs =
!isCreating &&
(basicInfo.engine !== Engine.DYNAMODB || hasReadOnlyDataSource);
- // Show RO tips when not creating and no RO data source
const showROTips = showDataSourceTabs && !hasReadOnlyDataSource;
return (
- <>
+ <div>
+ {/* Data source tabs */}
+ {showDataSourceTabs && (
+ <div className="mb-4 flex items-center gap-x-2 border-b border-block-border">
+ <button
+ type="button"
+ className={`pb-2 px-1 text-sm font-medium border-b-2 transition-colors ${
+ dataSourceEditState.editingDataSourceId === adminDataSource.id
+ ? "border-accent text-accent"
+ : "border-transparent text-control-light hover:text-main"
+ }`}
+ onClick={() => handleTabChange(adminDataSource.id)}
+ >
+ {t("common.admin")}
+ {incompleteMarker(adminDataSource)}
+ </button>
+ {readonlyDataSourceList.map((ds) => (
+ <div key={ds.id} className="flex items-center">
+ <button
+ type="button"
+ className={`pb-2 px-1 text-sm font-medium border-b-2 transition-colors ${
+ dataSourceEditState.editingDataSourceId === ds.id
+ ? "border-accent text-accent"
+ : "border-transparent text-control-light hover:text-main"
+ }`}
+ onClick={() => handleTabChange(ds.id)}
+ >
+ {t("common.read-only")}
+ {incompleteMarker(ds)}
+ </button>
+ {hasReadOnlyDataSource && (
+ <button
+ type="button"
+ className="ml-1 text-red-500 hover:text-red-700 text-xs pb-2"
+ disabled={!allowUpdate}
+ onClick={() => {
+ if (
+ ds.pendingCreate ||
+ window.confirm(
+ `${t("data-source.delete-read-only-data-source")}?`
+ )
+ ) {
+ handleDeleteDataSource(ds);
+ }
+ }}
+ >
+ ✕
+ </button>
+ )}
+ </div>
+ ))}
+ {!hasReadOnlyDataSource && (
+ <span className="pb-2 px-1 text-sm text-control-light">
+ {t("common.read-only")}
+ </span>
+ )}
+ {allowEdit && (
+ <button
+ type="button"
+ className="pb-2 px-1 text-control-light hover:text-main disabled:opacity-50"
+ disabled={!allowUpdate}
+ onClick={handleCreateRODataSource}
+ >
+ <Plus className="w-4 h-4" />
+ </button>
+ )}
+ </div>
+ )}
+
{showROTips && (
<Alert
variant="warning"
@@ -151,88 +221,30 @@ export function DataSourceSection({
/>
)}
- <div className="mt-4 gap-y-2 gap-x-4 border-none">
- {/* Data source tabs */}
- {showDataSourceTabs && (
- <div className="mb-4 flex items-center gap-x-2 border-b border-block-border">
- <button
- type="button"
- className={`pb-2 px-1 text-sm font-medium border-b-2 transition-colors ${
- dataSourceEditState.editingDataSourceId === adminDataSource.id
- ? "border-accent text-accent"
- : "border-transparent text-control-light hover:text-main"
- }`}
- onClick={() => handleTabChange(adminDataSource.id)}
- >
- {t("common.admin")}
- {incompleteMarker(adminDataSource)}
- </button>
- {readonlyDataSourceList.map((ds) => (
- <div key={ds.id} className="flex items-center">
- <button
- type="button"
- className={`pb-2 px-1 text-sm font-medium border-b-2 transition-colors ${
- dataSourceEditState.editingDataSourceId === ds.id
- ? "border-accent text-accent"
- : "border-transparent text-control-light hover:text-main"
- }`}
- onClick={() => handleTabChange(ds.id)}
- >
- {t("common.read-only")}
- {incompleteMarker(ds)}
- </button>
- {hasReadOnlyDataSource && (
- <button
- type="button"
- className="ml-1 text-red-500 hover:text-red-700 text-xs pb-2"
- disabled={!allowUpdate}
- onClick={() => {
- if (
- ds.pendingCreate ||
- window.confirm(
- `${t("data-source.delete-read-only-data-source")}?`
- )
- ) {
- handleDeleteDataSource(ds);
- }
- }}
- >
- ✕
- </button>
- )}
- </div>
- ))}
- {!hasReadOnlyDataSource && (
- <span className="pb-2 px-1 text-sm text-control-light">
- {t("common.read-only")}
- </span>
- )}
- {allowEdit && (
- <button
- type="button"
- className="pb-2 px-1 text-control-light hover:text-main disabled:opacity-50"
- disabled={!allowUpdate}
- onClick={handleCreateRODataSource}
- >
- <Plus className="w-4 h-4" />
- </button>
- )}
- </div>
- )}
+ {!isCreating && editingDataSource && (
+ <CreateDataSourceExample
+ key={editingDataSource.id}
+ className="mb-4"
+ engine={basicInfo.engine}
+ dataSourceType={editingDataSource.type}
+ authenticationType={editingDataSource.authenticationType}
+ createInstanceFlag={false}
+ />
+ )}
- {editingDataSource && (
+ {children}
+
+ {editingDataSource && (
+ <div className="mt-4">
<DataSourceForm
dataSource={editingDataSource}
hideOptions={hideOptions}
- hideAuthentication={
- hideAdminAuthentication &&
- editingDataSource.id === adminDataSource.id
- }
+ hideAuthentication={hideAuthentication}
onDataSourceChange={handleDataSourceChange}
onOpenInfoPanel={onOpenInfoPanel}
/>
- )}
- </div>
- </>
+ </div>
+ )}
+ </div>
);
}
diff --git a/frontend/src/components/instance/InstanceFormBody.test.tsx b/frontend/src/components/instance/InstanceFormBody.test.tsx
new file mode 100644
index 0000000000..f6a768e77e
--- /dev/null
+++ b/frontend/src/components/instance/InstanceFormBody.test.tsx
@@ -0,0 +1,380 @@
+import { create } from "@bufbuild/protobuf";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, expect, test, vi } from "vitest";
+import { Engine, State } from "@/types/proto-es/v1/common_pb";
+import {
+ DataSource_AuthenticationType,
+ DataSource_RedisType,
+ DataSourceType,
+ InstanceSchema,
+} from "@/types/proto-es/v1/instance_service_pb";
+import type { EditDataSource } from "./common";
+import {
+ InstanceFormProvider,
+ useInstanceFormContext,
+} from "./InstanceFormContext";
+
+const mocks = vi.hoisted(() => ({
+ translate: (key: string) => key,
+ hasInstancePermission: vi.fn(() => true),
+ pushNotification: vi.fn(),
+ createInstance: vi.fn(),
+ isSaaSMode: false,
+ hasSSL: false,
+ hasExtraParameters: false,
+ listInstanceDatabases: vi.fn(async () => ({
+ databases: ["app", "analytics"],
+ })),
+}));
+
+vi.mock("@/components/EngineIcon", () => ({ EngineIcon: () => null }));
+vi.mock("@/components/EnvironmentSelect", () => ({
+ EnvironmentSelect: () => null,
+}));
+vi.mock("@/components/FeatureBadge", () => ({ FeatureBadge: () => null }));
+vi.mock("@/components/LabelListEditor", () => ({
+ LabelListEditor: () => null,
+}));
+vi.mock("@/components/LearnMoreLink", () => ({ LearnMoreLink: () => null }));
+vi.mock("@/components/ResourceIdField", () => ({
+ ResourceIdField: () => null,
+}));
+vi.mock("@/components/RouterLink", () => ({ RouterLink: () => null }));
+vi.mock("./DataSourceForm", () => ({
+ DataSourceForm: ({
+ dataSource,
+ authOnly,
+ hideAuthentication,
+ onDataSourceChange,
+ }: {
+ dataSource: EditDataSource;
+ authOnly?: boolean;
+ hideAuthentication?: boolean;
+ onDataSourceChange: (value: EditDataSource) => void;
+ }) =>
+ authOnly ? (
+ <button
+ type="button"
+ onClick={() =>
+ onDataSourceChange({
+ ...dataSource,
+ authenticationType:
+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM,
+ })
+ }
+ >
+ authentication:{dataSource.id}
+ </button>
+ ) : (
+ <div
+ data-testid="credentials"
+ data-source={dataSource.id}
+ data-hide-auth={hideAuthentication}
+ />
+ ),
+ RedisSentinelFields: () => null,
+}));
+
+vi.mock("./permission", () => ({
+ hasInstancePermission: mocks.hasInstancePermission,
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: mocks.translate,
+ }),
+}));
+
+vi.mock("@/lib/i18n", () => ({
+ default: {
+ t: mocks.translate,
+ },
+}));
+
+vi.mock("monaco-editor", () => ({}));
+
+vi.mock(
+ "@codingame/monaco-vscode-editor-api/vscode/src/vs/editor/standalone/browser/standalone-tokens.css",
+ () => ({})
+);
+
+vi.mock("@/types", () => ({
+ UNKNOWN_ID: -1,
+ languageOfEngineV1: () => "sql",
+ isValidEnvironmentName: () => false,
+ DATASOURCE_ADMIN_USER_NAME: "bytebase",
+ DATASOURCE_READONLY_USER_NAME: "bytebase_readonly",
+ UNKNOWN_INSTANCE_NAME: "instances/-",
+ unknownDataSource: () => ({
+ id: "admin",
+ type: 1,
+ host: "",
+ port: "",
+ username: "",
+ password: "",
+ database: "",
+ additionalAddresses: [],
+ extraConnectionParameters: {},
+ }),
+}));
+
+vi.mock("@/stores", () => ({
+ pushNotification: mocks.pushNotification,
+}));
+
+let mockEnvironmentList: { id: string; name: string }[] = [];
+
+vi.mock("@/stores/app", () => {
+ const appState = () => ({
+ createDataSource: vi.fn(),
+ createInstance: mocks.createInstance,
+ listInstanceDatabases: mocks.listInstanceDatabases,
+ updateDataSource: vi.fn(),
+ getEnvironmentByName: (name: string) => ({ name }),
+ hasInstanceFeature: () => false,
+ hasUnifiedInstanceLicense: () => false,
+ instanceLicenseCount: () => 1,
+ activatedInstanceCount: () => 0,
+ currentPlan: () => 1,
+ isSaaSMode: () => mocks.isSaaSMode,
+ environmentList: mockEnvironmentList,
+ });
+ return {
+ useAppStore: Object.assign(
+ (selector: (state: unknown) => unknown) => selector(appState()),
+ { getState: appState }
+ ),
+ };
+});
+
+vi.mock("@/utils", () => ({
+ MAX_LABEL_VALUE_LENGTH: 63,
+ calcUpdateMask: () => [],
+ convertKVListToLabels: (list: { key: string; value: string }[]) =>
+ Object.fromEntries(list.map(({ key, value }) => [key, value])),
+ convertLabelsToKVList: (labels: Record<string, string>) =>
+ Object.entries(labels).map(([key, value]) => ({ key, value })),
+ hasWorkspacePermissionV2: () => true,
+ isValidEnvironmentName: () => false,
+ engineNameV1: () => "Engine",
+ extractInstanceResourceName: () => "prod",
+ onlyAllowNumber: (value: string) => /^\d+$/.test(value),
+ RE_GCP_PROJECT_ID: /^[a-z-]+$/,
+ RE_GCP_INSTANCE_ID: /^[a-z-]+$/,
+ instanceV1HasExtraParameters: () => mocks.hasExtraParameters,
+ instanceV1HasSSH: () => false,
+ instanceV1HasSSL: () => mocks.hasSSL,
+ isValidSpannerDataSource: (ds: { projectId: string; instanceId: string }) =>
+ ds.projectId !== "" && ds.instanceId !== "",
+ isValidBigQueryDataSource: (ds: { projectId: string }) => ds.projectId !== "",
+}));
+
+vi.mock("@/utils/connect", () => ({
+ extractGrpcErrorMessage: (error: unknown) =>
+ error instanceof Error ? error.message : String(error),
+}));
+
+vi.mock("@/components/ui/feature-modal", () => ({
+ FeatureModal: ({
+ open,
+ feature,
+ instance,
+ onOpenChange,
+ }: {
+ open: boolean;
+ feature: number | undefined;
+ instance?: { name: string };
+ onOpenChange: (open: boolean) => void;
+ }) =>
+ open ? (
+ <div
+ data-testid="feature-modal"
+ data-feature={String(feature)}
+ data-instance={instance?.name}
+ >
+ <button
+ data-testid="feature-modal-close"
+ type="button"
+ onClick={() => onOpenChange(false)}
+ />
+ </div>
+ ) : null,
+}));
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+import { InstanceFormBody } from "./InstanceFormBody";
+
+let context: ReturnType<typeof useInstanceFormContext>;
+function Editor() {
+ context = useInstanceFormContext();
+ return <InstanceFormBody />;
+}
+function mount(engine: Engine) {
+ return render(
+ <InstanceFormProvider
+ instance={create(InstanceSchema, {
+ name: "instances/prod",
+ title: "Prod",
+ engine,
+ state: State.ACTIVE,
+ dataSources: [
+ {
+ id: "admin",
+ type: DataSourceType.ADMIN,
+ authenticationType: DataSource_AuthenticationType.PASSWORD,
+ host: "primary.example.com",
+ port: "5432",
+ database: "postgres",
+ projectId: "admin-project",
+ instanceId: "admin-instance",
+ additionalAddresses: [{ host: "admin-node", port: "1234" }],
+ },
+ {
+ id: "readonly",
+ type: DataSourceType.READ_ONLY,
+ host: "replica.example.com",
+ port: "5433",
+ projectId: "reader-project",
+ instanceId: "reader-instance",
+ additionalAddresses: [{ host: "reader-node", port: "5678" }],
+ },
+ ],
+ })}
+ >
+ <Editor />
+ </InstanceFormProvider>
+ );
+}
+
+afterEach(cleanup);
+
+const input = (container: HTMLElement, id: string) =>
+ container.querySelector<HTMLInputElement>(`#${id}`)!;
+
+test("each connection tab edits its own endpoint and authentication", () => {
+ const { container } = mount(Engine.POSTGRES);
+ expect(input(container, "host").value).toBe("primary.example.com");
+ fireEvent.click(screen.getByRole("button", { name: "common.read-only" }));
+ expect(input(container, "host").value).toBe("replica.example.com");
+ expect(input(container, "port").value).toBe("5433");
+ expect(screen.getAllByTestId("credentials")[0].dataset.hideAuth).toBe("true");
+ fireEvent.change(input(container, "host"), {
+ target: { value: "new-replica.example.com" },
+ });
+ fireEvent.change(input(container, "port"), { target: { value: "6432" } });
+ fireEvent.click(
+ screen.getByRole("button", { name: "authentication:readonly" })
+ );
+ expect(context.editingDataSource).toMatchObject({
+ host: "new-replica.example.com",
+ port: "6432",
+ authenticationType: DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM,
+ });
+ expect(context.adminDataSource).toMatchObject({
+ host: "primary.example.com",
+ port: "5432",
+ authenticationType: DataSource_AuthenticationType.PASSWORD,
+ });
+ expect(
+ context.extractDataSourceFromEdit(Engine.POSTGRES, context.adminDataSource)
+ .database
+ ).toBe("postgres");
+ fireEvent.click(screen.getByRole("button", { name: "common.admin" }));
+ expect(input(container, "host").value).toBe("primary.example.com");
+ fireEvent.change(input(container, "host"), {
+ target: { value: "new-primary.example.com" },
+ });
+ expect(context.readonlyDataSourceList[0].host).toBe(
+ "new-replica.example.com"
+ );
+ fireEvent.click(screen.getByRole("button", { name: "common.read-only" }));
+ expect(input(container, "host").value).toBe("new-replica.example.com");
+});
+
+test.each([Engine.CASSANDRA, Engine.MONGODB])(
+ "additional addresses belong to the selected connection for engine %s",
+ (engine) => {
+ mount(engine);
+ fireEvent.click(screen.getByRole("button", { name: "common.read-only" }));
+ fireEvent.change(screen.getByDisplayValue("reader-node"), {
+ target: { value: "new-reader-node" },
+ });
+ fireEvent.change(screen.getByDisplayValue("5678"), {
+ target: { value: "8765" },
+ });
+ expect(context.readonlyDataSourceList[0].additionalAddresses).toEqual([
+ {
+ host: "new-reader-node",
+ port: "8765",
+ $typeName: "bytebase.v1.DataSource.Address",
+ },
+ ]);
+ fireEvent.click(
+ screen.getByRole("button", { name: "common.delete" })
+ );
+ expect(context.readonlyDataSourceList[0].additionalAddresses).toHaveLength(
+ 0
+ );
+ fireEvent.click(
+ screen.getByRole("button", { name: "common.add" })
+ );
+ expect(context.readonlyDataSourceList[0].additionalAddresses).toHaveLength(
+ 1
+ );
+ expect(context.adminDataSource.additionalAddresses[0]).toMatchObject({
+ host: "admin-node",
+ port: "1234",
+ });
+ }
+);
+
+test.each([Engine.SPANNER, Engine.BIGQUERY])(
+ "GCP resource fields belong to the selected connection for engine %s",
+ (engine) => {
+ mount(engine);
+ fireEvent.click(screen.getByRole("button", { name: "common.read-only" }));
+ fireEvent.change(screen.getByDisplayValue("reader-project"), {
+ target: { value: "updated-project" },
+ });
+ expect(context.readonlyDataSourceList[0].projectId).toBe("updated-project");
+ expect(context.adminDataSource.projectId).toBe("admin-project");
+ if (engine === Engine.SPANNER) {
+ fireEvent.change(screen.getByDisplayValue("reader-instance"), {
+ target: { value: "updated-instance" },
+ });
+ expect(context.readonlyDataSourceList[0].instanceId).toBe(
+ "updated-instance"
+ );
+ expect(context.adminDataSource.instanceId).toBe("admin-instance");
+ }
+ }
+);
+
+test("MongoDB SRV mode only clears the selected connection's address fields", () => {
+ const { container } = mount(Engine.MONGODB);
+ fireEvent.click(screen.getByRole("button", { name: "common.read-only" }));
+ fireEvent.click(screen.getByRole("radio", { name: "mongodb+srv://" }));
+ expect(context.readonlyDataSourceList[0]).toMatchObject({
+ srv: true,
+ port: "",
+ additionalAddresses: [],
+ });
+ expect(input(container, "port").disabled).toBe(true);
+ expect(context.adminDataSource).toMatchObject({ srv: false, port: "5432" });
+ expect(context.adminDataSource.additionalAddresses).toHaveLength(1);
+});
+
+test("Redis connection mode belongs to the selected data source", () => {
+ mount(Engine.REDIS);
+ fireEvent.click(screen.getByRole("button", { name: "common.read-only" }));
+ fireEvent.click(screen.getByRole("radio", { name: "Cluster" }));
+ expect(context.readonlyDataSourceList[0].redisType).toBe(
+ DataSource_RedisType.CLUSTER
+ );
+ expect(context.adminDataSource.redisType).not.toBe(
+ DataSource_RedisType.CLUSTER
+ );
+});
diff --git a/frontend/src/components/instance/InstanceFormBody.tsx b/frontend/src/components/instance/InstanceFormBody.tsx
index 4b9d505b5f..628f5d6e3e 100644
--- a/frontend/src/components/instance/InstanceFormBody.tsx
+++ b/frontend/src/components/instance/InstanceFormBody.tsx
@@ -850,7 +850,6 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
setBasicInfo,
labelKVList,
setLabelKVList,
- dataSourceEditState,
setDataSourceEditState,
adminDataSource,
editingDataSource,
@@ -858,6 +857,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
setResourceIdValidated,
parent,
} = ctx;
+ const connectionDataSource = editingDataSource ?? adminDataSource;
const {
isEngineBeta,
defaultPort,
@@ -940,13 +940,13 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
);
const currentMongoDBConnectionSchema = useMemo(() => {
- return adminDataSource.srv === false
+ return connectionDataSource.srv === false
? MongoDBConnectionStringSchemaList[0]
: MongoDBConnectionStringSchemaList[1];
- }, [adminDataSource.srv]);
+ }, [connectionDataSource.srv]);
const currentRedisConnectionType = useMemo(() => {
- switch (adminDataSource.redisType) {
+ switch (connectionDataSource.redisType) {
case DataSource_RedisType.STANDALONE:
return RedisConnectionType[0];
case DataSource_RedisType.SENTINEL:
@@ -956,20 +956,24 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
default:
return RedisConnectionType[0];
}
- }, [adminDataSource.redisType]);
+ }, [connectionDataSource.redisType]);
const showAdditionalAddresses = useMemo(() => {
if (basicInfo.engine === Engine.CASSANDRA) return true;
- if (basicInfo.engine === Engine.MONGODB && !adminDataSource.srv)
+ if (basicInfo.engine === Engine.MONGODB && !connectionDataSource.srv)
return true;
if (
basicInfo.engine === Engine.REDIS &&
- (adminDataSource.redisType === DataSource_RedisType.CLUSTER ||
- adminDataSource.redisType === DataSource_RedisType.SENTINEL)
+ (connectionDataSource.redisType === DataSource_RedisType.CLUSTER ||
+ connectionDataSource.redisType === DataSource_RedisType.SENTINEL)
)
return true;
return false;
- }, [basicInfo.engine, adminDataSource.srv, adminDataSource.redisType]);
+ }, [
+ basicInfo.engine,
+ connectionDataSource.srv,
+ connectionDataSource.redisType,
+ ]);
const hasHostInfo = useMemo(
() => hasInfoContent(basicInfo.engine, "host"),
@@ -985,12 +989,12 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
[setBasicInfo]
);
- const updateAdminDS = useCallback(
+ const updateConnectionDataSource = useCallback(
(partial: Partial<EditDataSource>) => {
setDataSourceEditState((prev) => ({
...prev,
dataSources: prev.dataSources.map((ds) =>
- ds.type === DataSourceType.ADMIN ? { ...ds, ...partial } : ds
+ ds.id === prev.editingDataSourceId ? { ...ds, ...partial } : ds
),
}));
},
@@ -1084,15 +1088,15 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
redisType = DataSource_RedisType.CLUSTER;
break;
}
- updateAdminDS({ redisType });
+ updateConnectionDataSource({ redisType });
},
- [updateAdminDS]
+ [updateConnectionDataSource]
);
const handleMongodbConnectionStringSchemaChange = useCallback(
(type: string) => {
if (type === MongoDBConnectionStringSchemaList[1]) {
- updateAdminDS({
+ updateConnectionDataSource({
port: "",
additionalAddresses: [],
replicaSet: "",
@@ -1100,10 +1104,10 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
srv: true,
});
} else {
- updateAdminDS({ srv: false });
+ updateConnectionDataSource({ srv: false });
}
},
- [updateAdminDS]
+ [updateConnectionDataSource]
);
const removeDSAdditionalAddress = useCallback(
@@ -1111,7 +1115,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
setDataSourceEditState((prev) => ({
...prev,
dataSources: prev.dataSources.map((ds) => {
- if (ds.type !== DataSourceType.ADMIN) return ds;
+ if (ds.id !== prev.editingDataSourceId) return ds;
const newAddresses = [...ds.additionalAddresses];
newAddresses.splice(index, 1);
return {
@@ -1130,7 +1134,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
setDataSourceEditState((prev) => ({
...prev,
dataSources: prev.dataSources.map((ds) => {
- if (ds.id !== dataSourceEditState.editingDataSourceId) return ds;
+ if (ds.id !== prev.editingDataSourceId) return ds;
const newAddresses = [
...ds.additionalAddresses,
create(DataSource_AddressSchema, { host: "", port: "" }),
@@ -1143,7 +1147,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
};
}),
}));
- }, [setDataSourceEditState, dataSourceEditState.editingDataSourceId]);
+ }, [setDataSourceEditState]);
const changeInstanceActivation = useCallback(
async (on: boolean) => {
@@ -1190,10 +1194,10 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
(e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
if (value === "" || /^\d+$/.test(value)) {
- updateAdminDS({ port: value });
+ updateConnectionDataSource({ port: value });
}
},
- [updateAdminDS]
+ [updateConnectionDataSource]
);
const handleAdditionalAddressHostChange = useCallback(
@@ -1201,7 +1205,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
setDataSourceEditState((prev) => ({
...prev,
dataSources: prev.dataSources.map((ds) => {
- if (ds.type !== DataSourceType.ADMIN) return ds;
+ if (ds.id !== prev.editingDataSourceId) return ds;
const newAddresses = [...ds.additionalAddresses];
newAddresses[index] = { ...newAddresses[index], host };
return { ...ds, additionalAddresses: newAddresses };
@@ -1217,7 +1221,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
setDataSourceEditState((prev) => ({
...prev,
dataSources: prev.dataSources.map((ds) => {
- if (ds.type !== DataSourceType.ADMIN) return ds;
+ if (ds.id !== prev.editingDataSourceId) return ds;
const newAddresses = [...ds.additionalAddresses];
newAddresses[index] = { ...newAddresses[index], port };
return { ...ds, additionalAddresses: newAddresses };
@@ -1231,7 +1235,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
<ValidationProvider
className="flex flex-col pb-2"
errors={{
- ...ctx.getDataSourceErrors(adminDataSource),
+ ...ctx.getDataSourceErrors(connectionDataSource),
...(!basicInfo.title.trim() ? { title: "required" } : {}),
}}
>
@@ -1444,154 +1448,247 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
{/* Connection Card */}
<FormSection layout="stacked" title={t("instance.section.connection")}>
- <div className="flex flex-col gap-4">
- {isSaaSMode && (
- <Alert variant="info">
- <div className="flex flex-wrap items-center gap-x-2">
- <span>{t("instance.sentence.firewall-info")}</span>
- <LearnMoreLink href="https://docs.bytebase.com/get-started/cloud#prerequisites" />
- </div>
- </Alert>
- )}
- {editingDataSource?.id === adminDataSource.id && (
- <DataSourceForm
- authOnly
- dataSource={adminDataSource}
- onDataSourceChange={handleDataSourceChange}
- onOpenInfoPanel={onOpenInfoPanel}
- />
- )}
- {/* Host input */}
- {basicInfo.engine === Engine.SPANNER ? (
- <SpannerHostInput
- projectId={adminDataSource.projectId}
- instanceId={adminDataSource.instanceId}
- endpoint={adminDataSource.host}
- port={adminDataSource.port}
- onUpdate={(update) => updateAdminDS(update)}
- allowEdit={allowEdit}
- />
- ) : basicInfo.engine === Engine.BIGQUERY ? (
- <BigQueryHostInput
- projectId={adminDataSource.projectId}
- endpoint={adminDataSource.host}
- port={adminDataSource.port}
- onUpdate={(update) => updateAdminDS(update)}
- allowEdit={allowEdit}
- />
- ) : (
- <FormField
- validationField="host"
- title={
- <span className="flex items-center gap-1">
- <FormLabel htmlFor="host">
- {basicInfo.engine === Engine.SNOWFLAKE
- ? t("instance.account-locator")
- : basicInfo.engine === Engine.COSMOSDB
- ? t("instance.endpoint")
- : adminDataSource.authenticationType ===
- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM
- ? t(
- "instance.sentence.google-cloud-sql.instance-name"
- )
- : t("instance.hostname")}
- {basicInfo.engine !== Engine.DYNAMODB && (
- <span className="text-error"> *</span>
+ <DataSourceSection
+ hideOptions
+ hideAuthentication
+ onOpenInfoPanel={onOpenInfoPanel}
+ >
+ <div className="flex flex-col gap-4">
+ {isSaaSMode && (
+ <Alert variant="info">
+ <div className="flex flex-wrap items-center gap-x-2">
+ <span>{t("instance.sentence.firewall-info")}</span>
+ <LearnMoreLink href="https://docs.bytebase.com/get-started/cloud#prerequisites" />
+ </div>
+ </Alert>
+ )}
+ {editingDataSource && (
+ <DataSourceForm
+ authOnly
+ dataSource={connectionDataSource}
+ onDataSourceChange={handleDataSourceChange}
+ onOpenInfoPanel={onOpenInfoPanel}
+ />
+ )}
+ {/* Host input */}
+ {basicInfo.engine === Engine.SPANNER ? (
+ <SpannerHostInput
+ projectId={connectionDataSource.projectId}
+ instanceId={connectionDataSource.instanceId}
+ endpoint={connectionDataSource.host}
+ port={connectionDataSource.port}
+ onUpdate={(update) => updateConnectionDataSource(update)}
+ allowEdit={allowEdit}
+ />
+ ) : basicInfo.engine === Engine.BIGQUERY ? (
+ <BigQueryHostInput
+ projectId={connectionDataSource.projectId}
+ endpoint={connectionDataSource.host}
+ port={connectionDataSource.port}
+ onUpdate={(update) => updateConnectionDataSource(update)}
+ allowEdit={allowEdit}
+ />
+ ) : (
+ <FormField
+ validationField="host"
+ title={
+ <span className="flex items-center gap-1">
+ <FormLabel htmlFor="host">
+ {basicInfo.engine === Engine.SNOWFLAKE
+ ? t("instance.account-locator")
+ : basicInfo.engine === Engine.COSMOSDB
+ ? t("instance.endpoint")
+ : connectionDataSource.authenticationType ===
+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM
+ ? t(
+ "instance.sentence.google-cloud-sql.instance-name"
+ )
+ : t("instance.hostname")}
+ {basicInfo.engine !== Engine.DYNAMODB && (
+ <span className="text-error"> *</span>
+ )}
+ </FormLabel>
+ {onOpenInfoPanel && hasHostInfo && (
+ <Button
+ appearance="link"
+ size="xs"
+ className="h-auto shrink-0 p-0"
+ aria-label={t("instance.hostname")}
+ onClick={() => openInfoPanel("host")}
+ >
+ <Info className="size-3.5" />
+ </Button>
)}
- </FormLabel>
- {onOpenInfoPanel && hasHostInfo && (
- <Button
- appearance="link"
- size="xs"
- className="h-auto shrink-0 p-0"
- aria-label={t("instance.hostname")}
- onClick={() => openInfoPanel("host")}
- >
- <Info className="size-3.5" />
- </Button>
- )}
- </span>
- }
- >
- <div className="flex items-center gap-2">
- <Input
- id="host"
- value={adminDataSource.host}
- required={basicInfo.engine !== Engine.DYNAMODB}
- placeholder={
- basicInfo.engine === Engine.SNOWFLAKE
- ? t("instance.your-snowflake-account-locator")
- : isSaaSMode
- ? t("instance.sentence.host.saas")
- : t("instance.sentence.host.none-snowflake")
- }
- className="min-w-0 flex-1"
- disabled={!allowEdit}
- onChange={(e) => updateAdminDS({ host: e.target.value })}
- />
- {basicInfo.engine !== Engine.DATABRICKS &&
- basicInfo.engine !== Engine.COSMOSDB &&
- adminDataSource.authenticationType !==
- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM && (
- <>
- <FormLabel htmlFor="port">
- {t("instance.port")}
- </FormLabel>
- <Input
- id="port"
- value={adminDataSource.port}
- className="w-20 shrink-0"
- placeholder={defaultPort}
- disabled={!allowEdit || !allowEditPort}
- onChange={handlePortChange}
- />
- </>
- )}
- </div>
- {adminDataSource.authenticationType ===
- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM && (
- <p className="text-xs text-control-light">
- {t(
- "instance.sentence.google-cloud-sql.instance-name-tips",
- { instance: "{project-id}:{region}:{instance-name}" }
- )}
- </p>
- )}
- {basicInfo.engine === Engine.SNOWFLAKE && (
- <LearnMoreLink href="https://docs.snowflake.com/en/user-guide/admin-account-identifier#using-an-account-locator-as-an-identifier" />
- )}
- </FormField>
- )}
-
- {/* MongoDB connection string schema */}
- {basicInfo.engine === Engine.MONGODB && (
- <FormField>
- <FormLabel htmlFor="connectionStringSchema">
- {t("data-source.connection-string-schema")}
- </FormLabel>
- <RadioGroup
- className="gap-x-4"
- value={currentMongoDBConnectionSchema}
- onValueChange={(value) =>
- handleMongodbConnectionStringSchemaChange(value as string)
+ </span>
}
>
- {MongoDBConnectionStringSchemaList.map((type) => (
- <RadioGroupItem key={type} value={type}>
- {type}
- </RadioGroupItem>
- ))}
- </RadioGroup>
- {!adminDataSource.srv && (
- <ResponsiveFormLayout className="mt-2">
- <fieldset
- aria-label={t("data-source.connection-string-schema")}
- className="flex flex-col gap-4 rounded-xs border border-control-border px-3 py-2"
- >
- {/* Additional addresses */}
- {showAdditionalAddresses && (
+ <div className="flex items-center gap-2">
+ <Input
+ id="host"
+ value={connectionDataSource.host}
+ required={basicInfo.engine !== Engine.DYNAMODB}
+ placeholder={
+ basicInfo.engine === Engine.SNOWFLAKE
+ ? t("instance.your-snowflake-account-locator")
+ : isSaaSMode
+ ? t("instance.sentence.host.saas")
+ : t("instance.sentence.host.none-snowflake")
+ }
+ className="min-w-0 flex-1"
+ disabled={!allowEdit}
+ onChange={(e) =>
+ updateConnectionDataSource({ host: e.target.value })
+ }
+ />
+ {basicInfo.engine !== Engine.DATABRICKS &&
+ basicInfo.engine !== Engine.COSMOSDB &&
+ connectionDataSource.authenticationType !==
+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM && (
+ <>
+ <FormLabel htmlFor="port">
+ {t("instance.port")}
+ </FormLabel>
+ <Input
+ id="port"
+ value={connectionDataSource.port}
+ className="w-20 shrink-0"
+ placeholder={defaultPort}
+ disabled={!allowEdit || !allowEditPort}
+ onChange={handlePortChange}
+ />
+ </>
+ )}
+ </div>
+ {connectionDataSource.authenticationType ===
+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM && (
+ <p className="text-xs text-control-light">
+ {t(
+ "instance.sentence.google-cloud-sql.instance-name-tips",
+ { instance: "{project-id}:{region}:{instance-name}" }
+ )}
+ </p>
+ )}
+ {basicInfo.engine === Engine.SNOWFLAKE && (
+ <LearnMoreLink href="https://docs.snowflake.com/en/user-guide/admin-account-identifier#using-an-account-locator-as-an-identifier" />
+ )}
+ </FormField>
+ )}
+
+ {/* MongoDB connection string schema */}
+ {basicInfo.engine === Engine.MONGODB && (
+ <FormField>
+ <FormLabel htmlFor="connectionStringSchema">
+ {t("data-source.connection-string-schema")}
+ </FormLabel>
+ <RadioGroup
+ className="gap-x-4"
+ value={currentMongoDBConnectionSchema}
+ onValueChange={(value) =>
+ handleMongodbConnectionStringSchemaChange(value as string)
+ }
+ >
+ {MongoDBConnectionStringSchemaList.map((type) => (
+ <RadioGroupItem key={type} value={type}>
+ {type}
+ </RadioGroupItem>
+ ))}
+ </RadioGroup>
+ {!connectionDataSource.srv && (
+ <ResponsiveFormLayout className="mt-2">
+ <fieldset
+ aria-label={t("data-source.connection-string-schema")}
+ className="flex flex-col gap-4 rounded-xs border border-control-border px-3 py-2"
+ >
+ {/* Additional addresses */}
+ {showAdditionalAddresses && (
+ <AdditionalAddressesFields
+ addresses={connectionDataSource.additionalAddresses}
+ defaultPort={defaultPort}
+ allowEdit={allowEdit}
+ allowEditPort={allowEditPort}
+ onAdd={addDSAdditionalAddress}
+ onRemove={removeDSAdditionalAddress}
+ onHostChange={handleAdditionalAddressHostChange}
+ onPortChange={handleAdditionalAddressPortChange}
+ />
+ )}
+ {/* MongoDB replica set */}
+ {basicInfo.engine === Engine.MONGODB &&
+ !connectionDataSource.srv && (
+ <FormField>
+ <FormLabel htmlFor="replicaSet">
+ {t("data-source.replica-set")}
+ </FormLabel>
+ <Input
+ value={connectionDataSource.replicaSet}
+ required
+ className="w-full"
+ disabled={!allowEdit}
+ onChange={(e) =>
+ updateConnectionDataSource({
+ replicaSet: e.target.value,
+ })
+ }
+ />
+ </FormField>
+ )}
+ {/* MongoDB direct connection */}
+ {basicInfo.engine === Engine.MONGODB &&
+ !connectionDataSource.srv &&
+ connectionDataSource.additionalAddresses.length ===
+ 0 && (
+ <FormControlRow className="w-fit">
+ <Checkbox
+ id="directConnection"
+ checked={connectionDataSource.directConnection}
+ disabled={!allowEdit}
+ onCheckedChange={(checked) =>
+ updateConnectionDataSource({
+ directConnection: checked,
+ })
+ }
+ />
+ <FormLabel
+ htmlFor="directConnection"
+ className="font-normal!"
+ >
+ {t("data-source.direct-connection")}
+ </FormLabel>
+ </FormControlRow>
+ )}{" "}
+ </fieldset>
+ </ResponsiveFormLayout>
+ )}
+ </FormField>
+ )}
+
+ {/* Redis connection type */}
+ {basicInfo.engine === Engine.REDIS && (
+ <FormField>
+ <FormLabel htmlFor="connectionStringSchema">
+ {t("data-source.connection-type")}
+ </FormLabel>
+ <RadioGroup
+ className="gap-x-4"
+ value={currentRedisConnectionType}
+ onValueChange={(value) =>
+ handleRedisConnectionTypeChange(value as string)
+ }
+ >
+ {RedisConnectionType.map((type) => (
+ <RadioGroupItem key={type} value={type}>
+ {type}
+ </RadioGroupItem>
+ ))}
+ </RadioGroup>
+ {showAdditionalAddresses && (
+ <ResponsiveFormLayout className="mt-2">
+ <fieldset
+ aria-label={currentRedisConnectionType}
+ className="flex flex-col gap-4 rounded-xs border border-control-border px-3 py-2"
+ >
<AdditionalAddressesFields
- addresses={adminDataSource.additionalAddresses}
+ addresses={connectionDataSource.additionalAddresses}
defaultPort={defaultPort}
allowEdit={allowEdit}
allowEditPort={allowEditPort}
@@ -1600,128 +1697,39 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
onHostChange={handleAdditionalAddressHostChange}
onPortChange={handleAdditionalAddressPortChange}
/>
- )}
- {/* MongoDB replica set */}
- {basicInfo.engine === Engine.MONGODB &&
- !adminDataSource.srv && (
- <FormField>
- <FormLabel htmlFor="replicaSet">
- {t("data-source.replica-set")}
- </FormLabel>
- <Input
- value={adminDataSource.replicaSet}
- required
- className="w-full"
- disabled={!allowEdit}
- onChange={(e) =>
- updateAdminDS({ replicaSet: e.target.value })
- }
- />
- </FormField>
- )}
- {/* MongoDB direct connection */}
- {basicInfo.engine === Engine.MONGODB &&
- !adminDataSource.srv &&
- adminDataSource.additionalAddresses.length === 0 && (
- <FormControlRow className="w-fit">
- <Checkbox
- id="directConnection"
- checked={adminDataSource.directConnection}
- disabled={!allowEdit}
- onCheckedChange={(checked) =>
- updateAdminDS({
- directConnection: checked,
- })
- }
- />
- <FormLabel
- htmlFor="directConnection"
- className="font-normal!"
- >
- {t("data-source.direct-connection")}
- </FormLabel>
- </FormControlRow>
- )}{" "}
- </fieldset>
- </ResponsiveFormLayout>
- )}
- </FormField>
- )}
-
- {/* Redis connection type */}
- {basicInfo.engine === Engine.REDIS && (
- <FormField>
- <FormLabel htmlFor="connectionStringSchema">
- {t("data-source.connection-type")}
- </FormLabel>
- <RadioGroup
- className="gap-x-4"
- value={currentRedisConnectionType}
- onValueChange={(value) =>
- handleRedisConnectionTypeChange(value as string)
- }
- >
- {RedisConnectionType.map((type) => (
- <RadioGroupItem key={type} value={type}>
- {type}
- </RadioGroupItem>
- ))}
- </RadioGroup>
- {showAdditionalAddresses && (
- <ResponsiveFormLayout className="mt-2">
- <fieldset
- aria-label={currentRedisConnectionType}
- className="flex flex-col gap-4 rounded-xs border border-control-border px-3 py-2"
- >
- <AdditionalAddressesFields
- addresses={adminDataSource.additionalAddresses}
- defaultPort={defaultPort}
+ </fieldset>
+ </ResponsiveFormLayout>
+ )}
+ {editingDataSource?.redisType ===
+ DataSource_RedisType.SENTINEL && (
+ <ResponsiveFormLayout className="mt-2">
+ <RedisSentinelFields
+ dataSource={editingDataSource}
+ isCreating={isCreating}
allowEdit={allowEdit}
- allowEditPort={allowEditPort}
- onAdd={addDSAdditionalAddress}
- onRemove={removeDSAdditionalAddress}
- onHostChange={handleAdditionalAddressHostChange}
- onPortChange={handleAdditionalAddressPortChange}
+ allowUsingEmptyPassword={allowUsingEmptyPassword}
+ onDataSourceChange={handleDataSourceChange}
/>
- </fieldset>
- </ResponsiveFormLayout>
- )}
- {editingDataSource?.redisType ===
- DataSource_RedisType.SENTINEL && (
- <ResponsiveFormLayout className="mt-2">
- <RedisSentinelFields
- dataSource={editingDataSource}
- isCreating={isCreating}
- allowEdit={allowEdit}
- allowUsingEmptyPassword={allowUsingEmptyPassword}
- onDataSourceChange={handleDataSourceChange}
- />
- </ResponsiveFormLayout>
- )}
- </FormField>
- )}
-
- {/* Additional addresses */}
- {basicInfo.engine === Engine.CASSANDRA && (
- <AdditionalAddressesFields
- addresses={adminDataSource.additionalAddresses}
- defaultPort={defaultPort}
- allowEdit={allowEdit}
- allowEditPort={allowEditPort}
- onAdd={addDSAdditionalAddress}
- onRemove={removeDSAdditionalAddress}
- onHostChange={handleAdditionalAddressHostChange}
- onPortChange={handleAdditionalAddressPortChange}
- />
- )}
- </div>
+ </ResponsiveFormLayout>
+ )}
+ </FormField>
+ )}
- {/* Credentials (auth method, username, password) */}
- <DataSourceSection
- hideOptions
- hideAdminAuthentication
- onOpenInfoPanel={onOpenInfoPanel}
- />
+ {/* Additional addresses */}
+ {basicInfo.engine === Engine.CASSANDRA && (
+ <AdditionalAddressesFields
+ addresses={connectionDataSource.additionalAddresses}
+ defaultPort={defaultPort}
+ allowEdit={allowEdit}
+ allowEditPort={allowEditPort}
+ onAdd={addDSAdditionalAddress}
+ onRemove={removeDSAdditionalAddress}
+ onHostChange={handleAdditionalAddressHostChange}
+ onPortChange={handleAdditionalAddressPortChange}
+ />
+ )}
+ </div>
+ </DataSourceSection>
{basicInfo.engine !== Engine.DYNAMODB && editingDataSource && (
<div className="mt-4">
@@ -1736,31 +1744,34 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
</div>
)}
- {basicInfo.engine !== Engine.DYNAMODB && (
- <div className="mt-4">
- <SyncDatabases
- isCreating={isCreating}
- showLabel
- allowEdit={isCreating ? allowEdit && !!allowCreate : allowEdit}
- disabledReason={
- isCreating && allowEdit && !allowCreate
- ? !adminDataSource.host &&
- ![
- Engine.SPANNER,
- Engine.BIGQUERY,
- Engine.DYNAMODB,
- ].includes(basicInfo.engine)
- ? t("instance.sync-databases.hostname-required")
- : t("instance.sync-databases.required-fields")
- : undefined
- }
- projectName={parent}
- onOpenInfoPanel={onOpenInfoPanel}
- syncDatabases={basicInfo.syncDatabases}
- onSyncDatabasesChange={handleChangeSyncDatabases}
- />
- </div>
- )}
+ {basicInfo.engine !== Engine.DYNAMODB &&
+ connectionDataSource.type === DataSourceType.ADMIN && (
+ <div className="mt-4">
+ <SyncDatabases
+ isCreating={isCreating}
+ showLabel
+ allowEdit={
+ isCreating ? allowEdit && !!allowCreate : allowEdit
+ }
+ disabledReason={
+ isCreating && allowEdit && !allowCreate
+ ? !adminDataSource.host &&
+ ![
+ Engine.SPANNER,
+ Engine.BIGQUERY,
+ Engine.DYNAMODB,
+ ].includes(basicInfo.engine)
+ ? t("instance.sync-databases.hostname-required")
+ : t("instance.sync-databases.required-fields")
+ : undefined
+ }
+ projectName={parent}
+ onOpenInfoPanel={onOpenInfoPanel}
+ syncDatabases={basicInfo.syncDatabases}
+ onSyncDatabasesChange={handleChangeSyncDatabases}
+ />
+ </div>
+ )}
</FormSection>
</div>
</ValidationProvider>
diff --git a/frontend/src/components/instance/InstanceFormContext.tsx b/frontend/src/components/instance/InstanceFormContext.tsx
index 2ba2f0fb22..4c82c88775 100644
--- a/frontend/src/components/instance/InstanceFormContext.tsx
+++ b/frontend/src/components/instance/InstanceFormContext.tsx
@@ -46,7 +46,11 @@ import {
} from "./common";
import { effectivePortForEngine } from "./constants";
import { hasInstancePermission } from "./permission";
-import { type InstanceSpecs, useInstanceSpecs } from "./specs";
+import {
+ hasConnectionDatabase,
+ type InstanceSpecs,
+ useInstanceSpecs,
+} from "./specs";
import { type ValidationErrors, validateDataSource } from "./validation";
export type LocalState = {
@@ -325,7 +329,7 @@ export function InstanceFormProvider({
ds.externalSecret = undefined;
}
ds.port = effectivePortForEngine(engine, ds.port, ds.srv);
- if (!specs.showDatabase) ds.database = "";
+ if (!hasConnectionDatabase(engine, ds.type)) ds.database = "";
if (engine !== Engine.ORACLE) {
ds.sid = "";
ds.serviceName = "";
diff --git a/frontend/src/components/instance/specs.ts b/frontend/src/components/instance/specs.ts
index 72b92e607b..5b35488ec1 100644
--- a/frontend/src/components/instance/specs.ts
+++ b/frontend/src/components/instance/specs.ts
@@ -19,23 +19,24 @@ export interface InstanceSpecs {
allowEditPort: boolean;
allowUsingEmptyPassword: boolean;
showAuthenticationDatabase: boolean;
- hasReadonlyReplicaHost: boolean;
- hasReadonlyReplicaPort: boolean;
hasExtraParameters: boolean;
}
+export const hasConnectionDatabase = (engine: Engine, type: DataSourceType) =>
+ [Engine.POSTGRES, Engine.REDSHIFT, Engine.COCKROACHDB, Engine.MSSQL].includes(
+ engine
+ ) && type === DataSourceType.ADMIN;
+
export const useInstanceSpecs = (
basicInfo: BasicInfo,
adminDataSource: EditDataSource,
editingDataSource: EditDataSource | undefined
): InstanceSpecs => {
return useMemo(() => {
- const showDatabase =
- (basicInfo.engine === Engine.POSTGRES ||
- basicInfo.engine === Engine.REDSHIFT ||
- basicInfo.engine === Engine.COCKROACHDB ||
- basicInfo.engine === Engine.MSSQL) &&
- editingDataSource?.type === DataSourceType.ADMIN;
+ const showDatabase = hasConnectionDatabase(
+ basicInfo.engine,
+ editingDataSource?.type ?? DataSourceType.DATA_SOURCE_UNSPECIFIED
+ );
const showSSL = instanceV1HasSSL(basicInfo.engine);
const showSSH = instanceV1HasSSH(basicInfo.engine);
@@ -59,8 +60,6 @@ export const useInstanceSpecs = (
const allowUsingEmptyPassword = basicInfo.engine !== Engine.SPANNER;
const showAuthenticationDatabase = basicInfo.engine === Engine.MONGODB;
- const hasReadonlyReplicaHost = basicInfo.engine !== Engine.SPANNER;
- const hasReadonlyReplicaPort = basicInfo.engine !== Engine.SPANNER;
const hasExtraParameters = instanceV1HasExtraParameters(basicInfo.engine);
return {
@@ -73,8 +72,6 @@ export const useInstanceSpecs = (
allowEditPort,
allowUsingEmptyPassword,
showAuthenticationDatabase,
- hasReadonlyReplicaHost,
- hasReadonlyReplicaPort,
hasExtraParameters,
};
}, [
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 806a4749ad..d1ba6811ce 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -633,8 +633,6 @@
"private-key-passphrase": "Private Key Passphrase",
"private-key-passphrase-tip": "Optional passphrase for encrypted private keys",
"read-only": "RO",
- "read-replica-host": "Read-replica Host",
- "read-replica-port": "Read-replica Port",
"replica-set": "Replica Set",
"select-query-data-source": "Select query data source",
"snowflake-keypair-tip": "Key-pair authentication",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 2ab483705b..15d596ea6f 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -633,8 +633,6 @@
"private-key-passphrase": "Frase de contraseña de clave privada",
"private-key-passphrase-tip": "Frase de contraseña opcional para claves privadas cifradas",
"read-only": "Solo lectura",
- "read-replica-host": "Anfitrión de réplica de lectura",
- "read-replica-port": "Puerto de réplica de lectura",
"replica-set": "Conjunto de réplicas",
"select-query-data-source": "Seleccionar fuente de datos de consulta",
"snowflake-keypair-tip": "Autenticación de par de claves",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index c35644ef5e..4bd9b63f3d 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -633,8 +633,6 @@
"private-key-passphrase": "秘密鍵のパスフレーズ",
"private-key-passphrase-tip": "暗号化された秘密鍵のオプションパスフレーズ",
"read-only": "読み取り専用",
- "read-replica-host": "リードレプリカホスト",
- "read-replica-port": "リードレプリカポート",
"replica-set": "レプリカセット",
"select-query-data-source": "クエリデータソースの選択",
"snowflake-keypair-tip": "キーペア認証",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index ea7572a35e..7a57d2f8f4 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -633,8 +633,6 @@
"private-key-passphrase": "Mật khẩu khóa riêng",
"private-key-passphrase-tip": "Mật khẩu tùy chọn cho khóa riêng được mã hóa",
"read-only": "Chỉ đọc",
- "read-replica-host": "Máy chủ bản sao đọc",
- "read-replica-port": "Cổng bản sao đọc",
"replica-set": "Bộ bản sao",
"select-query-data-source": "Chọn nguồn dữ liệu truy vấn",
"snowflake-keypair-tip": "Xác thực cặp khóa",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index b850d903c0..d444776672 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -633,8 +633,6 @@
"private-key-passphrase": "私钥密码",
"private-key-passphrase-tip": "加密私钥的可选密码",
"read-only": "只读",
- "read-replica-host": "只读副本 Host",
- "read-replica-port": "只读副本端口",
"replica-set": "副本集",
"select-query-data-source": "选择查询数据源",
"snowflake-keypair-tip": "密钥对认证",