Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix error when seeding in AWS non-production (#1400)
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-run `npm 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](https://www.postgresql.org/docs/current/sql-insert.html), 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.
- Loading branch information