-
Notifications
You must be signed in to change notification settings - Fork 3
/
db.go
58 lines (49 loc) · 1.43 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package internal
import (
"database/sql"
"fmt"
"log"
"os"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
// Database for creating connection and handling transaction to the database
type Database struct {
logger *log.Logger
}
// NewDatabase returns a new database connection with the given logger
func NewDatabase(logger *log.Logger) *Database {
return &Database{logger}
}
// CreateConnection creates a connection to the postgres database
// It is not closing the connection to the database
func (d *Database) CreateConnection() (*sql.DB, *gorm.DB) {
dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%v sslmode=disable",
os.Getenv("DB_HOST"),
os.Getenv("DB_USERNAME"),
os.Getenv("DB_PASSWORD"),
os.Getenv("DB_DATABASE"),
os.Getenv("DB_PORT"),
)
gormInstance, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
d.logger.Printf("Error connecting to database: %s\n", err)
os.Exit(1)
}
database, err := gormInstance.DB()
if err != nil {
d.logger.Printf("Error connecting to database: %s\n", err)
os.Exit(1)
}
err = createTables(gormInstance)
if err != nil {
d.logger.Printf("Something went wrong while creating tables: %s\n", err)
os.Exit(1)
}
d.logger.Println("Successfully connected to postgres database")
return database, gormInstance
}
// CreateTables creates all tables that are constructed in the types
func createTables(db *gorm.DB) error {
return db.AutoMigrate(&Account{})
}