Skip to content

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

feat(mongodb): support ping mongodb instance (#3775)

h3n4l04236509abd0
diff --git a/api/instance.go b/api/instance.go
index 7d66dd23c3..fd0252210f 100644
--- a/api/instance.go
+++ b/api/instance.go
@@ -34,6 +34,8 @@ type Instance struct {
// Database is the initial connection database for PostgreSQL only.
Database string `jsonapi:"attr,database"`
Username string `jsonapi:"attr,username"`
+ // SRV record is used for MongoDB only.
+ SRV bool `jsonapi:"attr,srv"`
// Password is not returned to the client
Password string
}
@@ -59,6 +61,9 @@ type InstanceCreate struct {
SslCa string `jsonapi:"attr,sslCa"`
SslCert string `jsonapi:"attr,sslCert"`
SslKey string `jsonapi:"attr,sslKey"`
+
+ // SRV record is used for MongoDB only.
+ SRV bool `jsonapi:"attr,srv"`
}
// InstanceFind is the API message for finding instances.
@@ -101,6 +106,8 @@ type InstancePatch struct {
Host *string `jsonapi:"attr,host"`
Port *string `jsonapi:"attr,port"`
Database *string `jsonapi:"attr,database"`
+ // SRV record is used for MongoDB only.
+ SRV bool `jsonapi:"attr,srv"`
}
// DataSourceFromInstanceWithType gets a typed data source from a instance.
diff --git a/api/sql.go b/api/sql.go
index 924aa3a4a8..b7ca3e36f8 100644
--- a/api/sql.go
+++ b/api/sql.go
@@ -15,10 +15,12 @@ type ConnectionInfo struct {
Username string `jsonapi:"attr,username"`
Password string `jsonapi:"attr,password"`
UseEmptyPassword bool `jsonapi:"attr,useEmptyPassword"`
+ Database string `jsonapi:"attr,database"`
InstanceID *int `jsonapi:"attr,instanceId"`
SslCa *string `jsonapi:"attr,sslCa"`
SslCert *string `jsonapi:"attr,sslCert"`
SslKey *string `jsonapi:"attr,sslKey"`
+ SRV bool `jsonapi:"attr,srv"`
}
// SQLSyncSchema is the API message for sync schemas.
diff --git a/frontend/src/assets/db-mongodb.png b/frontend/src/assets/db-mongodb.png
new file mode 100644
index 0000000000..6fc7a99d40
Binary files /dev/null and b/frontend/src/assets/db-mongodb.png differ
diff --git a/frontend/src/components/CreateInstanceForm.vue b/frontend/src/components/CreateInstanceForm.vue
index 45fc9ae857..5369dcefea 100644
--- a/frontend/src/components/CreateInstanceForm.vue
+++ b/frontend/src/components/CreateInstanceForm.vue
@@ -113,6 +113,17 @@
@input="handleInstancePortInput"
/>
</div>
+
+ <template v-if="state.instance.engine == 'MONGODB'">
+ <div class="sm:row-span-1">
+ <div class="ml-1">
+ <BBCheckbox
+ title="DNS SRV Record"
+ :value="state.instance.useDNSSRVRecord"
+ @toggle="handleToggleDNSSRVRecord"
+ />
+ </div></div
+ ></template>
</div>
<p class="mt-6 pt-4 w-full text-lg leading-6 font-medium text-gray-900">
@@ -239,7 +250,8 @@
:disabled="
!allowCreate ||
state.isCreatingInstance ||
- state.isPingingInstance
+ state.isPingingInstance ||
+ state.instance.engine == 'MONGODB'
"
@click.prevent="tryCreate"
>
@@ -302,13 +314,19 @@ const router = useRouter();
const { t } = useI18n();
const sqlStore = useSQLStore();
-const engineList: EngineType[] = [
- "MYSQL",
- "POSTGRES",
- "TIDB",
- "SNOWFLAKE",
- "CLICKHOUSE",
-];
+const engineList = computed(() => {
+ const engines: EngineType[] = [
+ "MYSQL",
+ "POSTGRES",
+ "TIDB",
+ "SNOWFLAKE",
+ "CLICKHOUSE",
+ ];
+ if (isDev()) {
+ engines.push("MONGODB");
+ }
+ return engines;
+});
const EngineIconPath = {
MYSQL: new URL("../assets/db-mysql.png", import.meta.url).href,
@@ -316,6 +334,7 @@ const EngineIconPath = {
TIDB: new URL("../assets/db-tidb.png", import.meta.url).href,
SNOWFLAKE: new URL("../assets/db-snowflake.png", import.meta.url).href,
CLICKHOUSE: new URL("../assets/db-clickhouse.png", import.meta.url).href,
+ MONGODB: new URL("../assets/db-mongodb.png", import.meta.url).href,
};
const state = reactive<LocalState>({
@@ -327,6 +346,7 @@ const state = reactive<LocalState>({
// 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: "",
+ useDNSSRVRecord: false,
},
showCreateInstanceWarningModal: false,
createInstanceWarning: "",
@@ -355,6 +375,8 @@ const defaultPort = computed(() => {
return "443";
} else if (state.instance.engine == "TIDB") {
return "4000";
+ } else if (state.instance.engine == "MONGODB") {
+ return "27017";
}
return "3306";
});
@@ -364,7 +386,9 @@ const showSSL = computed((): boolean => {
});
const showDatabase = computed((): boolean => {
- return state.instance.engine === "POSTGRES";
+ return (
+ state.instance.engine === "POSTGRES" || state.instance.engine === "MONGODB"
+ );
});
const isInOnboaringCreateDatabaseGuide = computed(() => {
@@ -414,6 +438,8 @@ const engineName = (type: EngineType): string => {
return "Snowflake";
case "TIDB":
return "TiDB";
+ case "MONGODB":
+ return "MongoDB";
}
};
@@ -463,7 +489,11 @@ const handleInstanceDatabaseInput = (event: Event) => {
updateInstance("database", (event.target as HTMLInputElement).value);
};
-const updateInstance = (field: string, value: string) => {
+const handleToggleDNSSRVRecord = (on: boolean) => {
+ updateInstance("useDNSSRVRecord", on);
+};
+
+const updateInstance = (field: string, value: string | boolean) => {
let str = value;
if (
field === "name" ||
@@ -474,7 +504,7 @@ const updateInstance = (field: string, value: string) => {
field === "password" ||
field === "database"
) {
- str = value.trim();
+ str = (value as string).trim();
}
(state.instance as any)[field] = str;
};
@@ -527,6 +557,7 @@ const tryCreate = () => {
useEmptyPassword: false,
host: instance.host,
port: instance.port,
+ srv: instance.useDNSSRVRecord,
};
if (showSSL.value) {
@@ -595,9 +626,13 @@ const testConnection = () => {
username: instance.username,
password: instance.password,
// Use the `database` field only when needed.
- database: instance.engine === "POSTGRES" ? instance.database : undefined,
+ database:
+ instance.engine === "POSTGRES" || instance.engine === "MONGODB"
+ ? instance.database
+ : undefined,
useEmptyPassword: false,
instanceId: undefined,
+ srv: instance.useDNSSRVRecord,
};
if (showSSL.value) {
diff --git a/frontend/src/components/InstanceEngineIcon.vue b/frontend/src/components/InstanceEngineIcon.vue
index 0da6fc00e1..c00f5abe75 100644
--- a/frontend/src/components/InstanceEngineIcon.vue
+++ b/frontend/src/components/InstanceEngineIcon.vue
@@ -37,6 +37,7 @@ export default defineComponent({
TIDB: new URL("../assets/db-tidb.png", import.meta.url).href,
SNOWFLAKE: new URL("../assets/db-snowflake.png", import.meta.url).href,
CLICKHOUSE: new URL("../assets/db-clickhouse.png", import.meta.url).href,
+ MONGODB: new URL("../assets/db-mongodb.png", import.meta.url).href,
};
const SelectedEngineIconPath = computed(() => {
return EngineIconPath[props.instance.engine];
diff --git a/frontend/src/components/InstanceForm.vue b/frontend/src/components/InstanceForm.vue
index f59c36c286..ee32700ebf 100644
--- a/frontend/src/components/InstanceForm.vue
+++ b/frontend/src/components/InstanceForm.vue
@@ -426,6 +426,7 @@ interface State {
dataSourceList: EditDataSource[];
currentDataSourceType: DataSourceType;
showFeatureModal: boolean;
+ useDNSSRVRecord: boolean;
}
const props = defineProps({
@@ -458,6 +459,7 @@ const state = reactive<State>({
dataSourceList: dataSourceList,
currentDataSourceType: "ADMIN",
showFeatureModal: false,
+ useDNSSRVRecord: false,
});
const allowEdit = computed(() => {
@@ -892,6 +894,7 @@ const testConnection = () => {
port: connectionPort,
database: instance.database,
instanceId: instance.id,
+ srv: state.useDNSSRVRecord,
};
if (typeof dataSource.sslCa !== "undefined") {
diff --git a/frontend/src/types/instance.ts b/frontend/src/types/instance.ts
index 90f297ebea..d26db11a54 100644
--- a/frontend/src/types/instance.ts
+++ b/frontend/src/types/instance.ts
@@ -10,7 +10,8 @@ export type EngineType =
| "MYSQL"
| "POSTGRES"
| "SNOWFLAKE"
- | "TIDB";
+ | "TIDB"
+ | "MONGODB";
export function defaultCharset(type: EngineType): string {
switch (type) {
@@ -22,6 +23,8 @@ export function defaultCharset(type: EngineType): string {
return "utf8mb4";
case "POSTGRES":
return "UTF8";
+ case "MONGODB":
+ return "";
}
}
@@ -38,6 +41,8 @@ export function defaultCollation(type: EngineType): string {
// install it.
case "POSTGRES":
return "";
+ case "MONGODB":
+ return "";
}
}
@@ -83,6 +88,8 @@ export type InstanceCreate = {
sslCa?: string;
sslCert?: string;
sslKey?: string;
+ // DNS SRV record is only used for MongoDB.
+ useDNSSRVRecord: boolean;
};
export type InstancePatch = {
diff --git a/frontend/src/types/sql.ts b/frontend/src/types/sql.ts
index 5b97890172..92a6e77004 100644
--- a/frontend/src/types/sql.ts
+++ b/frontend/src/types/sql.ts
@@ -18,6 +18,7 @@ export type ConnectionInfo = {
sslCa?: string;
sslCert?: string;
sslKey?: string;
+ srv: boolean;
};
export type QueryInfo = {
diff --git a/go.mod b/go.mod
index a347379a57..a07adb0013 100644
--- a/go.mod
+++ b/go.mod
@@ -36,6 +36,7 @@ require (
github.com/swaggo/swag v1.8.7
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8
github.com/xo/dburl v0.12.4
+ go.mongodb.org/mongo-driver v1.11.1
go.uber.org/multierr v1.8.0
go.uber.org/zap v1.23.0
golang.org/x/crypto v0.1.0
@@ -109,6 +110,7 @@ require (
github.com/mattn/go-ieproxy v0.0.9 // indirect
github.com/mattn/go-isatty v0.0.16 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
+ github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
github.com/openark/golib v0.0.0-20210531070646-355f37940af8 // indirect
github.com/opentracing/basictracer-go v1.1.0 // indirect
github.com/opentracing/opentracing-go v1.2.0 // indirect
@@ -143,7 +145,11 @@ require (
github.com/uber/jaeger-lib v2.4.1+incompatible // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
+ github.com/xdg-go/pbkdf2 v1.0.0 // indirect
+ github.com/xdg-go/scram v1.1.1 // indirect
+ github.com/xdg-go/stringprep v1.0.3 // indirect
github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c // indirect
+ github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
github.com/yusufpapurcu/wmi v1.2.2 // indirect
go.opentelemetry.io/otel v1.11.1 // indirect
go.opentelemetry.io/otel/trace v1.11.1 // indirect
diff --git a/go.sum b/go.sum
index df38f77828..5056a434ef 100644
--- a/go.sum
+++ b/go.sum
@@ -301,6 +301,7 @@ github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
+github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
@@ -317,6 +318,7 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
@@ -431,6 +433,7 @@ github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQL
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.13.1/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg=
+github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/klauspost/compress v1.15.12 h1:YClS/PImqYbn+UILDnqxQCZ3RehC9N318SU3kElDUEM=
github.com/klauspost/compress v1.15.12/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM=
github.com/klauspost/cpuid v1.3.1 h1:5JNjFYYQrZeKRJ0734q51WCEEn2huer72Dc7K+R/b6s=
@@ -495,6 +498,8 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0=
+github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/ncw/directio v1.0.5 h1:JSUBhdjEvVaJvOoyPAbcW0fnd0tvRXD76wEfZ1KcQz4=
@@ -656,6 +661,8 @@ github.com/swaggo/files v0.0.0-20220728132757-551d4a08d97a/go.mod h1:lKJPbtWzJ9J
github.com/swaggo/swag v1.8.1/go.mod h1:ugemnJsPZm/kRwFUnzBlbHRd0JY9zE1M4F+uy2pAaPQ=
github.com/swaggo/swag v1.8.7 h1:2K9ivTD3teEO+2fXV6zrZKDqk5IuU2aJtBDo8U7omWU=
github.com/swaggo/swag v1.8.7/go.mod h1:ezQVUUhly8dludpVk+/PuwJWvLLanB13ygV5Pr9enSk=
+github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
+github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tikv/client-go/v2 v2.0.1-0.20220725090834-0cdc7c1d0fb9 h1:RW/8xnBK618j7B33mP4TTCVhzj1dgwZv/TT7vHaMpbg=
github.com/tikv/client-go/v2 v2.0.1-0.20220725090834-0cdc7c1d0fb9/go.mod h1:v3DEt8LS9olI6D6El17pYBWq7B28hw3NnDFTxQHDLpY=
github.com/tikv/pd/client v0.0.0-20221101140400-25982e60b78a h1:oxTdzFI/Ln7yrh2FCWqQvGdaCUopGuzAK43U+ZBAY0s=
@@ -676,12 +683,20 @@ github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/wangjohn/quickselect v0.0.0-20161129230411-ed8402a42d5f h1:9DDCDwOyEy/gId+IEMrFHLuQ5R/WV0KNxWLler8X2OY=
+github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
+github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
+github.com/xdg-go/scram v1.1.1 h1:VOMT+81stJgXW3CpHyqHN3AXDYIMsx56mEFrB37Mb/E=
+github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g=
+github.com/xdg-go/stringprep v1.0.3 h1:kdwGpVNwPFtjs98xCGkHjQtGKh86rDcRZN17QEMCOIs=
+github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8=
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo=
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos=
github.com/xo/dburl v0.12.4 h1:mAIQjCNqCRtfytZNN0tZzK01rfng3n4Ei1s+H9lh61I=
github.com/xo/dburl v0.12.4/go.mod h1:K6rSPgbVqP3ZFT0RHkdg/M3M5KhLeV2MaS/ZqaLd1kA=
github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c h1:3lbZUMbMiGUW/LMkfsEABsc5zNT9+b1CvsJx47JzJ8g=
github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c/go.mod h1:UrdRz5enIKZ63MEE3IF9l2/ebyx59GyGgPi+tICQdmM=
+github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
+github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
@@ -695,6 +710,8 @@ github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxt
go.etcd.io/etcd/api/v3 v3.5.2 h1:tXok5yLlKyuQ/SXSjtqHc4uzNaMqZi2XsoSPr/LlJXI=
go.etcd.io/etcd/client/pkg/v3 v3.5.2 h1:4hzqQ6hIb3blLyQ8usCU4h3NghkqcsohEQ3o3VetYxE=
go.etcd.io/etcd/client/v3 v3.5.2 h1:WdnejrUtQC4nCxK0/dLTMqKOB+U5TP/2Ya0BJL+1otA=
+go.mongodb.org/mongo-driver v1.11.1 h1:QP0znIRTuL0jf1oBQoAoM0C6ZJfBK4kx0Uumtv1A7w8=
+go.mongodb.org/mongo-driver v1.11.1/go.mod h1:s7p5vEtfbeR1gYi6pnj3c3/urpbLv2T5Sfd6Rp2HBB8=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
@@ -750,6 +767,7 @@ golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5y
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
+golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU=
golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw=
diff --git a/plugin/db/driver.go b/plugin/db/driver.go
index 0d4d1cac37..75b96130e9 100644
--- a/plugin/db/driver.go
+++ b/plugin/db/driver.go
@@ -33,6 +33,8 @@ const (
SQLite Type = "SQLITE"
// TiDB is the database type for TiDB.
TiDB Type = "TIDB"
+ // MongoDB is the database type for MongoDB.
+ MongoDB Type = "MONGODB"
// BytebaseDatabase is the database installed in the controlled database server.
BytebaseDatabase = "bytebase"
@@ -447,6 +449,8 @@ type ConnectionConfig struct {
ReadOnly bool
// StrictUseDb will only set as true if the user gives only a database instead of a whole instance to access.
StrictUseDb bool
+ // SRV is only supported for MongoDB now.
+ SRV bool
}
// ConnectionContext is the context for connection.
diff --git a/plugin/db/mongodb/mongodb.go b/plugin/db/mongodb/mongodb.go
new file mode 100644
index 0000000000..40f930b031
--- /dev/null
+++ b/plugin/db/mongodb/mongodb.go
@@ -0,0 +1,155 @@
+// Package mongodb is the plugin for MongoDB driver.
+package mongodb
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "io"
+ "strings"
+
+ "go.mongodb.org/mongo-driver/mongo"
+ "go.mongodb.org/mongo-driver/mongo/options"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/plugin/db"
+)
+
+var (
+ _ db.Driver = (*Driver)(nil)
+)
+
+func init() {
+ db.Register(db.MongoDB, newDriver)
+}
+
+// Driver is the MongoDB driver.
+type Driver struct {
+ client *mongo.Client
+}
+
+func newDriver(_ db.DriverConfig) db.Driver {
+ return &Driver{}
+}
+
+// Open opens a MongoDB driver.
+func (driver *Driver) Open(ctx context.Context, _ db.Type, connCfg db.ConnectionConfig, _ db.ConnectionContext) (db.Driver, error) {
+ connectionURI := getMongoDBConnectionURI(connCfg)
+ opts := options.Client().ApplyURI(connectionURI)
+ client, err := mongo.Connect(ctx, opts)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to create MongoDB client")
+ }
+ driver.client = client
+ return driver, nil
+}
+
+// Close closes the MongoDB driver.
+func (driver *Driver) Close(ctx context.Context) error {
+ if err := driver.client.Disconnect(ctx); err != nil {
+ return errors.Wrap(err, "failed to disconnect MongoDB")
+ }
+ return nil
+}
+
+// Ping pings the database.
+func (driver *Driver) Ping(ctx context.Context) error {
+ if err := driver.client.Ping(ctx, nil); err != nil {
+ return errors.Wrap(err, "failed to ping MongoDB")
+ }
+ return nil
+}
+
+// GetDBConnection returns a database connection.
+func (*Driver) GetDBConnection(_ context.Context, _ string) (*sql.DB, error) {
+ panic("not implemented")
+}
+
+// Execute executes a statement.
+func (*Driver) Execute(_ context.Context, _ string, _ bool) (int64, error) {
+ panic("not implemented")
+}
+
+// Query queries a statement.
+func (*Driver) Query(_ context.Context, _ string, _ *db.QueryContext) ([]interface{}, error) {
+ panic("not implemented")
+}
+
+// SyncInstance syncs the instance meta.
+func (*Driver) SyncInstance(_ context.Context) (*db.InstanceMeta, error) {
+ panic("not implemented")
+}
+
+// SyncDBSchema syncs the database schema.
+func (*Driver) SyncDBSchema(_ context.Context, _ string) (*db.Schema, error) {
+ panic("not implemented")
+}
+
+// NeedsSetupMigration returns whether the driver needs to setup migration.
+func (*Driver) NeedsSetupMigration(_ context.Context) (bool, error) {
+ panic("not implemented")
+}
+
+// SetupMigrationIfNeeded sets up migration if needed.
+func (*Driver) SetupMigrationIfNeeded(_ context.Context) error {
+ panic("not implemented")
+}
+
+// ExecuteMigration executes a migration.
+func (*Driver) ExecuteMigration(_ context.Context, _ *db.MigrationInfo, _ string) (int64, string, error) {
+ panic("not implemented")
+}
+
+// FindMigrationHistoryList finds the migration history list.
+func (*Driver) FindMigrationHistoryList(_ context.Context, _ *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {
+ panic("not implemented")
+}
+
+// Dump dumps the database.
+func (*Driver) Dump(_ context.Context, _ string, _ io.Writer, _ bool) (string, error) {
+ panic("not implemented")
+}
+
+// Restore restores the backup read from src.
+func (*Driver) Restore(_ context.Context, _ io.Reader) error {
+ panic("not implemented")
+}
+
+// getMongoDBConnectionURI returns the MongoDB connection URI.
+// https://www.mongodb.com/docs/manual/reference/connection-string/
+func getMongoDBConnectionURI(connConfig db.ConnectionConfig) string {
+ connectionURL := "mongodb://"
+ if connConfig.SRV {
+ connectionURL = "mongodb+srv://"
+ }
+ if connConfig.Username != "" {
+ percentEncodingUsername := replaceCharacterWithPercentEncoding(connConfig.Username)
+ percentEncodingPassword := replaceCharacterWithPercentEncoding(connConfig.Password)
+ connectionURL = fmt.Sprintf("%s%s:%s@", connectionURL, percentEncodingUsername, percentEncodingPassword)
+ }
+ connectionURL = fmt.Sprintf("%s%s", connectionURL, connConfig.Host)
+ if connConfig.Port != "" {
+ connectionURL = fmt.Sprintf("%s:%s", connectionURL, connConfig.Port)
+ }
+ if connConfig.Database != "" {
+ connectionURL = fmt.Sprintf("%s/%s", connectionURL, connConfig.Database)
+ }
+ return connectionURL
+}
+
+func replaceCharacterWithPercentEncoding(s string) string {
+ m := map[string]string{
+ ":": `%3A`,
+ "/": `%2F`,
+ "?": `%3F`,
+ "#": `%23`,
+ "[": `%5B`,
+ "]": `%5D`,
+ "@": `%40`,
+ }
+ for k, v := range m {
+ s = strings.ReplaceAll(s, k, v)
+ }
+ return s
+}
diff --git a/plugin/db/mongodb/mongodb_test.go b/plugin/db/mongodb/mongodb_test.go
new file mode 100644
index 0000000000..9eca989f97
--- /dev/null
+++ b/plugin/db/mongodb/mongodb_test.go
@@ -0,0 +1,74 @@
+package mongodb
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/plugin/db"
+)
+
+func TestGetMongoDBConnectionURL(t *testing.T) {
+ tests := []struct {
+ connConfig db.ConnectionConfig
+ want string
+ }{
+ {
+ connConfig: db.ConnectionConfig{
+ Host: "localhost",
+ Port: "27017",
+ Username: "",
+ Password: "",
+ },
+ want: "mongodb://localhost:27017",
+ },
+ {
+ connConfig: db.ConnectionConfig{
+ Host: "localhost",
+ Port: "27017",
+ Username: "",
+ Password: "",
+ Database: "sampleDB",
+ },
+ want: "mongodb://localhost:27017/sampleDB",
+ },
+ {
+ connConfig: db.ConnectionConfig{
+ Host: "cluster0.sample.mongodb.net",
+ Username: "bytebase",
+ Password: "passwd",
+ Database: "sampleDB",
+ SRV: true,
+ },
+ want: "mongodb+srv://bytebase:[email protected]/sampleDB",
+ },
+ }
+
+ a := require.New(t)
+ for _, tt := range tests {
+ got := getMongoDBConnectionURI(tt.connConfig)
+ a.Equal(tt.want, got)
+ }
+}
+
+func TestReplaceCharactersWithPercentEncoding(t *testing.T) {
+ tests := []struct {
+ s string
+ want string
+ }{
+ {
+ s: "passw@rd",
+ want: `passw%40rd`,
+ },
+ {
+ s: "passw@rd:/?#[]",
+ want: `passw%40rd%3A%2F%3F%23%5B%5D`,
+ },
+ }
+
+ a := require.New(t)
+ for _, tt := range tests {
+ got := replaceCharacterWithPercentEncoding(tt.s)
+ a.Equal(tt.want, got)
+ }
+}
diff --git a/server/server.go b/server/server.go
index 64084c1251..d9a046488f 100644
--- a/server/server.go
+++ b/server/server.go
@@ -60,6 +60,8 @@ import (
_ "github.com/bytebase/bytebase/plugin/db/snowflake"
// Register sqlite driver.
_ "github.com/bytebase/bytebase/plugin/db/sqlite"
+ // Register mongodb driver.
+ _ "github.com/bytebase/bytebase/plugin/db/mongodb"
// Register pingcap parser driver.
_ "github.com/pingcap/tidb/types/parser_driver"
diff --git a/server/sql.go b/server/sql.go
index 6224c24a89..7fce3023ae 100644
--- a/server/sql.go
+++ b/server/sql.go
@@ -73,6 +73,7 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, "TLS/SSL suite must all be set or not be set")
}
}
+
db, err := db.Open(
ctx,
connectionInfo.Engine,
@@ -83,6 +84,8 @@ func (s *Server) registerSQLRoutes(g *echo.Group) {
Host: connectionInfo.Host,
Port: connectionInfo.Port,
TLSConfig: tlsConfig,
+ SRV: connectionInfo.SRV,
+ Database: connectionInfo.Database,
},
db.ConnectionContext{},
)