1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-11-10 01:19:53 +01:00
unleash.unleash/src/migrations/20250529153326-cr-uniqueness.js
Jaanus Sellin d8c83fb824
fix: do not allow creating cr for same environment (#10010)
If there are two concurrent requests to create or edit change requests,
two separate ones may be created in parallel. The UI does not currently
handle this scenario, and if additional changes are made, they might be
added to a random existing change request—resulting in a messy and
unpredictable state.

This PR adds a unique index to the `change_requests` table 
```
on (created_by, project, environment)
WHERE state NOT IN ('Applied', 'Cancelled', 'Rejected', 'Scheduled').
```

In the extremely rare case where such conflicting data already exists in
a database, the migration will automatically cancel one of the
conflicting change requests.
2025-05-30 08:20:11 +03:00

33 lines
1.0 KiB
JavaScript

exports.up = (db, callback) => {
db.runSql(
`
WITH ranked AS (
SELECT id,
ROW_NUMBER() OVER (
PARTITION BY created_by, project, environment
ORDER BY created_at DESC
) AS rn
FROM change_requests
WHERE state NOT IN ('Applied', 'Cancelled', 'Rejected', 'Scheduled')
)
UPDATE change_requests
SET state = 'Cancelled'
WHERE id IN (
SELECT id FROM ranked WHERE rn > 1
);
CREATE UNIQUE INDEX IF NOT EXISTS unique_pending_request_per_user_project_env
ON change_requests (created_by, project, environment)
WHERE state NOT IN ('Applied', 'Cancelled', 'Rejected', 'Scheduled');
`,
callback,
);
};
exports.down = (db, callback) => {
db.runSql(
` DROP INDEX IF EXISTS unique_pending_request_per_user_project_env;`,
callback,
);
};