Drop narration, history and restated-code comments across the repo, keep short ones for security boundaries, upstream quirks and ordering constraints, and record the convention in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
89 lines
1.9 KiB
Go
89 lines
1.9 KiB
Go
package services
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"adam-french.co.uk/backend/models"
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// SQLConfig holds the PostgreSQL connection parameters, all read from the
|
|
// environment in main.
|
|
type SQLConfig struct {
|
|
User string
|
|
Password string
|
|
DBName string
|
|
Host string
|
|
Port string
|
|
}
|
|
|
|
// sslmode=disable: Postgres is only on the Docker network.
|
|
func connectToPostgreSQL(config *SQLConfig) (*gorm.DB, error) {
|
|
dsn := fmt.Sprintf(
|
|
"user=%s password=%s dbname=%s host=%s port=%s sslmode=disable",
|
|
config.User, config.Password, config.DBName, config.Host, config.Port,
|
|
)
|
|
|
|
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return db, nil
|
|
}
|
|
|
|
// AutoMigrate never drops or renames, so removed fields leave columns and
|
|
// renamed ones start empty. New models must be listed here.
|
|
func migrateDatabase(db *gorm.DB) error {
|
|
err := db.AutoMigrate(
|
|
&models.User{},
|
|
&models.Post{},
|
|
&models.Activity{},
|
|
&models.Favorite{},
|
|
&models.Rowing{},
|
|
&models.Message{},
|
|
&models.Bookmark{},
|
|
&models.Place{},
|
|
&models.Box{},
|
|
&models.Page{},
|
|
&models.Background{},
|
|
&models.Layout{},
|
|
&models.Component{},
|
|
&models.CoverLetter{},
|
|
&models.CoverSnippet{},
|
|
)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return ensureStpPage(db)
|
|
}
|
|
|
|
// ensureStpPage creates the /stp Page row once. Unscoped, so deleting it sticks.
|
|
func ensureStpPage(db *gorm.DB) error {
|
|
var count int64
|
|
if err := db.Unscoped().Model(&models.Page{}).Where("slug = ?", "stp").Count(&count).Error; err != nil {
|
|
return err
|
|
}
|
|
if count > 0 {
|
|
return nil
|
|
}
|
|
return db.Create(&models.Page{Slug: "stp", Title: "STP"}).Error
|
|
}
|
|
|
|
// InitDatabase connects to Postgres and runs the auto-migration.
|
|
func InitDatabase(config *SQLConfig) (*gorm.DB, error) {
|
|
db, err := connectToPostgreSQL(config)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
err = migrateDatabase(db)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return db, nil
|
|
}
|