Skip to content

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

feat(mongodb): support sync MongoDB instance (part1) (#3912)

h3n4la8a5b6b3b92a
diff --git a/frontend/src/components/DatabaseOverviewPanel.vue b/frontend/src/components/DatabaseOverviewPanel.vue
index 177b92c11c..0b767a5977 100644
--- a/frontend/src/components/DatabaseOverviewPanel.vue
+++ b/frontend/src/components/DatabaseOverviewPanel.vue
@@ -73,7 +73,10 @@
<div class="pt-6">
<div class="text-lg leading-6 font-medium text-main mb-4">
- {{ $t("db.tables") }}
+ <span v-if="databaseEngine === 'MONGODB'">{{
+ $t("db.collections")
+ }}</span>
+ <span v-else>{{ $t("db.tables") }}</span>
</div>
<TableTable :database="database" :table-list="tableList" />
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 25117819da..c06c0070ed 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -634,6 +634,7 @@
"select-instance-first": "Select instance first",
"select-environment-first": "Select environment first",
"tables": "Tables",
+ "collections": "Collections",
"views": "Views",
"extensions": "Extensions",
"parent": "Parent",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index d883899acc..9d78a48e84 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -634,6 +634,7 @@
"select-instance-first": "先选择实例",
"select-environment-first": "先选择环境",
"tables": "表",
+ "collections": "集合",
"views": "视图",
"extensions": "插件",
"parent": "母",
diff --git a/plugin/db/driver.go b/plugin/db/driver.go
index ca3abea4eb..9e232b6626 100644
--- a/plugin/db/driver.go
+++ b/plugin/db/driver.go
@@ -108,25 +108,25 @@ type Table struct {
ShortName string
// Schema is the schema name for a table. It should be supported only for Postgres and Snowflake.
Schema string
- // CreatedTs isn't supported for ClickHouse, SQLite.
+ // CreatedTs isn't supported for ClickHouse, SQLite, MongoDB.
CreatedTs int64
- // UpdatedTs isn't supported for SQLite.
+ // UpdatedTs isn't supported for SQLite, MongoDB.
UpdatedTs int64
Type string
- // Engine isn't supported for Postgres, Snowflake, SQLite.
+ // Engine isn't supported for Postgres, Snowflake, SQLite, MongoDB.
Engine string
- // Collation isn't supported for Postgres, ClickHouse, Snowflake, SQLite.
+ // Collation isn't supported for Postgres, ClickHouse, Snowflake, SQLite, MongoDB.
Collation string
RowCount int64
// DataSize isn't supported for SQLite.
DataSize int64
// IndexSize isn't supported for ClickHouse, Snowflake, SQLite.
IndexSize int64
- // DataFree isn't supported for Postgres, ClickHouse, Snowflake, SQLite.
+ // DataFree isn't supported for Postgres, ClickHouse, Snowflake, SQLite, MongoDB.
DataFree int64
- // CreateOptions isn't supported for Postgres, ClickHouse, Snowflake, SQLite.
+ // CreateOptions isn't supported for Postgres, ClickHouse, Snowflake, SQLite, MongoDB.
CreateOptions string
- // Comment isn't supported for SQLite.
+ // Comment isn't supported for SQLite, MongoDB.
Comment string
ColumnList []Column
// IndexList isn't supported for ClickHouse, Snowflake.
@@ -152,9 +152,9 @@ type DatabaseMeta struct {
// Schema is the database schema.
type Schema struct {
Name string
- // CharacterSet isn't supported for ClickHouse, Snowflake.
+ // CharacterSet isn't supported for ClickHouse, Snowflake, MongoDB.
CharacterSet string
- // Collation isn't supported for ClickHouse, Snowflake.
+ // Collation isn't supported for ClickHouse, Snowflake, MongoDB.
Collation string
TableList []Table
ViewList []View
diff --git a/plugin/db/mongodb/migrate.go b/plugin/db/mongodb/migrate.go
index eb4acf7cd1..6d7a89311d 100644
--- a/plugin/db/mongodb/migrate.go
+++ b/plugin/db/mongodb/migrate.go
@@ -91,5 +91,10 @@ func (*Driver) ExecuteMigration(_ context.Context, _ *db.MigrationInfo, _ string
// FindMigrationHistoryList finds the migration history list.
func (*Driver) FindMigrationHistoryList(_ context.Context, _ *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {
- panic("not implemented")
+ // TODO(zp): implement
+ return []*db.MigrationHistory{
+ {
+ Version: "0000.0000.0000-FAKEIMPLEMENT",
+ },
+ }, nil
}
diff --git a/plugin/db/mongodb/mongodb.go b/plugin/db/mongodb/mongodb.go
index 1e28b0eb5e..c32488c77a 100644
--- a/plugin/db/mongodb/mongodb.go
+++ b/plugin/db/mongodb/mongodb.go
@@ -17,6 +17,8 @@ import (
)
var (
+ collectionType = "collection"
+
_ db.Driver = (*Driver)(nil)
)
@@ -80,7 +82,7 @@ func (*Driver) Query(_ context.Context, _ string, _ *db.QueryContext) ([]interfa
// Dump dumps the database.
func (*Driver) Dump(_ context.Context, _ string, _ io.Writer, _ bool) (string, error) {
- panic("not implemented")
+ return "", nil
}
// Restore restores the backup read from src.
diff --git a/plugin/db/mongodb/sync.go b/plugin/db/mongodb/sync.go
index 7b1044e596..b8320107b9 100644
--- a/plugin/db/mongodb/sync.go
+++ b/plugin/db/mongodb/sync.go
@@ -30,14 +30,6 @@ type Role struct {
DB string `json:"db" bson:"db"`
}
-var (
- systemDatabases = map[string]bool{
- "admin": true,
- "config": true,
- "local": true,
- }
-)
-
// SyncInstance syncs the instance meta.
func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error) {
version, err := driver.getVersion(ctx)
@@ -49,7 +41,7 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error
return nil, err
}
var databaseMetaList []db.DatabaseMeta
- dbList, err := driver.getDatabaseList(ctx)
+ dbList, err := driver.getNonSystemDatabaseList(ctx)
if err != nil {
return nil, err
}
@@ -67,8 +59,94 @@ func (driver *Driver) SyncInstance(ctx context.Context) (*db.InstanceMeta, error
}
// SyncDBSchema syncs the database schema.
-func (*Driver) SyncDBSchema(_ context.Context, _ string) (*db.Schema, error) {
- panic("not implemented")
+func (driver *Driver) SyncDBSchema(ctx context.Context, databaseName string) (*db.Schema, error) {
+ exist, err := driver.isDatabaseExist(ctx, databaseName)
+ if err != nil {
+ return nil, err
+ }
+ if !exist {
+ return nil, errors.Errorf("database %s does not exist", databaseName)
+ }
+ schema := db.Schema{}
+ schema.Name = databaseName
+
+ tableList, err := driver.syncAllCollectionSchema(ctx, databaseName)
+ if err != nil {
+ return nil, err
+ }
+ schema.TableList = tableList
+
+ // TODO(zp): sync View schema
+ return &schema, nil
+}
+
+func (driver *Driver) syncAllCollectionSchema(ctx context.Context, databaseName string) ([]db.Table, error) {
+ database := driver.client.Database(databaseName)
+ collectionFilter := bson.M{"type": collectionType}
+ collectionList, err := database.ListCollectionNames(ctx, collectionFilter)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to list collection names")
+ }
+ var tableList []db.Table
+ for _, collectionName := range collectionList {
+ table, err := driver.syncCollectionSchema(ctx, databaseName, collectionName)
+ if err != nil {
+ return nil, err
+ }
+ tableList = append(tableList, table)
+ }
+ return tableList, nil
+}
+
+func (driver *Driver) syncCollectionSchema(ctx context.Context, databaseName string, collectionName string) (db.Table, error) {
+ var table db.Table
+ table.Name = collectionName
+ table.ShortName = collectionName
+ table.Type = collectionType
+
+ // Get estimated document count.
+ database := driver.client.Database(databaseName)
+ collection := database.Collection(collectionName)
+ count, err := collection.EstimatedDocumentCount(ctx)
+ if err != nil {
+ return table, errors.Wrap(err, "failed to get estimated document count")
+ }
+ table.RowCount = count
+
+ // Get collection data size and total index size in byte.
+ dataSize, totalIndexSize, err := driver.getCollectionDataSizeAndIndexSizeInByte(ctx, databaseName, collectionName)
+ if err != nil {
+ return table, errors.Wrapf(err, "failed to get collection size and index size in byte of collection %s", collectionName)
+ }
+ table.DataSize = int64(dataSize)
+ table.IndexSize = int64(totalIndexSize)
+
+ // TODO(zp): sync Column and Index schema
+
+ return table, nil
+}
+
+// getCollectionDataSizeAndIndexSizeInByte returns the collection data size and total index size in bytes.
+func (driver *Driver) getCollectionDataSizeAndIndexSizeInByte(ctx context.Context, databaseName string, collectionName string) (int32, int32, error) {
+ database := driver.client.Database(databaseName)
+ command := bson.D{{
+ Key: "collStats",
+ Value: collectionName,
+ }}
+ var commandResult bson.M
+ if err := database.RunCommand(ctx, command).Decode(&commandResult); err != nil {
+ return 0, 0, errors.Wrap(err, "cannot run collStats command")
+ }
+ size, ok := commandResult["size"]
+ if !ok {
+ return 0, 0, errors.New("cannot get size from collStats command result")
+ }
+
+ totalIndexSize, ok := commandResult["totalIndexSize"]
+ if !ok {
+ return 0, 0, errors.New("cannot get totalIndexSize from collStats command result")
+ }
+ return size.(int32), totalIndexSize.(int32), nil
}
// getVersion returns the version of mongod or mongos instance.
@@ -114,19 +192,21 @@ func (driver *Driver) getUserMetaList(ctx context.Context) ([]db.User, error) {
return dbUserList, nil
}
-func flattenSystemDatabase() []string {
- var systemDatabaseList []string
- for databaseName := range systemDatabases {
- systemDatabaseList = append(systemDatabaseList, databaseName)
+// isDatabaseExist returns true if the database exists.
+func (driver *Driver) isDatabaseExist(ctx context.Context, databaseName string) (bool, error) {
+ filter := bson.M{"name": databaseName}
+ databaseList, err := driver.client.ListDatabaseNames(ctx, filter)
+ if err != nil {
+ return false, errors.Wrap(err, "failed to list database names")
}
- return systemDatabaseList
+ return len(databaseList) == 1, nil
}
-// getDatabaseList returns the list of databases.
-func (driver *Driver) getDatabaseList(ctx context.Context) ([]string, error) {
+// getNonSystemDatabaseList returns the list of non system databases.
+func (driver *Driver) getNonSystemDatabaseList(ctx context.Context) ([]string, error) {
filter := bson.M{
"name": bson.M{
- "$nin": append(flattenSystemDatabase(), "bytebase"),
+ "$nin": []string{"admin", "config", "local", "bytebase"},
},
}
return driver.client.ListDatabaseNames(ctx, filter)
diff --git a/resources/mysqlutil/resources_linux_arm64.go b/resources/mysqlutil/resources_linux_arm64.go
index 6b099f9ea4..1595232079 100644
--- a/resources/mysqlutil/resources_linux_arm64.go
+++ b/resources/mysqlutil/resources_linux_arm64.go
@@ -2,6 +2,7 @@ package mysqlutil
import "embed"
-//TODO(zp): We cheat go build here, we don't provide mysqlutil on linux arm64 now.
+// TODO(zp): We cheat go build here, we don't provide mysqlutil on linux arm64 now.
+//
//go:embed mysqlutil-8.0.28-linux-glibc2.17-x86_64.tar.gz
var resources embed.FS
diff --git a/server/runner/schemasync/syncer.go b/server/runner/schemasync/syncer.go
index a176a33a27..2ddea6a657 100644
--- a/server/runner/schemasync/syncer.go
+++ b/server/runner/schemasync/syncer.go
@@ -329,10 +329,6 @@ func (s *Syncer) syncInstanceSchema(ctx context.Context, instance *api.Instance,
// SyncDatabaseSchema will sync the schema for a database.
func (s *Syncer) SyncDatabaseSchema(ctx context.Context, instance *api.Instance, databaseName string, force bool) error {
- // TODO(zp): Support Sync Database Schema for MongoDB later.
- if instance.Engine == db.MongoDB {
- return nil
- }
driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, databaseName)
if err != nil {
return err