92 lines
2.3 KiB
Go
92 lines
2.3 KiB
Go
package migrations
|
|
|
|
import (
|
|
"context"
|
|
|
|
"git.haelnorr.com/h/oslstats/internal/db"
|
|
"github.com/uptrace/bun"
|
|
)
|
|
|
|
func init() {
|
|
Migrations.MustRegister(
|
|
// UP migration
|
|
func(ctx context.Context, conn *bun.DB) error {
|
|
// Create fixture_results table
|
|
_, err := conn.NewCreateTable().
|
|
Model((*db.FixtureResult)(nil)).
|
|
IfNotExists().
|
|
ForeignKey(`("fixture_id") REFERENCES "fixtures" ("id") ON DELETE CASCADE`).
|
|
ForeignKey(`("uploaded_by_user_id") REFERENCES "users" ("id")`).
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Create fixture_result_player_stats table
|
|
_, err = conn.NewCreateTable().
|
|
Model((*db.FixtureResultPlayerStats)(nil)).
|
|
IfNotExists().
|
|
ForeignKey(`("fixture_result_id") REFERENCES "fixture_results" ("id") ON DELETE CASCADE`).
|
|
ForeignKey(`("player_id") REFERENCES "players" ("id") ON DELETE SET NULL`).
|
|
ForeignKey(`("team_id") REFERENCES "teams" ("id") ON DELETE SET NULL`).
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Create index on fixture_result_id for faster lookups
|
|
_, err = conn.NewCreateIndex().
|
|
Model((*db.FixtureResultPlayerStats)(nil)).
|
|
Index("idx_frps_fixture_result_id").
|
|
Column("fixture_result_id").
|
|
IfNotExists().
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Create index on player_id for stats queries
|
|
_, err = conn.NewCreateIndex().
|
|
Model((*db.FixtureResultPlayerStats)(nil)).
|
|
Index("idx_frps_player_id").
|
|
Column("player_id").
|
|
IfNotExists().
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Create composite index for period+team filtering
|
|
_, err = conn.NewCreateIndex().
|
|
Model((*db.FixtureResultPlayerStats)(nil)).
|
|
Index("idx_frps_result_period_team").
|
|
Column("fixture_result_id", "period_num", "team").
|
|
IfNotExists().
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
},
|
|
// DOWN migration
|
|
func(ctx context.Context, conn *bun.DB) error {
|
|
// Drop fixture_result_player_stats first (has FK to fixture_results)
|
|
_, err := conn.NewDropTable().
|
|
Model((*db.FixtureResultPlayerStats)(nil)).
|
|
IfExists().
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Drop fixture_results
|
|
_, err = conn.NewDropTable().
|
|
Model((*db.FixtureResult)(nil)).
|
|
IfExists().
|
|
Exec(ctx)
|
|
return err
|
|
},
|
|
)
|
|
}
|