Skip to content

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

feat(frontend): import spanner instance (#4112)

p0nyf26296df8ddc
diff --git a/frontend/src/assets/db-spanner.png b/frontend/src/assets/db-spanner.png
new file mode 100644
index 0000000000..04e3cb401d
Binary files /dev/null and b/frontend/src/assets/db-spanner.png differ
diff --git a/frontend/src/components/CreateInstanceForm.vue b/frontend/src/components/CreateInstanceForm.vue
index c3acc1f202..6a90badcd4 100644
--- a/frontend/src/components/CreateInstanceForm.vue
+++ b/frontend/src/components/CreateInstanceForm.vue
@@ -72,6 +72,15 @@
{{ $t("instance.account-name") }}
<span style="color: red">*</span>
</template>
+ <template v-else-if="state.instance.engine == 'SPANNER'">
+ {{ $t("instance.project-id-and-instance-id") }}
+ <span style="color: red">*</span>
+ <p class="text-sm text-gray-500 mt-1 mb-2">
+ Don't know where to find project ID and instance ID? Check this
+ link!
+ <!-- TODO(p0ny): fix the link -->
+ </p>
+ </template>
<template v-else>
{{ $t("instance.host-or-socket") }}
<span style="color: red">*</span>
@@ -85,6 +94,8 @@
:placeholder="
state.instance.engine == 'SNOWFLAKE'
? $t('instance.your-snowflake-account-name')
+ : state.instance.engine === 'SPANNER'
+ ? 'projects/<projectID>/instances/<instanceID>'
: $t('instance.sentence.host.snowflake')
"
class="textfield mt-1 w-full"
@@ -100,22 +111,24 @@
</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"
- @wheel="handleInstancePortWheelScroll"
- @input="handleInstancePortInput"
- />
- </div>
+ <template v-if="state.instance.engine !== 'SPANNER'">
+ <div class="sm:col-span-1">
+ <label for="port" class="textlabel block">{{
+ $t("instance.port")
+ }}</label>
+ <input
+ id="port"
+ type="number"
+ name="port"
+ class="textfield mt-1 w-full"
+ :placeholder="defaultPort"
+ :disabled="!allowEdit"
+ :value="state.instance.port"
+ @wheel="handleInstancePortWheelScroll"
+ @input="handleInstancePortInput"
+ />
+ </div>
+ </template>
<template v-if="state.instance.engine == 'MONGODB'">
<div class="sm:row-span-1">
@@ -142,30 +155,40 @@
: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.
+
+ <template v-if="state.instance.engine !== 'SPANNER'">
+ <div class="sm:col-span-1 sm:col-start-1">
+ <label for="username" class="textlabel block">{{
+ $t("common.username")
+ }}</label>
+ <!-- For mysql, username can be empty indicating anonymous user.
But it's a very bad practice to use anonymous user for admin operation,
thus we make it REQUIRED here.-->
- <input
- id="username"
- name="username"
- type="text"
- class="textfield mt-1 w-full"
- :placeholder="
- state.instance.engine == 'CLICKHOUSE' ? $t('common.default') : ''
- "
- :value="state.instance.username"
- @input="handleInstanceUsernameInput"
- />
- </div>
+ <input
+ id="username"
+ name="username"
+ type="text"
+ class="textfield mt-1 w-full"
+ :placeholder="
+ state.instance.engine === 'CLICKHOUSE'
+ ? $t('common.default')
+ : ''
+ "
+ :value="state.instance.username"
+ @input="handleInstanceUsernameInput"
+ />
+ </div>
+ </template>
<div 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") }}
+ <template v-if="state.instance.engine == 'SPANNER'">
+ {{ $t("common.credentials") }}
+ </template>
+ <template v-else>
+ {{ $t("common.password") }}
+ </template>
</label>
</div>
<input
@@ -174,7 +197,11 @@
type="text"
class="textfield mt-1 w-full"
autocomplete="off"
- :placeholder="$t('instance.password-write-only')"
+ :placeholder="
+ state.instance.engine === 'SPANNER'
+ ? $t('instance.credentials-write-only')
+ : $t('instance.password-write-only')
+ "
:value="state.instance.password"
@input="handleInstancePasswordInput"
/>
@@ -347,6 +374,9 @@ const engineList = computed(() => {
"CLICKHOUSE",
"MONGODB",
];
+ if (isDev()) {
+ engines.push("SPANNER");
+ }
return engines;
});
@@ -357,6 +387,7 @@ const EngineIconPath = {
SNOWFLAKE: new URL("../assets/db-snowflake.png", import.meta.url).href,
CLICKHOUSE: new URL("../assets/db-clickhouse.png", import.meta.url).href,
MONGODB: new URL("../assets/db-mongodb.png", import.meta.url).href,
+ SPANNER: new URL("../assets/db-spanner.png", import.meta.url).href,
};
const state = reactive<LocalState>({
@@ -413,7 +444,9 @@ const showSSL = computed((): boolean => {
});
const showDatabase = computed((): boolean => {
- return state.instance.engine === "POSTGRES";
+ return (
+ state.instance.engine === "POSTGRES" || state.instance.engine === "SPANNER"
+ );
});
const showAuthenticationDatabase = computed((): boolean => {
@@ -458,7 +491,7 @@ watch(showSSL, (ssl) => {
// 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 (engine === "SNOWFLAKE" || engine === "SPANNER") {
if (
state.instance.host == "127.0.0.1" ||
state.instance.host == "host.docker.internal"
@@ -593,6 +626,11 @@ const tryCreate = () => {
if (instance.engine === "MONGODB") {
connectionInfo.database = instance.database;
}
+ // Spanner must connect to a specific database.
+ // To test connection, we must set database.
+ if (instance.engine === "SPANNER") {
+ connectionInfo.database = instance.database;
+ }
state.isPingingInstance = true;
sqlStore
@@ -659,7 +697,7 @@ const testConnection = () => {
username: instance.username,
password: instance.password,
// Use the `database` field only when needed.
- database: instance.engine === "POSTGRES" ? instance.database : undefined,
+ database: showDatabase.value ? instance.database : undefined,
useEmptyPassword: false,
instanceId: undefined,
srv: instance.srv,
diff --git a/frontend/src/components/InstanceEngineIcon.vue b/frontend/src/components/InstanceEngineIcon.vue
index 3083da068d..fa46b9e477 100644
--- a/frontend/src/components/InstanceEngineIcon.vue
+++ b/frontend/src/components/InstanceEngineIcon.vue
@@ -38,6 +38,7 @@ export default defineComponent({
SNOWFLAKE: new URL("../assets/db-snowflake.png", import.meta.url).href,
CLICKHOUSE: new URL("../assets/db-clickhouse.png", import.meta.url).href,
MONGODB: new URL("../assets/db-mongodb.png", import.meta.url).href,
+ SPANNER: new URL("../assets/db-spanner.png", import.meta.url).href,
};
const SelectedEngineIconPath = computed(() => {
return EngineIconPath[props.instance.engine];
diff --git a/frontend/src/components/InstanceForm.vue b/frontend/src/components/InstanceForm.vue
index 2908010538..6266100241 100644
--- a/frontend/src/components/InstanceForm.vue
+++ b/frontend/src/components/InstanceForm.vue
@@ -51,6 +51,15 @@
{{ $t("instance.account-name") }}
<span class="text-red-600 mr-2">*</span>
</template>
+ <template v-else-if="state.instance.engine === 'SPANNER'">
+ {{ $t("instance.project-id-and-instance-id") }}
+ <span style="color: red">*</span>
+ <p class="text-sm text-gray-500 mt-1 mb-2">
+ Don't know where to find project ID and instance ID? Check this
+ link!
+ <!-- TODO(p0ny): fix the link -->
+ </p>
+ </template>
<template v-else>
{{ $t("instance.host-or-socket") }}
<span class="text-red-600 mr-2">*</span>
@@ -64,6 +73,8 @@
:placeholder="
state.instance.engine == 'SNOWFLAKE'
? $t('instance.your-snowflake-account-name')
+ : state.instance.engine === 'SPANNER'
+ ? 'projects/<projectID>/instances/<instanceID>'
: $t('instance.sentence.host.snowflake')
"
class="textfield mt-1 w-full"
@@ -78,24 +89,24 @@
{{ $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="adminDataSource.port"
- @wheel="handleInstancePortWheelScroll"
- @input="handleInstancePortInput"
- />
- </div>
-
+ <template v-if="state.instance.engine !== 'SPANNER'">
+ <div class="sm:col-span-1">
+ <label for="port" class="textlabel block">{{
+ $t("instance.port")
+ }}</label>
+ <input
+ id="port"
+ type="number"
+ name="port"
+ class="textfield mt-1 w-full"
+ :placeholder="defaultPort"
+ :disabled="!allowEdit"
+ :value="adminDataSource.port"
+ @wheel="handleInstancePortWheelScroll"
+ @input="handleInstancePortInput"
+ />
+ </div>
+ </template>
<!--Do not show external link on create to reduce cognitive load-->
<div class="sm:col-span-3 sm:col-start-1">
<label for="externallink" class="textlabel inline-flex">
@@ -192,38 +203,47 @@
/>
</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") }}
- <span class="text-red-600">*</span>
- </label>
- <!-- For mysql, username can be empty indicating anonymous user.
+
+ <template v-if="state.instance.engine !== 'SPANNER'">
+ <div class="mt-2 sm:col-span-1 sm:col-start-1">
+ <label for="username" class="textlabel block">
+ {{ $t("common.username") }}
+ <span class="text-red-600">*</span>
+ </label>
+ <!-- For mysql, username can be empty indicating anonymous user.
But it's a very bad practice to use anonymous user for admin operation,
thus we make it REQUIRED here.-->
- <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>
+ <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>
+ </template>
<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") }}
+ <template v-if="state.instance.engine === 'SPANNER'">
+ {{ $t("common.credentials") }}
+ </template>
+ <template v-else>
+ {{ $t("common.password") }}
+ </template>
<span class="text-red-600">*</span>
</label>
<BBCheckbox
@@ -241,6 +261,8 @@
:placeholder="
currentDataSource.useEmptyPassword
? $t('instance.no-password')
+ : state.instance.engine === 'SPANNER'
+ ? $t('instance.credentials-write-only')
: $t('instance.password-write-only')
"
:disabled="!allowEdit || currentDataSource.useEmptyPassword"
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 1465e85625..d8c88e5535 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -27,6 +27,7 @@
"sign-up": "Sign up",
"email": "Email",
"username": "Username",
+ "credentials": "Credentials",
"password": "Password",
"activate": "Activate",
"save": "Save",
@@ -678,6 +679,7 @@
"account": "Account",
"name": "Name",
"host-or-socket": "Host or Socket",
+ "project-id-and-instance-id": "Project ID and instance ID",
"your-snowflake-account-name": "your Snowflake account name",
"port": "Port",
"authentication-database": "Authentication Database",
@@ -725,6 +727,7 @@
}
},
"no-password": "No password",
+ "credentials-write-only": "CREDENTIALS - write only",
"password-write-only": "YOUR_DB_PWD - write only",
"test-connection": "Test Connection",
"ignore-and-create": "Ignore and create",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 1ced64c999..f240b4c31d 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -27,6 +27,7 @@
"sign-up": "注册",
"email": "邮箱",
"username": "用户名",
+ "credentials": "凭据",
"password": "密码",
"activate": "激活",
"save": "保存",
@@ -678,6 +679,7 @@
"account": "账户",
"name": "名称",
"host-or-socket": "Host 或 Socket",
+ "project-id-and-instance-id": "项目 ID 与实例 ID",
"your-snowflake-account-name": "您的 Snowflake @:{'instance.account'}@:{'instance.name'}",
"port": "端口",
"instance-name": "@:common.instance@:instance.name",
@@ -724,6 +726,7 @@
}
},
"no-password": "无密码",
+ "credentials-write-only": "CREDENTIALS - 仅写入",
"password-write-only": "YOUR_DB_PWD - 仅写入",
"test-connection": "测试连接",
"ignore-and-create": "忽略并创建",
diff --git a/frontend/src/types/instance.ts b/frontend/src/types/instance.ts
index 2b1c229049..67a6247b5d 100644
--- a/frontend/src/types/instance.ts
+++ b/frontend/src/types/instance.ts
@@ -11,7 +11,8 @@ export type EngineType =
| "POSTGRES"
| "SNOWFLAKE"
| "TIDB"
- | "MONGODB";
+ | "MONGODB"
+ | "SPANNER";
export function defaultCharset(type: EngineType): string {
switch (type) {
@@ -25,6 +26,8 @@ export function defaultCharset(type: EngineType): string {
return "UTF8";
case "MONGODB":
return "";
+ case "SPANNER":
+ return "";
}
}
@@ -42,6 +45,8 @@ export function engineName(type: EngineType): string {
return "TiDB";
case "MONGODB":
return "MongoDB";
+ case "SPANNER":
+ return "Spanner";
}
}
@@ -60,6 +65,8 @@ export function defaultCollation(type: EngineType): string {
return "";
case "MONGODB":
return "";
+ case "SPANNER":
+ return "";
}
}
diff --git a/plugin/db/driver.go b/plugin/db/driver.go
index ba738f0556..9e9e6b2237 100644
--- a/plugin/db/driver.go
+++ b/plugin/db/driver.go
@@ -137,7 +137,7 @@ type Table struct {
CreateOptions string
// Comment isn't supported for SQLite, MongoDB.
Comment string
- // Columnlist isn't supported for MongoDB.
+ // ColumnList isn't supported for MongoDB.
ColumnList []Column
// IndexList isn't supported for ClickHouse, Snowflake.
IndexList []Index
diff --git a/plugin/db/spanner/migrate.go b/plugin/db/spanner/migrate.go
index 77b9116bf2..fb2f9a6262 100644
--- a/plugin/db/spanner/migrate.go
+++ b/plugin/db/spanner/migrate.go
@@ -15,7 +15,8 @@ import (
// NeedsSetupMigration checks if it needs to set up migration.
func (d *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {
- _, err := d.dbClient.GetDatabase(ctx, &databasepb.GetDatabaseRequest{Name: db.BytebaseDatabase})
+ dsn := getDSN(d.config.Host, db.BytebaseDatabase)
+ _, err := d.dbClient.GetDatabase(ctx, &databasepb.GetDatabaseRequest{Name: dsn})
if status.Code(err) == codes.NotFound {
return true, nil
}
diff --git a/plugin/db/spanner/spanner.go b/plugin/db/spanner/spanner.go
index 2117978156..1e371f4a73 100644
--- a/plugin/db/spanner/spanner.go
+++ b/plugin/db/spanner/spanner.go
@@ -5,25 +5,37 @@ import (
"context"
"database/sql"
_ "embed"
- "errors"
"fmt"
+ "regexp"
"strings"
spanner "cloud.google.com/go/spanner"
spannerdb "cloud.google.com/go/spanner/admin/database/apiv1"
+ "go.uber.org/zap"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/common/log"
"github.com/bytebase/bytebase/plugin/db"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
)
var (
//go:embed spanner_migration_schema.sql
migrationSchema string
+ excludedDatabaseList = map[string]bool{
+ "bytebase": true,
+ }
+
createBytebaseDatabaseStatement = `CREATE DATABASE bytebase`
+ dsnRegExp = regexp.MustCompile("projects/(?P<PROJECTGROUP>([a-z]|[-.:]|[0-9])+)/instances/(?P<INSTANCEGROUP>([a-z]|[-]|[0-9])+)/databases/(?P<DATABASEGROUP>([a-z]|[-]|[_]|[0-9])+)")
+
_ db.Driver = (*Driver)(nil)
)
@@ -43,28 +55,49 @@ func newDriver(_ db.DriverConfig) db.Driver {
return &Driver{}
}
-// Open opens a Spanner driver.
+// Open opens a Spanner driver. It must connect to a specific database.
+// If database isn't provided, the driver tries to connect to "bytebase" database.
+// If connecting to "bytebase" also fails, part of the driver cannot function.
func (d *Driver) Open(ctx context.Context, _ db.Type, config db.ConnectionConfig, connCtx db.ConnectionContext) (db.Driver, error) {
- dsn := fmt.Sprintf("%s/databases/%s", config.Host, config.Database)
- client, err := spanner.NewClient(ctx, dsn, option.WithCredentialsJSON([]byte(config.Password)))
- if err != nil {
- return nil, err
+ if config.Host == "" {
+ return nil, errors.New("host cannot be empty")
+ }
+ d.config = config
+ d.connCtx = connCtx
+ if config.Database == "" {
+ // try to connect to bytebase
+ dsn := getDSN(d.config.Host, db.BytebaseDatabase)
+ client, err := spanner.NewClient(ctx, dsn, option.WithCredentialsJSON([]byte(config.Password)))
+ if status.Code(err) == codes.NotFound {
+ log.Debug(`spanner driver: no database provided, try connecting to "bytebase" database which is not found`, zap.Error(err))
+ } else if err != nil {
+ return nil, err
+ } else {
+ d.client = client
+ }
+ } else {
+ dsn := getDSN(d.config.Host, d.config.Database)
+ client, err := spanner.NewClient(ctx, dsn, option.WithCredentialsJSON([]byte(config.Password)))
+ if err != nil {
+ return nil, err
+ }
+ d.client = client
}
+
dbClient, err := spannerdb.NewDatabaseAdminClient(ctx, option.WithCredentialsJSON([]byte(config.Password)))
if err != nil {
return nil, err
}
- d.client = client
d.dbClient = dbClient
- d.config = config
- d.connCtx = connCtx
return d, nil
}
// Close closes the driver.
func (d *Driver) Close(_ context.Context) error {
- d.client.Close()
+ if d.client != nil {
+ d.client.Close()
+ }
return d.dbClient.Close()
}
@@ -110,6 +143,25 @@ func (*Driver) Query(_ context.Context, _ string, _ *db.QueryContext) ([]interfa
panic("not implemented")
}
+func getDSN(host, database string) string {
+ return fmt.Sprintf("%s/databases/%s", host, database)
+}
+
+// get `<database>` from `projects/<project>/instances/<instance>/databases/<database>`.
+func getDatabaseFromDSN(dsn string) (string, error) {
+ match := dsnRegExp.FindStringSubmatch(dsn)
+ if match == nil {
+ return "", errors.New("invalid DSN")
+ }
+ matches := make(map[string]string)
+ for i, name := range dsnRegExp.SubexpNames() {
+ if i != 0 && name != "" {
+ matches[name] = match[i]
+ }
+ }
+ return matches["DATABASEGROUP"], nil
+}
+
func splitStatement(statement string) []string {
var res []string
for _, s := range strings.Split(statement, ";") {
diff --git a/plugin/db/spanner/spanner_test.go b/plugin/db/spanner/spanner_test.go
new file mode 100644
index 0000000000..36609b1d63
--- /dev/null
+++ b/plugin/db/spanner/spanner_test.go
@@ -0,0 +1,37 @@
+package spanner
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestGetDatabaseFromDSN(t *testing.T) {
+ tests := []struct {
+ dsn string
+ match bool
+ want string
+ }{
+ {
+ dsn: "projects/p/instances/i/databases/d",
+ match: true,
+ want: "d",
+ },
+ {
+ dsn: "projects/p/instances/i/databases/",
+ match: false,
+ want: "",
+ },
+ }
+ a := require.New(t)
+ for i := range tests {
+ test := tests[i]
+ got, err := getDatabaseFromDSN(test.dsn)
+ if test.match {
+ a.NoError(err)
+ a.Equal(test.want, got)
+ } else {
+ a.Error(err)
+ }
+ }
+}
diff --git a/plugin/db/spanner/sync.go b/plugin/db/spanner/sync.go
index 61c73c6066..6818c11205 100644
--- a/plugin/db/spanner/sync.go
+++ b/plugin/db/spanner/sync.go
@@ -6,6 +6,8 @@ import (
"cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
"google.golang.org/api/iterator"
+ "github.com/pkg/errors"
+
"github.com/bytebase/bytebase/plugin/db"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -24,7 +26,18 @@ func (d *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error) {
if err != nil {
return nil, err
}
- databaseList = append(databaseList, db.DatabaseMeta{Name: database.Name})
+
+ // database.Name is of the form `projects/<project>/instances/<instance>/databases/<database>`
+ // We use regular expression to extract <database> from it.
+ databaseName, err := getDatabaseFromDSN(database.Name)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get database name from %s", database.Name)
+ }
+ if excludedDatabaseList[databaseName] {
+ continue
+ }
+
+ databaseList = append(databaseList, db.DatabaseMeta{Name: databaseName})
}
return &db.InstanceMeta{
@@ -34,5 +47,5 @@ func (d *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error) {
// SyncDBSchema syncs a single database schema.
func (*Driver) SyncDBSchema(_ context.Context, _ string) (*db.Schema, map[string][]*storepb.ForeignKeyMetadata, error) {
- panic("not implemented")
+ return nil, nil, errors.New("not implemented")
}