Skip to content

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

feat(mongodb): support creating MongoDB instance (#3813)

h3n4l62830a43fbd5
diff --git a/api/data_source.go b/api/data_source.go
index a840bfcdfd..d8e7a74f8c 100644
--- a/api/data_source.go
+++ b/api/data_source.go
@@ -2,6 +2,7 @@ package api
import (
"encoding/json"
+ "errors"
)
const (
@@ -40,6 +41,32 @@ const (
RO DataSourceType = "RO"
)
+// DataSourceOptions is the options for a data source.
+type DataSourceOptions struct {
+ // SRV is used for MongoDB only.
+ SRV bool `json:"srv" jsonapi:"attr,srv"`
+}
+
+// getDefaultDataSourceOptions returns the default data source options.
+func getDefaultDataSourceOptions() DataSourceOptions {
+ return DataSourceOptions{
+ SRV: false,
+ }
+}
+
+// Scan implements database/sql Scanner interface, converts JSONB to DataSourceOptions struct.
+func (d *DataSourceOptions) Scan(src interface{}) error {
+ if bs, ok := src.([]byte); ok {
+ if string(bs) == "{}" {
+ // handle '{}', return default values
+ *d = getDefaultDataSourceOptions()
+ return nil
+ }
+ return json.Unmarshal(bs, d)
+ }
+ return errors.New("failed to scan data source options")
+}
+
// DataSource is the API message for a data source.
type DataSource struct {
ID int `jsonapi:"primary,dataSource"`
@@ -67,8 +94,9 @@ type DataSource struct {
SslCert string
SslKey string
// HostOverride and PortOverride are only used for read-only data sources for user's read-replica instances.
- HostOverride string `jsonapi:"attr,hostOverride"`
- PortOverride string `jsonapi:"attr,portOverride"`
+ HostOverride string `jsonapi:"attr,hostOverride"`
+ PortOverride string `jsonapi:"attr,portOverride"`
+ Options DataSourceOptions `jsonapi:"attr,options"`
}
// DataSourceCreate is the API message for creating a data source.
@@ -82,15 +110,16 @@ type DataSourceCreate struct {
DatabaseID int `jsonapi:"attr,databaseId"`
// Domain specific fields
- Name string `jsonapi:"attr,name"`
- Type DataSourceType `jsonapi:"attr,type"`
- Username string `jsonapi:"attr,username"`
- Password string `jsonapi:"attr,password"`
- SslCa string `jsonapi:"attr,sslCa"`
- SslCert string `jsonapi:"attr,sslCert"`
- SslKey string `jsonapi:"attr,sslKey"`
- HostOverride string `jsonapi:"attr,hostOverride"`
- PortOverride string `jsonapi:"attr,portOverride"`
+ Name string `jsonapi:"attr,name"`
+ Type DataSourceType `jsonapi:"attr,type"`
+ Username string `jsonapi:"attr,username"`
+ Password string `jsonapi:"attr,password"`
+ SslCa string `jsonapi:"attr,sslCa"`
+ SslCert string `jsonapi:"attr,sslCert"`
+ SslKey string `jsonapi:"attr,sslKey"`
+ HostOverride string `jsonapi:"attr,hostOverride"`
+ PortOverride string `jsonapi:"attr,portOverride"`
+ Options DataSourceOptions `jsonapi:"attr,options"`
}
// DataSourceFind is the API message for finding data sources.
@@ -122,14 +151,15 @@ type DataSourcePatch struct {
UpdaterID int
// Domain specific fields
- Username *string `jsonapi:"attr,username"`
- Password *string `jsonapi:"attr,password"`
- UseEmptyPassword *bool `jsonapi:"attr,useEmptyPassword"`
- SslCa *string `jsonapi:"attr,sslCa"`
- SslCert *string `jsonapi:"attr,sslCert"`
- SslKey *string `jsonapi:"attr,sslKey"`
- HostOverride *string `jsonapi:"attr,hostOverride"`
- PortOverride *string `jsonapi:"attr,portOverride"`
+ Username *string `jsonapi:"attr,username"`
+ Password *string `jsonapi:"attr,password"`
+ UseEmptyPassword *bool `jsonapi:"attr,useEmptyPassword"`
+ SslCa *string `jsonapi:"attr,sslCa"`
+ SslCert *string `jsonapi:"attr,sslCert"`
+ SslKey *string `jsonapi:"attr,sslKey"`
+ HostOverride *string `jsonapi:"attr,hostOverride"`
+ PortOverride *string `jsonapi:"attr,portOverride"`
+ Options *DataSourceOptions `jsonapi:"attr,options"`
}
// DataSourceDelete is the API message for deleting data sources.
diff --git a/api/instance.go b/api/instance.go
index fd0252210f..147a6eb305 100644
--- a/api/instance.go
+++ b/api/instance.go
@@ -34,8 +34,6 @@ 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
}
diff --git a/frontend/src/components/CreateInstanceForm.vue b/frontend/src/components/CreateInstanceForm.vue
index f755604229..b03da0f737 100644
--- a/frontend/src/components/CreateInstanceForm.vue
+++ b/frontend/src/components/CreateInstanceForm.vue
@@ -122,8 +122,8 @@
<div class="ml-1">
<BBCheckbox
title="DNS SRV Record"
- :value="state.instance.useDNSSRVRecord"
- @toggle="handleToggleDNSSRVRecord"
+ :value="state.instance.srv"
+ @toggle="handleToggleSRV"
/>
</div></div
></template>
@@ -253,8 +253,7 @@
:disabled="
!allowCreate ||
state.isCreatingInstance ||
- state.isPingingInstance ||
- state.instance.engine == 'MONGODB'
+ state.isPingingInstance
"
@click.prevent="tryCreate"
>
@@ -350,7 +349,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,
+ srv: false,
},
showCreateInstanceWarningModal: false,
createInstanceWarning: "",
@@ -476,8 +475,8 @@ const handleInstanceDatabaseInput = (event: Event) => {
updateInstance("database", (event.target as HTMLInputElement).value);
};
-const handleToggleDNSSRVRecord = (on: boolean) => {
- updateInstance("useDNSSRVRecord", on);
+const handleToggleSRV = (on: boolean) => {
+ updateInstance("srv", on);
};
const updateInstance = (field: string, value: string | boolean) => {
@@ -544,7 +543,7 @@ const tryCreate = () => {
useEmptyPassword: false,
host: instance.host,
port: instance.port,
- srv: instance.useDNSSRVRecord,
+ srv: instance.srv,
};
if (showSSL.value) {
@@ -554,6 +553,12 @@ const tryCreate = () => {
connectionInfo.sslCert = instance.sslCert ?? "";
}
+ // MongoDB can use auth database.
+ // https://www.mongodb.com/docs/manual/tutorial/authenticate-a-user/#std-label-authentication-auth-as-user
+ if (instance.engine === "MONGODB") {
+ connectionInfo.database = instance.database;
+ }
+
state.isPingingInstance = true;
sqlStore
.ping(connectionInfo)
@@ -580,7 +585,10 @@ const tryCreate = () => {
const doCreate = () => {
state.isCreatingInstance = true;
- if (state.instance.engine !== "POSTGRES") {
+ if (
+ state.instance.engine !== "POSTGRES" &&
+ state.instance.engine !== "MONGODB"
+ ) {
// Clear the `database` field if not needed.
state.instance.database = "";
}
@@ -622,7 +630,7 @@ const testConnection = () => {
: undefined,
useEmptyPassword: false,
instanceId: undefined,
- srv: instance.useDNSSRVRecord,
+ srv: instance.srv,
};
if (showSSL.value) {
diff --git a/frontend/src/components/InstanceForm.vue b/frontend/src/components/InstanceForm.vue
index 3ddcae93e1..ba6a2e22a2 100644
--- a/frontend/src/components/InstanceForm.vue
+++ b/frontend/src/components/InstanceForm.vue
@@ -255,6 +255,17 @@
/>
</div>
+ <template v-if="state.instance.engine == 'MONGODB'">
+ <div class="mt-2 sm:col-span-1 sm:col-start-1">
+ <div class="lex flex-row items-center space-x-2">
+ <BBCheckbox
+ title="DNS SRV Record"
+ :value="currentDataSource.options.srv"
+ @toggle="handleToggleSRV"
+ />
+ </div></div
+ ></template>
+
<template v-if="state.currentDataSourceType === 'RO'">
<div class="mt-2 sm:col-span-1 sm:col-start-1">
<div class="flex flex-row items-center space-x-2">
@@ -429,7 +440,6 @@ interface State {
dataSourceList: EditDataSource[];
currentDataSourceType: DataSourceType;
showFeatureModal: boolean;
- useDNSSRVRecord: boolean;
}
const props = defineProps({
@@ -462,7 +472,6 @@ const state = reactive<State>({
dataSourceList: dataSourceList,
currentDataSourceType: "ADMIN",
showFeatureModal: false,
- useDNSSRVRecord: false,
});
const allowEdit = computed(() => {
@@ -504,6 +513,8 @@ const defaultPort = computed(() => {
return "443";
} else if (state.instance.engine == "TIDB") {
return "4000";
+ } else if (state.instance.engine == "MONGODB") {
+ return "27017";
}
return "3306";
});
@@ -597,6 +608,11 @@ const handleCurrentDataSourcePasswordInput = (event: Event) => {
updateInstanceDataSource();
};
+const handleToggleSRV = (on: boolean) => {
+ currentDataSource.value.options.srv = on;
+ updateInstanceDataSource();
+};
+
const handleCurrentDataSourceHostOverrideInput = (event: Event) => {
const str = (event.target as HTMLInputElement).value.trim();
currentDataSource.value.hostOverride = str;
@@ -661,6 +677,7 @@ const updateInstanceDataSource = () => {
let newValue = {
...state.instance.dataSourceList[index],
username: curr.username,
+ options: curr.options,
};
if (curr.type === "RO") {
@@ -897,7 +914,7 @@ const testConnection = () => {
port: connectionPort,
database: instance.database,
instanceId: instance.id,
- srv: state.useDNSSRVRecord,
+ srv: dataSource.options.srv,
};
if (typeof dataSource.sslCa !== "undefined") {
diff --git a/frontend/src/types/dataSource.ts b/frontend/src/types/dataSource.ts
index 372427edff..5bc8a2fa95 100644
--- a/frontend/src/types/dataSource.ts
+++ b/frontend/src/types/dataSource.ts
@@ -13,6 +13,11 @@ import { Principal } from "./principal";
// which from the ops perspective, having different meaning from the normal RW data source.
export type DataSourceType = "ADMIN" | "RW" | "RO";
+// DataSourceOptions is the options for a data source.
+export type DataSourceOptions = {
+ srv: boolean;
+};
+
export type DataSource = {
id: DataSourceId;
@@ -40,6 +45,7 @@ export type DataSource = {
hostOverride: string;
portOverride: string;
+ options: DataSourceOptions;
// UI-only fields
updateSsl?: boolean;
};
@@ -72,6 +78,7 @@ export type DataSourcePatch = {
sslKey?: string;
hostOverride?: string;
portOverride?: string;
+ options?: DataSourceOptions;
};
export type DataSourceMember = {
diff --git a/frontend/src/types/instance.ts b/frontend/src/types/instance.ts
index 8f656e36eb..34a140cc6d 100644
--- a/frontend/src/types/instance.ts
+++ b/frontend/src/types/instance.ts
@@ -86,6 +86,7 @@ export type Instance = {
database: string;
host: string;
port?: string;
+ srv: boolean;
};
export type InstanceCreate = {
@@ -106,7 +107,7 @@ export type InstanceCreate = {
sslCert?: string;
sslKey?: string;
// DNS SRV record is only used for MongoDB.
- useDNSSRVRecord: boolean;
+ srv: boolean;
};
export type InstancePatch = {
diff --git a/plugin/db/mongodb/collmod_migrationHistory_collection_command.json b/plugin/db/mongodb/collmod_migrationHistory_collection_command.json
new file mode 100644
index 0000000000..79c6bba126
--- /dev/null
+++ b/plugin/db/mongodb/collmod_migrationHistory_collection_command.json
@@ -0,0 +1,67 @@
+{
+ "collMod": "migration_history",
+ "validator": {
+ "$jsonSchema": {
+ "title": "Bytebase Migration History Object Validation",
+ "required": [
+ "_id",
+ "created_by",
+ "created_ts",
+ "release_version",
+ "namespace",
+ "sequence",
+ "source",
+ "status",
+ "description",
+ "statement",
+ "executon_duration_ns",
+ "issue_id",
+ "payload"
+ ],
+ "properties": {
+ "_id": {
+ "bsonType": "objectId"
+ },
+ "created_by": {
+ "bsonType": "string"
+ },
+ "created_ts": {
+ "bsonType": "long"
+ },
+ "release_version": {
+ "bsonType": "string"
+ },
+ "namespace": {
+ "bsonType": "string"
+ },
+ "sequence": {
+ "bsonType": "long",
+ "minimum": 0
+ },
+ "source": {
+ "bsonType": "string"
+ },
+ "status": {
+ "bsonType": "string"
+ },
+ "description": {
+ "bsonType": "string"
+ },
+ "statement": {
+ "bsonType": "string"
+ },
+ "execution_duration_ns": {
+ "bsonType": "long"
+ },
+ "issue_id": {
+ "bsonType": "string"
+ },
+ "payload": {
+ "bsonType": "string"
+ }
+ },
+ "additionalProperties": false
+ }
+ },
+ "writeConcern": { "w": "majority" }
+}
diff --git a/plugin/db/mongodb/create_index_on_migrationHistory_collection_command.json b/plugin/db/mongodb/create_index_on_migrationHistory_collection_command.json
new file mode 100644
index 0000000000..4746189ee7
--- /dev/null
+++ b/plugin/db/mongodb/create_index_on_migrationHistory_collection_command.json
@@ -0,0 +1,37 @@
+{
+ "createIndexes": "migration_history",
+ "indexes": [
+ {
+ "key": {
+ "namespace": 1,
+ "sequence": 1
+ },
+ "name": "bytebase_idx_unique_migration_history_namespace_sequence",
+ "unique": true
+ },
+ {
+ "key": {
+ "namespace": 1,
+ "version": 1
+ },
+ "name": "bytebase_idx_unique_migration_history_namespace_version",
+ "unique": true
+ },
+ {
+ "key": {
+ "namespace": 1,
+ "source": 1,
+ "type": 1
+ },
+ "name": "bytebase_idx_migration_history_namespace_source_type"
+ },
+ {
+ "key": {
+ "namespace": 1,
+ "created_ts": 1
+ },
+ "name": "bytebase_idx_migration_history_namespace_created"
+ }
+ ],
+ "writeConcern": { "w": "majority" }
+}
diff --git a/plugin/db/mongodb/migrate.go b/plugin/db/mongodb/migrate.go
new file mode 100644
index 0000000000..eb4acf7cd1
--- /dev/null
+++ b/plugin/db/mongodb/migrate.go
@@ -0,0 +1,95 @@
+package mongodb
+
+import (
+ "context"
+
+ // embed will embeds the migration schema.
+ _ "embed"
+
+ "go.mongodb.org/mongo-driver/bson"
+ "go.uber.org/zap"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/common/log"
+ "github.com/bytebase/bytebase/plugin/db"
+)
+
+const (
+ // migrationHistoryDefaultDatabase is the default database name for migration history.
+ migrationHistoryDefaultDatabase = "bytebase"
+ // migrationHistoryDefaultCollection is the default collection name for migration history.
+ migrationHistoryDefaultCollection = "migration_history"
+)
+
+var (
+ //go:embed collmod_migrationHistory_collection_command.json
+ collmodMigrationHistoryCollectionCommand string
+ //go:embed create_index_on_migrationHistory_collection_command.json
+ createIndexOnMigrationHistoryCollectionCommand string
+)
+
+// NeedsSetupMigration returns whether the driver needs to setup migration.
+func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {
+ database := driver.client.Database(migrationHistoryDefaultDatabase)
+ collectionNames, err := database.ListCollectionNames(ctx, bson.M{})
+ if err != nil {
+ return false, errors.Wrapf(err, "failed to list collection names for database %q", migrationHistoryDefaultDatabase)
+ }
+ for _, collectionName := range collectionNames {
+ if collectionName == migrationHistoryDefaultCollection {
+ return false, nil
+ }
+ }
+ return true, nil
+}
+
+// SetupMigrationIfNeeded sets up migration if needed.
+func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {
+ setup, err := driver.NeedsSetupMigration(ctx)
+ if err != nil {
+ return err
+ }
+ if !setup {
+ return nil
+ }
+ log.Info("Bytebase migration schema not found, creating schema for mongodb...",
+ zap.String("environment", driver.connectionCtx.EnvironmentName),
+ zap.String("instance", driver.connectionCtx.InstanceName),
+ )
+ database := driver.client.Database(migrationHistoryDefaultDatabase)
+ if err := database.CreateCollection(ctx, migrationHistoryDefaultCollection); err != nil {
+ return errors.Wrapf(err, "failed to create collection %q in mongodb database %q for instance named %q", migrationHistoryDefaultCollection, migrationHistoryDefaultDatabase, driver.connectionCtx.InstanceName)
+ }
+
+ var b interface{}
+ if err := bson.UnmarshalExtJSON([]byte(collmodMigrationHistoryCollectionCommand), true, &b); err != nil {
+ return errors.Wrap(err, "failed to unmarshal collmod command")
+ }
+ var result interface{}
+ if err := database.RunCommand(context.Background(), b).Decode(&result); err != nil {
+ return errors.Wrap(err, "failed to run collmod command")
+ }
+
+ if err := bson.UnmarshalExtJSON([]byte(createIndexOnMigrationHistoryCollectionCommand), true, &b); err != nil {
+ return errors.Wrap(err, "failed to unmarshal create index command")
+ }
+ if err := database.RunCommand(context.Background(), b).Decode(&result); err != nil {
+ return errors.Wrap(err, "failed to run create index command")
+ }
+ log.Info("Successfully created migration schema for mongodb.",
+ zap.String("environment", driver.connectionCtx.EnvironmentName),
+ zap.String("instance", driver.connectionCtx.InstanceName),
+ )
+ return nil
+}
+
+// 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")
+}
diff --git a/plugin/db/mongodb/mongodb.go b/plugin/db/mongodb/mongodb.go
index 40f930b031..f9b6ba53e5 100644
--- a/plugin/db/mongodb/mongodb.go
+++ b/plugin/db/mongodb/mongodb.go
@@ -26,7 +26,8 @@ func init() {
// Driver is the MongoDB driver.
type Driver struct {
- client *mongo.Client
+ connectionCtx db.ConnectionContext
+ client *mongo.Client
}
func newDriver(_ db.DriverConfig) db.Driver {
@@ -34,7 +35,7 @@ func newDriver(_ db.DriverConfig) db.Driver {
}
// Open opens a MongoDB driver.
-func (driver *Driver) Open(ctx context.Context, _ db.Type, connCfg db.ConnectionConfig, _ db.ConnectionContext) (db.Driver, error) {
+func (driver *Driver) Open(ctx context.Context, _ db.Type, connCfg db.ConnectionConfig, connCtx db.ConnectionContext) (db.Driver, error) {
connectionURI := getMongoDBConnectionURI(connCfg)
opts := options.Client().ApplyURI(connectionURI)
client, err := mongo.Connect(ctx, opts)
@@ -42,6 +43,7 @@ func (driver *Driver) Open(ctx context.Context, _ db.Type, connCfg db.Connection
return nil, errors.Wrap(err, "failed to create MongoDB client")
}
driver.client = client
+ driver.connectionCtx = connCtx
return driver, nil
}
@@ -86,26 +88,6 @@ 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")
diff --git a/server/component/dbfactory/dbfactory.go b/server/component/dbfactory/dbfactory.go
index 7f73774f22..d0fd4ba3c0 100644
--- a/server/component/dbfactory/dbfactory.go
+++ b/server/component/dbfactory/dbfactory.go
@@ -62,6 +62,7 @@ func (d *DBFactory) GetAdminDatabaseDriver(ctx context.Context, instance *api.In
Host: instance.Host,
Port: instance.Port,
Database: databaseName,
+ SRV: adminDataSource.Options.SRV,
},
db.ConnectionContext{
EnvironmentName: instance.Environment.Name,
diff --git a/server/instance.go b/server/instance.go
index 964ae83636..a54f5aba97 100644
--- a/server/instance.go
+++ b/server/instance.go
@@ -50,6 +50,9 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {
SslCa: instanceCreate.SslCa,
SslCert: instanceCreate.SslCert,
SslKey: instanceCreate.SslKey,
+ Options: api.DataSourceOptions{
+ SRV: instanceCreate.SRV,
+ },
},
},
Name: instanceCreate.Name,
@@ -473,8 +476,8 @@ func (s *Server) createInstance(ctx context.Context, create *store.InstanceCreat
if err := s.disallowBytebaseStore(create.Engine, create.Host, create.Port); err != nil {
return nil, echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
}
- if create.Engine != db.Postgres && create.Database != "" {
- return nil, echo.NewHTTPError(http.StatusBadRequest, "database parameter is only allowed for Postgres")
+ if create.Engine != db.Postgres && create.Engine != db.MongoDB && create.Database != "" {
+ return nil, echo.NewHTTPError(http.StatusBadRequest, "database parameter is only allowed for Postgres and MongoDB")
}
instance, err := s.store.CreateInstance(ctx, create)
@@ -488,10 +491,10 @@ func (s *Server) createInstance(ctx context.Context, create *store.InstanceCreat
// Try creating the "bytebase" db in the added instance if needed.
// Since we allow user to add new instance upfront even providing the incorrect username/password,
// thus it's OK if it fails. Frontend will surface relevant info suggesting the "bytebase" db hasn't created yet.
- db, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)
+ driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "" /* databaseName */)
if err == nil {
- defer db.Close(ctx)
- if err := db.SetupMigrationIfNeeded(ctx); err != nil {
+ defer driver.Close(ctx)
+ if err := driver.SetupMigrationIfNeeded(ctx); err != nil {
log.Warn("Failed to setup migration schema on instance creation",
zap.String("instance_name", instance.Name),
zap.String("engine", string(instance.Engine)),
@@ -542,8 +545,8 @@ func (s *Server) updateInstance(ctx context.Context, patch *store.InstancePatch)
if err := s.disallowBytebaseStore(instance.Engine, host, port); err != nil {
return nil, echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)
}
- if instance.Engine != db.Postgres && database != "" {
- return nil, echo.NewHTTPError(http.StatusBadRequest, "database parameter is only allowed for Postgres")
+ if instance.Engine != db.Postgres && instance.Engine != db.MongoDB && database != "" {
+ return nil, echo.NewHTTPError(http.StatusBadRequest, "database parameter is only allowed for Postgres and MongoDB")
}
instancePatched := instance
diff --git a/server/runner/schemasync/syncer.go b/server/runner/schemasync/syncer.go
index 7a1e6cecb0..95714322bc 100644
--- a/server/runner/schemasync/syncer.go
+++ b/server/runner/schemasync/syncer.go
@@ -167,6 +167,10 @@ func (s *Syncer) syncAllDatabases(ctx context.Context, instanceID *int) {
// SyncInstance syncs the schema for all databases in an instance.
func (s *Syncer) SyncInstance(ctx context.Context, instance *api.Instance) ([]string, error) {
+ // TODO(zp): support sync schema for mongodb.
+ if instance.Engine == db.MongoDB {
+ return nil, nil
+ }
driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, "")
if err != nil {
return nil, err
diff --git a/store/data_source.go b/store/data_source.go
index d8f1c80b18..2a345cc703 100644
--- a/store/data_source.go
+++ b/store/data_source.go
@@ -37,6 +37,7 @@ type dataSourceRaw struct {
SslKey string
HostOverride string
PortOverride string
+ Options api.DataSourceOptions
}
// toDataSource creates an instance of DataSource based on the dataSourceRaw.
@@ -65,6 +66,7 @@ func (raw *dataSourceRaw) toDataSource() *api.DataSource {
SslKey: raw.SslKey,
HostOverride: raw.HostOverride,
PortOverride: raw.PortOverride,
+ Options: raw.Options,
}
}
@@ -298,10 +300,11 @@ func (*Store) createDataSourceImpl(ctx context.Context, tx *Tx, create *api.Data
ssl_cert,
ssl_ca,
host_override,
- port_override
+ port_override,
+ options
)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
- RETURNING id, creator_id, created_ts, updater_id, updated_ts, instance_id, database_id, name, type, username, password, ssl_key, ssl_cert, ssl_ca, host_override, port_override
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, instance_id, database_id, name, type, username, password, ssl_key, ssl_cert, ssl_ca, host_override, port_override, options
`
var dataSourceRaw dataSourceRaw
if err := tx.QueryRowContext(ctx, query,
@@ -318,6 +321,7 @@ func (*Store) createDataSourceImpl(ctx context.Context, tx *Tx, create *api.Data
create.SslCa,
create.HostOverride,
create.PortOverride,
+ create.Options,
).Scan(
&dataSourceRaw.ID,
&dataSourceRaw.CreatorID,
@@ -335,6 +339,7 @@ func (*Store) createDataSourceImpl(ctx context.Context, tx *Tx, create *api.Data
&dataSourceRaw.SslCa,
&dataSourceRaw.HostOverride,
&dataSourceRaw.PortOverride,
+ &dataSourceRaw.Options,
); err != nil {
if err == sql.ErrNoRows {
return nil, common.FormatDBErrorEmptyRowWithQuery(query)
@@ -377,7 +382,8 @@ func (*Store) findDataSourceImpl(ctx context.Context, tx *Tx, find *api.DataSour
ssl_cert,
ssl_ca,
host_override,
- port_override
+ port_override,
+ options
FROM data_source
WHERE `+strings.Join(where, " AND "),
args...,
@@ -408,6 +414,7 @@ func (*Store) findDataSourceImpl(ctx context.Context, tx *Tx, find *api.DataSour
&dataSourceRaw.SslCa,
&dataSourceRaw.HostOverride,
&dataSourceRaw.PortOverride,
+ &dataSourceRaw.Options,
); err != nil {
return nil, FormatError(err)
}
@@ -446,6 +453,9 @@ func (*Store) patchDataSourceImpl(ctx context.Context, tx *Tx, patch *api.DataSo
if v := patch.PortOverride; v != nil {
set, args = append(set, fmt.Sprintf("port_override= $%d", len(args)+1)), append(args, *v)
}
+ if v := patch.Options; v != nil {
+ set, args = append(set, fmt.Sprintf("options= $%d", len(args)+1)), append(args, *v)
+ }
args = append(args, patch.ID)
var dataSourceRaw dataSourceRaw
@@ -454,7 +464,7 @@ func (*Store) patchDataSourceImpl(ctx context.Context, tx *Tx, patch *api.DataSo
UPDATE data_source
SET `+strings.Join(set, ", ")+`
WHERE id = $%d
- RETURNING id, creator_id, created_ts, updater_id, updated_ts, instance_id, database_id, name, type, username, password, ssl_key, ssl_cert, ssl_ca, host_override, port_override
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, instance_id, database_id, name, type, username, password, ssl_key, ssl_cert, ssl_ca, host_override, port_override, options
`, len(args)),
args...,
).Scan(
@@ -474,6 +484,7 @@ func (*Store) patchDataSourceImpl(ctx context.Context, tx *Tx, patch *api.DataSo
&dataSourceRaw.SslCa,
&dataSourceRaw.HostOverride,
&dataSourceRaw.PortOverride,
+ &dataSourceRaw.Options,
); err != nil {
if err == sql.ErrNoRows {
return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("DataSource not found with ID %d", patch.ID)}
diff --git a/store/instance.go b/store/instance.go
index 21224ff224..c8652931ce 100644
--- a/store/instance.go
+++ b/store/instance.go
@@ -415,6 +415,7 @@ func (s *Store) createInstanceRaw(ctx context.Context, create *InstanceCreate) (
SslCa: dataSource.SslCa,
HostOverride: dataSource.HostOverride,
PortOverride: dataSource.PortOverride,
+ Options: dataSource.Options,
}
if err := s.createDataSourceRawTx(ctx, tx, dataSourceCreate); err != nil {
return nil, err