2025-02-26 22:28:19 +08:00

47 lines
780 B
Go

package database
import (
"fmt"
"github.com/ardeman/project-legalgo-go/config"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type DB struct {
*gorm.DB
}
func NewDB() (*DB, error) {
dsn := fmt.Sprintf(
"host=%s user=%s password=%s dbname=%s port=%v sslmode=disable",
config.DB_HOST,
config.DB_USER,
config.DB_PASSWORD,
config.DB_NAME,
config.DB_PORT,
)
if dsn == "" {
return nil, fmt.Errorf("DATABASE_URL environment is not set")
}
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
return nil, fmt.Errorf("failed to connect to database: %w", err)
}
return &DB{db}, nil
}
func (db *DB) Migrate() error {
// Auto Migrate the User model
return db.AutoMigrate(
&Staff{},
&SubscribePlan{},
&Subscribe{},
&User{},
)
}