HR-ATS-Portal/backend/migrations/manual/041_requisition_department_...

54 lines
2.1 KiB
SQL

-- 041_requisition_department_id.sql
-- Restores requisitions.department_id: many requisitions -> one department. This
-- is the FK behind Requisition.department_id / Requisition.department_ref
-- (backend/candidate_forms/models.py) and Department.requisitions
-- (backend/department/models.py). department_ref/requisitions are ORM
-- relationships only — they add no column, the FK below is the whole schema
-- change, and a requisition is linked by writing department_id.
--
-- 039 added this column and 040 dropped it again when the department link moved
-- to job_posts; job_posts.department_id from 040 stays. A new file rather than
-- an edit to either: manual migrations run once and are recorded in
-- manual_migrations, so edits to an applied file never reach an existing
-- database. Applied at startup by alembic_setup.run_manual_sql().
--
-- The legacy free-text requisitions.department column is kept and only read here
-- to backfill; 040 wrote the department name back into it before dropping the
-- FK, so rows linked under 039 recover their link. Unmatched rows stay NULL.
ALTER TABLE app.requisitions
ADD COLUMN IF NOT EXISTS department_id uuid;
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'fk_requisitions_department_id_departments'
) THEN
ALTER TABLE app.requisitions
ADD CONSTRAINT fk_requisitions_department_id_departments
FOREIGN KEY (department_id) REFERENCES app.departments (id);
END IF;
END $$;
CREATE INDEX IF NOT EXISTS ix_requisitions_department_id
ON app.requisitions (department_id);
-- Backfill from the legacy text column, if it is still there: match a
-- department's name or short code, case-insensitive and trimmed.
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'app'
AND table_name = 'requisitions'
AND column_name = 'department'
) THEN
UPDATE app.requisitions r
SET department_id = d.id
FROM app.departments d
WHERE r.department_id IS NULL
AND lower(btrim(r.department)) IN (lower(d.name), lower(d.short_code));
END IF;
END $$;