-
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 repeatable SQL migration for function
`subjects_is_unique_type_identifier`
- Loading branch information
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
36 changes: 36 additions & 0 deletions
36
...ata/server/backend/impl/database/migration/R__func_subjects_is_unique_type_identifier.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,36 @@ | ||
CREATE OR REPLACE FUNCTION public.subjects_is_unique_type_identifier(puuid uuid, ptype character varying, ids dbidentifier[], plabel jsonb) | ||
RETURNS boolean | ||
STABLE LANGUAGE plpgsql | ||
AS $function$ | ||
/** | ||
* Ensures uniqueness of `type` and single identifier across table `subjects`. | ||
* | ||
* If there are not any identifiers then `type` and `label` must be unique. | ||
* It is intended for check constraints and | ||
* returns `false` on violation. | ||
*/ | ||
declare | ||
db_ident record; --dbidentifier actually but makes trouble in backups | ||
tuple_exists boolean; | ||
begin | ||
if ids is null or cardinality(ids) = 0 then | ||
execute 'select exists(select 1 from public.subjects where $1 = type and $2 = label and $3 <> uuid)' | ||
into tuple_exists | ||
using ptype, plabel, puuid; | ||
if tuple_exists then | ||
return false; | ||
end if; | ||
else | ||
foreach db_ident in array ids loop | ||
execute 'select exists(select 1 from public.subjects where $1 = type and $2 = any (identifiers) and $3 <> uuid)' | ||
into tuple_exists | ||
using ptype, db_ident, puuid; | ||
if tuple_exists then | ||
return false; | ||
end if; | ||
end loop; | ||
end if; | ||
return true; | ||
end; | ||
$function$; | ||
|