github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/db/mysql_adapter.go (about) 1 package db 2 3 import ( 4 "fmt" 5 "os" 6 "time" 7 8 "github.com/safedep/dry/log" 9 "github.com/safedep/dry/retry" 10 11 "gorm.io/driver/mysql" 12 "gorm.io/gorm" 13 14 "gorm.io/plugin/opentelemetry/tracing" 15 ) 16 17 type MySqlAdapter struct { 18 *baseSqlAdapter 19 20 db *gorm.DB 21 config MySqlAdapterConfig 22 } 23 24 type MySqlAdapterConfig struct { 25 Host string 26 Port int16 27 Username string 28 Password string 29 Database string 30 } 31 32 func NewMySqlAdapter(config MySqlAdapterConfig) (SqlDataAdapter, error) { 33 dsn := os.Getenv("DATABASE_URL") 34 if dsn == "" { 35 dsn = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", 36 config.Username, config.Password, config.Host, config.Port, config.Database) 37 log.Debugf("Connecting to MySQL database with %s@%s:%d", config.Username, config.Host, config.Port) 38 } else { 39 log.Debugf("Connecting to MySQL database with DSN from env") 40 } 41 42 var db *gorm.DB 43 var err error 44 45 retry.InvokeWithRetry(retry.RetryConfig{ 46 Count: 30, 47 Sleep: 1 * time.Second, 48 }, func(arg retry.RetryFuncArg) error { 49 db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) 50 if err != nil { 51 log.Debugf("[%d/%d] Failed to connect to MySQL server: %v", 52 arg.Current, arg.Total, err) 53 } 54 55 return err 56 }) 57 58 if err != nil { 59 return nil, err 60 } 61 62 if err := db.Use(tracing.NewPlugin(tracing.WithoutMetrics())); err != nil { 63 return nil, err 64 } 65 66 baseSqlAdapter := &baseSqlAdapter{db: db} 67 mysqlAdapter := &MySqlAdapter{db: db, config: config, baseSqlAdapter: baseSqlAdapter} 68 69 err = mysqlAdapter.Ping() 70 return mysqlAdapter, err 71 }