Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100package database
import ( "fmt" "log/slog"
"gorm.io/gorm")
// dropStaleColumns removes leftover columns created by GORM's broken snake_case// conversion of acronym field names (DID → d_id, ATURI → a_t_u_r_i, etc.).// The correct columns (did, at_uri, subject_did) already exist; these are duplicates.func dropStaleColumns(db *gorm.DB) { drops := []struct { table, column string }{ {"subscriptions", "d_id"}, {"comments", "d_id"}, {"comments", "a_t_u_r_i"}, {"recommendations", "d_id"}, {"podcast_lists", "d_id"}, {"bookmarks", "d_id"}, {"profiles", "d_id"}, {"episode_states", "d_id"}, {"blocks", "d_id"}, {"blocks", "a_t_u_r_i"}, {"blocks", "subject_d_i_d"}, {"reports", "d_id"}, }
for _, d := range drops { // Use raw SQL to check — GORM's HasColumn applies its own naming convention // which defeats the purpose of checking for the misnamed column. sql := fmt.Sprintf( `ALTER TABLE %q DROP COLUMN IF EXISTS %q`, d.table, d.column, ) if err := db.Exec(sql).Error; err != nil { slog.Warn("drop column failed", "table", d.table, "column", d.column, "err", err) } }}
// widenIntColumns changes integer columns to bigint where PodcastIndex IDs// can exceed int4 max (~2.1 billion). Safe to run repeatedly.func widenIntColumns(db *gorm.DB) { alters := []struct { table, column string }{ {"subscriptions", "feed_id"}, {"comments", "feed_id"}, {"comments", "episode_id"}, {"recommendations", "feed_id"}, {"recommendations", "episode_id"}, {"bookmarks", "feed_id"}, {"bookmarks", "episode_id"}, {"podcast_stats", "feed_id"}, {"episode_stats", "episode_id"}, {"episode_stats", "feed_id"}, {"episode_states", "feed_id"}, {"episode_states", "episode_id"}, }
for _, a := range alters { if !db.Migrator().HasTable(a.table) { continue } sql := fmt.Sprintf(`ALTER TABLE %q ALTER COLUMN %q TYPE bigint`, a.table, a.column) if err := db.Exec(sql).Error; err != nil { slog.Warn("widen column failed (may already be bigint)", "table", a.table, "column", a.column, "err", err) } }}
func AutoMigrateAll(db *gorm.DB) error { dropStaleColumns(db) widenIntColumns(db)
if err := db.AutoMigrate( &FirehoseCursor{}, &Subscription{}, &Comment{}, &Recommendation{}, &PodcastList{}, &Bookmark{}, &Profile{}, &PICache{}, &PodcastStats{}, &EpisodeStats{}, &EpisodeState{}, &Block{}, &Report{}, &AttestChallenge{}, &DeviceToken{}, ); err != nil { return fmt.Errorf("auto migrate: %w", err) } return nil}