package store import ( "fmt" "os" "sync" "gorm.io/driver/postgres" "gorm.io/driver/sqlite" "gorm.io/gorm" ) const DB_TYPE string = "DB_TYPE" const DB_CONNECTION_SETTINGS string = "DB_CONNECTION_SETTINGS" const MAX_ACCOUNT_INDEX int = 4294967295 var db *gorm.DB var once sync.Once func Init() (*gorm.DB, error) { dbType, isDbTypePresent := os.LookupEnv(DB_TYPE) dbConn, isDbConnPresent := os.LookupEnv(DB_CONNECTION_SETTINGS) if !isDbConnPresent || !isDbTypePresent { return nil, fmt.Errorf("missing environment variables: %s=%s, %s=%s", DB_CONNECTION_SETTINGS, dbConn, DB_TYPE, dbType) } if db != nil { return db, nil } fmt.Println("dbType: ", dbType) fmt.Println("dbConn: ", dbConn) var _err error once.Do(func() { var dialect gorm.Dialector switch dbType { case "sqlite": dialect = sqlite.Open(dbConn) case "postgres": dialect = postgres.Open(dbConn) default: _err = fmt.Errorf("unknown database type: %s", dbType) return } _db, err := gorm.Open(dialect, &gorm.Config{}) if err != nil { _err = err return } db = _db db.AutoMigrate(&TronAccount{}) db.AutoMigrate(&EthereumAccount{}) db.AutoMigrate(&Webhook{}) }) if _err != nil { return nil, _err } return db, nil }