-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorm.go
41 lines (34 loc) · 994 Bytes
/
gorm.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
package database
import (
"database/sql"
"fmt"
"github.com/alexhokl/helper/iohelper"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func GetDatabaseDailector(pathToConnectionStringFile string) (gorm.Dialector, error) {
if pathToConnectionStringFile == "" {
return nil, fmt.Errorf("file path to database connection string is not set")
}
connectionString, err := iohelper.ReadFirstLineFromFile(pathToConnectionStringFile)
if err != nil {
return nil, fmt.Errorf("unable to read password: %w", err)
}
if connectionString == "" {
return nil, fmt.Errorf("database connection string is empty")
}
return postgres.Open(connectionString), nil
}
func GetDatabaseDialectorFromConnection(conn *sql.DB) gorm.Dialector {
return postgres.New(postgres.Config{
Conn: conn,
DriverName: "postgres",
})
}
func GetDatabaseConnection(dialector gorm.Dialector) (*gorm.DB, error) {
conn, err := gorm.Open(dialector, &gorm.Config{})
if err != nil {
return nil, err
}
return conn, nil
}