Skip to content

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

feat: update instance with read-only data source (#729)

STEVEN288739edfc40
diff --git a/frontend/src/components/CreateDataSourceExample.vue b/frontend/src/components/CreateDataSourceExample.vue
new file mode 100644
index 0000000000..79eb90e1c7
--- /dev/null
+++ b/frontend/src/components/CreateDataSourceExample.vue
@@ -0,0 +1,201 @@
+<template>
+ <div class="w-full flex flex-col justify-start" :class="props.className">
+ <p
+ class="w-full mt-1 text-sm text-gray-500"
+ :class="props.createInstanceFlag ? 'max-w-xl' : ''"
+ >
+ {{
+ props.dataSourceType === "ADMIN"
+ ? $t("instance.sentence.create-admin-user")
+ : $t("instance.sentence.create-readonly-user")
+ }}
+ <span
+ v-if="!props.createInstanceFlag"
+ class="normal-link select-none"
+ @click="toggleCreateUserExample"
+ >
+ {{ $t("instance.show-how-to-create") }}
+ </span>
+ </p>
+ <!-- Specify the fixed width so the create instance dialog width won't shift when switching engine types-->
+ <div
+ v-if="state.showCreateUserExample"
+ class="mt-2 text-sm text-main w-208"
+ >
+ <template·
+ v-if="props.engineType == 'MYSQL' || props.engineType == 'TIDB'"
+ >
+ <i18n-t
+ tag="p"
+ keypath="instance.sentence.create-user-example.mysql.template"
+ >
+ <template #user>{{
+ $t("instance.sentence.create-user-example.mysql.user")
+ }}</template>
+ <template #password>
+ <span class="text-red-600">
+ {{ $t("instance.sentence.create-user-example.mysql.password") }}
+ </span>
+ </template>
+ </i18n-t>
+ <a
+ href="https://docs.bytebase.com/install/docker#start-a-local-mysql-server-for-testing"
+ target="_blank"
+ class="normal-link"
+ >
+ {{ $t("common.detailed-guide") }}
+ </a>
+ </template·>
+ <template v-else-if="props.engineType == 'CLICKHOUSE'">
+ <i18n-t
+ tag="p"
+ keypath="instance.sentence.create-user-example.clickhouse.template"
+ >
+ <template #password>
+ <span class="text-red-600">YOUR_DB_PWD</span>
+ </template>
+ <template #link>
+ <a
+ class="normal-link"
+ href="https://clickhouse.com/docs/en/operations/access-rights/#access-control-usage"
+ target="__blank"
+ >
+ {{
+ $t(
+ "instance.sentence.create-user-example.clickhouse.sql-driven-workflow"
+ )
+ }}
+ </a>
+ </template>
+ </i18n-t>
+ </template>
+ <template v-else-if="props.engineType == 'POSTGRES'">
+ <BBAttention
+ class="mb-1"
+ :style="'WARN'"
+ :title="$t('instance.sentence.create-user-example.postgres.warn')"
+ />
+ <i18n-t
+ tag="p"
+ keypath="instance.sentence.create-user-example.postgres.template"
+ >
+ <template #password>
+ <span class="text-red-600">YOUR_DB_PWD</span>
+ </template>
+ </i18n-t>
+ </template>
+ <template v-else-if="props.engineType == 'SNOWFLAKE'">
+ <i18n-t
+ tag="p"
+ keypath="instance.sentence.create-user-example.snowflake.template"
+ >
+ <template #password>
+ <span class="text-red-600">YOUR_DB_PWD</span>
+ </template>
+ <template #warehouse>
+ <span class="text-red-600">YOUR_COMPUTE_WAREHOUSE</span>
+ </template>
+ </i18n-t>
+ </template>
+ <div class="mt-2 flex flex-row">
+ <span
+ class="flex-1 min-w-0 w-full inline-flex items-center px-3 py-2 border border-r border-control-border bg-gray-50 sm:text-sm whitespace-pre"
+ >
+ {{ grantStatement(props.engineType, props.dataSourceType) }}
+ </span>
+ <button
+ tabindex="-1"
+ class="-ml-px px-2 py-2 border border-gray-300 text-sm font-medium text-control-light disabled:text-gray-300 bg-gray-50 hover:bg-gray-100 disabled:bg-gray-50 focus:ring-control focus:outline-none focus-visible:ring-2 focus:ring-offset-1 disabled:cursor-not-allowed"
+ @click.prevent="copyGrantStatement"
+ >
+ <heroicons-outline:clipboard class="w-6 h-6" />
+ </button>
+ </div>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { defineProps, reactive, PropType } from "vue";
+import { useStore } from "vuex";
+import { toClipboard } from "@soerenmartius/vue3-clipboard";
+import { useI18n } from "vue-i18n";
+import { DataSourceType, EngineType } from "../types";
+
+interface LocalState {
+ showCreateUserExample: boolean;
+}
+
+const props = defineProps({
+ className: {
+ type: String,
+ default: "",
+ },
+ createInstanceFlag: {
+ type: Boolean,
+ default: false,
+ },
+ engineType: {
+ type: String as PropType<EngineType>,
+ default: "MYSQL",
+ },
+ dataSourceType: {
+ type: String as PropType<DataSourceType>,
+ default: "ADMIN",
+ },
+});
+
+const store = useStore();
+const { t } = useI18n();
+
+const state = reactive<LocalState>({
+ showCreateUserExample: props.createInstanceFlag,
+});
+
+const grantStatement = (
+ engineType: EngineType,
+ dataSourceType: DataSourceType
+): string => {
+ if (dataSourceType === "ADMIN") {
+ switch (engineType) {
+ case "MYSQL":
+ case "TIDB":
+ return "CREATE USER bytebase@'%' IDENTIFIED BY 'YOUR_DB_PWD';\n\nGRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, \nDELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, \nSELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE \nON *.* to bytebase@'%';";
+ case "CLICKHOUSE":
+ return "CREATE USER bytebase IDENTIFIED BY 'YOUR_DB_PWD';\n\nGRANT ALL ON *.* TO bytebase WITH GRANT OPTION;";
+ case "SNOWFLAKE":
+ return "CREATE OR REPLACE USER bytebase PASSWORD = 'YOUR_DB_PWD'\nDEFAULT_ROLE = \"ACCOUNTADMIN\"\nDEFAULT_WAREHOUSE = 'YOUR_COMPUTE_WAREHOUSE';\n\nGRANT ROLE \"ACCOUNTADMIN\" TO USER bytebase;";
+ case "POSTGRES":
+ return "CREATE USER bytebase WITH ENCRYPTED PASSWORD 'YOUR_DB_PWD';\n\nALTER USER bytebase WITH SUPERUSER;";
+ }
+ } else {
+ switch (engineType) {
+ case "MYSQL":
+ case "TIDB":
+ return "CREATE USER bytebase@'%' IDENTIFIED BY 'YOUR_DB_PWD';\n\nGRANT SELECT, SHOW DATABASES, SHOW VIEW, USAGE ON *.* to bytebase@'%';";
+ case "CLICKHOUSE":
+ return "CREATE USER bytebase IDENTIFIED BY 'YOUR_DB_PWD';\n\nGRANT SHOW TABLES, SELECT ON database.* TO bytebase;";
+ case "SNOWFLAKE":
+ return "CREATE OR REPLACE USER bytebase PASSWORD = 'YOUR_DB_PWD'\nDEFAULT_ROLE = \"ACCOUNTADMIN\"\nDEFAULT_WAREHOUSE = 'YOUR_COMPUTE_WAREHOUSE';\n\nGRANT ROLE \"ACCOUNTADMIN\" TO USER bytebase;";
+ case "POSTGRES":
+ return "CREATE USER bytebase WITH ENCRYPTED PASSWORD 'YOUR_DB_PWD';\n\nALTER USER bytebase WITH SUPERUSER;";
+ }
+ }
+};
+
+const toggleCreateUserExample = () => {
+ state.showCreateUserExample = !state.showCreateUserExample;
+};
+
+const copyGrantStatement = () => {
+ toClipboard(grantStatement(props.engineType, props.dataSourceType)).then(
+ () => {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "INFO",
+ title: t("instance.copy-grant-statement"),
+ });
+ }
+ );
+};
+</script>
diff --git a/frontend/src/components/CreateInstanceForm.vue b/frontend/src/components/CreateInstanceForm.vue
new file mode 100644
index 0000000000..cbd3927e34
--- /dev/null
+++ b/frontend/src/components/CreateInstanceForm.vue
@@ -0,0 +1,474 @@
+<template>
+ <form class="space-y-6 divide-y divide-block-border">
+ <div class="divide-y divide-block-border px-1">
+ <div class="grid grid-cols-1 gap-4 sm:grid-cols-6">
+ <template v-for="engine in engineList" :key="engine">
+ <div
+ class="flex 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-1 text-center textlabel">
+ {{ engineName(engine) }}
+ </p>
+ <div class="mt-3 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") }}
+ &nbsp;
+ <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">
+ <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>
+ </div>
+
+ <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"
+ @input="handleInstancePortInput"
+ />
+ </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"
+ >
+ <CreateDataSourceExample
+ className="sm:col-span-3"
+ :createInstanceFlag="true"
+ :engineType="state.instance.engine"
+ :dataSourceType="'ADMIN'"
+ />
+ <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>
+
+ <div 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>
+ </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="!state.instance.host"
+ @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>
+ <BBSpin
+ v-if="state.isCreatingInstance"
+ :title="$t('common.creating')"
+ />
+ </div>
+ <div class="ml-2">
+ <button
+ type="button"
+ class="btn-normal py-2 px-4"
+ :disabled="state.isCreatingInstance"
+ @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"
+ @click.prevent="tryCreate"
+ >
+ {{ $t("common.create") }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </form>
+ <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"
+ @ok="
+ () => {
+ state.showCreateInstanceWarningModal = false;
+ doCreate();
+ }
+ "
+ @cancel="state.showCreateInstanceWarningModal = false"
+ ></BBAlert>
+</template>
+
+<script lang="ts" setup>
+import { computed, defineEmits, reactive } from "vue";
+import { useStore } from "vuex";
+import { useRouter } from "vue-router";
+import EnvironmentSelect from "./EnvironmentSelect.vue";
+import CreateDataSourceExample from "./CreateDataSourceExample.vue";
+import { instanceSlug, isDev } from "../utils";
+import {
+ InstanceCreate,
+ UNKNOWN_ID,
+ ConnectionInfo,
+ SqlResultSet,
+ EngineType,
+} from "../types";
+import isEmpty from "lodash-es/isEmpty";
+import { useI18n } from "vue-i18n";
+
+interface LocalState {
+ instance: InstanceCreate;
+ isCreatingInstance: boolean;
+ showCreateInstanceWarningModal: boolean;
+ createInstanceWarning: string;
+}
+
+const emit = defineEmits(["dismiss"]);
+
+const store = useStore();
+const router = useRouter();
+const { t } = useI18n();
+
+const engineList: EngineType[] = [
+ "MYSQL",
+ "POSTGRES",
+ "TIDB",
+ "SNOWFLAKE",
+ "CLICKHOUSE",
+];
+
+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,
+};
+
+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: "",
+ },
+ showCreateInstanceWarningModal: false,
+ createInstanceWarning: "",
+ isCreatingInstance: false,
+});
+
+const allowCreate = computed(() => {
+ 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";
+ }
+ return "3306";
+});
+
+const engineName = (type: EngineType): string => {
+ switch (type) {
+ case "CLICKHOUSE":
+ return "ClickHouse";
+ case "MYSQL":
+ return "MySQL";
+ case "POSTGRES":
+ return "PostgreSQL";
+ case "SNOWFLAKE":
+ return "Snowflake";
+ case "TIDB":
+ return "TiDB";
+ }
+};
+
+// 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") {
+ 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 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 updateInstance = (field: string, value: string) => {
+ let str = value;
+ if (
+ field === "name" ||
+ field === "host" ||
+ field === "port" ||
+ field === "externalLink" ||
+ field === "username" ||
+ field === "password"
+ ) {
+ str = value.trim();
+ }
+ (state.instance as any)[field] = str;
+};
+
+const cancel = () => {
+ emit("dismiss");
+};
+
+const tryCreate = () => {
+ const connectionInfo: ConnectionInfo = {
+ engine: state.instance.engine,
+ username: state.instance.username,
+ password: state.instance.password,
+ // When creating instance, the password is always needed.
+ useEmptyPassword: false,
+ host: state.instance.host,
+ port: state.instance.port,
+ };
+ store.dispatch("sql/ping", connectionInfo).then((resultSet: SqlResultSet) => {
+ if (isEmpty(resultSet.error)) {
+ doCreate();
+ } else {
+ state.createInstanceWarning = t("instance.unable-to-connect", [
+ resultSet.error,
+ ]);
+ state.showCreateInstanceWarningModal = true;
+ }
+ });
+};
+
+// 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;
+ store
+ .dispatch("instance/createInstance", state.instance)
+ .then((createdInstance) => {
+ state.isCreatingInstance = false;
+ emit("dismiss");
+
+ router.push(`/instance/${instanceSlug(createdInstance)}`);
+
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t(
+ "instance.successfully-created-instance-createdinstance-name",
+ [createdInstance.name]
+ ),
+ });
+ });
+};
+
+const testConnection = () => {
+ const connectionInfo: ConnectionInfo = {
+ host: state.instance.host,
+ port: state.instance.port,
+ engine: state.instance.engine,
+ username: state.instance.username,
+ password: state.instance.password,
+ useEmptyPassword: false,
+ instanceId: undefined,
+ };
+ store.dispatch("sql/ping", connectionInfo).then((resultSet: SqlResultSet) => {
+ if (isEmpty(resultSet.error)) {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("instance.successfully-connected-instance"),
+ });
+ } else {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("instance.failed-to-connect-instance"),
+ description: resultSet.error,
+ // Manual hide, because user may need time to inspect the error
+ manualHide: true,
+ });
+ }
+ });
+};
+</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/DataSourceConnectionPanel.vue b/frontend/src/components/DataSourceConnectionPanel.vue
index df64aaa703..8a85d2d65a 100644
--- a/frontend/src/components/DataSourceConnectionPanel.vue
+++ b/frontend/src/components/DataSourceConnectionPanel.vue
@@ -147,8 +147,8 @@ export default {
const database = computed(() => {
return store.getters["database/databaseById"](
- props.dataSource.database.id,
- props.dataSource.instance.id
+ props.dataSource.databaseId,
+ props.dataSource.instanceId
);
});
diff --git a/frontend/src/components/DataSourceCreateForm.vue b/frontend/src/components/DataSourceCreateForm.vue
index 20bcc5ea8c..02e379a612 100644
--- a/frontend/src/components/DataSourceCreateForm.vue
+++ b/frontend/src/components/DataSourceCreateForm.vue
@@ -167,7 +167,6 @@ export default {
type: "RO",
databaseId: props.database ? props.database.id : UNKNOWN_ID,
instanceId: props.instanceId,
- memberList: [],
},
showPassword: false,
});
diff --git a/frontend/src/components/DatabaseOverviewPanel.vue b/frontend/src/components/DatabaseOverviewPanel.vue
index 070a12a8a1..9711e93e80 100644
--- a/frontend/src/components/DatabaseOverviewPanel.vue
+++ b/frontend/src/components/DatabaseOverviewPanel.vue
@@ -337,8 +337,8 @@ export default {
};
store
.dispatch("dataSource/patchDataSource", {
- databaseId: state.editingDataSource!.database.id,
- dataSourceId: state.editingDataSource!.id,
+ databaseId: state.editingDataSource?.databaseId,
+ dataSourceId: state.editingDataSource?.id,
dataSource: dataSourcePatch,
})
.then(() => {
diff --git a/frontend/src/components/InstanceConnectionForm.vue b/frontend/src/components/InstanceConnectionForm.vue
deleted file mode 100644
index 93bed65fbf..0000000000
--- a/frontend/src/components/InstanceConnectionForm.vue
+++ /dev/null
@@ -1,330 +0,0 @@
-<template>
- <div class="pt-4">
- <div class="flex justify-between">
- <div>
- <h3 class="text-lg leading-6 font-medium text-gray-900">{{ $t("instance.connection-info") }}</h3>
- <p class="mt-1 text-sm text-gray-500" :class="create ? 'max-w-xl' : ''">
- {{ $t("instance.sentence.create-user") }}
- <span
- v-if="!create"
- class="normal-link"
- @click="toggleCreateUserExample"
- >{{ $t("instance.show-how-to-create") }}</span>
- </p>
- <!-- Specify the fixed width so the create instance dialog width won't shift when switching engine types-->
- <div v-if="state.showCreateUserExample" class="mt-2 text-sm text-main w-208">
- <template
- v-if="
- instance.engine == 'MYSQL' ||
- instance.engine == 'TIDB'
- "
- >
- <i18n-t tag="p" keypath="instance.sentence.create-user-example.mysql.template">
- <template #user>{{ $t("instance.sentence.create-user-example.mysql.user") }}</template>
- <template #password>
- <span class="text-red-600">
- {{
- $t(
- "instance.sentence.create-user-example.mysql.password"
- )
- }}
- </span>
- </template>
- </i18n-t>
- <a
- href="https://docs.bytebase.com/install/docker#start-a-local-mysql-server-for-testing"
- target="_blank"
- class="normal-link"
- >{{ $t("common.detailed-guide") }}</a>
- </template>
- <template v-else-if="instance.engine == 'CLICKHOUSE'">
- <i18n-t tag="p" keypath="instance.sentence.create-user-example.clickhouse.template">
- <template #password>
- <span class="text-red-600">YOUR_DB_PWD</span>
- </template>
- <template #link>
- <a
- class="normal-link"
- href="https://clickhouse.com/docs/en/operations/access-rights/#access-control-usage"
- target="__blank"
- >
- {{
- $t(
- "instance.sentence.create-user-example.clickhouse.sql-driven-workflow"
- )
- }}
- </a>
- </template>
- </i18n-t>
- </template>
- <template v-else-if="instance.engine == 'POSTGRES'">
- <BBAttention
- class="mb-1"
- :style="'WARN'"
- :title="
- $t('instance.sentence.create-user-example.postgres.warn')
- "
- />
- <i18n-t tag="p" keypath="instance.sentence.create-user-example.postgres.template">
- <template #password>
- <span class="text-red-600">YOUR_DB_PWD</span>
- </template>
- </i18n-t>
- </template>
- <template v-else-if="instance.engine == 'SNOWFLAKE'">
- <i18n-t tag="p" keypath="instance.sentence.create-user-example.snowflake.template">
- <template #password>
- <span class="text-red-600">YOUR_DB_PWD</span>
- </template>
- <template #warehouse>
- <span class="text-red-600">YOUR_COMPUTE_WAREHOUSE</span>
- </template>
- </i18n-t>
- </template>
- <div class="mt-2 flex flex-row">
- <span
- class="flex-1 min-w-0 w-full inline-flex items-center px-3 py-2 border border-r border-control-border bg-gray-50 sm:text-sm whitespace-pre"
- >{{ grantStatement(instance.engine) }}</span>
- <button
- tabindex="-1"
- class="-ml-px px-2 py-2 border border-gray-300 text-sm font-medium text-control-light disabled:text-gray-300 bg-gray-50 hover:bg-gray-100 disabled:bg-gray-50 focus:ring-control focus:outline-none focus-visible:ring-2 focus:ring-offset-1 disabled:cursor-not-allowed"
- @click.prevent="copyGrantStatement"
- >
- <heroicons-outline:clipboard class="w-6 h-6" />
- </button>
- </div>
- </div>
- </div>
- </div>
- <div class="pt-4 grid grid-cols-1 gap-y-4 gap-x-4 sm:grid-cols-3">
- <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"
- :disabled="!allowEdit"
- :placeholder="
- instance.engine == 'CLICKHOUSE'
- ? $t('common.default')
- : ''
- "
- :value="instance.username"
- @input="$emit('update-username', $event.target.value.trim())"
- />
- </div>
-
- <div 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>
- <!-- In create mode, user can leave the password field empty and create the instance,
- so there is no need to show the checkbox.-->
- <BBCheckbox
- v-if="!create"
- :title="$t('common.empty')"
- :value="state.useEmptyPassword"
- @toggle="
- (on) => {
- state.useEmptyPassword = on;
- $emit('toggle-empty-password', on);
- }
- "
- />
- </div>
- <input
- id="password"
- name="password"
- type="text"
- class="textfield mt-1 w-full"
- autocomplete="off"
- :placeholder="
- state.useEmptyPassword
- ? $t('instance.no-password')
- : $t('instance.password-write-only')
- "
- :disabled="!allowEdit || state.useEmptyPassword"
- :value="
- create
- ? state.useEmptyPassword
- ? ''
- : instance.password
- : state.useEmptyPassword
- ? ''
- : state.updatedPassword
- "
- @input="(e) => {
- state.updatedPassword = e.target.value
- $emit('update-password', e.target.value)
- }"
- />
- </div>
- </div>
- <div v-if="showTestConnection" class="pt-8 space-y-2">
- <div class="flex flex-row space-x-2">
- <button
- type="button"
- class="btn-normal whitespace-nowrap items-center"
- :disabled="!instance.host"
- @click.prevent="testConnection"
- >{{ $t("instance.test-connection") }}</button>
- </div>
- </div>
- </div>
-</template>
-
-<script lang="ts">
-import { computed, reactive, watch, PropType, ComputedRef } from "vue";
-import { useStore } from "vuex";
-import { toClipboard } from "@soerenmartius/vue3-clipboard";
-import { isDBAOrOwner } from "../utils";
-import {
- Instance,
- Principal,
- ConnectionInfo,
- SqlResultSet,
- EngineType,
-} from "../types";
-import isEmpty from "lodash-es/isEmpty";
-import { useI18n } from "vue-i18n";
-
-interface LocalState {
- // Only used in non-create case.
- updatedPassword: string;
- useEmptyPassword: boolean;
- showCreateUserExample: boolean;
-}
-
-export default {
- name: "InstanceConnectionForm",
- components: {},
- props: {
- create: {
- default: false,
- type: Boolean,
- },
- allowEdit: {
- required: true,
- type: Boolean,
- },
- instance: {
- // Can be false when create is true
- required: false,
- type: Object as PropType<Instance>,
- },
- },
- emits: ["update-username", "update-password", "toggle-empty-password"],
- setup(props, { }) {
- const store = useStore();
- const { t } = useI18n();
-
- const currentUser: ComputedRef<Principal> = computed(() =>
- store.getters["auth/currentUser"]()
- );
-
- const state = reactive<LocalState>({
- updatedPassword: "",
- useEmptyPassword: false,
- showCreateUserExample: props.create,
- });
-
- watch(
- () => props.instance,
- () => {
- state.updatedPassword = "";
- state.useEmptyPassword = false;
- }
- );
-
- const showTestConnection = computed(() => {
- return (
- props.create ||
- (props.instance.rowStatus == "NORMAL" &&
- isDBAOrOwner(currentUser.value.role))
- );
- });
-
- const grantStatement = (type: EngineType): string => {
- switch (type) {
- case "CLICKHOUSE":
- return "CREATE USER bytebase IDENTIFIED BY 'YOUR_DB_PWD';\n\nGRANT ALL ON *.* TO bytebase WITH GRANT OPTION;";
- case "SNOWFLAKE":
- return "CREATE OR REPLACE USER bytebase PASSWORD = 'YOUR_DB_PWD'\nDEFAULT_ROLE = \"ACCOUNTADMIN\"\nDEFAULT_WAREHOUSE = 'YOUR_COMPUTE_WAREHOUSE';\n\nGRANT ROLE \"ACCOUNTADMIN\" TO USER bytebase;";
- case "MYSQL":
- case "TIDB":
- return "CREATE USER bytebase@'%' IDENTIFIED BY 'YOUR_DB_PWD';\n\nGRANT ALTER, ALTER ROUTINE, CREATE, CREATE ROUTINE, CREATE VIEW, \nDELETE, DROP, EVENT, EXECUTE, INDEX, INSERT, PROCESS, REFERENCES, \nSELECT, SHOW DATABASES, SHOW VIEW, TRIGGER, UPDATE, USAGE \nON *.* to bytebase@'%';";
- case "POSTGRES":
- return "CREATE USER bytebase WITH ENCRYPTED PASSWORD 'YOUR_DB_PWD';\n\nALTER USER bytebase WITH SUPERUSER;";
- }
- };
-
- const toggleCreateUserExample = () => {
- state.showCreateUserExample = !state.showCreateUserExample;
- };
-
- const copyGrantStatement = () => {
- toClipboard(grantStatement(props.instance.engine)).then(() => {
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "INFO",
- title: t("instance.copy-grant-statement"),
- });
- });
- };
-
- const testConnection = () => {
- const connectionInfo: ConnectionInfo = {
- engine: props.instance.engine,
- username: props.instance.username,
- password: props.create
- ? state.useEmptyPassword
- ? ""
- : props.instance.password
- : state.useEmptyPassword
- ? ""
- : state.updatedPassword,
- useEmptyPassword: state.useEmptyPassword,
- host: props.instance.host,
- port: props.instance.port,
- instanceId: props.create ? undefined : (props.instance as Instance).id,
- };
- store
- .dispatch("sql/ping", connectionInfo)
- .then((resultSet: SqlResultSet) => {
- if (isEmpty(resultSet.error)) {
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "SUCCESS",
- title: t("instance.successfully-connected-instance"),
- });
- } else {
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "CRITICAL",
- title: t("instance.failed-to-connect-instance"),
- description: resultSet.error,
- // Manual hide, because user may need time to inspect the error
- manualHide: true,
- });
- }
- });
- };
-
- return {
- state,
- showTestConnection,
- grantStatement,
- toggleCreateUserExample,
- copyGrantStatement,
- testConnection,
- };
- },
-};
-</script>
\ No newline at end of file
diff --git a/frontend/src/components/InstanceForm.vue b/frontend/src/components/InstanceForm.vue
index b6fdc532af..779f84a8d5 100644
--- a/frontend/src/components/InstanceForm.vue
+++ b/frontend/src/components/InstanceForm.vue
@@ -1,49 +1,15 @@
<template>
<form class="space-y-6 divide-y divide-block-border">
- <div class="space-y-6 divide-y divide-block-border px-1">
- <div v-if="create" class="grid grid-cols-1 gap-4 sm:grid-cols-6">
- <template
- v-for="(engine, index) in [
- 'MYSQL',
- 'POSTGRES',
- 'TIDB',
- 'SNOWFLAKE',
- 'CLICKHOUSE',
- ]"
- :key="index"
- >
- <div
- class="flex 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]" alt />
- <p class="mt-1 text-center textlabel">{{ engineName(engine) }}</p>
- <div class="mt-3 radio text-sm">
- <input
- type="radio"
- class="btn"
- :checked="state.instance.engine == engine"
- />
- </div>
- </div>
- </div>
- </template>
- </div>
+ <div class="divide-y divide-block-border px-1">
<!-- Instance Name -->
- <div
- class="grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4"
- :class="create ? 'pt-4' : ''"
- >
+ <div class="mt-6 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") }}
&nbsp;
<span style="color: red">*</span>
- <template v-if="!create">
- <InstanceEngineIcon class="ml-1" :instance="state.instance" />
- <span class="ml-1">{{ state.instance.engineVersion }}</span>
- </template>
+ <InstanceEngineIcon class="ml-1" :instance="state.instance" />
+ <span class="ml-1">{{ state.instance.engineVersion }}</span>
</label>
<input
id="name"
@@ -53,14 +19,13 @@
class="textfield mt-1 w-full"
:disabled="!allowEdit"
:value="state.instance.name"
- @input="updateInstance('name', $event.target.value)"
+ @input="handleInstanceNameInput"
/>
</div>
<div class="sm:col-span-2 sm:col-start-1">
<label for="environment" class="textlabel">
{{ $t("common.environment") }}
- <span v-if="create" 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 -->
@@ -68,19 +33,11 @@
id="environment"
class="mt-1 w-full"
name="environment"
- :disabled="!create"
- :selectedId="
- create
- ? state.instance.environmentId
- : state.instance.environment.id
- "
+ :disabled="true"
+ :selectedId="state.instance.environment.id"
@select-environment-id="
(environmentId) => {
- if (create) {
- state.instance.environmentId = environmentId;
- } else {
- updateInstance('environmentId', environmentId);
- }
+ updateInstance('environmentId', environmentId);
}
"
/>
@@ -110,7 +67,7 @@
class="textfield mt-1 w-full"
:disabled="!allowEdit"
:value="state.instance.host"
- @input="updateInstance('host', $event.target.value)"
+ @input="handleInstanceHostInput"
/>
<div
v-if="state.instance.engine == 'SNOWFLAKE'"
@@ -132,12 +89,12 @@
:placeholder="defaultPort"
:disabled="!allowEdit"
:value="state.instance.port"
- @input="updateInstance('port', $event.target.value)"
+ @input="handleInstancePortInput"
/>
</div>
<!--Do not show external link on create to reduce cognitive load-->
- <div v-if="!create" class="sm:col-span-3 sm:col-start-1">
+ <div class="sm:col-span-3 sm:col-start-1">
<label for="externallink" class="textlabel inline-flex">
<span class>
{{
@@ -176,67 +133,137 @@
required
name="externallink"
type="text"
- class="textfield mt-1 w-full"
- placeholder="https://us-west-1.console.aws.amazon.com/rds/home?region=us-west-1#database:id=mysql-instance-foo;is-cluster=false"
:disabled="!allowEdit"
:value="state.instance.externalLink"
- @input="updateInstance('externalLink', $event.target.value)"
+ class="textfield mt-1 w-full"
+ :placeholder="snowflakeExtraLinkPlaceHolder"
+ @input="handleInstanceExternalLinkInput"
/>
</template>
</div>
</div>
- <!-- Read/Write Connection Info -->
- <InstanceConnectionForm
- :create="create"
- :allowEdit="allowEdit"
- :instance="state.instance"
- @update-username="updateUsername"
- @update-password="updatePassword"
- @toggle-empty-password="toggleEmptyPassword"
- />
- </div>
- <!-- Action Button Group -->
- <div class="pt-4">
- <!-- Create button group -->
- <div v-if="create" class="flex justify-end items-center">
- <div>
- <BBSpin
- v-if="state.creatingOrUpdating"
- :title="$t('common.creating')"
+
+ <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"
+ class="mt-4 flex flex-row justify-start items-center bg-yellow-50 border-none rounded-lg p-2 px-3 mt-0"
+ >
+ <heroicons-outline:exclamation
+ class="h-6 w-6 text-yellow-400 flex-shrink-0 mr-1"
+ />
+ <span class="text-yellow-800 text-sm">{{
+ $t("instance.no-read-only-data-source-warn")
+ }}</span>
+ <button
+ type="button"
+ class="btn-normal ml-4 text-sm"
+ @click.prevent="handleCreateDataSource('RO')"
+ >
+ {{ $t("common.create") }}
+ </button>
+ </div>
+
+ <div
+ class="mt-2 grid grid-cols-1 gap-y-2 gap-x-4 border-none sm:grid-cols-3"
+ >
+ <NTabs
+ class="sm:col-span-3"
+ type="line"
+ :value="state.currentDataSourceType"
+ @update:value="handleDataSourceTypeChange"
+ >
+ <NTab name="ADMIN">Admin</NTab>
+ <NTab name="RO" :disabled="!hasReadonlyDataSource">Read only</NTab>
+ </NTabs>
+ <CreateDataSourceExample
+ className="sm:col-span-3 border-none mt-2"
+ :createInstanceFlag="false"
+ :engineType="state.instance.engine"
+ :dataSourceType="state.currentDataSourceType"
+ />
+ <div class="mt-2 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"
+ :disabled="!allowEdit"
+ :placeholder="
+ instance.engine == 'CLICKHOUSE' ? $t('common.default') : ''
+ "
+ :value="currentDataSource.username"
+ @input="handleCurrentDataSourceNameInput"
/>
</div>
- <div class="ml-2">
- <button
- type="button"
- class="btn-normal py-2 px-4"
- :disabled="state.creatingOrUpdating"
- @click.prevent="cancel"
- >
- {{ $t("common.cancel") }}
- </button>
+
+ <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
+ :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>
+ </div>
+ <div class="mt-6 pt-0 border-none">
+ <div class="flex flex-row space-x-2">
<button
type="button"
- class="btn-primary ml-3 inline-flex justify-center py-2 px-4"
- :disabled="!allowCreate || state.creatingOrUpdating"
- @click.prevent="tryCreate"
+ class="btn-normal whitespace-nowrap items-center"
+ :disabled="!instance.host"
+ @click.prevent="testConnection"
>
- {{ $t("common.create") }}
+ {{ $t("instance.test-connection") }}
</button>
</div>
</div>
- <!-- Update button group -->
- <div v-else class="flex justify-end items-center">
+ </div>
+
+ <!-- Action Button Group -->
+ <div class="pt-4">
+ <div class="flex justify-end items-center">
<div>
- <BBSpin
- v-if="state.creatingOrUpdating"
- :title="$t('common.updating')"
- />
+ <BBSpin v-if="state.isUpdating" :title="$t('common.updating')" />
</div>
<button
v-if="allowEdit"
type="button"
- class="btn-normal ml-2 inline-flex justify-center py-2 px-4"
- :disabled="!valueChanged || state.creatingOrUpdating"
+ :disabled="!valueChanged || state.isUpdating"
+ :class="
+ !valueChanged || state.isUpdating ? 'btn-normal' : 'btn-primary'
+ "
@click.prevent="doUpdate"
>
{{ $t("common.update") }}
@@ -244,326 +271,326 @@
</div>
</div>
</form>
- <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"
- @ok="
- () => {
- state.showCreateInstanceWarningModal = false;
- doCreate();
- }
- "
- @cancel="state.showCreateInstanceWarningModal = false"
- ></BBAlert>
</template>
-<script lang="ts">
-import {
- computed,
- reactive,
- PropType,
- ComputedRef,
- defineComponent,
-} from "vue";
+<script lang="ts" setup>
+import { computed, defineProps, reactive, PropType, ComputedRef } from "vue";
import { useStore } from "vuex";
-import { useRouter } from "vue-router";
import cloneDeep from "lodash-es/cloneDeep";
import isEqual from "lodash-es/isEqual";
import EnvironmentSelect from "../components/EnvironmentSelect.vue";
-import InstanceConnectionForm from "../components/InstanceConnectionForm.vue";
import InstanceEngineIcon from "../components/InstanceEngineIcon.vue";
-import { instanceSlug, isDBAOrOwner, isDev } from "../utils";
+import { isDBAOrOwner } from "../utils";
import {
- Instance,
- InstanceCreate,
- UNKNOWN_ID,
Principal,
InstancePatch,
- ConnectionInfo,
+ DataSourceType,
+ Instance,
SqlResultSet,
- EngineType,
+ ConnectionInfo,
+ DataSource,
+ UNKNOWN_ID,
} from "../types";
import isEmpty from "lodash-es/isEmpty";
import { useI18n } from "vue-i18n";
-interface LocalState {
- originalInstance?: Instance;
- instance: Instance | InstanceCreate;
- // Only used in non-create case.
+interface EditDataSource extends DataSource {
updatedPassword: string;
useEmptyPassword: boolean;
- showCreateInstanceWarningModal: boolean;
- createInstanceWarning: string;
- creatingOrUpdating: boolean;
}
-export default defineComponent({
- name: "InstanceForm",
- components: { EnvironmentSelect, InstanceConnectionForm, InstanceEngineIcon },
- props: {
- create: {
- default: false,
- type: Boolean,
- },
- instance: {
- // Can be false when create is true
- required: false,
- type: Object as PropType<Instance>,
- default: undefined,
- },
+interface State {
+ originalInstance: Instance;
+ instance: Instance;
+ isUpdating: boolean;
+ dataSourceList: EditDataSource[];
+ currentDataSourceType: DataSourceType;
+}
+
+const props = defineProps({
+ instance: {
+ required: true,
+ type: Object as PropType<Instance>,
},
- emits: ["dismiss"],
- setup(props, { emit }) {
- const store = useStore();
- const router = useRouter();
- const { t } = useI18n();
-
- const currentUser: ComputedRef<Principal> = computed(() =>
- store.getters["auth/currentUser"]()
- );
-
- 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,
- };
-
- const state = reactive<LocalState>({
- originalInstance: props.instance,
- // Make hard copy since we are going to make equal comparison to determine the update button enable state.
- instance: props.instance
- ? cloneDeep(props.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: "",
- },
- updatedPassword: "",
- useEmptyPassword: false,
- showCreateInstanceWarningModal: false,
- createInstanceWarning: "",
- creatingOrUpdating: false,
- });
+});
- const allowCreate = computed(() => {
- return state.instance.name && state.instance.host;
- });
+const store = useStore();
+const { t } = useI18n();
- const allowEdit = computed(() => {
- return (
- props.create ||
- ((state.instance as Instance).rowStatus == "NORMAL" &&
- isDBAOrOwner(currentUser.value.role))
- );
- });
+const currentUser: ComputedRef<Principal> = computed(() =>
+ store.getters["auth/currentUser"]()
+);
- const valueChanged = computed(() => {
- return (
- !isEqual(state.instance, state.originalInstance) ||
- !isEmpty(state.updatedPassword) ||
- state.useEmptyPassword
- );
- });
+const dataSourceList = props.instance.dataSourceList.map((dataSource) => {
+ return {
+ ...cloneDeep(dataSource),
+ updatedPassword: "",
+ useEmptyPassword: dataSource.password === "",
+ } as EditDataSource;
+});
- 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";
- }
- return "3306";
- });
+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,
+ currentDataSourceType: "ADMIN",
+});
- const engineName = (type: EngineType): string => {
- switch (type) {
- case "CLICKHOUSE":
- return "ClickHouse";
- case "MYSQL":
- return "MySQL";
- case "POSTGRES":
- return "PostgreSQL";
- case "SNOWFLAKE":
- return "Snowflake";
- case "TIDB":
- return "TiDB";
- }
- };
-
- const instanceLink = (instance: Instance): string => {
- if (instance.engine == "SNOWFLAKE") {
- if (instance.host) {
- return `https://${
- instance.host.split("@")[0]
- }.snowflakecomputing.com/console`;
- }
- }
- return instance.externalLink || "";
- };
-
- // 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") {
- 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 updateUsername = (username: string) => {
- state.instance.username = username;
- };
-
- const updatePassword = (password: string) => {
- if (props.create) {
- state.instance.password = password;
- } else {
- state.updatedPassword = password;
- }
- };
-
- const toggleEmptyPassword = (useEmptyPassword: boolean) => {
- state.useEmptyPassword = useEmptyPassword;
- };
-
- const updateInstance = (field: string, value: string) => {
- let str = value;
- if (
- field == "name" ||
- field == "host" ||
- field == "port" ||
- field == "externalLink"
- ) {
- str = value.trim();
- }
- (state.instance as any)[field] = str;
- };
-
- const cancel = () => {
- emit("dismiss");
- };
-
- const tryCreate = () => {
- const connectionInfo: ConnectionInfo = {
- engine: state.instance.engine,
- username: state.instance.username,
- password: state.useEmptyPassword ? "" : state.instance.password,
- useEmptyPassword: state.useEmptyPassword,
- host: state.instance.host,
- port: state.instance.port,
- };
- store
- .dispatch("sql/ping", connectionInfo)
- .then((resultSet: SqlResultSet) => {
- if (isEmpty(resultSet.error)) {
- doCreate();
- } else {
- state.createInstanceWarning = t("instance.unable-to-connect", [
- resultSet.error,
- ]);
- state.showCreateInstanceWarningModal = true;
- }
- });
- };
-
- // 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.creatingOrUpdating = true;
- if (state.useEmptyPassword) {
- state.instance.password = "";
- }
- store
- .dispatch("instance/createInstance", state.instance)
- .then((createdInstance) => {
- state.creatingOrUpdating = false;
- state.useEmptyPassword = false;
- emit("dismiss");
+const allowEdit = computed(() => {
+ return (
+ state.instance.rowStatus == "NORMAL" && isDBAOrOwner(currentUser.value.role)
+ );
+});
- router.push(`/instance/${instanceSlug(createdInstance)}`);
+const valueChanged = computed(() => {
+ return !isEqual(state.instance, state.originalInstance);
+});
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "SUCCESS",
- title: t(
- "instance.successfully-created-instance-createdinstance-name",
- [createdInstance.name]
- ),
- });
+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";
+ }
+ return "3306";
+});
- // After creating the instance, we will check if migration schema exists on the instance.
- // setTimeout(() => {}, 1000);
- })
- .finally(() => {
- state.creatingOrUpdating = false;
- });
- };
+const adminDataSource = computed(() => {
+ const temp = state.dataSourceList.find(
+ (ds) => ds.type === "ADMIN"
+ ) as DataSource;
+ return temp;
+});
- const doUpdate = () => {
- const patchedInstance: InstancePatch = { useEmptyPassword: false };
- let connectionInfoChanged = false;
- if (state.instance.name != state.originalInstance!.name) {
- patchedInstance.name = state.instance.name;
- }
- if (state.instance.externalLink != state.originalInstance!.externalLink) {
- patchedInstance.externalLink = state.instance.externalLink;
- }
- if (state.instance.host != state.originalInstance!.host) {
- patchedInstance.host = state.instance.host;
- connectionInfoChanged = true;
- }
- if (state.instance.port != state.originalInstance!.port) {
- patchedInstance.port = state.instance.port;
- connectionInfoChanged = true;
- }
- if (state.instance.username != state.originalInstance!.username) {
- patchedInstance.username = state.instance.username;
- connectionInfoChanged = true;
- }
- if (state.useEmptyPassword) {
- patchedInstance.useEmptyPassword = true;
- connectionInfoChanged = true;
- } else if (!isEmpty(state.updatedPassword)) {
- patchedInstance.password = state.updatedPassword;
- connectionInfoChanged = true;
+const hasReadonlyDataSource = computed(() => {
+ for (const ds of state.dataSourceList) {
+ if (ds.type === "RO") {
+ return true;
+ }
+ }
+ return false;
+});
+
+const currentDataSource = computed(() => {
+ const temp = state.dataSourceList.find(
+ (ds) => ds.type === state.currentDataSourceType
+ ) as EditDataSource;
+ return temp;
+});
+
+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 = (instance: Instance): string => {
+ if (instance.engine == "SNOWFLAKE") {
+ if (instance.host) {
+ return `https://${
+ instance.host.split("@")[0]
+ }.snowflakecomputing.com/console`;
+ }
+ }
+ return instance.host;
+};
+
+const handleInstanceNameInput = (event: Event) => {
+ updateInstance("name", (event.target as HTMLInputElement).value);
+};
+
+const handleInstanceHostInput = (event: Event) => {
+ updateInstance("host", (event.target as HTMLInputElement).value);
+};
+
+const handleInstancePortInput = (event: Event) => {
+ updateInstance("port", (event.target as HTMLInputElement).value);
+};
+
+const handleInstanceExternalLinkInput = (event: Event) => {
+ updateInstance("externalLink", (event.target as HTMLInputElement).value);
+};
+
+const handleDataSourceTypeChange = (value: string) => {
+ state.currentDataSourceType = value as DataSourceType;
+};
+
+const handleCurrentDataSourceNameInput = (event: Event) => {
+ const str = (event.target as HTMLInputElement).value.trim();
+ currentDataSource.value.username = str;
+ updateInstanceDataSource();
+};
+
+const handleToggleUseEmptyPassword = (on: boolean) => {
+ currentDataSource.value.useEmptyPassword = on;
+ updateInstanceDataSource();
+};
+
+const handleCurrentDataSourcePasswordInput = (event: Event) => {
+ const str = (event.target as HTMLInputElement).value.trim();
+ currentDataSource.value.updatedPassword = str;
+ updateInstanceDataSource();
+};
+
+const updateInstanceDataSource = () => {
+ const index = state.dataSourceList.findIndex(
+ (ds) => ds === currentDataSource.value
+ );
+ state.instance.dataSourceList[index] = {
+ ...state.instance.dataSourceList[index],
+ username: currentDataSource.value.username,
+ password: currentDataSource.value.useEmptyPassword
+ ? ""
+ : currentDataSource.value.updatedPassword
+ ? currentDataSource.value.updatedPassword
+ : currentDataSource.value.password,
+ };
+};
+
+const handleCreateDataSource = (type: DataSourceType) => {
+ // Don't allow creating RO in UI for SNOWFLAKE/POSTGRES till we figure out the grant.
+ if (
+ state.instance.engine === "SNOWFLAKE" ||
+ state.instance.engine === "POSTGRES"
+ ) {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "WARN",
+ title: t("instance.no-read-only-data-source-support", {
+ database: state.instance.engine,
+ }),
+ });
+ return;
+ }
+
+ const tempDataSource = {
+ id: UNKNOWN_ID,
+ instanceId: state.instance.id,
+ databaseId: adminDataSource.value.databaseId,
+ name: `${type} data source`,
+ type: type,
+ username: "",
+ password: "",
+ } as DataSource;
+ state.instance.dataSourceList.push(tempDataSource);
+ state.dataSourceList.push({
+ ...tempDataSource,
+ updatedPassword: "",
+ useEmptyPassword: false,
+ });
+ state.currentDataSourceType = type;
+};
+
+const updateInstance = (field: string, value: string) => {
+ let str = value;
+ if (
+ field == "name" ||
+ field == "host" ||
+ field == "port" ||
+ field == "externalLink"
+ ) {
+ str = value.trim();
+ }
+ (state.instance as any)[field] = str;
+};
+
+const doUpdate = () => {
+ const patchedInstance: InstancePatch = {};
+ let instanceInfoChanged = false;
+ let dataSourceListChanged = false;
+ let connectionInfoChanged = false;
+
+ if (state.instance.name != state.originalInstance.name) {
+ patchedInstance.name = state.instance.name;
+ instanceInfoChanged = true;
+ }
+ if (state.instance.externalLink != state.originalInstance.externalLink) {
+ patchedInstance.externalLink = state.instance.externalLink;
+ instanceInfoChanged = true;
+ }
+ if (state.instance.host != state.originalInstance.host) {
+ patchedInstance.host = state.instance.host;
+ connectionInfoChanged = true;
+ instanceInfoChanged = true;
+ }
+ if (state.instance.port != state.originalInstance.port) {
+ patchedInstance.port = state.instance.port;
+ instanceInfoChanged = true;
+ connectionInfoChanged = true;
+ }
+
+ if (
+ !isEqual(
+ state.originalInstance.dataSourceList,
+ state.instance.dataSourceList
+ )
+ ) {
+ dataSourceListChanged = true;
+ }
+
+ if (instanceInfoChanged || dataSourceListChanged) {
+ state.isUpdating = true;
+ const requests = [];
+
+ 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") {
+ requests.push(
+ store.dispatch("dataSource/createDataSource", {
+ databaseId: dataSource.databaseId,
+ instanceId: state.instance.id,
+ name: dataSource.name,
+ type: dataSource.type,
+ username: dataSource.username,
+ password: dataSource.password,
+ })
+ );
+ }
+ } else if (
+ !isEqual(dataSource, state.originalInstance.dataSourceList[i])
+ ) {
+ requests.push(
+ store.dispatch("dataSource/patchDataSource", {
+ databaseId: dataSource.databaseId,
+ dataSourceId: dataSource.id,
+ dataSource: dataSource,
+ })
+ );
+ }
}
+ }
- state.creatingOrUpdating = true;
- store
- .dispatch("instance/patchInstance", {
- instanceId: (state.instance as Instance).id,
+ if (instanceInfoChanged) {
+ requests.push(
+ store.dispatch("instance/patchInstance", {
+ instanceId: state.instance.id,
instancePatch: patchedInstance,
})
+ );
+ }
+
+ Promise.all(requests).then(() => {
+ store
+ .dispatch("instance/fetchInstanceById", state.instance.id)
.then((instance) => {
- state.creatingOrUpdating = false;
+ state.isUpdating = false;
state.originalInstance = instance;
- // Make hard copy since we are going to make equal comparison to determine the update button enable state.
- state.instance = cloneDeep(state.originalInstance!);
- state.updatedPassword = "";
- state.useEmptyPassword = false;
+ state.instance = cloneDeep(state.originalInstance);
+ state.dataSourceList = state.instance.dataSourceList.map(
+ (dataSource) => {
+ return {
+ ...cloneDeep(dataSource),
+ updatedPassword: "",
+ useEmptyPassword: dataSource.password === "",
+ } as EditDataSource;
+ }
+ );
store.dispatch("notification/pushNotification", {
module: "bytebase",
@@ -577,36 +604,50 @@ export default defineComponent({
if (connectionInfoChanged) {
store.dispatch(
"database/fetchDatabaseListByInstanceId",
- instance.id
+ state.instance.id
);
}
})
.finally(() => {
- state.creatingOrUpdating = false;
+ state.isUpdating = false;
});
- };
-
- return {
- state,
- allowCreate,
- allowEdit,
- valueChanged,
- EngineIconPath,
- defaultPort,
- engineName,
- instanceLink,
- changeInstanceEngine,
- updateUsername,
- updatePassword,
- toggleEmptyPassword,
- updateInstance,
- cancel,
- tryCreate,
- doCreate,
- doUpdate,
- };
- },
-});
+ });
+ }
+};
+
+const testConnection = () => {
+ const connectionInfo: ConnectionInfo = {
+ engine: state.instance.engine,
+ username: currentDataSource.value.username,
+ password: currentDataSource.value.useEmptyPassword
+ ? ""
+ : currentDataSource.value.updatedPassword
+ ? currentDataSource.value.updatedPassword
+ : currentDataSource.value.password,
+ useEmptyPassword: currentDataSource.value.useEmptyPassword,
+ host: state.instance.host,
+ port: state.instance.port,
+ instanceId: state.instance.id,
+ };
+ store.dispatch("sql/ping", connectionInfo).then((resultSet: SqlResultSet) => {
+ if (isEmpty(resultSet.error)) {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("instance.successfully-connected-instance"),
+ });
+ } else {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("instance.failed-to-connect-instance"),
+ description: resultSet.error,
+ // Manual hide, because user may need time to inspect the error
+ manualHide: true,
+ });
+ }
+ });
+};
</script>
<style scoped>
diff --git a/frontend/src/components/QuickActionPanel.vue b/frontend/src/components/QuickActionPanel.vue
index 3e3e43dfae..84b8997678 100644
--- a/frontend/src/components/QuickActionPanel.vue
+++ b/frontend/src/components/QuickActionPanel.vue
@@ -197,7 +197,7 @@
<template
v-else-if="state.quickActionType == 'quickaction.bb.instance.create'"
>
- <InstanceForm :create="true" @dismiss="state.showModal = false" />
+ <CreateInstanceForm @dismiss="state.showModal = false" />
</template>
<template
v-else-if="
@@ -259,7 +259,7 @@ import { defineComponent, reactive, PropType, computed } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import ProjectCreate from "../components/ProjectCreate.vue";
-import InstanceForm from "../components/InstanceForm.vue";
+import CreateInstanceForm from "../components/CreateInstanceForm.vue";
import AlterSchemaPrepForm from "./AlterSchemaPrepForm/";
import CreateDatabasePrepForm from "../components/CreateDatabasePrepForm.vue";
import RequestDatabasePrepForm from "../components/RequestDatabasePrepForm.vue";
@@ -282,7 +282,7 @@ export default defineComponent({
name: "QuickActionPanel",
components: {
ProjectCreate,
- InstanceForm,
+ CreateInstanceForm,
AlterSchemaPrepForm,
CreateDatabasePrepForm,
RequestDatabasePrepForm,
diff --git a/frontend/src/locales/en.yml b/frontend/src/locales/en.yml
index 25babd8c83..421e9312bb 100644
--- a/frontend/src/locales/en.yml
+++ b/frontend/src/locales/en.yml
@@ -150,6 +150,7 @@ common:
added-time: Added time
data-source: Data Source
grant: Grant
+ admin: Admin
read-only: Read-only
connection-string: Connection string
agents: Agents
@@ -503,6 +504,7 @@ instance:
below-is-an-example-to-create-user-bytebase-with-password: Below is an example to create user 'bytebase{'@'}%' with password
below-is-an-example-to-create-user-bytebase-with-password-clickhouse: Below is an example to create user 'bytebase' with password
your_db_pwd: YOUR_DB_PWD
+ no-read-only-data-source-warn: The instance has not configured read-only user, please consider adding one.
sentence:
host:
snowflake: e.g. host.docker.internal {'|'} <<ip>> {'|'} <<local socket>>
@@ -514,9 +516,11 @@ instance:
snowflake: >-
The external console URL managing this instance (e.g. AWS RDS console,
your in-house DB instance console)
- create-user: >-
- This is the connection user used by Bytebase to perform DDL and DML
+ create-admin-user: >-
+ This is the connection user used by Bytebase to perform DDL and DML (non-SELECT)
operations.
+ create-readonly-user: >-
+ This is the connection user used by Bytebase to perform read-only operations such as SELECT query.
create-user-example:
snowflake:
user: bytebase{'@'}%
@@ -577,6 +581,7 @@ instance:
Bytebase requires read/write (NOT the super privilege) access to the
instance in order to perform database operations on behalf of the user.
search-instance-name: Search instance name
+ no-read-only-data-source-support: The {database} does not currently support creating read-only connections
grants: Grants
environment:
select: Select environment
@@ -1085,6 +1090,7 @@ deployment-config:
project-has-no-deployment-config: This project has no deployment config yet. Please {go} first.
go-and-config: Go and config
datasource:
+ role-type: Role Type
successfully-deleted-data-source-name: Successfully deleted data source '{0}'.
create-data-source: Create data source
data-source-list: Data source list
@@ -1164,6 +1170,7 @@ sql-editor:
read
public: Public
public-desc: Sheet OWNER can read/write, and all others can read
+ create-read-only-data-source: Go to create
go-back: Go Back
label:
empty-label-value: <Empty Value>
diff --git a/frontend/src/locales/zh-CN.yml b/frontend/src/locales/zh-CN.yml
index 62a631d9ae..45446bfd49 100644
--- a/frontend/src/locales/zh-CN.yml
+++ b/frontend/src/locales/zh-CN.yml
@@ -150,6 +150,7 @@ common:
added-time: 添加时间
data-source: 数据源
grant: 授予
+ admin: 管理员
read-only: 只读
connection-string: 连接字符串
agents: Agents
@@ -477,6 +478,7 @@ instance:
connection-info: 连接信息
show-how-to-create: 如何创建
below-is-an-example-to-create-user-bytebase-with-password: 创建用户 'bytebase{'@'}%' 及其密码的例子如下
+ no-read-only-data-source-warn: 该实例没有配置只读用户,请考虑配置。
sentence:
host:
snowflake: 例如 host.docker.internal {'|'} <<ip>> {'|'} <<local socket>>
@@ -484,7 +486,8 @@ instance:
snowflake: 对于代理服务器,加上 {'@'}PROXY_HOST,并在端口里指定 PROXY_PORT
console:
snowflake: "\b管理该@:{'common.instance'}的外部控制台 URL(如 AWS RDS 控制台,您的@:{'common.database'}控制台)"
- create-user: 这是 Bytebase 用于连接数据库,执行 DDL 和 DML 操作的用户。
+ create-admin-user: 这是 Bytebase 用于连接数据库,执行 DDL 和 DML (非 SELECT) 操作的用户。
+ create-readonly-user: 这是 Bytebase 用于连接数据库,执行诸如 SELECT 的只读操作。
create-user-example:
snowflake:
user: bytebase{'@'}%
@@ -526,6 +529,7 @@ instance:
RDS 实例,也可能是您私有化部署的 MySQL 实例。
Bytebase 要求实例的读写权限(而不是 super 权限)以代表用户执行数据库操作。
search-instance-name: 搜索实例名称
+ no-read-only-data-source-support: 暂时不支持 {database} 创建只读连接
grants: 权限
environment:
select: 选择环境
@@ -948,6 +952,7 @@ deployment-config:
project-has-no-deployment-config: 这个项目还没有部署配置。请先{go}。
go-and-config: 去配置
datasource:
+ role-type: 权限类型
successfully-deleted-data-source-name: 成功删除数据源'{0}'。
create-data-source: 创建数据源
data-source-list: 数据源列表
@@ -1023,6 +1028,7 @@ sql-editor:
project-desc: 工作表所有者或者项目所有者拥有读、写权限,项目开发者拥有只读权限
public: 公开
public-desc: 工作表所有者拥有读写权限,其他人只拥有只读权限.
+ create-read-only-data-source: 前去创建
go-back: 返回
label:
empty-label-value: <空值>
diff --git a/frontend/src/plugins/naive-ui.ts b/frontend/src/plugins/naive-ui.ts
index b42f4551f4..3721b7940e 100644
--- a/frontend/src/plugins/naive-ui.ts
+++ b/frontend/src/plugins/naive-ui.ts
@@ -16,6 +16,7 @@ import {
NPopselect,
NPopconfirm,
NSpace,
+ NTab,
NTabs,
NTabPane,
NTag,
@@ -42,6 +43,7 @@ const naive = create({
NPopselect,
NPopconfirm,
NSpace,
+ NTab,
NTabs,
NTabPane,
NTag,
diff --git a/frontend/src/store/modules/dataSource.ts b/frontend/src/store/modules/dataSource.ts
index 6eff9967f7..d9b545d453 100644
--- a/frontend/src/store/modules/dataSource.ts
+++ b/frontend/src/store/modules/dataSource.ts
@@ -3,19 +3,14 @@ import {
DataSourceId,
DataSource,
DataSourceCreate,
- DataSourceMember,
- DataSourceMemberCreate,
DataSourceState,
- PrincipalId,
ResourceObject,
- ResourceIdentifier,
DatabaseId,
unknown,
- Database,
- Instance,
DataSourcePatch,
EMPTY_ID,
empty,
+ UNKNOWN_ID,
} from "../../types";
import { getPrincipalFromIncludedList } from "./principal";
@@ -24,44 +19,17 @@ function convert(
includedList: ResourceObject[],
rootGetters: any
): DataSource {
- const databaseId = (
- dataSource.relationships!.database.data as ResourceIdentifier
- ).id;
- const instanceId = (
- dataSource.relationships!.instance.data as ResourceIdentifier
- ).id;
- const memberList = (dataSource.attributes.memberList as []).map(
- (item: any): DataSourceMember => {
- return {
- principal: rootGetters["principal/principalById"](item.principalId),
- issueId: item.issueId,
- createdTs: item.createdTs,
- };
- }
- );
-
- let instance: Instance = unknown("INSTANCE") as Instance;
- for (const item of includedList || []) {
- if (item.type == "instance" && item.id == instanceId) {
- instance = rootGetters["instance/convert"](item);
- break;
- }
- }
-
- let database: Database = unknown("DATABASE") as Database;
- for (const item of includedList || []) {
- if (item.type == "database" && item.id == databaseId) {
- database = rootGetters["database/convert"](item);
- break;
- }
- }
+ const databaseId = dataSource.attributes!.databaseId as string;
+ const instanceId = dataSource.attributes!.instanceId as string;
return {
...(dataSource.attributes as Omit<
DataSource,
- "id" | "instanceId" | "database" | "memberList" | "creator" | "updater"
+ "id" | "instanceId" | "databaseId" | "creator" | "updater"
>),
id: parseInt(dataSource.id),
+ databaseId: parseInt(databaseId),
+ instanceId: parseInt(instanceId),
creator: getPrincipalFromIncludedList(
dataSource.relationships!.creator.data,
includedList
@@ -70,9 +38,6 @@ function convert(
dataSource.relationships!.updater.data,
includedList
),
- instance,
- database,
- memberList,
};
}
@@ -144,12 +109,14 @@ const actions = {
dataSource: createdDataSource,
});
- // Refresh the corresponding database as it contains data source.
- dispatch(
- "database/fetchDatabaseById",
- { databaseId: newDataSource.databaseId },
- { root: true }
- );
+ if (createdDataSource.databaseId !== UNKNOWN_ID) {
+ // Refresh the corresponding database as it contains data source.
+ dispatch(
+ "database/fetchDatabaseById",
+ { databaseId: createdDataSource.databaseId },
+ { root: true }
+ );
+ }
return createdDataSource;
},
@@ -184,8 +151,10 @@ const actions = {
dataSource: updatedDataSource,
});
- // Refresh the corresponding database as it contains data source.
- dispatch("database/fetchDatabaseById", { databaseId }, { root: true });
+ if (databaseId !== UNKNOWN_ID) {
+ // Refresh the corresponding database as it contains data source.
+ dispatch("database/fetchDatabaseById", { databaseId }, { root: true });
+ }
return updatedDataSource;
},
@@ -206,72 +175,6 @@ const actions = {
// Refresh the corresponding database as it contains data source.
dispatch("database/fetchDatabaseById", { databaseId }, { root: true });
},
-
- async createDataSourceMember(
- { commit, dispatch, rootGetters }: any,
- {
- dataSourceId,
- databaseId,
- newDataSourceMember,
- }: {
- dataSourceId: DataSourceId;
- databaseId: DatabaseId;
- newDataSourceMember: DataSourceMemberCreate;
- }
- ) {
- const data = (
- await axios.post(
- `/api/database/${databaseId}/datasource/${dataSourceId}/member`,
- {
- data: {
- type: "dataSourceMember",
- attributes: newDataSourceMember,
- },
- }
- )
- ).data;
- // It's patching the data source and returns the updated data source
- const updatedDataSource = convert(data.data, data.included, rootGetters);
-
- commit("setDataSourceById", {
- databaseId,
- dataSource: updatedDataSource,
- });
-
- // Refresh the corresponding database as it contains data source and its membership info.
- dispatch("database/fetchDatabaseById", { databaseId }, { root: true });
-
- return updatedDataSource;
- },
-
- async deleteDataSourceMemberByMemberId(
- { commit, dispatch, rootGetters }: any,
- {
- databaseId,
- dataSourceId,
- memberId,
- }: {
- databaseId: DatabaseId;
- dataSourceId: DataSourceId;
- memberId: PrincipalId;
- }
- ) {
- const data = (
- await axios.delete(
- `/api/database/${databaseId}/datasource/${dataSourceId}/member/${memberId}`
- )
- ).data;
- // It's patching the data source and returns the updated data source
- const updatedDataSource = convert(data.data, data.included, rootGetters);
-
- commit("setDataSourceById", {
- dataSourceId: updatedDataSource.id,
- dataSource: updatedDataSource,
- });
-
- // Refresh the corresponding database as it contains data source and its membership info.
- dispatch("database/fetchDatabaseById", { databaseId }, { root: true });
- },
};
const mutations = {
diff --git a/frontend/src/store/modules/instance.ts b/frontend/src/store/modules/instance.ts
index cd4e358428..e378d0334c 100644
--- a/frontend/src/store/modules/instance.ts
+++ b/frontend/src/store/modules/instance.ts
@@ -1,6 +1,7 @@
import axios from "axios";
import {
Anomaly,
+ DataSource,
empty,
EMPTY_ID,
Environment,
@@ -43,10 +44,24 @@ function convert(
anomalyList.push(anomaly);
}
+ const dataSourceIdList = instance.relationships!.dataSourceList
+ .data as ResourceIdentifier[];
+ const dataSourceList: DataSource[] = [];
+ for (const item of dataSourceIdList) {
+ const dataSource = unknown("DATA_SOURCE") as DataSource;
+ dataSource.id = parseInt(item.id);
+ dataSourceList.push(dataSource);
+ }
+
const instancePartial = {
...(instance.attributes as Omit<
Instance,
- "id" | "environment" | "anomalyList" | "creator" | "updater"
+ | "id"
+ | "environment"
+ | "anomalyList"
+ | "dataSourceList"
+ | "creator"
+ | "updater"
>),
id: parseInt(instance.id),
creator: getPrincipalFromIncludedList(
@@ -59,6 +74,7 @@ function convert(
),
environment,
anomalyList: [],
+ dataSourceList: [],
};
for (const item of includedList || []) {
@@ -82,6 +98,18 @@ function convert(
anomalyList[i].instance = instancePartial;
}
}
+
+ if (
+ item.type == "dataSource" &&
+ item.attributes.instanceId == instancePartial.id
+ ) {
+ const i = dataSourceList.findIndex(
+ (dataSource: DataSource) => parseInt(item.id) == dataSource.id
+ );
+ if (i != -1) {
+ dataSourceList[i] = rootGetters["dataSource/convert"](item);
+ }
+ }
}
for (const anomaly of anomalyList) {
@@ -91,12 +119,11 @@ function convert(
return {
...(instancePartial as Omit<
Instance,
- "environment" | "password" | "anomalyList"
+ "environment" | "anomalyList" | "dataSourceList"
>),
environment,
- // Password is not returned by the server, we just take extra caution here to redact it.
- password: "",
anomalyList,
+ dataSourceList,
};
}
diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.ts
index d7dadad710..4c0b3e676b 100644
--- a/frontend/src/types/common.ts
+++ b/frontend/src/types/common.ts
@@ -240,6 +240,7 @@ export const unknown = (
rowStatus: "NORMAL",
environment: UNKNOWN_ENVIRONMENT,
anomalyList: [],
+ dataSourceList: [],
creator: UNKNOWN_PRINCIPAL,
updater: UNKNOWN_PRINCIPAL,
createdTs: 0,
@@ -277,7 +278,6 @@ export const unknown = (
createdTs: 0,
updater: UNKNOWN_PRINCIPAL,
updatedTs: 0,
- memberList: [],
name: "<<Unknown data source>>",
type: "RO",
};
@@ -628,6 +628,7 @@ export const empty = (
rowStatus: "NORMAL",
environment: EMPTY_ENVIRONMENT,
anomalyList: [],
+ dataSourceList: [],
creator: EMPTY_PRINCIPAL,
updater: EMPTY_PRINCIPAL,
createdTs: 0,
@@ -665,7 +666,6 @@ export const empty = (
createdTs: 0,
updater: EMPTY_PRINCIPAL,
updatedTs: 0,
- memberList: [],
name: "",
type: "RO",
};
diff --git a/frontend/src/types/dataSource.ts b/frontend/src/types/dataSource.ts
index 439a903dd4..368733c33a 100644
--- a/frontend/src/types/dataSource.ts
+++ b/frontend/src/types/dataSource.ts
@@ -1,7 +1,6 @@
// For now the ADMIN requires the same database privilege as RW.
// The seperation is to make it explicit which one serves as the ADMIN data source,
-import { Database } from "./database";
import {
DatabaseId,
DataSourceId,
@@ -9,7 +8,6 @@ import {
IssueId,
PrincipalId,
} from "./id";
-import { Instance } from "./instance";
import { Principal } from "./principal";
// which from the ops perspective, having different meaning from the normal RW data source.
@@ -19,11 +17,8 @@ export type DataSource = {
id: DataSourceId;
// Related fields
- database: Database;
- instance: Instance;
- // Returns the member list directly because we need it quite frequently in order
- // to do various access check.
- memberList: DataSourceMember[];
+ databaseId: DatabaseId;
+ instanceId: InstanceId;
// Standard fields
creator: Principal;
@@ -43,7 +38,6 @@ export type DataSourceCreate = {
// Related fields
databaseId: DatabaseId;
instanceId: InstanceId;
- memberList: DataSourceMemberCreate[];
// Domain specific fields
name: string;
@@ -57,6 +51,7 @@ export type DataSourcePatch = {
name?: string;
username?: string;
password?: string;
+ useEmptyPassword?: boolean;
};
export type DataSourceMember = {
diff --git a/frontend/src/types/instance.ts b/frontend/src/types/instance.ts
index d3bae36a25..bfe25e66ab 100644
--- a/frontend/src/types/instance.ts
+++ b/frontend/src/types/instance.ts
@@ -1,4 +1,4 @@
-import { Anomaly } from ".";
+import { Anomaly, DataSource } from ".";
import { RowStatus } from "./common";
import { Environment } from "./environment";
import { EnvironmentId, InstanceId, MigrationHistoryId } from "./id";
@@ -47,6 +47,8 @@ export type Instance = {
// Related fields
environment: Environment;
anomalyList: Anomaly[];
+ // An instance must have a admin data source, maybe a read-only data source.
+ dataSourceList: DataSource[];
// Standard fields
creator: Principal;
@@ -62,9 +64,6 @@ export type Instance = {
externalLink?: string;
host: string;
port?: string;
- // In mysql, username can be empty which means anonymous user
- username?: string;
- password?: string;
};
export type InstanceCreate = {
@@ -91,9 +90,6 @@ export type InstancePatch = {
externalLink?: string;
host?: string;
port?: string;
- username?: string;
- password?: string;
- useEmptyPassword: boolean;
};
export type MigrationSchemaStatus = "UNKNOWN" | "OK" | "NOT_EXIST";
diff --git a/frontend/src/utils/database.ts b/frontend/src/utils/database.ts
index 52896e30dc..848154c65b 100644
--- a/frontend/src/utils/database.ts
+++ b/frontend/src/utils/database.ts
@@ -1,10 +1,4 @@
-import {
- Database,
- DataSourceMember,
- DataSourceType,
- Environment,
- Principal,
-} from "../types";
+import { Database, DataSourceType, Environment, Principal } from "../types";
import { isDBAOrOwner } from "./role";
import { isDev } from "./util";
@@ -31,17 +25,6 @@ export function allowDatabaseAccess(
return true;
}
- for (const dataSource of database.dataSourceList) {
- if (
- // Returns true if the current user has equal or higher access
- (dataSource.type == type || (dataSource.type == "RW" && type == "RO")) &&
- dataSource.memberList.find((item: DataSourceMember) => {
- return item.principal.id == principal.id;
- })
- ) {
- return true;
- }
- }
return false;
}
diff --git a/frontend/src/views/DataSourceDetail.vue b/frontend/src/views/DataSourceDetail.vue
index fd04c4459f..cc8d15c74b 100644
--- a/frontend/src/views/DataSourceDetail.vue
+++ b/frontend/src/views/DataSourceDetail.vue
@@ -241,7 +241,7 @@ export default {
};
store
.dispatch("dataSource/patchDataSource", {
- databaseId: dataSource.value.database.id,
+ databaseId: dataSource.value.databaseId,
dataSourceid: dataSource.value.id,
dataSource: dataSourcePatch,
})
@@ -255,7 +255,7 @@ export default {
const name = dataSource.value.name;
store
.dispatch("dataSource/deleteDataSourceById", {
- databaseId: dataSource.value.database.id,
+ databaseId: dataSource.value.databaseId,
dataSourceId,
})
.then(() => {
diff --git a/frontend/src/views/InstanceDetail.vue b/frontend/src/views/InstanceDetail.vue
index d2665419dd..f6e4e0ff11 100644
--- a/frontend/src/views/InstanceDetail.vue
+++ b/frontend/src/views/InstanceDetail.vue
@@ -10,7 +10,7 @@
@click-action="state.showCreateMigrationSchemaModal = true"
/>
<div class="px-6 space-y-6">
- <InstanceForm :create="false" :instance="instance" />
+ <InstanceForm :instance="instance" />
<div
v-if="hasDataSourceFeature"
class="py-6 space-y-4 border-t divide-control-border"
@@ -124,10 +124,9 @@
:title="$t('quick-action.create-db')"
@close="state.showCreateDatabaseModal = false"
>
- <!-- eslint-disable vue/attribute-hyphenation -->
<CreateDatabasePrepForm
- :environmentId="instance.environment.id"
- :instanceId="instance.id"
+ :environment-id="instance.environment.id"
+ :instance-id="instance.id"
@dismiss="state.showCreateDatabaseModal = false"
/>
</BBModal>
@@ -138,8 +137,8 @@
/>
</template>
-<script lang="ts">
-import { computed, reactive, watchEffect } from "vue";
+<script lang="ts" setup>
+import { computed, defineProps, reactive, watchEffect } from "vue";
import { useStore } from "vuex";
import { idFromSlug, isDBAOrOwner } from "../utils";
import ArchiveBanner from "../components/ArchiveBanner.vue";
@@ -172,293 +171,255 @@ interface LocalState {
showFeatureModal: boolean;
}
-export default {
- name: "InstanceDetail",
- components: {
- ArchiveBanner,
- DatabaseTable,
- DataSourceTable,
- InstanceUserTable,
- InstanceForm,
- CreateDatabasePrepForm,
+const props = defineProps({
+ instanceSlug: {
+ required: true,
+ type: String,
},
- props: {
- instanceSlug: {
- required: true,
- type: String,
- },
- },
- setup(props) {
- const store = useStore();
- const { t } = useI18n();
+});
- const currentUser = computed(() => store.getters["auth/currentUser"]());
+const store = useStore();
+const { t } = useI18n();
- const state = reactive<LocalState>({
- selectedIndex: DATABASE_TAB,
- migrationSetupStatus: "OK",
- showCreateMigrationSchemaModal: false,
- creatingMigrationSchema: false,
- showCreateDatabaseModal: false,
- syncingSchema: false,
- showFeatureModal: false,
- });
+const currentUser = computed(() => store.getters["auth/currentUser"]());
+
+const state = reactive<LocalState>({
+ selectedIndex: DATABASE_TAB,
+ migrationSetupStatus: "OK",
+ showCreateMigrationSchemaModal: false,
+ creatingMigrationSchema: false,
+ showCreateDatabaseModal: false,
+ syncingSchema: false,
+ showFeatureModal: false,
+});
+
+const instance = computed((): Instance => {
+ return store.getters["instance/instanceById"](idFromSlug(props.instanceSlug));
+});
- const instance = computed((): Instance => {
- return store.getters["instance/instanceById"](
- idFromSlug(props.instanceSlug)
- );
+const checkMigrationSetup = () => {
+ store
+ .dispatch("instance/checkMigrationSetup", instance.value.id)
+ .then((migration: InstanceMigration) => {
+ state.migrationSetupStatus = migration.status;
});
+};
- const checkMigrationSetup = () => {
- store
- .dispatch("instance/checkMigrationSetup", instance.value.id)
- .then((migration: InstanceMigration) => {
- state.migrationSetupStatus = migration.status;
- });
- };
+const prepareMigrationSchemaStatus = () => {
+ checkMigrationSetup();
+};
+watchEffect(prepareMigrationSchemaStatus);
- const prepareMigrationSchemaStatus = () => {
- checkMigrationSetup();
- };
- watchEffect(prepareMigrationSchemaStatus);
+const attentionTitle = computed((): string => {
+ if (state.migrationSetupStatus == "NOT_EXIST") {
+ return t("instance.missing-migration-schema");
+ } else if (state.migrationSetupStatus == "UNKNOWN") {
+ return t("instance.unable-to-connect-instance-to-check-migration-schema");
+ }
+ return "";
+});
- const attentionTitle = computed((): string => {
- if (state.migrationSetupStatus == "NOT_EXIST") {
- return t("instance.missing-migration-schema");
- } else if (state.migrationSetupStatus == "UNKNOWN") {
- return t(
- "instance.unable-to-connect-instance-to-check-migration-schema"
- );
- }
- return "";
- });
+const attentionText = computed((): string => {
+ if (state.migrationSetupStatus == "NOT_EXIST") {
+ return (
+ t(
+ "instance.bytebase-relies-on-migration-schema-to-manage-version-control-based-schema-migration-for-databases-belonged-to-this-instance"
+ ) +
+ (isDBAOrOwner(currentUser.value.role)
+ ? ""
+ : " " + t("instance.please-contact-your-dba-to-configure-it"))
+ );
+ } else if (state.migrationSetupStatus == "UNKNOWN") {
+ return (
+ t(
+ "instance.bytebase-relies-on-migration-schema-to-manage-version-control-based-schema-migration-for-databases-belonged-to-this-instance"
+ ) +
+ (isDBAOrOwner(currentUser.value.role)
+ ? " " +
+ t("instance.please-check-the-instance-connection-info-is-correct")
+ : " " + t("instance.please-contact-your-dba-to-configure-it"))
+ );
+ }
+ return "";
+});
- const attentionText = computed((): string => {
- if (state.migrationSetupStatus == "NOT_EXIST") {
- return (
- t(
- "instance.bytebase-relies-on-migration-schema-to-manage-version-control-based-schema-migration-for-databases-belonged-to-this-instance"
- ) +
- (isDBAOrOwner(currentUser.value.role)
- ? ""
- : " " + t("instance.please-contact-your-dba-to-configure-it"))
- );
- } else if (state.migrationSetupStatus == "UNKNOWN") {
- return (
- t(
- "instance.bytebase-relies-on-migration-schema-to-manage-version-control-based-schema-migration-for-databases-belonged-to-this-instance"
- ) +
- (isDBAOrOwner(currentUser.value.role)
- ? " " +
- t("instance.please-check-the-instance-connection-info-is-correct")
- : " " + t("instance.please-contact-your-dba-to-configure-it"))
- );
- }
+const attentionActionText = computed((): string => {
+ if (isDBAOrOwner(currentUser.value.role)) {
+ if (state.migrationSetupStatus == "NOT_EXIST") {
+ return t("instance.create-migration-schema");
+ } else if (state.migrationSetupStatus == "UNKNOWN") {
return "";
- });
+ }
+ }
+ return "";
+});
- const attentionActionText = computed((): string => {
- if (isDBAOrOwner(currentUser.value.role)) {
- if (state.migrationSetupStatus == "NOT_EXIST") {
- return t("instance.create-migration-schema");
- } else if (state.migrationSetupStatus == "UNKNOWN") {
- return "";
- }
- }
- return "";
- });
+const hasDataSourceFeature = computed(() =>
+ store.getters["subscription/feature"]("bb.feature.data-source")
+);
- const hasDataSourceFeature = computed(() =>
- store.getters["subscription/feature"]("bb.feature.data-source")
- );
+const databaseList = computed(() => {
+ const list = store.getters["database/databaseListByInstanceId"](
+ instance.value.id
+ );
+ if (isDBAOrOwner(currentUser.value.role)) {
+ return list;
+ }
- const databaseList = computed(() => {
- const list = store.getters["database/databaseListByInstanceId"](
- instance.value.id
- );
- if (isDBAOrOwner(currentUser.value.role)) {
- return list;
+ // In edge case when the user is no longer an Owner or DBA, we only want to display the database
+ // belonging to the project which the user is a member of. The returned list above may contain
+ // databases not meeting this criteria and we need to filter out them.
+ const filteredList: Database[] = [];
+ for (const database of list) {
+ for (const member of database.project.memberList) {
+ if (member.principal.id == currentUser.value.id) {
+ filteredList.push(database);
+ break;
}
+ }
+ }
+ return filteredList;
+});
- // In edge case when the user is no longer an Owner or DBA, we only want to display the database
- // belonging to the project which the user is a member of. The returned list above may contain
- // databases not meeting this criteria and we need to filter out them.
- const filteredList: Database[] = [];
- for (const database of list) {
- for (const member of database.project.memberList) {
- if (member.principal.id == currentUser.value.id) {
- filteredList.push(database);
- break;
- }
- }
- }
- return filteredList;
- });
+const instanceUserList = computed(() => {
+ return store.getters["instance/instanceUserListById"](instance.value.id);
+});
- const instanceUserList = computed(() => {
- return store.getters["instance/instanceUserListById"](instance.value.id);
- });
+const allowEdit = computed(() => {
+ return (
+ instance.value.rowStatus == "NORMAL" && isDBAOrOwner(currentUser.value.role)
+ );
+});
- const allowEdit = computed(() => {
- return (
- instance.value.rowStatus == "NORMAL" &&
- isDBAOrOwner(currentUser.value.role)
- );
- });
+const allowArchiveOrRestore = computed(() => {
+ return isDBAOrOwner(currentUser.value.role);
+});
+
+const tabItemList = computed((): BBTabFilterItem[] => {
+ return [
+ {
+ title: t("common.databases"),
+ alert: false,
+ },
+ {
+ title: t("instance.users"),
+ alert: false,
+ },
+ ];
+});
- const allowArchiveOrRestore = computed(() => {
- return isDBAOrOwner(currentUser.value.role);
+const doArchive = () => {
+ store
+ .dispatch("instance/patchInstance", {
+ instanceId: instance.value.id,
+ instancePatch: {
+ rowStatus: "ARCHIVED",
+ },
+ })
+ .then((updatedInstance) => {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t(
+ "instance.successfully-archived-instance-updatedinstance-name",
+ [updatedInstance.name]
+ ),
+ });
});
+};
- const tabItemList = computed((): BBTabFilterItem[] => {
- return [
- {
- title: t("common.databases"),
- alert: false,
- },
- {
- title: t("instance.users"),
- alert: false,
- },
- ];
+const doRestore = () => {
+ const subscription: Subscription | undefined =
+ store.getters["subscription/subscription"]();
+ const instanceList = store.getters["instance/instanceList"](["NORMAL"]);
+ if ((subscription?.instanceCount ?? 0) <= instanceList.length) {
+ state.showFeatureModal = true;
+ return;
+ }
+ store
+ .dispatch("instance/patchInstance", {
+ instanceId: instance.value.id,
+ instancePatch: {
+ rowStatus: "NORMAL",
+ },
+ })
+ .then((updatedInstance) => {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t(
+ "instance.successfully-restored-instance-updatedinstance-name",
+ [updatedInstance.name]
+ ),
+ });
});
+};
- const doArchive = () => {
- store
- .dispatch("instance/patchInstance", {
- instanceId: instance.value.id,
- instancePatch: {
- rowStatus: "ARCHIVED",
- },
- })
- .then((updatedInstance) => {
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "SUCCESS",
- title: t(
- "instance.successfully-archived-instance-updatedinstance-name",
- [updatedInstance.name]
- ),
- });
+const doCreateMigrationSchema = () => {
+ state.creatingMigrationSchema = true;
+ store
+ .dispatch("instance/createMigrationSetup", instance.value.id)
+ .then((resultSet: SqlResultSet) => {
+ state.creatingMigrationSchema = false;
+ if (resultSet.error) {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t(
+ "instance.failed-to-create-migration-schema-for-instance-instance-value-name",
+ [instance.value.name]
+ ),
+ description: resultSet.error,
});
- };
-
- const doRestore = () => {
- const subscription: Subscription | undefined =
- store.getters["subscription/subscription"]();
- const instanceList = store.getters["instance/instanceList"](["NORMAL"]);
- if ((subscription?.instanceCount ?? 0) <= instanceList.length) {
- state.showFeatureModal = true;
- return;
- }
- store
- .dispatch("instance/patchInstance", {
- instanceId: instance.value.id,
- instancePatch: {
- rowStatus: "NORMAL",
- },
- })
- .then((updatedInstance) => {
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "SUCCESS",
- title: t(
- "instance.successfully-restored-instance-updatedinstance-name",
- [updatedInstance.name]
- ),
- });
+ } else {
+ checkMigrationSetup();
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t(
+ "instance.successfully-created-migration-schema-for-instance-value-name",
+ [instance.value.name]
+ ),
});
- };
+ }
+ state.showCreateMigrationSchemaModal = false;
+ });
+};
- const doCreateMigrationSchema = () => {
- state.creatingMigrationSchema = true;
- store
- .dispatch("instance/createMigrationSetup", instance.value.id)
- .then((resultSet: SqlResultSet) => {
- state.creatingMigrationSchema = false;
- if (resultSet.error) {
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "CRITICAL",
- title: t(
- "instance.failed-to-create-migration-schema-for-instance-instance-value-name",
- [instance.value.name]
- ),
- description: resultSet.error,
- });
- } else {
- checkMigrationSetup();
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "SUCCESS",
- title: t(
- "instance.successfully-created-migration-schema-for-instance-value-name",
- [instance.value.name]
- ),
- });
- }
- state.showCreateMigrationSchemaModal = false;
+const syncSchema = () => {
+ state.syncingSchema = true;
+ store
+ .dispatch("sql/syncSchema", instance.value.id)
+ .then((resultSet: SqlResultSet) => {
+ state.syncingSchema = false;
+ if (resultSet.error) {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t(
+ "instance.failed-to-sync-schema-for-instance-instance-value-name",
+ [instance.value.name]
+ ),
+ description: resultSet.error,
});
- };
-
- const syncSchema = () => {
- state.syncingSchema = true;
- store
- .dispatch("sql/syncSchema", instance.value.id)
- .then((resultSet: SqlResultSet) => {
- state.syncingSchema = false;
- if (resultSet.error) {
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "CRITICAL",
- title: t(
- "instance.failed-to-sync-schema-for-instance-instance-value-name",
- [instance.value.name]
- ),
- description: resultSet.error,
- });
- } else {
- store.dispatch("notification/pushNotification", {
- module: "bytebase",
- style: "SUCCESS",
- title: t(
- "instance.successfully-synced-schema-for-instance-instance-value-name",
- [instance.value.name]
- ),
- description: resultSet.error,
- });
- }
- })
- .catch(() => {
- state.syncingSchema = false;
+ } else {
+ store.dispatch("notification/pushNotification", {
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t(
+ "instance.successfully-synced-schema-for-instance-instance-value-name",
+ [instance.value.name]
+ ),
+ description: resultSet.error,
});
- };
-
- const createDatabase = () => {
- state.showCreateDatabaseModal = true;
- };
+ }
+ })
+ .catch(() => {
+ state.syncingSchema = false;
+ });
+};
- return {
- DATABASE_TAB,
- USER_TAB,
- state,
- attentionTitle,
- attentionText,
- attentionActionText,
- hasDataSourceFeature,
- instance,
- databaseList,
- instanceUserList,
- allowEdit,
- allowArchiveOrRestore,
- tabItemList,
- doArchive,
- doRestore,
- doCreateMigrationSchema,
- syncSchema,
- createDatabase,
- };
- },
+const createDatabase = () => {
+ state.showCreateDatabaseModal = true;
};
</script>
diff --git a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
index b7d852b664..2031708012 100644
--- a/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
+++ b/frontend/src/views/SqlEditor/EditorPanel/EditorAction.vue
@@ -20,6 +20,29 @@
<template #trigger>
<label class="flex items-center text-sm space-x-1">
<div class="flex items-center">
+ <NPopover
+ v-if="
+ connectionContext.instanceId !== UNKNOWN_ID &&
+ !hasReadonlyDataSource
+ "
+ trigger="hover"
+ >
+ <template #trigger>
+ <heroicons-outline:exclamation
+ class="h-6 w-6 text-yellow-400 flex-shrink-0 mr-2"
+ />
+ </template>
+ <p class="py-1">
+ {{ $t("instance.no-read-only-data-source-warn") }}
+ <NButton
+ class="text-base underline text-accent"
+ text
+ @click="gotoInstanceDetailPage"
+ >
+ {{ $t("sql-editor.create-read-only-data-source") }}
+ </NButton>
+ </p>
+ </NPopover>
<InstanceEngineIcon
v-if="connectionContext.instanceId !== UNKNOWN_ID"
:instance="selectedInstance"
@@ -107,11 +130,15 @@ import {
TabActions,
SheetActions,
UNKNOWN_ID,
+ Instance,
} from "../../../types";
import { useExecuteSQL } from "../../../composables/useExecuteSQL";
import SharePopover from "./SharePopover.vue";
+import { useRouter } from "vue-router";
+import { instanceSlug } from "../../../utils/slug";
const store = useStore();
+const router = useRouter();
const { connectionContext } = useNamespacedState<SqlEditorState>("sqlEditor", [
"connectionContext",
@@ -134,7 +161,7 @@ const isShowSharePopover = ref(false);
const isEmptyStatement = computed(
() => !currentTab.value || currentTab.value.statement === ""
);
-const selectedInstance = computed(() => {
+const selectedInstance = computed<Instance>(() => {
const ctx = connectionContext.value;
return store.getters["instance/instanceById"](ctx.instanceId);
});
@@ -144,6 +171,15 @@ const selectedInstanceEngine = computed(() => {
) as string;
});
+const hasReadonlyDataSource = computed(() => {
+ for (const ds of selectedInstance.value.dataSourceList) {
+ if (ds.type === "RO") {
+ return true;
+ }
+ }
+ return false;
+});
+
const { execute, state: executeState } = useExecuteSQL();
const handleRunQuery = () => {
@@ -168,6 +204,15 @@ const handleSave = async () => {
});
};
+const gotoInstanceDetailPage = () => {
+ router.push({
+ name: "workspace.instance.detail",
+ params: {
+ instanceSlug: instanceSlug(selectedInstance.value),
+ },
+ });
+};
+
const handleClickoutside = (e: any) => {
isShowSharePopover.value = false;
};