-- Resync PostgreSQL identity sequences after bulk imports or manual ID inserts.
-- Safe to run multiple times. Run against the modwad database when new rows fail with:
--   duplicate key value violates unique constraint "Recipes_pkey"

SELECT setval(
    pg_get_serial_sequence('diet."Recipes"', 'Id'),
    COALESCE((SELECT MAX("Id") FROM diet."Recipes"), 1),
    (SELECT MAX("Id") IS NOT NULL FROM diet."Recipes")
);

SELECT setval(
    pg_get_serial_sequence('diet."Ingredients"', 'Id'),
    COALESCE((SELECT MAX("Id") FROM diet."Ingredients"), 1),
    (SELECT MAX("Id") IS NOT NULL FROM diet."Ingredients")
);

SELECT setval(
    pg_get_serial_sequence('diet."RecipeSteps"', 'Id'),
    COALESCE((SELECT MAX("Id") FROM diet."RecipeSteps"), 1),
    (SELECT MAX("Id") IS NOT NULL FROM diet."RecipeSteps")
);

SELECT setval(
    pg_get_serial_sequence('diet."RecipeGeneratorSessions"', 'Id'),
    COALESCE((SELECT MAX("Id") FROM diet."RecipeGeneratorSessions"), 1),
    (SELECT MAX("Id") IS NOT NULL FROM diet."RecipeGeneratorSessions")
);
