52 lines
1008 B
Go
52 lines
1008 B
Go
package db
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
"lst.net/internal/models"
|
|
)
|
|
|
|
var DB *gorm.DB
|
|
|
|
type DBConfig struct {
|
|
DB *gorm.DB
|
|
DSN string
|
|
}
|
|
|
|
func InitDB() (*DBConfig, error) {
|
|
dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s",
|
|
os.Getenv("DB_HOST"),
|
|
os.Getenv("DB_PORT"),
|
|
os.Getenv("DB_USER"),
|
|
os.Getenv("DB_PASSWORD"),
|
|
os.Getenv("DB_NAME"))
|
|
|
|
var err error
|
|
|
|
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to connect to database: %v", err)
|
|
}
|
|
|
|
fmt.Println("✅ Connected to database")
|
|
|
|
// ensures we have the uuid stuff setup properly
|
|
DB.Exec(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`)
|
|
|
|
err = DB.AutoMigrate(&models.Log{}, &models.Settings{}) // &ClientRecord{}, &Servers{}
|
|
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to auto-migrate models: %v", err)
|
|
}
|
|
|
|
fmt.Println("✅ Database migration completed successfully")
|
|
|
|
return &DBConfig{
|
|
DB: DB,
|
|
DSN: dsn,
|
|
}, nil
|
|
}
|