64 lines
2.5 KiB
SQL
64 lines
2.5 KiB
SQL
-- 040_job_post_department_id.sql
|
|
-- Move the department link from requisitions to job posts: many job posts -> one
|
|
-- department. Reverses 039 (requisitions.department_id) and adds
|
|
-- job_posts.department_id, the FK behind JobPosts.department_id /
|
|
-- JobPosts.department_ref and Department.job_posts.
|
|
--
|
|
-- job_posts.department (free text) stays: analytics, filters and the talent pool
|
|
-- key off it, and the app now writes the department's name there whenever
|
|
-- department_id is set.
|
|
--
|
|
-- Idempotent; applied at startup by alembic_setup.run_manual_sql() after 039.
|
|
|
|
-- =============================================================================
|
|
-- 1. requisitions: drop the 039 link, keeping the department name as text
|
|
-- =============================================================================
|
|
DO $$
|
|
BEGIN
|
|
IF EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = 'app' AND table_name = 'requisitions' AND column_name = 'department_id'
|
|
) THEN
|
|
-- Rows created while the link existed wrote only department_id; carry the name back.
|
|
UPDATE app.requisitions r
|
|
SET department = d.name
|
|
FROM app.departments d
|
|
WHERE r.department_id = d.id
|
|
AND (r.department IS NULL OR btrim(r.department) = '');
|
|
|
|
ALTER TABLE app.requisitions
|
|
DROP CONSTRAINT IF EXISTS fk_requisitions_department_id_departments;
|
|
DROP INDEX IF EXISTS app.ix_requisitions_department_id;
|
|
ALTER TABLE app.requisitions DROP COLUMN department_id;
|
|
END IF;
|
|
END $$;
|
|
|
|
-- =============================================================================
|
|
-- 2. job_posts.department_id -> departments.id
|
|
-- =============================================================================
|
|
ALTER TABLE app.job_posts
|
|
ADD COLUMN IF NOT EXISTS department_id uuid;
|
|
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM pg_constraint
|
|
WHERE conname = 'fk_job_posts_department_id_departments'
|
|
) THEN
|
|
ALTER TABLE app.job_posts
|
|
ADD CONSTRAINT fk_job_posts_department_id_departments
|
|
FOREIGN KEY (department_id) REFERENCES app.departments (id);
|
|
END IF;
|
|
END $$;
|
|
|
|
CREATE INDEX IF NOT EXISTS ix_job_posts_department_id
|
|
ON app.job_posts (department_id);
|
|
|
|
-- Backfill: job posts whose text department equals a department's name or short
|
|
-- code (case-insensitive, trimmed). Unmatched rows stay NULL.
|
|
UPDATE app.job_posts j
|
|
SET department_id = d.id
|
|
FROM app.departments d
|
|
WHERE j.department_id IS NULL
|
|
AND lower(btrim(j.department)) IN (lower(d.name), lower(d.short_code));
|