-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostgres.go
More file actions
50 lines (43 loc) · 1.02 KB
/
postgres.go
File metadata and controls
50 lines (43 loc) · 1.02 KB
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
package repository
import (
"fmt"
"log"
"github.com/Arjuna-Ragil/Localbase/Internal/config"
"github.com/Arjuna-Ragil/Localbase/Internal/core/domain"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type DBContainer struct {
Gorm *gorm.DB
Sqlx *sqlx.DB
}
func ConnectDB() (*DBContainer, error) {
cfg := config.LoadConfig()
gormDB, err := gorm.Open(postgres.Open(cfg.DBURL), &gorm.Config{})
if err != nil {
log.Fatalf("Failed to connect to gorm database: %v", err)
}
fmt.Println("Connected to gorm database")
sqlxDB, err := sqlx.Connect("postgres", cfg.DBURL)
if err != nil {
log.Fatalf("Failed to connect to sqlx database: %v", err)
}
fmt.Println("Connected to sqlx database")
return &DBContainer{
Gorm: gormDB,
Sqlx: sqlxDB,
}, nil
}
func (db *DBContainer) Migrate() error {
err := db.Gorm.AutoMigrate(
&domain.User{},
&domain.Invitation{},
)
if err != nil {
log.Fatalf("Failed to migrate users: %v", err)
}
fmt.Println("Migrated users")
return nil
}