47 lines
1.6 KiB
Go
47 lines
1.6 KiB
Go
package services
|
|
|
|
import (
|
|
"adam-french.co.uk/job-tracker/internal/models"
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// migrateDatabase brings the schema up to date. There are no migration
|
|
// files: GORM's AutoMigrate is the only schema source, so it will add tables,
|
|
// columns and indexes but never drop or rename anything. Removing a field
|
|
// from a model therefore leaves the column behind, and a renamed field
|
|
// appears as a brand-new column with no data. Any model added to models.go
|
|
// must also be listed here or its table will never be created.
|
|
//
|
|
// The tables were created by the main site's backend before the tracker
|
|
// became its own app, and were copied across with pg_dump, so on a migrated
|
|
// database this finds nothing to do.
|
|
func migrateDatabase(db *gorm.DB) error {
|
|
return db.AutoMigrate(
|
|
&models.JobApplication{},
|
|
&models.JobApplicationEvent{},
|
|
&models.JobAppReference{},
|
|
// Dormant since the email pipeline was removed; see the model.
|
|
&models.ProcessedEmail{},
|
|
&models.JobSource{},
|
|
&models.JobLead{},
|
|
&models.JobSearchProfile{},
|
|
)
|
|
}
|
|
|
|
// InitDatabase connects to Postgres at dsn and runs the auto-migration. dsn
|
|
// is DATABASE_URL, in either of the forms pgx accepts
|
|
// (postgres://user:pass@host:port/db?sslmode=disable, or key=value pairs).
|
|
// sslmode=disable is fine only because Postgres is reachable exclusively on
|
|
// the private Docker network.
|
|
func InitDatabase(dsn string) (*gorm.DB, error) {
|
|
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := migrateDatabase(db); err != nil {
|
|
return nil, err
|
|
}
|
|
return db, nil
|
|
}
|