-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a migration script to make existing property names unique (#719)
- Loading branch information
1 parent
5fa018c
commit 97864d6
Showing
1 changed file
with
21 additions
and
0 deletions.
There are no files selected for viewing
21 changes: 21 additions & 0 deletions
21
migrations/20240910115224_make_json_str_name_unique_per_user/migration.sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
-- Update records with duplicate names for the same user | ||
UPDATE "Model" | ||
SET json_str = jsonb_set( | ||
json_str::jsonb, | ||
'{name}', | ||
-- Append a random 5-digit suffix to the name | ||
to_jsonb(json_str->>'name' || '_' || LPAD(FLOOR(RANDOM() * 100000)::text, 5, '0')) | ||
) | ||
-- Select records with duplicate names | ||
WHERE (user_uuid, json_str->>'name') IN ( | ||
SELECT user_uuid, json_str->>'name' | ||
FROM "Model" | ||
GROUP BY user_uuid, json_str->>'name' | ||
HAVING COUNT(*) > 1 | ||
) | ||
-- Exclude the first occurrence of each duplicate set | ||
AND uuid NOT IN ( | ||
SELECT DISTINCT ON (user_uuid, json_str->>'name') uuid | ||
FROM "Model" | ||
ORDER BY user_uuid, json_str->>'name', created_at | ||
); |