Init initializes DB connection instance and do migration at startup.
()
| 20 | |
| 21 | // Init initializes DB connection instance and do migration at startup. |
| 22 | func Init() { |
| 23 | if DB != nil { // initialized |
| 24 | return |
| 25 | } |
| 26 | dsn := config.GetDatabaseDSN(config.C.DB.Host) |
| 27 | var err error |
| 28 | |
| 29 | DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{}) |
| 30 | if err != nil { |
| 31 | l.Fatalf("Error when opening DB: %s\n", err.Error()) |
| 32 | } |
| 33 | |
| 34 | err = DB.AutoMigrate( |
| 35 | &Proof{}, |
| 36 | &ProofChain{}, |
| 37 | ) |
| 38 | if err != nil { |
| 39 | panic(err) |
| 40 | } |
| 41 | |
| 42 | readOnlyHost := lo.Sample(config.C.DB.ReadOnlyHosts) |
| 43 | readOnlyDSN := config.GetDatabaseDSN(readOnlyHost) |
| 44 | ReadOnlyDB, err = gorm.Open(postgres.Open(readOnlyDSN), &gorm.Config{}) |
| 45 | if err != nil { |
| 46 | panic(err) |
| 47 | } |
| 48 | |
| 49 | l.Info("database initialized") |
| 50 | } |