31 lines
1.1 KiB
SQL
31 lines
1.1 KiB
SQL
-- Pro Mitarbeiter darf maximal eine Stelle als primary markiert sein.
|
|
-- ====================================================================
|
|
-- bisher: position_assignments.is_primary konnte mehrfach true sein —
|
|
-- ein Mitarbeiter hatte dann widersprüchliche "Hauptstellen". Im UI
|
|
-- wurde immer die zuletzt gefundene gewonnen, was inkonsistent war.
|
|
--
|
|
-- Schritt 1: bestehende Mehrfach-Primaries bereinigen — pro Mitarbeiter
|
|
-- bleibt die mit jüngstem valid_from primary, alle anderen werden auf
|
|
-- false gesetzt.
|
|
--
|
|
-- Schritt 2: partial unique index (employee_id) where is_primary = true
|
|
-- verhindert künftige Mehrfach-Primaries auf DB-Ebene.
|
|
|
|
with ranked as (
|
|
select id,
|
|
row_number() over (
|
|
partition by employee_id
|
|
order by valid_from desc, created_at desc
|
|
) as rn
|
|
from public.position_assignments
|
|
where is_primary = true
|
|
)
|
|
update public.position_assignments pa
|
|
set is_primary = false
|
|
from ranked r
|
|
where pa.id = r.id and r.rn > 1;
|
|
|
|
create unique index if not exists position_assignments_one_primary_per_employee
|
|
on public.position_assignments (employee_id)
|
|
where is_primary = true;
|