62 lines
1006 B
Go
Raw Normal View History

package database
import (
"fmt"
"legalgo-BE-go/config"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type DB struct {
*gorm.DB
}
2025-03-03 18:59:25 +07:00
func NewDB(cfg *config.Config) (*DB, error) {
2025-02-26 22:28:19 +08:00
dsn := fmt.Sprintf(
"host=%s user=%s password=%s dbname=%s port=%v sslmode=disable",
2025-03-03 18:59:25 +07:00
cfg.Database.Host,
cfg.Database.Username,
cfg.Database.Password,
cfg.Database.DB,
cfg.Database.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
}
2025-03-02 04:36:17 +08:00
func (db *DB) DropTables() error {
// Auto Migrate the User model
return db.Migrator().DropTable(
&Tag{},
&Category{},
&News{},
)
}
func (db *DB) Migrate() error {
// Auto Migrate the User model
2025-02-24 16:48:20 +08:00
return db.AutoMigrate(
2025-02-26 22:28:19 +08:00
&Staff{},
&SubscribePlan{},
&Subscribe{},
&User{},
&News{},
&Tag{},
&Category{},
2025-03-09 00:47:24 +08:00
&Ads{},
2025-03-17 22:19:17 +08:00
&LogAds{},
&LogNews{},
2025-02-24 16:48:20 +08:00
)
}