Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(mongodb): support create mongodb database (#3949)
h3n4ld160c86d468f
diff --git a/api/issue.go b/api/issue.goindex e37201de73..40f802b491 100644--- a/api/issue.go+++ b/api/issue.go@@ -133,6 +133,9 @@ type CreateDatabaseContext struct {InstanceID int `json:"instanceId"`// DatabaseName is the name of the database.DatabaseName string `json:"databaseName"`+ // TableName is the name of the table, if it is not empty, Bytebase should create a table after creating the database.+ // For example, in MongoDB, it only creates the database when we first store data in that database.+ TableName string `json:"tableName"`// CharacterSet is the character set of the database.CharacterSet string `json:"characterSet"`// Collation is the collation of the database.diff --git a/api/task.go b/api/task.goindex d8b36f9827..6eff26fe24 100644--- a/api/task.go+++ b/api/task.go@@ -101,6 +101,7 @@ type TaskDatabaseCreatePayload struct {// The project owning the database.ProjectID int `json:"projectId,omitempty"`DatabaseName string `json:"databaseName,omitempty"`+ TableName string `json:"tableName,omitempty"`Statement string `json:"statement,omitempty"`CharacterSet string `json:"character,omitempty"`Collation string `json:"collation,omitempty"`diff --git a/frontend/src/components/CreateDatabasePrepForm.vue b/frontend/src/components/CreateDatabasePrepForm.vueindex 2453525658..3bc17a47c3 100644--- a/frontend/src/components/CreateDatabasePrepForm.vue+++ b/frontend/src/components/CreateDatabasePrepForm.vue@@ -51,10 +51,10 @@<span class="text-red-600">*</span></label><input- id="name"+ id="databaseName"v-model="state.databaseName"required- name="name"+ name="databaseName"type="text"class="textfield mt-1 w-full"/>@@ -67,6 +67,21 @@</span></div>+ <div v-if="selectedInstance.engine == 'MONGODB'" class="w-full">+ <label for="name" class="textlabel">+ {{ $t("create-db.new-collection-name") }}+ <span class="text-red-600">*</span>+ </label>+ <input+ id="tableName"+ v-model="state.tableName"+ required+ name="tableName"+ type="text"+ class="textfield mt-1 w-full"+ />+ </div>+<div v-if="selectedInstance.engine == 'CLICKHOUSE'" class="w-full"><label for="name" class="textlabel">{{ $t("create-db.cluster") }}@@ -155,12 +170,7 @@filter="optional"/>- <template- v-if="- selectedInstance.engine != 'CLICKHOUSE' &&- selectedInstance.engine != 'SNOWFLAKE'- "- >+ <template v-if="showCollationAndCharacterSet"><div class="w-full"><label for="charset" class="textlabel">{{@@ -304,6 +314,7 @@ interface LocalState {instanceUserId?: InstanceUserId;labelList: DatabaseLabel[];databaseName: string;+ tableName: string;characterSet: string;collation: string;cluster: string;@@ -378,6 +389,7 @@ export default defineComponent({environmentId: props.environmentId,instanceId: props.instanceId,labelList: [],+ tableName: "",characterSet: "",collation: "",cluster: "",@@ -464,6 +476,18 @@ export default defineComponent({: (unknown("INSTANCE") as Instance);});+ const showCollationAndCharacterSet = computed((): boolean => {+ const instance = selectedInstance.value;+ if (instance.id === UNKNOWN_ID) {+ return true;+ }+ return (+ instance.engine !== "MONGODB" &&+ instance.engine !== "CLICKHOUSE" &&+ instance.engine !== "SNOWFLAKE"+ );+ });+const requireDatabaseOwnerName = computed((): boolean => {const instance = selectedInstance.value;if (instance.id === UNKNOWN_ID) {@@ -514,6 +538,7 @@ export default defineComponent({const databaseName = isDbNameTemplateMode.value? generatedDatabaseName.value: state.databaseName;+ const tableName = state.tableName;const instanceId = state.instanceId as InstanceId;let owner = "";if (requireDatabaseOwnerName.value && state.instanceUserId) {@@ -536,6 +561,7 @@ export default defineComponent({const createDatabaseContext: CreateDatabaseContext = {instanceId: instanceId,databaseName: databaseName,+ tableName: tableName,owner,characterSet:state.characterSet || defaultCharset(selectedInstance.value.engine),@@ -628,6 +654,7 @@ export default defineComponent({allowEditEnvironment,allowEditInstance,selectedInstance,+ showCollationAndCharacterSet,requireDatabaseOwnerName,showAssigneeSelect,selectProject,diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 3406d45b6a..0f613e0b24 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -627,7 +627,8 @@"reserved-db-error": "{databaseName} is a reserved name","generated-database-name": "Generated database name","db-name-generated-by-template": "Generated by template \"{template}\"",- "input-label-value": "Input {key}"+ "input-label-value": "Input {key}",+ "new-collection-name": "New Collection Name"},"db": {"encoding": "Encoding",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex d977efd72e..e291e106c2 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -622,6 +622,7 @@},"create-db": {"new-database-name": "新数据库名称",+ "new-collection-name": "新集合名称","database-owner-name": "数据库所有者","cluster": "集群","reserved-db-error": "{databaseName} 是一个预留名称",diff --git a/frontend/src/types/issue.ts b/frontend/src/types/issue.tsindex e623689915..1a81e79df5 100644--- a/frontend/src/types/issue.ts+++ b/frontend/src/types/issue.ts@@ -36,6 +36,7 @@ export type IssueStatus = "OPEN" | "DONE" | "CANCELED";export type CreateDatabaseContext = {instanceId: InstanceId;databaseName: string;+ tableName: string;// Only applicable to PostgreSQL for "WITH OWNER <<owner>>"owner: string;characterSet: string;diff --git a/plugin/advisor/utils_for_tests.go b/plugin/advisor/utils_for_tests.goindex dbb8671144..fffe1d9b79 100644--- a/plugin/advisor/utils_for_tests.go+++ b/plugin/advisor/utils_for_tests.go@@ -233,6 +233,11 @@ func (*MockDriver) Ping(_ context.Context) error {return nil}+// GetType implements the Driver interface.+func (*MockDriver) GetType() database.Type {+ return database.Type("MOCK")+}+// GetDBConnection implements the Driver interface.func (*MockDriver) GetDBConnection(_ context.Context, _ string) (*sql.DB, error) {return nil, nildiff --git a/plugin/db/clickhouse/clickhouse.go b/plugin/db/clickhouse/clickhouse.goindex 6a79f96bb9..b2abf508ca 100644--- a/plugin/db/clickhouse/clickhouse.go+++ b/plugin/db/clickhouse/clickhouse.go@@ -96,6 +96,11 @@ func (driver *Driver) Ping(ctx context.Context) error {return driver.db.PingContext(ctx)}+// GetType returns the database type.+func (*Driver) GetType() db.Type {+ return db.ClickHouse+}+// GetDBConnection gets a database connection.func (driver *Driver) GetDBConnection(context.Context, string) (*sql.DB, error) {return driver.db, nildiff --git a/plugin/db/driver.go b/plugin/db/driver.goindex 4adcb9c2fc..08bfb7176b 100644--- a/plugin/db/driver.go+++ b/plugin/db/driver.go@@ -173,7 +173,7 @@ var (// DriverConfig is the driver configuration.type DriverConfig struct {- // The directiory contains db specific utilites (e.g. mysqldump for MySQL, pg_dump for PostgreSQL).+ // The directiory contains db specific utilites (e.g. mysqldump for MySQL, pg_dump for PostgreSQL, mongosh for MongoDB).DbBinDir string// NOTE, introducing db specific fields is the last resort.@@ -488,6 +488,7 @@ type Driver interface {// Remember to call Close to avoid connection leakClose(ctx context.Context) errorPing(ctx context.Context) error+ GetType() TypeGetDBConnection(ctx context.Context, database string) (*sql.DB, error)// Execute will execute the statement. For CREATE DATABASE statement, some types of databases such as Postgres// will not use transactions to execute the statement but will still use transactions to execute the rest of statements.diff --git a/plugin/db/mongodb/collmod_migrationHistory_collection_command.json b/plugin/db/mongodb/collmod_migrationHistory_collection_command.jsonindex 0ab55d9dd1..c551f72337 100644--- a/plugin/db/mongodb/collmod_migrationHistory_collection_command.json+++ b/plugin/db/mongodb/collmod_migrationHistory_collection_command.json@@ -5,6 +5,7 @@"title": "Bytebase Migration History Object Validation","required": ["_id",+ "id","created_by","created_ts","updated_by",@@ -18,7 +19,7 @@"version","description","statement",- "executon_duration_ns",+ "execution_duration_ns","issue_id","payload"],@@ -26,17 +27,21 @@"_id": {"bsonType": "objectId"},+ "id": {+ "bsonType": "long",+ "minimum": 0+ },"created_by": {"bsonType": "string"},"created_ts": {- "bsonType": "long"+ "bsonType": "timestamp"},"updated_by": {"bsonType": "string"},"updated_ts": {- "bsonType": "long"+ "bsonType": "timestamp"},"release_version": {"bsonType": "string"diff --git a/plugin/db/mongodb/create_index_on_migrationHistory_collection_command.json b/plugin/db/mongodb/create_index_on_migrationHistory_collection_command.jsonindex 4746189ee7..c64f95cf6a 100644--- a/plugin/db/mongodb/create_index_on_migrationHistory_collection_command.json+++ b/plugin/db/mongodb/create_index_on_migrationHistory_collection_command.json@@ -1,6 +1,13 @@{"createIndexes": "migration_history","indexes": [+ {+ "key": {+ "id": 1+ },+ "name": "bytebase_idx_unique_migration_history_id",+ "unique": true+ },{"key": {"namespace": 1,diff --git a/plugin/db/mongodb/migrate.go b/plugin/db/mongodb/migrate.goindex 6d7a89311d..6e5acdc103 100644--- a/plugin/db/mongodb/migrate.go+++ b/plugin/db/mongodb/migrate.go@@ -2,17 +2,24 @@ package mongodbimport ("context"+ "database/sql"+ "strconv"+ "time"// embed will embeds the migration schema._ "embed""go.mongodb.org/mongo-driver/bson"+ "go.mongodb.org/mongo-driver/bson/primitive"+ "go.mongodb.org/mongo-driver/mongo"+ "go.mongodb.org/mongo-driver/mongo/options""go.uber.org/zap""github.com/pkg/errors""github.com/bytebase/bytebase/common/log""github.com/bytebase/bytebase/plugin/db"+ "github.com/bytebase/bytebase/plugin/db/util")const (@@ -27,8 +34,31 @@ var (collmodMigrationHistoryCollectionCommand string//go:embed create_index_on_migrationHistory_collection_command.jsoncreateIndexOnMigrationHistoryCollectionCommand string++ _ util.MigrationExecutor = (*Driver)(nil))+// MigrationHistory is the migration history record in MongoDB.+type MigrationHistory struct {+ ID int64 `bson:"id"`+ CreatedBy string `bson:"created_by"`+ CreatedTs primitive.Timestamp `bson:"created_ts"`+ UpdatedBy string `bson:"updated_by"`+ UpdatedTs primitive.Timestamp `bson:"updated_ts"`+ ReleaseVersion string `bson:"release_version"`+ Namespace string `bson:"namespace"`+ Sequence int64 `bson:"sequence"`+ Source string `bson:"source"`+ Type string `bson:"type"`+ Status string `bson:"status"`+ Version string `bson:"version"`+ Description string `bson:"description"`+ Statement string `bson:"statement"`+ ExecutionDurationNs int64 `bson:"execution_duration_ns"`+ IssueID string `bson:"issue_id"`+ Payload string `bson:"payload"`+}+// NeedsSetupMigration returns whether the driver needs to setup migration.func (driver *Driver) NeedsSetupMigration(ctx context.Context) (bool, error) {database := driver.client.Database(migrationHistoryDefaultDatabase)@@ -85,16 +115,319 @@ func (driver *Driver) SetupMigrationIfNeeded(ctx context.Context) error {}// ExecuteMigration executes a migration.-func (*Driver) ExecuteMigration(_ context.Context, _ *db.MigrationInfo, _ string) (int64, string, error) {- panic("not implemented")+func (driver *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (int64, string, error) {+ return util.ExecuteMigration(ctx, driver, m, statement, migrationHistoryDefaultDatabase)}// FindMigrationHistoryList finds the migration history list.-func (*Driver) FindMigrationHistoryList(_ context.Context, _ *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {- // TODO(zp): implement- return []*db.MigrationHistory{+func (driver *Driver) FindMigrationHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {+ database := driver.client.Database(migrationHistoryDefaultDatabase)+ collection := database.Collection(migrationHistoryDefaultCollection)+ filter := bson.M{}+ if v := find.ID; v != nil {+ id, err := primitive.ObjectIDFromHex(strconv.Itoa(*v))+ if err != nil {+ return nil, errors.Wrapf(err, "failed to convert id %q to object id", strconv.Itoa(*v))+ }+ filter["id"] = id+ }+ if v := find.Database; v != nil {+ filter["namespace"] = *v+ }+ if v := find.Version; v != nil {+ storedVersion, err := util.ToStoredVersion(false, *v, "")+ if err != nil {+ return nil, err+ }+ filter["version"] = storedVersion+ }+ if v := find.Source; v != nil {+ filter["source"] = *v+ }+ findOptions := []*options.FindOptions{+ // Sort by id in descending order.+ options.Find().SetSort(bson.M{"id": -1}),+ }+ if v := find.Limit; v != nil {+ findOptions = append(findOptions, options.Find().SetLimit(int64(*v)))+ }++ cursor, err := collection.Find(ctx, filter, findOptions...)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to find migration history list")+ }+ defer cursor.Close(ctx)++ var migrationHistoryList []*db.MigrationHistory+ for cursor.Next(ctx) {+ var history MigrationHistory+ if err := cursor.Decode(&history); err != nil {+ return nil, errors.Wrapf(err, "failed to decode migration history")+ }+ migrationHistory := convertMigrationHistory(history)+ migrationHistoryList = append(migrationHistoryList, &migrationHistory)+ }++ return migrationHistoryList, nil+}++func convertMigrationHistory(history MigrationHistory) db.MigrationHistory {+ return db.MigrationHistory{+ ID: int(history.ID),+ Creator: history.CreatedBy,+ CreatedTs: int64(history.CreatedTs.T),+ Updater: history.UpdatedBy,+ UpdatedTs: int64(history.UpdatedTs.T),+ ReleaseVersion: history.ReleaseVersion,+ Namespace: history.Namespace,+ Sequence: int(history.Sequence),+ Source: db.MigrationSource(history.Source),+ Type: db.MigrationType(history.Type),+ Status: db.MigrationStatus(history.Status),+ Version: history.Version,+ Description: history.Description,+ Statement: history.Statement,+ ExecutionDurationNs: history.ExecutionDurationNs,+ IssueID: history.IssueID,+ Payload: history.Payload,+ }+}++// FindLargestSequence finds the largest sequence, return 0 if not found.+func (driver *Driver) FindLargestSequence(ctx context.Context, _ *sql.Tx, namespace string, baseline bool) (int, error) {+ collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)+ filter := bson.M{+ "namespace": namespace,+ }+ if baseline {+ filter["type"] = bson.M{"$in": []string{string(db.Baseline), string(db.Branch)}}+ }++ // Set up MAX(sequence) aggregation.+ aggregation := []bson.M{+ {+ "$match": filter,+ },+ {+ "$group": bson.M{+ "_id": nil,+ "sequence": bson.M{"$max": "$sequence"},+ },+ },+ }++ cursor, err := collection.Aggregate(ctx, aggregation)+ if err != nil {+ return 0, errors.Wrapf(err, "failed to aggregate migration history list to find largest sequence")+ }+ defer cursor.Close(ctx)++ var result bson.M+ if cursor.Next(ctx) {+ if err := cursor.Decode(&result); err != nil {+ return 0, errors.Wrapf(err, "failed to decode find largest sequence aggregation result")+ }+ if sequence, ok := result["sequence"]; ok {+ if sequenceInt, ok := sequence.(int64); ok {+ return int(sequenceInt), nil+ }+ }+ return 0, errors.Errorf("failed to get sequence from find largest sequence aggregation result: %+v", result)+ }+ // If cursor contains no data, we check the err, if err is nil, it means that the query is successful, but there is no data.+ if err := cursor.Err(); err != nil {+ return 0, errors.Wrapf(err, "failed to find largest sequence")+ }+ return 0, nil+}++// FindLargestVersionSinceBaseline will find the largest version since last baseline or branch.+func (driver *Driver) FindLargestVersionSinceBaseline(ctx context.Context, tx *sql.Tx, namespace string) (*string, error) {+ collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)+ largestBaselineSeuqence, err := driver.FindLargestSequence(ctx, tx, namespace, true /* baseline */)+ if err != nil {+ return nil, err+ }+ filter := bson.M{+ "namespace": namespace,+ "sequence": bson.M{"$gte": largestBaselineSeuqence},+ }+ // Set up MAX(version) aggregation.+ aggregation := []bson.M{+ {+ "$match": filter,+ },+ {+ "$group": bson.M{+ "_id": nil,+ "version": bson.M{"$max": "$version"},+ },+ },+ }+ cursor, err := collection.Aggregate(ctx, aggregation)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to aggregate migration history list to find largest version since baseline")+ }+ defer cursor.Close(ctx)++ if cursor.Next(ctx) {+ var result bson.M+ if err := cursor.Decode(&result); err != nil {+ return nil, errors.Wrapf(err, "failed to decode find largest version since baseline aggregation result")+ }+ if version, ok := result["version"]; ok {+ if versionStr, ok := version.(string); ok {+ return &versionStr, nil+ }+ }+ return nil, errors.Errorf("failed to get version from find largest version since baseline aggregation result: %v", result)+ }+ // If cursor contains no data, we check the err, if err is nil, it means that the query is successful, but there is no data.+ if err := cursor.Err(); err != nil {+ return nil, errors.Wrapf(err, "failed to find largest version since baseline")+ }+ return nil, nil+}++// InsertPendingHistory will insert the migration record with pending status and return the inserted ID.+func (driver *Driver) InsertPendingHistory(ctx context.Context, _ *sql.Tx, sequence int, _ string, m *db.MigrationInfo, storedVersion, statement string) (insertedID int64, err error) {+ collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)++ retryTimes := 3+ for i := 0; i < retryTimes; i++ {+ currentTimestamp := getMongoTimestamp()+ nextID, err := driver.getMigrationHistoryNextID(ctx)+ if err != nil {+ return 0, errors.Wrapf(err, "failed to get next migration history ID")+ }++ document := bson.M{+ "id": nextID,+ "created_by": m.Creator,+ "created_ts": currentTimestamp,+ "updated_by": m.Creator,+ "updated_ts": currentTimestamp,+ "release_version": m.ReleaseVersion,+ "namespace": m.Namespace,+ "sequence": int64(sequence),+ "source": m.Source,+ "type": m.Type,+ "status": db.Pending,+ "version": storedVersion,+ "description": m.Description,+ "statement": statement,+ "execution_duration_ns": int64(0),+ "issue_id": m.IssueID,+ "payload": m.Payload,+ }+ if _, err = collection.InsertOne(ctx, document); err != nil {+ // Detect if it's a duplicate key error.+ if driverErr, ok := err.(mongo.WriteException); ok {+ find := false+ for _, writeErr := range driverErr.WriteErrors {+ if writeErr.Code == 121 {+ log.Info("Duplicate key error with migration_history id: %d, retrying...", zap.Int64("id", nextID))+ find = true+ break+ }+ }+ if find {+ continue+ }+ }+ return 0, errors.Wrapf(err, "failed to insert a pending migration history record")+ }+ return nextID, nil+ }+ return 0, errors.Errorf("failed to insert a pending migration history record because of the duplidate id after %d retries", retryTimes)+}++// UpdateHistoryAsDone will update the migration record as done.+func (driver *Driver) UpdateHistoryAsDone(ctx context.Context, _ *sql.Tx, migrationDurationNs int64, _ string, insertedID int64) error {+ collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)+ filter := bson.M{+ "id": insertedID,+ }+ update := bson.M{+ "$set": bson.M{+ "status": db.Done,+ "execution_duration_ns": migrationDurationNs,+ },+ }++ updateResult, err := collection.UpdateOne(ctx, filter, update)+ if err != nil {+ return errors.Wrapf(err, "failed to update a migration history as done")+ }+ if updateResult.MatchedCount == 0 {+ return errors.Errorf("failed to find a migration history record to mark as done with ID %d ", insertedID)+ }+ return nil+}++// UpdateHistoryAsFailed will update the migration record as failed.+func (driver *Driver) UpdateHistoryAsFailed(ctx context.Context, _ *sql.Tx, migrationDurationNs int64, insertedID int64) error {+ collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)+ filter := bson.M{+ "id": insertedID,+ }+ update := bson.M{+ "$set": bson.M{+ "status": db.Failed,+ "execution_duration_ns": migrationDurationNs,+ },+ }+ updateResult, err := collection.UpdateOne(ctx, filter, update)+ if err != nil {+ return errors.Wrapf(err, "failed to update a migration history as failed")+ }+ if updateResult.MatchedCount == 0 {+ return errors.Errorf("failed to find a migration history record to mark as failed with ID %d ", insertedID)+ }+ return nil+}++func getMongoTimestamp() primitive.Timestamp {+ return primitive.Timestamp{T: uint32(time.Now().Unix()), I: 1}+}++// getMigrationHistoryNextID will get the next ID for the migration history.+// In RDBMS, it is usually auto-increment, but in MongoDB, we need to maintain the ID by ourselves.+// Multiple goroutines may call this function at the same time and the ID may be duplicated.+// It's caller's responsibility to handle the duplicated ID, likes retry.+func (driver *Driver) getMigrationHistoryNextID(ctx context.Context) (int64, error) {+ collection := driver.client.Database(migrationHistoryDefaultDatabase).Collection(migrationHistoryDefaultCollection)+ // Set up MAX(id) aggregation.+ aggregation := []bson.M{{- Version: "0000.0000.0000-FAKEIMPLEMENT",+ "$group": bson.M{+ "_id": nil,+ "id": bson.M{"$max": "$id"},+ },},- }, nil+ }+ cursor, err := collection.Aggregate(ctx, aggregation)+ if err != nil {+ return 0, errors.Wrapf(err, "failed to aggregate migration history list to find largest ID")+ }+ defer cursor.Close(ctx)++ if cursor.Next(ctx) {+ var result bson.M+ if err := cursor.Decode(&result); err != nil {+ return 0, errors.Wrapf(err, "failed to decode find largest ID aggregation result")+ }+ if resultID, ok := result["id"]; ok {+ if id, ok := resultID.(int64); ok {+ return id + 1, nil+ }+ }+ return 0, errors.Errorf("failed to get ID from find largest ID aggregation result: %v", result)+ }+ // If cursor contains no data, we check the err, if err is nil, it means that the query is successful, but there is no data.+ if err := cursor.Err(); err != nil {+ return 0, errors.Wrapf(err, "failed to find largest ID")+ }+ // Return 1 if there is no data.+ return 1, nil}diff --git a/plugin/db/mongodb/mongodb.go b/plugin/db/mongodb/mongodb.goindex c32488c77a..15ec68a3a8 100644--- a/plugin/db/mongodb/mongodb.go+++ b/plugin/db/mongodb/mongodb.go@@ -2,10 +2,13 @@package mongodbimport (+ "bytes""context""database/sql""fmt""io"+ "os"+ "os/exec""strings""go.mongodb.org/mongo-driver/mongo"@@ -14,6 +17,7 @@ import ("github.com/pkg/errors""github.com/bytebase/bytebase/plugin/db"+ "github.com/bytebase/bytebase/resources/mongoutil")var (@@ -28,12 +32,14 @@ func init() {// Driver is the MongoDB driver.type Driver struct {+ dbBinDir stringconnectionCtx db.ConnectionContext+ connCfg db.ConnectionConfigclient *mongo.Client}-func newDriver(_ db.DriverConfig) db.Driver {- return &Driver{}+func newDriver(dc db.DriverConfig) db.Driver {+ return &Driver{dbBinDir: dc.DbBinDir}}// Open opens a MongoDB driver.@@ -46,6 +52,7 @@ func (driver *Driver) Open(ctx context.Context, _ db.Type, connCfg db.Connection}driver.client = clientdriver.connectionCtx = connCtx+ driver.connCfg = connCfgreturn driver, nil}@@ -65,14 +72,58 @@ func (driver *Driver) Ping(ctx context.Context) error {return nil}+// GetType returns the database type.+func (*Driver) GetType() db.Type {+ return db.MongoDB+}+// GetDBConnection returns a database connection.+// It always return nil because it has not implemented the SQL interface, and we always return error, it's caller's responsibility to+// avoid calling this function for MongoDB.func (*Driver) GetDBConnection(_ context.Context, _ string) (*sql.DB, error) {- panic("not implemented")+ return nil, errors.New("mongodb doesn't support GetDBConnection")}-// Execute executes a statement.-func (*Driver) Execute(_ context.Context, _ string, _ bool) (int64, error) {- panic("not implemented")+// Execute executes a statement, always returns 0 as the number of rows affected because we execute the statement by mongosh, it's hard to catch the row effected number.+func (driver *Driver) Execute(_ context.Context, statement string, _ bool) (int64, error) {+ connectionURI := getMongoDBConnectionURI(driver.connCfg)+ // For MongoDB, we execute the statement in mongosh, which is a shell for MongoDB.+ // There are some ways to execute the statement in mongosh:+ // 1. Use the --eval option to execute the statement.+ // 2. Use the --file option to execute the statement from a file.+ // We choose the second way with the following reasons:+ // 1. The statement may too long to be executed in the command line.+ // 2. We cannot catch the error from the --eval option.++ // First, we create a temporary file to store the statement.+ tempDir := os.TempDir()+ tempFile, err := os.CreateTemp(tempDir, "mongodb-statement")+ if err != nil {+ return 0, errors.Wrap(err, "failed to create temporary file")+ }+ defer os.Remove(tempFile.Name())+ if _, err := tempFile.WriteString(statement); err != nil {+ return 0, errors.Wrap(err, "failed to write statement to temporary file")+ }+ if err := tempFile.Close(); err != nil {+ return 0, errors.Wrap(err, "failed to close temporary file")+ }++ // Then, we execute the statement in mongosh.+ mongoshArgs := []string{+ connectionURI,+ "--quiet",+ "--file",+ tempFile.Name(),+ }+ // We don't use the CommandContext here because the statement may take a long time to execute.+ mongoshCmd := exec.Command(mongoutil.GetMongoshPath(driver.dbBinDir), mongoshArgs...)+ var errContent bytes.Buffer+ mongoshCmd.Stderr = &errContent+ if err := mongoshCmd.Run(); err != nil {+ return 0, errors.Wrapf(err, "failed to execute statement in mongosh: %s", errContent.String())+ }+ return 0, nil}// Query queries a statement.diff --git a/plugin/db/mongodb/sync.go b/plugin/db/mongodb/sync.goindex 3666c304d4..c728af895c 100644--- a/plugin/db/mongodb/sync.go+++ b/plugin/db/mongodb/sync.go@@ -143,6 +143,7 @@ func (driver *Driver) syncAllIndexSchema(ctx context.Context, databaseName, collif err != nil {return nil, errors.Wrap(err, "failed to list indexes")}+ defer indexCursor.Close(ctx)var indexList []db.Indexfor indexCursor.Next(ctx) {diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.goindex 728d7dd5e6..1ec8f3e9a3 100644--- a/plugin/db/mysql/mysql.go+++ b/plugin/db/mysql/mysql.go@@ -125,6 +125,11 @@ func (driver *Driver) Ping(ctx context.Context) error {return driver.db.PingContext(ctx)}+// GetType returns the database type.+func (driver *Driver) GetType() db.Type {+ return driver.dbType+}+// GetDBConnection gets a database connection.func (driver *Driver) GetDBConnection(context.Context, string) (*sql.DB, error) {return driver.db, nildiff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.goindex a0123f3f91..bd0aeecdbb 100644--- a/plugin/db/pg/pg.go+++ b/plugin/db/pg/pg.go@@ -183,6 +183,11 @@ func (driver *Driver) Ping(ctx context.Context) error {return driver.db.PingContext(ctx)}+// GetType returns the database type.+func (*Driver) GetType() db.Type {+ return db.Postgres+}+// GetDBConnection gets a database connection.func (driver *Driver) GetDBConnection(_ context.Context, database string) (*sql.DB, error) {if err := driver.switchDatabase(database); err != nil {diff --git a/plugin/db/snowflake/snowflake.go b/plugin/db/snowflake/snowflake.goindex dc75e4463a..8c05bbffd4 100644--- a/plugin/db/snowflake/snowflake.go+++ b/plugin/db/snowflake/snowflake.go@@ -103,6 +103,11 @@ func (driver *Driver) Ping(ctx context.Context) error {return driver.db.PingContext(ctx)}+// GetType returns the database type.+func (*Driver) GetType() db.Type {+ return db.Snowflake+}+// GetDBConnection gets a database connection.func (driver *Driver) GetDBConnection(context.Context, string) (*sql.DB, error) {return driver.db, nildiff --git a/plugin/db/sqlite/sqlite.go b/plugin/db/sqlite/sqlite.goindex c5329e8caa..3d02053c31 100644--- a/plugin/db/sqlite/sqlite.go+++ b/plugin/db/sqlite/sqlite.go@@ -66,6 +66,11 @@ func (driver *Driver) Ping(ctx context.Context) error {return driver.db.PingContext(ctx)}+// GetType returns the database type.+func (*Driver) GetType() db.Type {+ return db.SQLite+}+// GetDBConnection gets a database connection.// If database is empty, we will get a connect to in-memory database.func (driver *Driver) GetDBConnection(_ context.Context, database string) (*sql.DB, error) {diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.goindex 8e7c82592f..adc6f46c59 100644--- a/plugin/db/util/driverutil.go+++ b/plugin/db/util/driverutil.go@@ -153,8 +153,8 @@ type MigrationExecutor interface {// Returns the created migration history id and the updated schema on success.func ExecuteMigration(ctx context.Context, executor MigrationExecutor, m *db.MigrationInfo, statement string, databaseName string) (migrationHistoryID int64, updatedSchema string, resErr error) {var prevSchemaBuf bytes.Buffer- // Don't record schema if the database hasn't exist yet.- if !m.CreateDatabase {+ // Don't record schema if the database hasn't existed yet or is schemaless (e.g. Mongo).+ if !m.CreateDatabase && executor.GetType() != db.MongoDB {// For baseline migration, we also record the live schema to detect the schema drift.// See https://bytebase.com/blog/what-is-database-schema-driftif _, err := executor.Dump(ctx, m.Database, &prevSchemaBuf, true /*schemaOnly*/); err != nil {@@ -196,6 +196,7 @@ func ExecuteMigration(ctx context.Context, executor MigrationExecutor, m *db.Mig}if doMigrate {// Switch to the target database only if we're NOT creating this target database.+ // We should not call GetDBConnection() if the instance is MongoDB because it doesn't support.if !m.CreateDatabase {if _, err := executor.GetDBConnection(ctx, m.Database); err != nil {return -1, "", err@@ -206,6 +207,10 @@ func ExecuteMigration(ctx context.Context, executor MigrationExecutor, m *db.Mig}}+ if executor.GetType() == db.MongoDB {+ // Skip schema dump for MongoDB because it's schemaless.+ return insertedID, "", nil+ }// Phase 4 - Dump the schema after migrationvar afterSchemaBuf bytes.Bufferif _, err := executor.Dump(ctx, m.Database, &afterSchemaBuf, true /*schemaOnly*/); err != nil {@@ -256,16 +261,24 @@ func BeginMigration(ctx context.Context, executor MigrationExecutor, m *db.Migra}}- sqldb, err := executor.GetDBConnection(ctx, databaseName)- if err != nil {- return -1, err- }- // From a concurrency perspective, there's no difference between using transaction or not. However, we use transaction here to save some code of starting a transaction inside each db engine executor.- tx, err := sqldb.BeginTx(ctx, nil)- if err != nil {- return -1, err+ var tx *sql.Tx+ // We don't use transaction for MongoDB for the following reasons:+ // 1. MongoDB support transaction only in replica set mode or shard cluster mode. But we need to+ // support standalone mode as well. https://stackoverflow.com/a/51462024/19075342+ // 2. We use mongodb driver, it has not implemented the SQL interface. So we can't use the same code.+ if executor.GetType() != db.MongoDB {+ // We use transaction here for the RDBMS.+ sqldb, err := executor.GetDBConnection(ctx, databaseName)+ if err != nil {+ return -1, err+ }+ // From a concurrency perspective, there's no difference between using transaction or not. However, we use transaction here to save some code of starting a transaction inside each db engine executor.+ tx, err = sqldb.BeginTx(ctx, nil)+ if err != nil {+ return -1, err+ }+ defer tx.Rollback()}- defer tx.Rollback()largestSequence, err := executor.FindLargestSequence(ctx, tx, m.Namespace, false /* baseline */)if err != nil {@@ -289,8 +302,10 @@ func BeginMigration(ctx context.Context, executor MigrationExecutor, m *db.Migrareturn -1, err}- if err := tx.Commit(); err != nil {- return -1, err+ if executor.GetType() != db.MongoDB {+ if err := tx.Commit(); err != nil {+ return -1, err+ }}return insertedID, nil@@ -300,15 +315,22 @@ func BeginMigration(ctx context.Context, executor MigrationExecutor, m *db.Migrafunc EndMigration(ctx context.Context, executor MigrationExecutor, startedNs int64, migrationHistoryID int64, updatedSchema string, databaseName string, isDone bool) (err error) {migrationDurationNs := time.Now().UnixNano() - startedNs- sqldb, err := executor.GetDBConnection(ctx, databaseName)- if err != nil {- return err- }- tx, err := sqldb.BeginTx(ctx, nil)- if err != nil {- return err+ var tx *sql.Tx+ // We don't use transaction for MongoDB for the following reasons:+ // 1. MongoDB support transaction only in replica set mode or shard cluster mode. But we need to+ // support standalone mode as well. https://stackoverflow.com/a/51462024/19075342+ // 2. We use mongodb driver, it had not implment the sql interface. So we can't use the same code.+ if executor.GetType() != db.MongoDB {+ sqldb, err := executor.GetDBConnection(ctx, databaseName)+ if err != nil {+ return err+ }+ tx, err = sqldb.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer tx.Rollback()}- defer tx.Rollback()if isDone {// Upon success, update the migration history as 'DONE', execution_duration_ns, updated schema.@@ -321,8 +343,10 @@ func EndMigration(ctx context.Context, executor MigrationExecutor, startedNs intif err != nil {return err}-- return tx.Commit()+ if executor.GetType() != db.MongoDB {+ return tx.Commit()+ }+ return nil}// Query will execute a readonly / SELECT query.diff --git a/resources/mongoutil/mongoutil.go b/resources/mongoutil/mongoutil.goindex 14a65bbae4..14aa5e6d24 100644--- a/resources/mongoutil/mongoutil.go+++ b/resources/mongoutil/mongoutil.go@@ -32,7 +32,7 @@ func getTarNameAndVersion() (tarname string, version string, err error) {default:return "", "", errors.Errorf("unsupported platform: %s/%s", runtime.GOOS, runtime.GOARCH)}- return tarName, strings.TrimRight(tarName, "txz"), nil+ return tarName, strings.TrimRight(tarName, ".txz"), nil}// Install installs mongoutil in resourceDir.diff --git a/server/component/dbfactory/dbfactory.go b/server/component/dbfactory/dbfactory.goindex abe4e32c2c..25d6da5790 100644--- a/server/component/dbfactory/dbfactory.go+++ b/server/component/dbfactory/dbfactory.go@@ -13,13 +13,15 @@ import (type DBFactory struct {mysqlBinDir stringpgBinDir string+ mongoBinDir stringdataDir string}// New creates a new database driver factory.-func New(mysqlBinDir, pgBinDir, dataDir string) *DBFactory {+func New(mysqlBinDir, mongoBinDir, pgBinDir, dataDir string) *DBFactory {return &DBFactory{mysqlBinDir: mysqlBinDir,+ mongoBinDir: mongoBinDir,pgBinDir: pgBinDir,dataDir: dataDir,}@@ -39,6 +41,8 @@ func (d *DBFactory) GetAdminDatabaseDriver(ctx context.Context, instance *api.IndbBinDir = d.mysqlBinDircase db.Postgres:dbBinDir = d.pgBinDir+ case db.MongoDB:+ dbBinDir = d.mongoBinDir}if databaseName == "" {diff --git a/server/issue.go b/server/issue.goindex 79613edade..fc701e4ee6 100644--- a/server/issue.go+++ b/server/issue.go@@ -600,6 +600,11 @@ func (s *Server) getPipelineCreateForDatabaseCreate(ctx context.Context, issueCrif instance == nil {return nil, errors.Errorf("instance ID not found %v", c.InstanceID)}++ if instance.Engine == db.MongoDB && c.TableName == "" {+ return nil, echo.NewHTTPError(http.StatusBadRequest, "Failed to create issue, collection name missing for MongoDB")+ }+// Find project.project, err := s.store.GetProjectByID(ctx, issueCreate.ProjectID)if err != nil {@@ -1006,6 +1011,9 @@ func (s *Server) createDatabaseCreateTaskList(ctx context.Context, c api.CreateD// Snowflake needs to use upper case of DatabaseName.c.DatabaseName = strings.ToUpper(c.DatabaseName)}+ if instance.Engine == db.MongoDB && c.TableName == "" {+ return nil, util.FormatError(common.Errorf(common.Invalid, "Failed to create issue, collection name missing for MongoDB"))+ }// Validate the labels. Labels are set upon task completion.if c.Labels != "" {if err := utils.SetDatabaseLabels(ctx, s.store, c.Labels, &api.Database{Name: c.DatabaseName, Instance: &instance} /* dummy database */, 0 /* dummy updaterID */, true /* validateOnly */); err != nil {@@ -1037,6 +1045,7 @@ func (s *Server) createDatabaseCreateTaskList(ctx context.Context, c api.CreateDpayload := api.TaskDatabaseCreatePayload{ProjectID: project.ID,CharacterSet: c.CharacterSet,+ TableName: c.TableName,Collation: c.Collation,Labels: c.Labels,DatabaseName: databaseName,@@ -1178,6 +1187,11 @@ func getCreateDatabaseStatement(dbType db.Type, createDatabaseContext api.Createcase db.SQLite:// This is a fake CREATE DATABASE and USE statement since a single SQLite file represents a database. Engine driver will recognize it and establish a connection to create the sqlite file representing the database.return fmt.Sprintf("CREATE DATABASE '%s';", databaseName), nil+ case db.MongoDB:+ // We just run createCollection in mongosh instead of execute `use <database>` first, because we execute the+ // mongodb statement in mongosh with --file flag, and it doesn't support `use <database>` statement in the file.+ // And we pass the database name to Bytebase engine driver, which will be used to build the connection string.+ return fmt.Sprintf(`db.createCollection("%s");`, createDatabaseContext.TableName), nil}return "", errors.Errorf("unsupported database type %s", dbType)}@@ -1252,7 +1266,7 @@ func checkCharacterSetCollationOwner(dbType db.Type, characterSet, collation, owif owner == "" {return errors.Errorf("database owner is required for PostgreSQL")}- case db.SQLite:+ case db.SQLite, db.MongoDB:// no-op.default:if characterSet == "" {diff --git a/server/runner/taskrun/database_create_executor.go b/server/runner/taskrun/database_create_executor.goindex 5ded54aba2..0526473c70 100644--- a/server/runner/taskrun/database_create_executor.go+++ b/server/runner/taskrun/database_create_executor.go@@ -54,9 +54,19 @@ func (exec *DatabaseCreateExecutor) RunOnce(ctx context.Context, task *api.Task)}instance := task.Instance- driver, err := exec.dbFactory.GetAdminDatabaseDriver(ctx, task.Instance, "" /* databaseName */)- if err != nil {- return true, nil, err+ var driver db.Driver+ if instance.Engine == db.MongoDB {+ // For MongoDB, it allows us to connect to the non-existing database. So we pass the database name to driver to let us connect to the specific database.+ // And run the create collection statement later.+ driver, err = exec.dbFactory.GetAdminDatabaseDriver(ctx, task.Instance, payload.DatabaseName)+ if err != nil {+ return true, nil, err+ }+ } else {+ driver, err = exec.dbFactory.GetAdminDatabaseDriver(ctx, task.Instance, "" /* databaseName */)+ if err != nil {+ return true, nil, err+ }}defer driver.Close(ctx)diff --git a/server/server.go b/server/server.goindex fd1203dc92..8b1b339f46 100644--- a/server/server.go+++ b/server/server.go@@ -34,6 +34,7 @@ import (metricCollector "github.com/bytebase/bytebase/metric/collector""github.com/bytebase/bytebase/plugin/app/feishu"bbs3 "github.com/bytebase/bytebase/plugin/storage/s3"+ "github.com/bytebase/bytebase/resources/mongoutil""github.com/bytebase/bytebase/resources/mysqlutil""github.com/bytebase/bytebase/resources/postgres""github.com/bytebase/bytebase/server/component/activity"@@ -122,6 +123,8 @@ type Server struct {// MySQL utility binariesmysqlBinDir string+ // MongoDB utility binaries+ mongoBinDir string// Postgres utility binariespgBinDir string@@ -209,6 +212,11 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {return nil, errors.Wrap(err, "cannot install mysql utility binaries")}+ s.mongoBinDir, err = mongoutil.Install(resourceDir)+ if err != nil {+ return nil, errors.Wrap(err, "cannot install mongo utility binaries")+ }+// Installs the Postgres and utility binaries and creates the 'activeProfile.pgUser' user/database// to store Bytebase's own metadata.log.Info(fmt.Sprintf("Installing Postgres OS %q Arch %q", runtime.GOOS, runtime.GOARCH))@@ -270,7 +278,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {s.workspaceID = config.workspaceIDs.ActivityManager = activity.NewManager(storeInstance, profile)- s.dbFactory = dbfactory.New(s.mysqlBinDir, s.pgBinDir, profile.DataDir)+ s.dbFactory = dbfactory.New(s.mysqlBinDir, s.mongoBinDir, s.pgBinDir, profile.DataDir)e := echo.New()e.Debug = profile.Debuge.HideBanner = true