diff --git a/gmm/builder.go b/gmm/builder.go index 1eb73d7..c3bc8d8 100644 --- a/gmm/builder.go +++ b/gmm/builder.go @@ -19,13 +19,14 @@ import ( // GMMBuilder struct for building and managing the mock MySQL server type GMMBuilder struct { - dbName string - port int - server *server.Server - sqlDB *sql.DB - gormDB *gorm.DB - err error - started atomic.Bool + dbName string + port int + server *server.Server + sqlDB *sql.DB + gormDB *gorm.DB + err error + started atomic.Bool + logSilent bool tables []schema.Tabler models []schema.Tabler @@ -37,11 +38,12 @@ type GMMBuilder struct { // if db name is not provided, gmm would generate a random db name. func Builder(db ...string) *GMMBuilder { b := &GMMBuilder{ - tables: make([]schema.Tabler, 0), - models: make([]schema.Tabler, 0), - sqlStmts: make([]string, 0), - sqlFiles: make([]string, 0), - started: atomic.Bool{}, + tables: make([]schema.Tabler, 0), + models: make([]schema.Tabler, 0), + sqlStmts: make([]string, 0), + sqlFiles: make([]string, 0), + started: atomic.Bool{}, + logSilent: true, } dbName := "gmm-test-db-" + uuid.NewString()[:6] if len(db) > 0 { @@ -58,6 +60,12 @@ func (b *GMMBuilder) Port(port int) *GMMBuilder { return b } +// LogSilent sets the log mode for the MySQL server, default is silent mode. +func (b *GMMBuilder) LogSilent(logSilent bool) *GMMBuilder { + b.logSilent = logSilent + return b +} + // Build initializes and starts the MySQL server, returns handles to SQL and Gorm DB func (b *GMMBuilder) Build() (sDB *sql.DB, gDB *gorm.DB, shutdown func(), err error) { if b.err != nil { @@ -104,7 +112,7 @@ func (b *GMMBuilder) Build() (sDB *sql.DB, gDB *gorm.DB, shutdown func(), err er } // Create client and connect to server - b.sqlDB, b.gormDB, err = createMySQLClient(b.port, b.dbName) + b.sqlDB, b.gormDB, err = createMySQLClient(b.port, b.dbName, b.logSilent) if err != nil { b.err = fmt.Errorf("failed to create sql client: %w", err) return nil, nil, nil, b.err diff --git a/gmm/client.go b/gmm/client.go index e3d7f4d..99c4c5d 100644 --- a/gmm/client.go +++ b/gmm/client.go @@ -6,16 +6,22 @@ import ( "gorm.io/driver/mysql" "gorm.io/gorm" + "gorm.io/gorm/logger" ) -func createMySQLClient(port int, dbName string) (sqlDB *sql.DB, gormDB *gorm.DB, err error) { +func createMySQLClient(port int, dbName string, logSilent bool) (sqlDB *sql.DB, gormDB *gorm.DB, err error) { dsn := fmt.Sprintf("root@tcp(127.0.0.1:%d)/%s", port, dbName) sqlDB, err = sql.Open("mysql", dsn) if err != nil { return nil, nil, fmt.Errorf("failed to open sql mysql client: %w", err) } - gormDB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) + gormConfig := &gorm.Config{} + if logSilent { + gormConfig.Logger = logger.Default.LogMode(logger.Silent) + } + + gormDB, err = gorm.Open(mysql.Open(dsn), gormConfig) if err != nil { return nil, nil, fmt.Errorf("failed to open gorm mysql client: %w", err) }