Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: combine `CreateInstanceForm` and `InstanceForm` (#4880)
boojack88510ea14e9c
diff --git a/frontend/src/components/CreateInstanceForm.vue b/frontend/src/components/CreateInstanceForm.vuedeleted file mode 100644index feb40bc175..0000000000--- a/frontend/src/components/CreateInstanceForm.vue+++ /dev/null@@ -1,795 +0,0 @@-<template>- <div class="space-y-6 divide-y divide-block-border">- <div class="divide-y divide-block-border">- <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-7">- <template v-for="engine in engineList" :key="engine">- <div- class="flex relative justify-center px-2 py-4 border border-control-border hover:bg-control-bg-hover cursor-pointer"- @click.capture="changeInstanceEngine(engine)"- >- <div class="flex flex-col items-center">- <img class="h-8 w-auto" :src="EngineIconPath[engine]" />- <p class="mt-2 text-center textlabel">- {{ engineName(engine) }}- </p>- <template v-if="isEngineBeta(engine)">- <BBBetaBadge class="absolute right-0.5 top-1" />- </template>- <div class="mt-4 radio text-sm">- <input- type="radio"- class="btn"- :checked="state.instance.engine == engine"- />- </div>- </div>- </div>- </template>- </div>- <!-- Instance Name -->- <div class="mt-6 grid grid-cols-1 gap-y-6 gap-x-4 pt-4 sm:grid-cols-4">- <div class="sm:col-span-2 sm:col-start-1">- <label for="name" class="textlabel flex flex-row items-center">- {{ $t("instance.instance-name") }}- - <span style="color: red">*</span>- </label>- <input- id="name"- required- name="name"- type="text"- class="textfield mt-1 w-full"- :disabled="!allowEdit"- :value="state.instance.name"- @input="handleInstanceNameInput"- />- </div>-- <div class="sm:col-span-2 sm:col-start-1">- <label for="environment" class="textlabel">- {{ $t("common.environment") }}- <span style="color: red">*</span>- </label>- <!-- Disallow changing environment after creation. This is to take the conservative approach to limit capability -->- <!-- eslint-disable vue/attribute-hyphenation -->- <EnvironmentSelect- id="environment"- class="mt-1 w-full"- name="environment"- :selectedId="state.instance.environmentId"- @select-environment-id="- (environmentId) => {- state.instance.environmentId = environmentId;- }- "- />- </div>-- <div class="sm:col-span-3 sm:col-start-1">- <template v-if="state.instance.engine !== 'SPANNER'">- <label for="host" class="textlabel block">- <template v-if="state.instance.engine == 'SNOWFLAKE'">- {{ $t("instance.account-name") }}- <span style="color: red">*</span>- </template>- <template v-else>- {{ $t("instance.host-or-socket") }}- <span style="color: red">*</span>- </template>- </label>- <input- id="host"- required- type="text"- name="host"- :placeholder="- state.instance.engine == 'SNOWFLAKE'- ? $t('instance.your-snowflake-account-name')- : $t('instance.sentence.host.snowflake')- "- class="textfield mt-1 w-full"- :disabled="!allowEdit"- :value="state.instance.host"- @input="handleInstanceHostInput"- />- <div- v-if="state.instance.engine == 'SNOWFLAKE'"- class="mt-2 textinfolabel"- >- {{ $t("instance.sentence.proxy.snowflake") }}- </div>- </template>- <SpannerHostInput- v-else- v-model:host="state.instance.host"- :allow-edit="allowEdit"- />- </div>-- <template v-if="state.instance.engine !== 'SPANNER'">- <div class="sm:col-span-1">- <label for="port" class="textlabel block">{{- $t("instance.port")- }}</label>- <input- id="port"- type="number"- name="port"- class="textfield mt-1 w-full"- :placeholder="defaultPort"- :disabled="!allowEdit"- :value="state.instance.port"- @wheel="handleInstancePortWheelScroll"- @input="handleInstancePortInput"- />- </div>- </template>-- <div- v-if="state.instance.engine === 'MONGODB'"- class="sm:col-span-4 sm:col-start-1"- >- <label- for="connectionStringSchema"- class="textlabel flex flex-row items-center"- >- {{ $t("data-source.connection-string-schema") }}- </label>- <label- v-for="type in mongodbConnectionStringSchemaList"- :key="type"- class="radio h-7"- >- <input- type="radio"- class="btn"- name="connectionStringSchema"- :value="type"- :checked="type === mongodbConnectionStringSchemaList[0]"- @change="handleMongodbConnectionStringSchemaChange"- />- <span class="label">- {{ type }}- </span>- </label>- </div>- </div>-- <p class="mt-6 pt-4 w-full text-lg leading-6 font-medium text-gray-900">- {{ $t("instance.connection-info") }}- </p>-- <div- class="mt-2 grid grid-cols-1 gap-y-2 gap-x-4 border-none sm:grid-cols-3"- >- <template v-if="state.instance.engine !== 'SPANNER'">- <CreateDataSourceExample- className="sm:col-span-3"- :createInstanceFlag="true"- :engineType="state.instance.engine"- :dataSourceType="'ADMIN'"- />- </template>-- <template v-if="state.instance.engine !== 'SPANNER'">- <div class="sm:col-span-1 sm:col-start-1">- <label for="username" class="textlabel block">{{- $t("common.username")- }}</label>- <!-- For mysql, username can be empty indicating anonymous user.- But it's a very bad practice to use anonymous user for admin operation,- thus we make it REQUIRED here.-->- <input- id="username"- name="username"- type="text"- class="textfield mt-1 w-full"- :placeholder="- state.instance.engine === 'CLICKHOUSE'- ? $t('common.default')- : ''- "- :value="state.instance.username"- @input="handleInstanceUsernameInput"- />- </div>- </template>-- <div- v-if="state.instance.engine !== 'SPANNER'"- class="sm:col-span-1 sm:col-start-1"- >- <div class="flex flex-row items-center space-x-2">- <label for="password" class="textlabel block">- {{ $t("common.password") }}- </label>- </div>- <input- id="password"- name="password"- type="text"- class="textfield mt-1 w-full"- autocomplete="off"- :placeholder="$t('instance.password-write-only')"- :value="state.instance.password"- @input="handleInstancePasswordInput"- />- </div>-- <SpannerCredentialInput- v-else- :value="state.instance.password ?? ''"- :write-only="false"- class="mt-2 sm:col-span-3 sm:col-start-1"- @update:value="(value) => (state.instance.password = value)"- />-- <div v-if="showDatabase" class="sm:col-span-1 sm:col-start-1">- <div class="flex flex-row items-center space-x-2">- <label for="database" class="textlabel block">- {{ $t("common.database") }}- </label>- </div>- <input- id="database"- name="database"- type="text"- class="textfield mt-1 w-full"- autocomplete="off"- :placeholder="$t('common.database')"- :value="state.instance.database"- @input="handleInstanceDatabaseInput"- />- </div>-- <div- v-if="showAuthenticationDatabase"- class="sm:col-span-1 sm:col-start-1"- >- <div class="flex flex-row items-center space-x-2">- <label for="authenticationDatabase" class="textlabel block">- {{ $t("instance.authentication-database") }}- </label>- </div>- <input- id="authenticationDatabase"- name="authenticationDatabase"- type="text"- class="textfield mt-1 w-full"- autocomplete="off"- placeholder="admin"- :value="state.instance.authenticationDatabase"- @input="handleInstanceAuthenticationDatabaseInput"- />- </div>-- <div v-if="showSSL" class="sm:col-span-3 sm:col-start-1">- <div class="flex flex-row items-center space-x-2">- <label class="textlabel block">{{- $t("data-source.ssl-connection")- }}</label>- </div>- <SslCertificateForm- :value="state.instance"- @change="Object.assign(state.instance, $event)"- />- </div>- </div>-- <div class="mt-6 border-none">- <div class="flex flex-row space-x-2">- <button- type="button"- class="btn-normal whitespace-nowrap items-center"- :disabled="!allowCreate || state.isPingingInstance"- @click.prevent="testConnection"- >- {{ $t("instance.test-connection") }}- </button>- </div>- </div>- </div>-- <!-- Action Button Group -->- <div class="pt-4">- <!-- Create button group -->- <div class="flex justify-end items-center">- <div class="flex justify-end items-center">- <BBSpin- v-if="state.isCreatingInstance"- :title="$t('common.creating')"- />- <BBSpin- v-if="state.isPingingInstance"- :title="$t('common.connecting')"- />- <div class="ml-2">- <button- type="button"- class="btn-normal py-2 px-4"- :disabled="state.isCreatingInstance || state.isPingingInstance"- @click.prevent="cancel"- >- {{ $t("common.cancel") }}- </button>- <button- type="button"- class="btn-primary ml-3 inline-flex justify-center py-2 px-4"- :disabled="- !allowCreate ||- state.isCreatingInstance ||- state.isPingingInstance- "- @click.prevent="tryCreate"- >- {{ $t("common.create") }}- </button>- </div>- </div>- </div>- </div>- </div>- <BBAlert- v-if="state.showCreateInstanceWarningModal"- :style="'WARN'"- :ok-text="warningModalOkText"- :title="$t('instance.connection-info-seems-to-be-incorrect')"- :description="state.createInstanceWarning"- :in-progress="shouldShowAddSamplePostgresButton && isAddingSampleInstance"- :progress-text="$t('common.creating')"- @ok="handleWarningModalOkClick"- @cancel="state.showCreateInstanceWarningModal = false"- ></BBAlert>-</template>--<script lang="ts" setup>-import { computed, reactive, ref, watch } from "vue";-import { useRouter } from "vue-router";-import EnvironmentSelect from "./EnvironmentSelect.vue";-import CreateDataSourceExample from "./CreateDataSourceExample.vue";-import {- SpannerHostInput,- SpannerCredentialInput,- SslCertificateForm,-} from "./InstanceForm";-import { instanceSlug, isDev, isValidSpannerHost } from "../utils";-import {- InstanceCreate,- UNKNOWN_ID,- ConnectionInfo,- SQLResultSet,- EngineType,- engineName,-} from "../types";-import isEmpty from "lodash-es/isEmpty";-import { useI18n } from "vue-i18n";-import {- pushNotification,- useInstanceStore,- useOnboardingGuideStore,- useSQLStore,-} from "@/store";-import { BBBetaBadge } from "@/bbkit";--interface LocalState {- instance: InstanceCreate;- isPingingInstance: boolean;- isCreatingInstance: boolean;- showCreateInstanceWarningModal: boolean;- createInstanceWarning: string;-}--const emit = defineEmits(["dismiss"]);--const router = useRouter();-const { t } = useI18n();-const sqlStore = useSQLStore();--const engineList = computed(() => {- const engines: EngineType[] = [- "MYSQL",- "POSTGRES",- "TIDB",- "SNOWFLAKE",- "CLICKHOUSE",- "MONGODB",- "SPANNER",- ];- return engines;-});--const EngineIconPath = {- MYSQL: new URL("../assets/db-mysql.png", import.meta.url).href,- POSTGRES: new URL("../assets/db-postgres.png", import.meta.url).href,- TIDB: new URL("../assets/db-tidb.png", import.meta.url).href,- SNOWFLAKE: new URL("../assets/db-snowflake.png", import.meta.url).href,- CLICKHOUSE: new URL("../assets/db-clickhouse.png", import.meta.url).href,- MONGODB: new URL("../assets/db-mongodb.png", import.meta.url).href,- SPANNER: new URL("../assets/db-spanner.png", import.meta.url).href,-};--const state = reactive<LocalState>({- instance: {- environmentId: UNKNOWN_ID,- name: t("instance.new-instance"),- engine: "MYSQL",- // In dev mode, Bytebase is likely run in naked style and access the local network via 127.0.0.1.- // In release mode, Bytebase is likely run inside docker and access the local network via host.docker.internal.- host: isDev() ? "127.0.0.1" : "host.docker.internal",- username: "",- srv: false,- authenticationDatabase: "",- },- showCreateInstanceWarningModal: false,- createInstanceWarning: "",- isPingingInstance: false,- isCreatingInstance: false,-});--const mongodbConnectionStringSchemaList = ["mongodb://", "mongodb+srv://"];--const isAddingSampleInstance = ref(false);-// For creating database onboarding guide, we only try to start our embedded sample postgres instance once.-const samplePostgresInstance = ref<Partial<InstanceCreate>>();--const allowCreate = computed(() => {- if (state.instance.engine === "SPANNER") {- return (- state.instance.name &&- isValidSpannerHost(state.instance.host) &&- state.instance.password- );- }- return state.instance.name && state.instance.host;-});--const allowEdit = computed(() => {- return true;-});--const defaultPort = computed(() => {- if (state.instance.engine == "CLICKHOUSE") {- return "9000";- } else if (state.instance.engine == "POSTGRES") {- return "5432";- } else if (state.instance.engine == "SNOWFLAKE") {- return "443";- } else if (state.instance.engine == "TIDB") {- return "4000";- } else if (state.instance.engine == "MONGODB") {- return "27017";- }- return "3306";-});--const showSSL = computed((): boolean => {- return (- state.instance.engine === "CLICKHOUSE" ||- state.instance.engine === "MYSQL" ||- state.instance.engine === "TIDB" ||- state.instance.engine === "POSTGRES"- );-});--const showDatabase = computed((): boolean => {- return state.instance.engine === "POSTGRES";-});--const showAuthenticationDatabase = computed((): boolean => {- return state.instance.engine === "MONGODB";-});--const isEngineBeta = (engine: EngineType): boolean => {- return engine === "MONGODB" || engine === "SPANNER";-};--const isInOnboaringCreateDatabaseGuide = computed(() => {- const guideName = useOnboardingGuideStore().guideName;- return guideName === "create-database";-});--const shouldShowAddSamplePostgresButton = computed(() => {- const tempInstance = samplePostgresInstance.value;- return (- isInOnboaringCreateDatabaseGuide.value &&- (!tempInstance ||- state.instance.engine !== tempInstance.engine ||- state.instance.host !== tempInstance.host ||- state.instance.port !== tempInstance.port ||- state.instance.username !== tempInstance.username ||- state.instance.password !== tempInstance.password)- );-});--const warningModalOkText = computed(() => {- if (shouldShowAddSamplePostgresButton.value) {- return t("instance.add-a-postgresql-sample-instance");- } else {- return t("instance.ignore-and-create");- }-});--watch(showSSL, (ssl) => {- // Clean up SSL options when they are not needed.- if (!ssl) {- state.instance.sslCa = "";- state.instance.sslKey = "";- state.instance.sslCert = "";- }-});--// The default host name is 127.0.0.1 or host.docker.internal which is not applicable to Snowflake, so we change-// the host name between 127.0.0.1/host.docker.internal and "" if user hasn't changed default yet.-const changeInstanceEngine = (engine: EngineType) => {- if (engine === "SNOWFLAKE" || engine === "SPANNER") {- if (- state.instance.host == "127.0.0.1" ||- state.instance.host == "host.docker.internal"- ) {- state.instance.host = "";- }- } else {- if (!state.instance.host) {- state.instance.host = isDev() ? "127.0.0.1" : "host.docker.internal";- }- }- state.instance.engine = engine;-};--const handleInstanceNameInput = (event: Event) => {- updateInstance("name", (event.target as HTMLInputElement).value);-};--const handleInstanceHostInput = (event: Event) => {- updateInstance("host", (event.target as HTMLInputElement).value);-};--const handleInstancePortWheelScroll = (event: MouseEvent) => {- (event.target as HTMLInputElement).blur();-};--const handleInstancePortInput = (event: Event) => {- updateInstance("port", (event.target as HTMLInputElement).value);-};--const handleInstanceUsernameInput = (event: Event) => {- updateInstance("username", (event.target as HTMLInputElement).value);-};--const handleInstancePasswordInput = (event: Event) => {- updateInstance("password", (event.target as HTMLInputElement).value);-};--const handleInstanceDatabaseInput = (event: Event) => {- updateInstance("database", (event.target as HTMLInputElement).value);-};--const handleInstanceAuthenticationDatabaseInput = (event: Event) => {- updateInstance(- "authenticationDatabase",- (event.target as HTMLInputElement).value- );-};--const handleMongodbConnectionStringSchemaChange = (event: Event) => {- switch ((event.target as HTMLInputElement).value) {- case mongodbConnectionStringSchemaList[0]:- state.instance.srv = false;- break;- case mongodbConnectionStringSchemaList[1]:- state.instance.srv = true;- break;- default:- state.instance.srv = false;- }-};--const updateInstance = (field: string, value: string | boolean) => {- let str = value;- if (- field === "name" ||- field === "host" ||- field === "port" ||- field === "externalLink" ||- field === "username" ||- field === "password" ||- field === "database" ||- field === "authenticationDatabase"- ) {- str = (value as string).trim();- }- (state.instance as any)[field] = str;-};--const handleWarningModalOkClick = async () => {- // When user gets the warning of incorrect instance info in creating database onboarding guide,- // we'd like to display the `add a sample PostgreSQL database` button instead of `ignore and create`.- if (shouldShowAddSamplePostgresButton.value) {- isAddingSampleInstance.value = true;- const connectionInfo = await useInstanceStore().getSamplePostgresInstance();- samplePostgresInstance.value = {- engine: "POSTGRES",- host: connectionInfo.host,- port: String(connectionInfo.port),- username: connectionInfo.username,- password: "",- };- state.instance = {- ...state.instance,- ...samplePostgresInstance.value,- };- isAddingSampleInstance.value = false;- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.success"),- description: t("instance.successfully-added-postgresql-instance"),- // This is a bit magic to the user, so do not auto dismiss the notification.- manualHide: true,- });- state.showCreateInstanceWarningModal = false;- } else {- state.showCreateInstanceWarningModal = false;- doCreate();- }-};--const cancel = () => {- emit("dismiss");-};--const tryCreate = () => {- const { instance } = state;- const connectionInfo: ConnectionInfo = {- engine: instance.engine,- username: instance.username,- password: instance.password,- // When creating instance, the password is always needed.- useEmptyPassword: false,- host: instance.host,- port: instance.port,- srv: instance.srv,- authenticationDatabase: instance.authenticationDatabase,- };-- if (showSSL.value) {- // Default to "NONE"- connectionInfo.sslCa = instance.sslCa ?? "";- connectionInfo.sslKey = instance.sslKey ?? "";- connectionInfo.sslCert = instance.sslCert ?? "";- }-- // MongoDB can use auth database.- // https://www.mongodb.com/docs/manual/tutorial/authenticate-a-user/#std-label-authentication-auth-as-user- if (instance.engine === "MONGODB") {- connectionInfo.database = instance.database;- }-- state.isPingingInstance = true;- sqlStore- .ping(connectionInfo)- .then((resultSet: SQLResultSet) => {- state.isPingingInstance = false;- if (isEmpty(resultSet.error)) {- doCreate();- } else {- state.createInstanceWarning = t("instance.unable-to-connect", [- resultSet.error,- ]);- state.showCreateInstanceWarningModal = true;- }- })- .catch(() => {- state.isPingingInstance = false;- });-};--// We will also create the database * denoting all databases-// and its RW data source. The username, password is actually-// stored in that data source object instead of in the instance self.-// Conceptually, data source is the proper place to store connection info (thinking of DSN)-const doCreate = () => {- state.isCreatingInstance = true;-- if (- state.instance.engine !== "POSTGRES" &&- state.instance.engine !== "MONGODB"- ) {- // Clear the `database` field if not needed.- state.instance.database = "";- }- useInstanceStore()- .createInstance(state.instance)- .then((createdInstance) => {- state.isCreatingInstance = false;- emit("dismiss");-- router.push(`/instance/${instanceSlug(createdInstance)}`);-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t(- "instance.successfully-created-instance-createdinstance-name",- [createdInstance.name]- ),- });- })- .finally(() => {- state.isCreatingInstance = false;- });-};--const testConnection = () => {- const { instance } = state;-- const connectionInfo: ConnectionInfo = {- host: instance.host,- port: instance.port,- engine: instance.engine,- username: instance.username,- password: instance.password,- // Use the `database` field only when needed.- database: showDatabase.value ? instance.database : undefined,- useEmptyPassword: false,- instanceId: undefined,- srv: instance.srv,- authenticationDatabase:- instance.engine === "MONGODB" ? instance.authenticationDatabase : "",- };-- if (showSSL.value) {- // Default to "NONE"- connectionInfo.sslCa = instance.sslCa ?? "";- connectionInfo.sslKey = instance.sslKey ?? "";- connectionInfo.sslCert = instance.sslCert ?? "";- }-- state.isPingingInstance = true;- sqlStore- .ping(connectionInfo)- .then((resultSet: SQLResultSet) => {- if (isEmpty(resultSet.error)) {- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("instance.successfully-connected-instance"),- });- } else {- let title = t("instance.failed-to-connect-instance");- if (- connectionInfo.host == "localhost" ||- connectionInfo.host == "127.0.0.1"- ) {- title = t("instance.failed-to-connect-instance-localhost");- }- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: title,- description: resultSet.error,- // Manual hide, because user may need time to inspect the error- manualHide: true,- });- }- })- .finally(() => {- state.isPingingInstance = false;- });-};-</script>--<style scoped>-/* Removed the ticker in the number field */-input::-webkit-outer-spin-button,-input::-webkit-inner-spin-button {- -webkit-appearance: none;- margin: 0;-}--/* Firefox */-input[type="number"] {- -moz-appearance: textfield;-}-</style>diff --git a/frontend/src/components/InstanceForm.vue b/frontend/src/components/InstanceForm.vueindex be25d0dfb3..b298582162 100644--- a/frontend/src/components/InstanceForm.vue+++ b/frontend/src/components/InstanceForm.vue@@ -1,14 +1,45 @@<template><div class="space-y-6 divide-y divide-block-border">- <div class="divide-y divide-block-border px-1">+ <div class="divide-y divide-block-border">+ <div+ v-if="isCreating"+ class="w-full mt-4 mb-6 grid grid-cols-1 gap-4 sm:grid-cols-7"+ >+ <template v-for="engine in engineList" :key="engine">+ <div+ class="flex relative justify-center px-2 py-4 border border-control-border hover:bg-control-bg-hover cursor-pointer"+ @click.capture="changeInstanceEngine(engine)"+ >+ <div class="flex flex-col items-center">+ <img class="h-8 w-auto" :src="EngineIconPath[engine]" />+ <p class="mt-2 text-center textlabel">+ {{ engineName(engine) }}+ </p>+ <template v-if="isEngineBeta(engine)">+ <BBBetaBadge class="absolute right-0.5 top-1" />+ </template>+ <div class="mt-4 radio text-sm">+ <input+ type="radio"+ class="btn"+ :checked="basicInformation.engine == engine"+ />+ </div>+ </div>+ </div>+ </template>+ </div>+<!-- Instance Name -->- <div class="mt-6 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4">+ <div class="pt-4 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4"><div class="sm:col-span-2 sm:col-start-1"><label for="name" class="textlabel flex flex-row items-center">{{ $t("instance.instance-name") }}<span class="text-red-600 mr-2">*</span>- <InstanceEngineIcon :instance="state.instance" />- <span class="ml-1">{{ state.instance.engineVersion }}</span>+ <template v-if="props.instance">+ <InstanceEngineIcon :instance="props.instance" />+ <span class="ml-1">{{ props.instance.engineVersion }}</span>+ </template></label><inputid="name"@@ -17,35 +48,32 @@type="text"class="textfield mt-1 w-full":disabled="!allowEdit"- :value="state.instance.name"+ :value="basicInformation.name"@input="handleInstanceNameInput"/></div>-<div class="sm:col-span-2 sm:col-start-1"><label for="environment" class="textlabel">{{ $t("common.environment") }}</label>- <!-- Disallow changing environment after creation. This is to take the conservative approach to limit capability -->- <!-- eslint-disable vue/attribute-hyphenation --><EnvironmentSelectid="environment"class="mt-1 w-full"name="environment"- :disabled="true"- :selectedId="state.instance.environment.id"+ :disabled="!isCreating"+ :selected-id="basicInformation.environmentId"@select-environment-id="(environmentId) => {- updateInstance('environmentId', environmentId);+ basicInformation.environmentId = environmentId;}"/></div><div class="sm:col-span-3 sm:col-start-1">- <template v-if="state.instance.engine !== 'SPANNER'">+ <template v-if="basicInformation.engine !== 'SPANNER'"><label for="host" class="textlabel block">- <template v-if="state.instance.engine == 'SNOWFLAKE'">+ <template v-if="basicInformation.engine == 'SNOWFLAKE'">{{ $t("instance.account-name") }}<span class="text-red-600 mr-2">*</span></template>@@ -60,7 +88,7 @@type="text"name="host":placeholder="- state.instance.engine == 'SNOWFLAKE'+ basicInformation.engine == 'SNOWFLAKE'? $t('instance.your-snowflake-account-name'): $t('instance.sentence.host.snowflake')"@@ -70,7 +98,7 @@@input="handleInstanceHostInput"/><div- v-if="state.instance.engine == 'SNOWFLAKE'"+ v-if="basicInformation.engine == 'SNOWFLAKE'"class="mt-2 textinfolabel">{{ $t("instance.sentence.proxy.snowflake") }}@@ -83,7 +111,8 @@@update:host="handleUpdateSpannerHost"/></div>- <template v-if="state.instance.engine !== 'SPANNER'">++ <template v-if="basicInformation.engine !== 'SPANNER'"><div class="sm:col-span-1"><label for="port" class="textlabel block">{{$t("instance.port")@@ -101,12 +130,42 @@/></div></template>++ <div+ v-if="basicInformation.engine === 'MONGODB'"+ class="sm:col-span-4 sm:col-start-1"+ >+ <label+ for="connectionStringSchema"+ class="textlabel flex flex-row items-center"+ >+ {{ $t("data-source.connection-string-schema") }}+ </label>+ <label+ v-for="type in mongodbConnectionStringSchemaList"+ :key="type"+ class="radio h-7"+ >+ <input+ type="radio"+ class="btn"+ name="connectionStringSchema"+ :value="type"+ :checked="type === currentMongoDBConnectionSchema"+ @change="handleMongodbConnectionStringSchemaChange"+ />+ <span class="label">+ {{ type }}+ </span>+ </label>+ </div>+<!--Do not show external link on create to reduce cognitive load-->- <div class="sm:col-span-3 sm:col-start-1">+ <div v-if="!isCreating" class="sm:col-span-3 sm:col-start-1"><label for="externallink" class="textlabel inline-flex"><span class>{{- state.instance.engine == "SNOWFLAKE"+ basicInformation.engine == "SNOWFLAKE"? $t("instance.snowflake-web-console"): $t("instance.external-link")}}@@ -119,7 +178,7 @@<heroicons-outline:external-link class="w-4 h-4" /></button></label>- <template v-if="state.instance.engine == 'SNOWFLAKE'">+ <template v-if="basicInformation.engine == 'SNOWFLAKE'"><inputid="externallink"required@@ -140,7 +199,7 @@name="externallink"type="text":disabled="!allowEdit"- :value="state.instance.externalLink"+ :value="basicInformation.externalLink"class="textfield mt-1 w-full":placeholder="snowflakeExtraLinkPlaceHolder"@input="handleInstanceExternalLinkInput"@@ -149,12 +208,12 @@</div></div>+ <!-- Connection Info --><p class="mt-6 pt-4 w-full text-lg leading-6 font-medium text-gray-900">{{ $t("instance.connection-info") }}</p>-<div- v-if="!hasReadOnlyDataSource"+ v-if="!isCreating && !hasReadOnlyDataSource"class="mt-2 flex flex-row justify-start items-center bg-yellow-50 border-none rounded-lg p-2 px-3"><heroicons-outline:exclamation@@ -166,7 +225,7 @@<buttontype="button"class="btn-normal ml-4 text-sm"- @click.prevent="handleCreateDataSource('RO')"+ @click.prevent="handleCreateRODataSource">{{ $t("common.create") }}</button>@@ -176,6 +235,7 @@class="mt-2 grid grid-cols-1 gap-y-2 gap-x-4 border-none sm:grid-cols-3"><NTabs+ v-if="!isCreating"class="sm:col-span-3"type="line":value="state.currentDataSourceType"@@ -188,34 +248,30 @@v-if="hasReadOnlyDataSource":style="'DELETE'"class="absolute left-full ml-1"- :require-confirm="currentDataSource.id !== UNKNOWN_ID"+ :require-confirm="readonlyDataSource?.id !== UNKNOWN_ID":ok-text="$t('common.delete')":confirm-title="$t('data-source.delete-read-only-data-source') + '?'"- @confirm="handleDeleteReadOnlyDataSource"+ @confirm="handleDeleteRODataSource"/></NTab></NTabs>- <template v-if="state.instance.engine !== 'SPANNER'">+ <template v-if="basicInformation.engine !== 'SPANNER'"><CreateDataSourceExample- className="sm:col-span-3 border-none mt-2"- :createInstanceFlag="false"- :engineType="state.instance.engine"- :dataSourceType="state.currentDataSourceType"+ class-name="sm:col-span-3 border-none mt-2"+ :create-instance-flag="isCreating"+ :engine-type="basicInformation.engine"+ :data-source-type="state.currentDataSourceType"/>- </template>-- <template v-if="state.instance.engine !== 'SPANNER'"><div class="mt-2 sm:col-span-1 sm:col-start-1"><label for="username" class="textlabel block">{{ $t("common.username") }}- <span class="text-red-600">*</span></label><!-- For mysql, username can be empty indicating anonymous user.- But it's a very bad practice to use anonymous user for admin operation,- thus we make it REQUIRED here.-->+ But it's a very bad practice to use anonymous user for admin operation,+ thus we make it REQUIRED here.--><inputid="username"name="username"@@ -223,55 +279,52 @@class="textfield mt-1 w-full":disabled="!allowEdit":placeholder="- instance.engine == 'CLICKHOUSE' ? $t('common.default') : ''+ basicInformation.engine == 'CLICKHOUSE'+ ? $t('common.default')+ : ''":value="currentDataSource.username"@input="handleCurrentDataSourceNameInput"/></div>- </template>-- <div- v-if="state.instance.engine !== 'SPANNER'"- class="mt-2 sm:col-span-1 sm:col-start-1"- >- <div class="flex flex-row items-center space-x-2">- <label for="password" class="textlabel block">- {{ $t("common.password") }}- <span class="text-red-600">*</span>- </label>- <BBCheckbox- v-if="allowUsingEmptyPassword"- :title="$t('common.empty')"- :value="currentDataSource.useEmptyPassword"- @toggle="handleToggleUseEmptyPassword"+ <div class="mt-2 sm:col-span-1 sm:col-start-1">+ <div class="flex flex-row items-center space-x-2">+ <label for="password" class="textlabel block">+ {{ $t("common.password") }}+ </label>+ <BBCheckbox+ v-if="!isCreating && allowUsingEmptyPassword"+ :title="$t('common.empty')"+ :value="currentDataSource.useEmptyPassword"+ @toggle="handleToggleUseEmptyPassword"+ />+ </div>+ <input+ id="password"+ name="password"+ type="text"+ class="textfield mt-1 w-full"+ autocomplete="off"+ :placeholder="+ currentDataSource.useEmptyPassword+ ? $t('instance.no-password')+ : $t('instance.password-write-only')+ "+ :disabled="!allowEdit || currentDataSource.useEmptyPassword"+ :value="+ currentDataSource.useEmptyPassword+ ? ''+ : currentDataSource.updatedPassword+ "+ @input="handleCurrentDataSourcePasswordInput"/></div>- <input- id="password"- name="password"- type="text"- class="textfield mt-1 w-full"- autocomplete="off"- :placeholder="- currentDataSource.useEmptyPassword- ? $t('instance.no-password')- : $t('instance.password-write-only')- "- :disabled="!allowEdit || currentDataSource.useEmptyPassword"- :value="- currentDataSource.useEmptyPassword- ? ''- : currentDataSource.updatedPassword- "- @input="handleCurrentDataSourcePasswordInput"- />- </div>+ </template><SpannerCredentialInputv-else:value="currentDataSource.updatedPassword"- :write-only="true"+ :write-only="!isCreating"class="mt-2 sm:col-span-3 sm:col-start-1"@update:value="handleUpdateSpannerCredential"/>@@ -296,35 +349,6 @@</div></template>- <div- v-if="state.instance.engine === 'MONGODB'"- class="sm:col-span-4 sm:col-start-1"- >- <label- for="connectionStringSchema"- class="textlabel flex flex-row items-center"- >- {{ $t("data-source.connection-string-schema") }}- </label>- <label- v-for="type in mongodbConnectionStringSchemaList"- :key="type"- class="radio h-7"- >- <input- type="radio"- class="btn"- name="connectionStringSchema"- :value="type"- :checked="type === currentMongoDBConnectionSchema"- @change="handleMongodbConnectionStringSchemaChange"- />- <span class="label">- {{ type }}- </span>- </label>- </div>-<templatev-if="state.currentDataSourceType === 'RO' &&@@ -407,23 +431,23 @@/></template><template v-else>- <button- class="btn-normal mt-2"- @click.prevent="handleEditSsl(true)"- >+ <button class="btn-normal mt-2" @click.prevent="handleEditSsl">{{ $t("common.edit") }} - {{ $t("common.write-only") }}</button></template></template></div></div>+<div class="mt-6 pt-0 border-none"><div class="flex flex-row space-x-2"><buttontype="button"class="btn-normal whitespace-nowrap items-center"+ :disabled="!allowCreate || state.isRequesting"@click.prevent="testConnection">+ <BBSpin v-if="state.isTestingConnection" />{{ $t("instance.test-connection") }}</button></div>@@ -431,23 +455,47 @@</div><!-- Action Button Group -->- <div class="pt-4 px-2">- <div class="flex justify-between items-center">- <div class="flex justify-end items-center">+ <div class="pt-4">+ <div class="w-full flex justify-between items-center">+ <div class="w-full flex justify-end items-center"><div>- <BBSpin v-if="state.isUpdating" :title="$t('common.updating')" />+ <BBSpin v-if="state.isRequesting" />+ </div>+ <div class="ml-2">+ <template v-if="isCreating">+ <button+ type="button"+ class="btn-normal py-2 px-4"+ :disabled="state.isRequesting"+ @click.prevent="cancel"+ >+ {{ $t("common.cancel") }}+ </button>+ <button+ type="button"+ class="btn-primary ml-3 inline-flex justify-center py-2 px-4"+ :disabled="!allowCreate || state.isRequesting"+ @click.prevent="tryCreate"+ >+ {{ $t("common.create") }}+ </button>+ </template>+ <template v-else>+ <button+ v-if="allowEdit"+ type="button"+ :disabled="!allowUpdate || state.isRequesting"+ :class="+ !allowUpdate || state.isRequesting+ ? 'btn-normal'+ : 'btn-primary'+ "+ @click.prevent="doUpdate"+ >+ {{ $t("common.update") }}+ </button>+ </template></div>- <button- v-if="allowEdit"- type="button"- :disabled="!allowUpdate || state.isUpdating"- :class="- !allowUpdate || state.isUpdating ? 'btn-normal' : 'btn-primary'- "- @click.prevent="doUpdate"- >- {{ $t("common.update") }}- </button></div></div></div>@@ -458,11 +506,22 @@feature="bb.feature.read-replica-connection"@cancel="state.showFeatureModal = false"/>++ <BBAlert+ v-if="state.showCreateInstanceWarningModal"+ :style="'WARN'"+ :ok-text="t('instance.ignore-and-create')"+ :title="$t('instance.connection-info-seems-to-be-incorrect')"+ :description="state.createInstanceWarning"+ :progress-text="$t('common.creating')"+ @ok="handleWarningModalOkClick"+ @cancel="state.showCreateInstanceWarningModal = false"+ ></BBAlert></template><script lang="ts" setup>import { cloneDeep, isEqual, omit } from "lodash-es";-import { computed, reactive, PropType } from "vue";+import { computed, reactive, PropType, ref, watch, onMounted } from "vue";import EnvironmentSelect from "../components/EnvironmentSelect.vue";import InstanceEngineIcon from "../components/InstanceEngineIcon.vue";import {@@ -471,20 +530,27 @@ import {SslCertificateForm,} from "./InstanceForm";import {- clearObject,hasWorkspacePermission,+ instanceSlug,+ isDev,isValidSpannerHost,} from "../utils";import {InstancePatch,DataSourceType,Instance,- SQLResultSet,ConnectionInfo,DataSource,UNKNOWN_ID,DataSourceCreate,DataSourcePatch,+ EngineType,+ engineName,+ InstanceId,+ ResourceId,+ RowStatus,+ InstanceCreate,+ unknown,} from "../types";import isEmpty from "lodash-es/isEmpty";import { useI18n } from "vue-i18n";@@ -497,65 +563,176 @@ import {useInstanceStore,useSQLStore,} from "@/store";-import { isNullOrUndefined } from "@/plugins/demo/utils";+import { useRouter } from "vue-router";++const props = defineProps({+ instance: {+ type: Object as PropType<Instance>,+ default: undefined,+ },+});++const emit = defineEmits(["dismiss"]);++const cancel = () => {+ emit("dismiss");+};interface EditDataSource extends DataSource {updatedPassword: string;useEmptyPassword: boolean;}-interface State {- originalInstance: Instance;- instance: Instance;- isUpdating: boolean;- dataSourceList: EditDataSource[];+interface BasicInformation {+ id: InstanceId;+ resourceId: ResourceId;+ rowStatus: RowStatus;+ name: string;+ engine: EngineType;+ externalLink?: string;+ environmentId: number;+}++interface LocalState {currentDataSourceType: DataSourceType;showFeatureModal: boolean;+ isTestingConnection: boolean;+ isRequesting: boolean;+ showCreateInstanceWarningModal: boolean;+ createInstanceWarning: string;}-const props = defineProps({- instance: {- required: true,- type: Object as PropType<Instance>,- },-});--const instanceStore = useInstanceStore();const { t } = useI18n();+const router = useRouter();+const instanceStore = useInstanceStore();const dataSourceStore = useDataSourceStore();-const currentUser = useCurrentUser();const sqlStore = useSQLStore();-const dataSourceList = props.instance.dataSourceList.map((dataSource) => {- return {- ...cloneDeep(dataSource),- updatedPassword: "",- useEmptyPassword: false,- } as EditDataSource;-});--const state = reactive<State>({- originalInstance: props.instance,- // Make hard copy since we are going to make equal comparison to determine the update button enable state.- instance: cloneDeep(props.instance),- isUpdating: false,- dataSourceList: dataSourceList,+const state = reactive<LocalState>({currentDataSourceType: "ADMIN",showFeatureModal: false,+ isTestingConnection: false,+ isRequesting: false,+ showCreateInstanceWarningModal: false,+ createInstanceWarning: "",+});++const basicInformation = ref<BasicInformation>({+ id: props.instance?.id || UNKNOWN_ID,+ resourceId: props.instance?.resourceId || "",+ rowStatus: props.instance?.rowStatus || "NORMAL",+ name: props.instance?.name || t("instance.new-instance"),+ engine: props.instance?.engine || "MYSQL",+ environmentId: (props.instance?.environment.id || UNKNOWN_ID) as number,+});++const getDataSourceWithType = (type: DataSourceType) =>+ props.instance?.dataSourceList.find((ds) => ds.type === type);++// We only support one admin data source and one read-only data source.+const adminDataSource = ref<EditDataSource>({+ ...(getDataSourceWithType("ADMIN") || unknown("DATA_SOURCE")),+ updatedPassword: "",+ useEmptyPassword: false,});+const readonlyDataSource = ref<EditDataSource | undefined>(+ getDataSourceWithType("RO")+ ? ({+ ...getDataSourceWithType("RO"),+ updatedPassword: "",+ useEmptyPassword: false,+ } as EditDataSource)+ : undefined+);++const getDefaultPort = (engine: EngineType) => {+ if (engine == "CLICKHOUSE") {+ return "9000";+ } else if (engine == "POSTGRES") {+ return "5432";+ } else if (engine == "SNOWFLAKE") {+ return "443";+ } else if (engine == "TIDB") {+ return "4000";+ } else if (engine == "MONGODB") {+ return "27017";+ }+ return "3306";+};++const isCreating = computed(() => props.instance === undefined);++onMounted(() => {+ if (isCreating.value) {+ (adminDataSource.value.host = isDev()+ ? "127.0.0.1"+ : "host.docker.internal"),+ (adminDataSource.value.options.srv = false);+ adminDataSource.value.options.authenticationDatabase = "";+ }+});++watch(+ () => basicInformation.value.engine,+ () => {+ if (isCreating.value) {+ adminDataSource.value.port = getDefaultPort(+ basicInformation.value.engine+ );+ }+ },+ {+ immediate: true,+ }+);++const engineList = computed(() => {+ const engines: EngineType[] = [+ "MYSQL",+ "POSTGRES",+ "TIDB",+ "SNOWFLAKE",+ "CLICKHOUSE",+ "MONGODB",+ "SPANNER",+ ];+ return engines;+});++const EngineIconPath = {+ MYSQL: new URL("../assets/db-mysql.png", import.meta.url).href,+ POSTGRES: new URL("../assets/db-postgres.png", import.meta.url).href,+ TIDB: new URL("../assets/db-tidb.png", import.meta.url).href,+ SNOWFLAKE: new URL("../assets/db-snowflake.png", import.meta.url).href,+ CLICKHOUSE: new URL("../assets/db-clickhouse.png", import.meta.url).href,+ MONGODB: new URL("../assets/db-mongodb.png", import.meta.url).href,+ SPANNER: new URL("../assets/db-spanner.png", import.meta.url).href,+};+const mongodbConnectionStringSchemaList = ["mongodb://", "mongodb+srv://"];const currentMongoDBConnectionSchema = computed(() => {- return currentDataSource.value.options.srv === false+ return adminDataSource.value.options.srv === false? mongodbConnectionStringSchemaList[0]: mongodbConnectionStringSchemaList[1];});+const allowCreate = computed(() => {+ if (basicInformation.value.engine === "SPANNER") {+ return (+ basicInformation.value.name &&+ isValidSpannerHost(adminDataSource.value.host) &&+ adminDataSource.value.password+ );+ }+ return basicInformation.value.name && adminDataSource.value.host;+});+const allowEdit = computed(() => {return (- state.instance.rowStatus == "NORMAL" &&+ basicInformation.value.rowStatus == "NORMAL" &&hasWorkspacePermission("bb.permission.workspace.manage-instance",currentUser.value.role@@ -564,11 +741,18 @@ const allowEdit = computed(() => {});const allowUsingEmptyPassword = computed(() => {- return state.instance.engine !== "SPANNER";+ return basicInformation.value.engine !== "SPANNER";});const valueChanged = computed(() => {- return !isEqual(state.instance, state.originalInstance);+ return !isEqual(+ {+ basicInformation: basicInformation.value,+ adminDataSource: adminDataSource.value,+ readonlyDataSource: readonlyDataSource.value,+ },+ getInstanceStateData()+ );});const connectionInfoChanged = computed(() => {@@ -576,116 +760,138 @@ const connectionInfoChanged = computed(() => {return false;}- return !isEqual(- state.originalInstance.dataSourceList,- state.instance.dataSourceList+ return (+ !isEqual(adminDataSource.value, getInstanceStateData().adminDataSource) ||+ !isEqual(+ readonlyDataSource.value,+ getInstanceStateData().readonlyDataSource+ ));});const defaultPort = computed(() => {- if (state.instance.engine == "CLICKHOUSE") {+ if (basicInformation.value.engine == "CLICKHOUSE") {return "9000";- } else if (state.instance.engine == "POSTGRES") {+ } else if (basicInformation.value.engine == "POSTGRES") {return "5432";- } else if (state.instance.engine == "SNOWFLAKE") {+ } else if (basicInformation.value.engine == "SNOWFLAKE") {return "443";- } else if (state.instance.engine == "TIDB") {+ } else if (basicInformation.value.engine == "TIDB") {return "4000";- } else if (state.instance.engine == "MONGODB") {+ } else if (basicInformation.value.engine == "MONGODB") {return "27017";}return "3306";});-const adminDataSource = computed(() => {- const temp = state.dataSourceList.find(- (ds) => ds.type === "ADMIN"- ) as EditDataSource;- return temp;-});--const hasReadOnlyDataSource = computed(() => {- for (const ds of state.dataSourceList) {- if (ds.type === "RO") {- return true;- }+const currentDataSource = computed(() => {+ if (state.currentDataSourceType === "ADMIN") {+ return adminDataSource.value;+ } else if (state.currentDataSourceType === "RO") {+ return readonlyDataSource.value as EditDataSource;+ } else {+ throw new Error("Unknown data source type");}- return false;});-const currentDataSource = computed(() => {- const temp = state.dataSourceList.find(- (ds) => ds.type === state.currentDataSourceType- ) as EditDataSource;- return temp;+const hasReadOnlyDataSource = computed(() => {+ return readonlyDataSource.value !== undefined;});const snowflakeExtraLinkPlaceHolder ="https://us-west-1.console.aws.amazon.com/rds/home?region=us-west-1#database:id=mysql-instance-foo;is-cluster=false";const instanceLink = computed(() => {- if (state.instance.engine == "SNOWFLAKE") {- if (currentDataSource.value.host) {+ if (basicInformation.value.engine == "SNOWFLAKE") {+ if (adminDataSource.value.host) {return `https://${- currentDataSource.value.host.split("@")[0]+ adminDataSource.value.host.split("@")[0]}.snowflakecomputing.com/console`;}}- return state.instance.externalLink || "";+ return basicInformation.value.externalLink || "";});const hasReadonlyReplicaHost = computed((): boolean => {- return state.instance.engine !== "SPANNER";+ return basicInformation.value.engine !== "SPANNER";});const hasReadonlyReplicaPort = computed((): boolean => {- return state.instance.engine !== "SPANNER";+ return basicInformation.value.engine !== "SPANNER";});const showDatabase = computed((): boolean => {return (- state.instance.engine === "POSTGRES" &&- currentDataSource.value.type === "ADMIN"+ basicInformation.value.engine === "POSTGRES" &&+ state.currentDataSourceType === "ADMIN");});const showSSL = computed((): boolean => {return (- state.instance.engine === "CLICKHOUSE" ||- state.instance.engine === "MYSQL" ||- state.instance.engine === "TIDB" ||- state.instance.engine === "POSTGRES"+ basicInformation.value.engine === "CLICKHOUSE" ||+ basicInformation.value.engine === "MYSQL" ||+ basicInformation.value.engine === "TIDB" ||+ basicInformation.value.engine === "POSTGRES");});const showAuthenticationDatabase = computed((): boolean => {- return state.instance.engine === "MONGODB";+ return basicInformation.value.engine === "MONGODB";});const allowUpdate = computed((): boolean => {if (!valueChanged.value) {return false;}- if (state.instance.engine === "SPANNER") {- if (state.dataSourceList.some((ds) => !isValidSpannerHost(ds.host))) {+ if (basicInformation.value.engine === "SPANNER") {+ if (!isValidSpannerHost(adminDataSource.value.host)) {+ return false;+ }+ if (+ readonlyDataSource.value &&+ !isValidSpannerHost(readonlyDataSource.value.host)+ ) {return false;}}return true;});+const isEngineBeta = (engine: EngineType): boolean => {+ return engine === "MONGODB" || engine === "SPANNER";+};++// The default host name is 127.0.0.1 or host.docker.internal which is not applicable to Snowflake, so we change+// the host name between 127.0.0.1/host.docker.internal and "" if user hasn't changed default yet.+const changeInstanceEngine = (engine: EngineType) => {+ if (engine === "SNOWFLAKE" || engine === "SPANNER") {+ if (+ adminDataSource.value.host == "127.0.0.1" ||+ adminDataSource.value.host == "host.docker.internal"+ ) {+ adminDataSource.value.host = "";+ }+ } else {+ if (!adminDataSource.value.host) {+ adminDataSource.value.host = isDev()+ ? "127.0.0.1"+ : "host.docker.internal";+ }+ }+ basicInformation.value.engine = engine;+};+const handleInstanceNameInput = (event: Event) => {- updateInstance("name", (event.target as HTMLInputElement).value);+ basicInformation.value.name = (event.target as HTMLInputElement).value.trim();};const handleInstanceHostInput = (event: Event) => {adminDataSource.value.host = (event.target as HTMLInputElement).value;- updateInstanceDataSource(adminDataSource.value);};const handleUpdateSpannerHost = (host: string) => {adminDataSource.value.host = host;- updateInstanceDataSource(adminDataSource.value);};const handleInstancePortWheelScroll = (event: MouseEvent) => {@@ -694,11 +900,12 @@ const handleInstancePortWheelScroll = (event: MouseEvent) => {const handleInstancePortInput = (event: Event) => {currentDataSource.value.port = (event.target as HTMLInputElement).value;- updateInstanceDataSource(adminDataSource.value);};const handleInstanceExternalLinkInput = (event: Event) => {- updateInstance("externalLink", (event.target as HTMLInputElement).value);+ basicInformation.value.externalLink = (+ event.target as HTMLInputElement+ ).value.trim();};const handleDataSourceTypeChange = (value: string) => {@@ -708,29 +915,24 @@ const handleDataSourceTypeChange = (value: string) => {const handleCurrentDataSourceNameInput = (event: Event) => {const str = (event.target as HTMLInputElement).value.trim();currentDataSource.value.username = str;- updateInstanceDataSource(currentDataSource.value);};const handleToggleUseEmptyPassword = (on: boolean) => {currentDataSource.value.useEmptyPassword = on;- updateInstanceDataSource(currentDataSource.value);};const handleCurrentDataSourcePasswordInput = (event: Event) => {- const str = (event.target as HTMLInputElement).value.trim();- currentDataSource.value.updatedPassword = str;- updateInstanceDataSource(currentDataSource.value);+ const password = (event.target as HTMLInputElement).value.trim();+ currentDataSource.value.updatedPassword = password;};const handleUpdateSpannerCredential = (credential: string) => {currentDataSource.value.updatedPassword = credential;- updateInstanceDataSource(currentDataSource.value);};const handleInstanceAuthenticationDatabaseInput = (event: Event) => {const str = (event.target as HTMLInputElement).value.trim();currentDataSource.value.options.authenticationDatabase = str;- updateInstanceDataSource(currentDataSource.value);};const handleMongodbConnectionStringSchemaChange = (event: Event) => {@@ -744,57 +946,46 @@ const handleMongodbConnectionStringSchemaChange = (event: Event) => {default:currentDataSource.value.options.srv = false;}- updateInstanceDataSource(currentDataSource.value);};const handleCurrentDataSourceHostInput = (event: Event) => {+ if (currentDataSource.value.type === "RO") {+ if (!hasFeature("bb.feature.read-replica-connection")) {+ if (currentDataSource.value.host || currentDataSource.value.port) {+ currentDataSource.value.host = "";+ currentDataSource.value.port = "";+ state.showFeatureModal = true;+ return;+ }+ }+ }+const str = (event.target as HTMLInputElement).value.trim();currentDataSource.value.host = str;- updateInstanceDataSource(currentDataSource.value);};const handleCurrentDataSourcePortInput = (event: Event) => {- const str = (event.target as HTMLInputElement).value.trim();- currentDataSource.value.port = str;- updateInstanceDataSource(currentDataSource.value);-};--const handleDeleteReadOnlyDataSource = async () => {- const dataSource = state.dataSourceList.find(- (item) => item.type === "RO"- ) as DataSource;- if (isNullOrUndefined(dataSource)) {- return;- }- if (dataSource.type !== "RO") {- return;- }-- if (dataSource.id !== UNKNOWN_ID) {- await dataSourceStore.deleteDataSourceById({- databaseId: dataSource.databaseId,- dataSourceId: dataSource.id,- });+ if (currentDataSource.value.type === "RO") {+ if (!hasFeature("bb.feature.read-replica-connection")) {+ if (currentDataSource.value.host || currentDataSource.value.port) {+ currentDataSource.value.host = "";+ currentDataSource.value.port = "";+ state.showFeatureModal = true;+ return;+ }+ }}- state.currentDataSourceType = "ADMIN";- await updateInstanceState();+ const str = (event.target as HTMLInputElement).value.trim();+ currentDataSource.value.port = str;};-const handleEditSsl = (edit: boolean) => {+const handleEditSsl = () => {const curr = currentDataSource.value;- if (!edit) {- delete curr.sslCa;- delete curr.sslCert;- delete curr.sslKey;- delete curr.updateSsl;- } else {- curr.sslCa = "";- curr.sslCert = "";- curr.sslKey = "";- curr.updateSsl = true;- }- updateInstanceDataSource(currentDataSource.value);+ curr.sslCa = "";+ curr.sslCert = "";+ curr.sslKey = "";+ curr.updateSsl = true;};const handleCurrentDataSourceSslChange = (@@ -802,64 +993,19 @@ const handleCurrentDataSourceSslChange = () => {Object.assign(currentDataSource.value, value);currentDataSource.value.updateSsl = true;- updateInstanceDataSource(currentDataSource.value);};-const updateInstanceDataSource = (dataSource: EditDataSource) => {- const index = state.dataSourceList.findIndex((ds) => ds === dataSource);- const newValue = {- ...state.instance.dataSourceList[index],- ...omit(dataSource, ["updatedPassword", "useEmptyPassword"]),- };-- if (dataSource.type === "RO") {- if (!hasFeature("bb.feature.read-replica-connection")) {- if (dataSource.host || dataSource.port) {- state.dataSourceList[index].host = "";- state.dataSourceList[index].port = "";- newValue.host = "";- newValue.port = "";- state.showFeatureModal = true;- }- }- }-- if (dataSource.useEmptyPassword) {- // When 'Password: Empty' is checked, we set the password to empty string.- newValue.password = "";- } else if (dataSource.updatedPassword) {- // When the user has typed something in the password textbox, we use the typed value.- newValue.password = dataSource.updatedPassword;- } else {- // When the user didn't touch the password textbox, or the user did typed something- // but cleared the textbox again, we won't update the password.- delete newValue.password;- }-- if (dataSource.updateSsl) {- newValue.sslCa = dataSource.sslCa;- newValue.sslKey = dataSource.sslKey;- newValue.sslCert = dataSource.sslCert;- } else {- delete newValue.sslCa;- delete newValue.sslCert;- delete newValue.sslKey;+const handleCreateRODataSource = () => {+ if (isCreating.value) {+ return;}- // Won't modify the obj ref, but modify its fields in-place, to avoid- // infinite loop caused by vue's reactivity.- const oldValue = state.instance.dataSourceList[index];- clearObject(oldValue);- Object.assign(oldValue, newValue);-};--const handleCreateDataSource = (type: DataSourceType) => {const tempDataSource = {id: UNKNOWN_ID,- instanceId: state.instance.id,+ instanceId: props.instance!.id,databaseId: adminDataSource.value.databaseId,- name: `${type} data source`,- type: type,+ name: `Read-only data source`,+ type: "RO",username: "",password: "",options: {@@ -867,93 +1013,251 @@ const handleCreateDataSource = (type: DataSourceType) => {srv: false,},} as DataSource;- if (state.instance.engine === "SPANNER") {+ if (basicInformation.value.engine === "SPANNER") {tempDataSource.host = adminDataSource.value.host;}- state.dataSourceList.push({+ readonlyDataSource.value = {...tempDataSource,updatedPassword: "",useEmptyPassword: false,- });- state.instance.dataSourceList = state.dataSourceList;- state.currentDataSourceType = type;+ };+ state.currentDataSourceType = "RO";};-const updateInstance = (field: string, value: string) => {- let str = value;- if (- field == "name" ||- field == "host" ||- field == "port" ||- field == "externalLink"- ) {- str = value.trim();+const handleDeleteRODataSource = async () => {+ if (!readonlyDataSource.value) {+ return;}- (state.instance as any)[field] = str;++ if (readonlyDataSource.value.id === UNKNOWN_ID) {+ readonlyDataSource.value = undefined;+ } else {+ await dataSourceStore.deleteDataSourceById({+ databaseId: readonlyDataSource.value.databaseId,+ dataSourceId: readonlyDataSource.value.id,+ });+ await updateInstanceState();+ }+ state.currentDataSourceType = "ADMIN";};const updateInstanceState = async () => {- const instance = await instanceStore.fetchInstanceById(state.instance.id);- state.originalInstance = instance;- state.instance = cloneDeep(state.originalInstance);- state.dataSourceList = instance.dataSourceList.map((dataSource) => {- return {- ...cloneDeep(dataSource),+ if (!props.instance) {+ return;+ }++ const instance = await instanceStore.fetchInstanceById(props.instance.id);+ basicInformation.value = {+ id: instance.id,+ resourceId: instance.resourceId,+ rowStatus: instance.rowStatus,+ name: instance.name,+ engine: instance.engine,+ environmentId: instance.environment.id as number,+ };+ adminDataSource.value = {+ ...cloneDeep(instance.dataSourceList.find((ds) => ds.type === "ADMIN")!),+ updatedPassword: "",+ useEmptyPassword: false,+ } as EditDataSource;+ if (instance.dataSourceList.find((ds) => ds.type === "RO")) {+ readonlyDataSource.value = {+ ...(cloneDeep(+ instance.dataSourceList.find((ds) => ds.type === "RO")!+ ) as EditDataSource),updatedPassword: "",useEmptyPassword: false,- } as EditDataSource;- });+ };+ }useDatabaseStore().fetchDatabaseListByInstanceId(instance.id);- useInstanceStore().fetchInstanceUserListById(instance.id);+ instanceStore.fetchInstanceUserListById(instance.id);const reloadDatabaseAndUser = connectionInfoChanged.value;- // Backend will sync the schema upon connection info change, so here we try to fetch the synced schema.+ // Backend will sync the schema when connection info changed, so we need to fetch the synced schema here.if (reloadDatabaseAndUser) {await useDatabaseStore().fetchDatabaseListByInstanceId(instance.id);- await useInstanceStore().fetchInstanceUserListById(instance.id);+ await instanceStore.fetchInstanceUserListById(instance.id);}return instance;};-const doUpdate = () => {+const handleWarningModalOkClick = async () => {+ state.showCreateInstanceWarningModal = false;+ doCreate();+};++const tryCreate = async () => {+ const connectionInfo: ConnectionInfo = {+ engine: basicInformation.value.engine,+ username: adminDataSource.value.username,+ password: adminDataSource.value.password,+ // When creating instance, the password is always needed.+ useEmptyPassword: false,+ host: adminDataSource.value.host,+ port: adminDataSource.value.port,+ srv: adminDataSource.value.options.srv,+ authenticationDatabase:+ adminDataSource.value.options.authenticationDatabase,+ };++ if (showSSL.value) {+ // Default to "NONE"+ connectionInfo.sslCa = adminDataSource.value.sslCa ?? "";+ connectionInfo.sslKey = adminDataSource.value.sslKey ?? "";+ connectionInfo.sslCert = adminDataSource.value.sslCert ?? "";+ }++ // MongoDB can use auth database.+ // https://www.mongodb.com/docs/manual/tutorial/authenticate-a-user/#std-label-authentication-auth-as-user+ if (basicInformation.value.engine === "MONGODB") {+ connectionInfo.database = adminDataSource.value.database;+ }++ state.isRequesting = true;+ try {+ const resultSet = await sqlStore.ping(connectionInfo);+ state.isRequesting = false;+ if (isEmpty(resultSet.error)) {+ await doCreate();+ } else {+ state.createInstanceWarning = t("instance.unable-to-connect", [+ resultSet.error,+ ]);+ state.showCreateInstanceWarningModal = true;+ }+ } catch (error) {+ state.isRequesting = false;+ }+};++// We will also create the database * denoting all databases+// and its RW data source. The username, password is actually+// stored in that data source object instead of in the instance self.+// Conceptually, data source is the proper place to store connection info (thinking of DSN)+const doCreate = async () => {+ state.isRequesting = true;++ const instanceCreate: InstanceCreate = {+ name: basicInformation.value.name,+ engine: basicInformation.value.engine,+ externalLink: basicInformation.value.externalLink,+ environmentId: basicInformation.value.environmentId,+ host: adminDataSource.value.host,+ port: adminDataSource.value.port,+ database: adminDataSource.value.database,+ username: adminDataSource.value.username,+ password: adminDataSource.value.password,+ sslCa: adminDataSource.value.sslCa,+ sslCert: adminDataSource.value.sslCert,+ sslKey: adminDataSource.value.sslKey,+ srv: adminDataSource.value.options.srv,+ authenticationDatabase:+ adminDataSource.value.options.authenticationDatabase,+ };++ if (+ instanceCreate.engine !== "POSTGRES" &&+ instanceCreate.engine !== "MONGODB"+ ) {+ // Clear the `database` field if not needed.+ instanceCreate.database = "";+ }+ const createdInstance = await instanceStore.createInstance(instanceCreate);+ state.isRequesting = false;+ emit("dismiss");+ router.push(`/instance/${instanceSlug(createdInstance)}`);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("instance.successfully-created-instance-createdinstance-name", [+ createdInstance.name,+ ]),+ });+};++const doUpdate = async () => {+ if (!props.instance) {+ return;+ }const patchedInstance: InstancePatch = {};let instanceInfoChanged = false;let dataSourceListChanged = false;- if (state.instance.name != state.originalInstance.name) {- patchedInstance.name = state.instance.name;+ if (basicInformation.value.name != props.instance.name) {+ patchedInstance.name = basicInformation.value.name;instanceInfoChanged = true;}- if (state.instance.externalLink != state.originalInstance.externalLink) {- patchedInstance.externalLink = state.instance.externalLink;+ if (basicInformation.value.externalLink != props.instance.externalLink) {+ patchedInstance.externalLink = basicInformation.value.externalLink;instanceInfoChanged = true;}+ const instance = await instanceStore.getOrFetchInstanceById(+ props.instance.id+ );+ const originAdminDataSource = instance.dataSourceList.find(+ (ds) => ds.type === "ADMIN"+ ) as DataSource;+ const originReadonlyDataSource = instance.dataSourceList.find(+ (ds) => ds.type === "RO"+ );if (!isEqual(- state.originalInstance.dataSourceList,- state.instance.dataSourceList+ originAdminDataSource,+ convertEditDataSource(adminDataSource.value)+ ) ||+ !isEqual(+ originReadonlyDataSource,+ readonlyDataSource.value+ ? convertEditDataSource(readonlyDataSource.value)+ : undefined)) {dataSourceListChanged = true;}if (instanceInfoChanged || dataSourceListChanged) {- state.isUpdating = true;+ state.isRequesting = true;const requests: Promise<any>[] = [];if (dataSourceListChanged) {- for (let i = 0; i < state.instance.dataSourceList.length; i++) {- const dataSource = state.instance.dataSourceList[i];- if (dataSource.id === UNKNOWN_ID) {- // Only used to create ReadOnly data source right now.- if (dataSource.type === "RO") {+ if (+ !isEqual(+ originAdminDataSource,+ convertEditDataSource(adminDataSource.value)+ )+ ) {+ const dataSource = convertEditDataSource(adminDataSource.value);+ const dataSourcePatch: DataSourcePatch = {+ ...dataSource,+ };+ requests.push(+ dataSourceStore.patchDataSource({+ databaseId: dataSource.databaseId,+ dataSourceId: dataSource.id,+ dataSourcePatch: dataSourcePatch,+ })+ );+ }++ if (+ !isEqual(+ originReadonlyDataSource,+ readonlyDataSource.value+ ? convertEditDataSource(readonlyDataSource.value)+ : undefined+ )+ ) {+ if (readonlyDataSource.value) {+ const dataSource = convertEditDataSource(readonlyDataSource.value);+ if (dataSource.id === UNKNOWN_ID) {const dataSourceCreate: DataSourceCreate = {- databaseId: dataSource.databaseId,- instanceId: state.instance.id,+ ...readonlyDataSource.value,+ databaseId: adminDataSource.value.databaseId,+ instanceId: props.instance.id,name: dataSource.name,- type: dataSource.type,+ type: "RO",username: dataSource.username,password: dataSource.password,host: dataSource.host,@@ -970,20 +1274,18 @@ const doUpdate = () => {dataSourceCreate.sslCert = dataSource.sslCert;}requests.push(dataSourceStore.createDataSource(dataSourceCreate));+ } else {+ const dataSourcePatch: DataSourcePatch = {+ ...dataSource,+ };+ requests.push(+ dataSourceStore.patchDataSource({+ databaseId: dataSource.databaseId,+ dataSourceId: dataSource.id,+ dataSourcePatch: dataSourcePatch,+ })+ );}- } else if (- !isEqual(dataSource, state.originalInstance.dataSourceList[i])- ) {- const dataSourcePatch: DataSourcePatch = {- ...dataSource,- };- requests.push(- dataSourceStore.patchDataSource({- databaseId: dataSource.databaseId,- dataSourceId: dataSource.id,- dataSourcePatch: dataSourcePatch,- })- );}}}@@ -991,32 +1293,26 @@ const doUpdate = () => {if (instanceInfoChanged) {requests.push(instanceStore.patchInstance({- instanceId: state.instance.id,+ instanceId: basicInformation.value.id,instancePatch: patchedInstance,}));}- Promise.all(requests).then(() => {- updateInstanceState()- .then((instance) => {- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("instance.successfully-updated-instance-instance-name", [- instance.name,- ]),- });- })- .finally(() => {- state.isUpdating = false;- });+ await Promise.all(requests);+ await updateInstanceState();+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("instance.successfully-updated-instance-instance-name", [+ basicInformation.value.name,+ ]),});+ state.isRequesting = false;}};-const testConnection = () => {- const instance = state.instance;+const testConnection = async () => {const dataSource = currentDataSource.value;let connectionHost = adminDataSource.value.host;let connectionPort = adminDataSource.value.port;@@ -1030,53 +1326,109 @@ const testConnection = () => {}const connectionInfo: ConnectionInfo = {- instanceId: instance.id,- engine: instance.engine,+ ...basicInformation.value,+ host: connectionHost,+ port: connectionPort,username: dataSource.username,password: dataSource.useEmptyPassword ? "" : dataSource.updatedPassword,useEmptyPassword: dataSource.useEmptyPassword,- host: connectionHost,- port: connectionPort,database: dataSource.database,- srv: dataSource.options.srv,- authenticationDatabase: dataSource.options.authenticationDatabase,+ srv: false,+ authenticationDatabase: "",};- if (typeof dataSource.sslCa !== "undefined") {- connectionInfo.sslCa = dataSource.sslCa;- }- if (typeof dataSource.sslKey !== "undefined") {- connectionInfo.sslKey = dataSource.sslKey;+ if (!isCreating.value) {+ connectionInfo.password = adminDataSource.value.password;+ connectionInfo.srv = dataSource.options.srv;+ connectionInfo.authenticationDatabase =+ dataSource.options.authenticationDatabase;}- if (typeof dataSource.sslCert !== "undefined") {- connectionInfo.sslCert = dataSource.sslCert;++ if (showSSL.value) {+ // Default to "NONE"+ connectionInfo.sslCa = adminDataSource.value.sslCa ?? "";+ connectionInfo.sslKey = adminDataSource.value.sslKey ?? "";+ connectionInfo.sslCert = adminDataSource.value.sslCert ?? "";++ if (typeof dataSource.sslCa !== "undefined") {+ connectionInfo.sslCa = dataSource.sslCa;+ }+ if (typeof dataSource.sslKey !== "undefined") {+ connectionInfo.sslKey = dataSource.sslKey;+ }+ if (typeof dataSource.sslCert !== "undefined") {+ connectionInfo.sslCert = dataSource.sslCert;+ }}- sqlStore.ping(connectionInfo).then((resultSet: SQLResultSet) => {- if (isEmpty(resultSet.error)) {- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("instance.successfully-connected-instance"),- });- } else {- let title = t("instance.failed-to-connect-instance");- if (- connectionInfo.host == "localhost" ||- connectionInfo.host == "127.0.0.1"- ) {- title = t("instance.failed-to-connect-instance-localhost");- }- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: title,- description: resultSet.error,- // Manual hide, because user may need time to inspect the error- manualHide: true,- });+ state.isTestingConnection = true;+ const resultSet = await sqlStore.ping(connectionInfo);+ if (isEmpty(resultSet.error)) {+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("instance.successfully-connected-instance"),+ });+ } else {+ let title = t("instance.failed-to-connect-instance");+ if (+ connectionInfo.host == "localhost" ||+ connectionInfo.host == "127.0.0.1"+ ) {+ title = t("instance.failed-to-connect-instance-localhost");}- });+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: title,+ description: resultSet.error,+ // Manual hide, because user may need time to inspect the error+ manualHide: true,+ });+ }+ state.isTestingConnection = false;+};++// getInstanceStateData returns the origin instance data including+// basic information, admin data source and read-only data source.+const getInstanceStateData = () => {+ const instanceData: {+ basicInformation: BasicInformation;+ adminDataSource: EditDataSource;+ readonlyDataSource?: EditDataSource;+ } = {+ basicInformation: {+ id: props.instance?.id || UNKNOWN_ID,+ resourceId: props.instance?.resourceId || "",+ rowStatus: props.instance?.rowStatus || "NORMAL",+ name: props.instance?.name || t("instance.new-instance"),+ engine: props.instance?.engine || "MYSQL",+ environmentId: (props.instance?.environment.id || UNKNOWN_ID) as number,+ },+ adminDataSource: {+ ...(getDataSourceWithType("ADMIN") || unknown("DATA_SOURCE")),+ updatedPassword: "",+ useEmptyPassword: false,+ },+ readonlyDataSource: getDataSourceWithType("RO")+ ? ({+ ...getDataSourceWithType("RO"),+ updatedPassword: "",+ useEmptyPassword: false,+ } as EditDataSource)+ : undefined,+ };+ return instanceData;+};++const convertEditDataSource = (editDataSource: EditDataSource): DataSource => {+ const password = editDataSource.useEmptyPassword+ ? ""+ : editDataSource.updatedPassword || editDataSource.password;+ return {+ ...omit(editDataSource, ["updatedPassword", "useEmptyPassword"]),+ password: password,+ };};</script>diff --git a/frontend/src/components/QuickActionPanel.vue b/frontend/src/components/QuickActionPanel.vueindex a8d89e8e04..bf18107fe6 100644--- a/frontend/src/components/QuickActionPanel.vue+++ b/frontend/src/components/QuickActionPanel.vue@@ -181,7 +181,7 @@<templatev-else-if="state.quickActionType == 'quickaction.bb.instance.create'">- <CreateInstanceForm @dismiss="state.showModal = false" />+ <InstanceForm @dismiss="state.showModal = false" /></template><templatev-else-if="@@ -258,7 +258,7 @@ import {} from "@/store";import ProjectCreate from "../components/ProjectCreate.vue";import BBBetaBadge from "@/bbkit/BBBetaBadge.vue";-import CreateInstanceForm from "../components/CreateInstanceForm.vue";+import InstanceForm from "../components/InstanceForm.vue";import AlterSchemaPrepForm from "./AlterSchemaPrepForm/";import CreateDatabasePrepForm from "../components/CreateDatabasePrepForm.vue";import RequestDatabasePrepForm from "../components/RequestDatabasePrepForm.vue";