Fix error when seeding in AWS non-production #1400
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Unlike migrations, which are only expected to be run once against a DB, seeders may be run repeatedly. For example, a new charge version, 'change reason', is required in the future. We would add it to our
db/seeds/data/change-reasons.js
and re-runnpm run seed
.Because of this, each seeder needs to be able to handle being run against an environment where the records may already exist.
In most cases, we can exploit constraints in the DB and PostgreSQL's ON CONFLICT clause, also known as an 'upsert'.
We try to insert a record, but when a conflict error is thrown because a matching record already exists, we can instruct PostgreSQL to update certain fields instead.
That is unless it is
idm.users
! The previous team appear to have opted instead to create their own custom sequence and use a number as the ID. 😩Instead of the expected
on conflict
being raised, we're getting a primary key violation. The simplest solution is to check if a record exists first. We can then determine if we need to insert our user record or update an existing one.If we are updating, we must then check if the seed ID we want to use is already in use. If it is, we have to drop ID from our insert statement and let the custom sequence assign us one instead.