Упростить ошибки сессий, логировать миграции и тестировать с рабочим клиентом Valkey
This commit is contained in:
@@ -54,24 +54,30 @@ func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// Migrate applies pending migrations. A session advisory lock serialises
|
||||
// concurrent starts, so several API replicas may call it at once; applied
|
||||
// versions are recorded, which makes a repeated run a no-op.
|
||||
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
// Migrate applies pending migrations and returns the versions it applied. A
|
||||
// session advisory lock serialises concurrent starts, so several API
|
||||
// replicas may call it at once; applied versions are recorded, which makes a
|
||||
// repeated run a no-op.
|
||||
func Migrate(ctx context.Context, pool *pgxpool.Pool) ([]int64, error) {
|
||||
db := stdlib.OpenDBFromPool(pool)
|
||||
defer db.Close()
|
||||
locker, err := lock.NewPostgresSessionLocker()
|
||||
if err != nil {
|
||||
return fmt.Errorf("migration lock: %w", err)
|
||||
return nil, fmt.Errorf("migration lock: %w", err)
|
||||
}
|
||||
provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.FS, goose.WithSessionLocker(locker))
|
||||
if err != nil {
|
||||
return fmt.Errorf("load migrations: %w", err)
|
||||
return nil, fmt.Errorf("load migrations: %w", err)
|
||||
}
|
||||
if _, err := provider.Up(ctx); err != nil {
|
||||
return fmt.Errorf("apply migrations: %w", err)
|
||||
results, err := provider.Up(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("apply migrations: %w", err)
|
||||
}
|
||||
return nil
|
||||
applied := make([]int64, 0, len(results))
|
||||
for _, r := range results {
|
||||
applied = append(applied, r.Source.Version)
|
||||
}
|
||||
return applied, nil
|
||||
}
|
||||
|
||||
// Classify marks a failure to reach the database as apperr.KindUnavailable,
|
||||
|
||||
@@ -32,9 +32,13 @@ func TestMain(m *testing.M) {
|
||||
|
||||
func TestMigrateIsRepeatable(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
if err := postgres.Migrate(ctx, db.Pool); err != nil {
|
||||
applied, err := postgres.Migrate(ctx, db.Pool)
|
||||
if err != nil {
|
||||
t.Fatalf("second migrate: %v", err)
|
||||
}
|
||||
if len(applied) != 0 {
|
||||
t.Fatalf("second migrate applied %v, want nothing", applied)
|
||||
}
|
||||
var version int64
|
||||
if err := db.Pool.QueryRow(ctx, `SELECT max(version_id) FROM goose_db_version`).Scan(&version); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
Reference in New Issue
Block a user