19 lines
1.1 KiB
PL/PgSQL
19 lines
1.1 KiB
PL/PgSQL
-- Migration: 047_optimize_job_indexes
|
|
-- Description: Creates an immutable wrapper function and a compound index to dramatically optimize the default sorting on the Homepage.
|
|
-- Removing the heavy Table Scan calculations for `ORDER BY j.is_featured DESC, COALESCE(j.date_posted, j.created_at) DESC`.
|
|
|
|
-- 1. Create an immutable function wrapper for COALESCE because PostgreSQL forbids volatile timestamps in indexes
|
|
CREATE OR REPLACE FUNCTION immutable_coalesce_dates(d1 timestamp with time zone, d2 timestamp without time zone)
|
|
RETURNS timestamp with time zone AS $$
|
|
BEGIN
|
|
RETURN COALESCE(d1, d2 AT TIME ZONE 'UTC');
|
|
END;
|
|
$$ LANGUAGE plpgsql IMMUTABLE;
|
|
|
|
-- 2. Create the precise index using the new immutable function
|
|
CREATE INDEX IF NOT EXISTS idx_jobs_featured_date_posted
|
|
ON jobs (is_featured DESC, immutable_coalesce_dates(date_posted, created_at) DESC);
|
|
|
|
-- 3. Also index jobs creation date explicitly if they search strictly by recents without features
|
|
CREATE INDEX IF NOT EXISTS idx_jobs_coalesce_date_posted
|
|
ON jobs (immutable_coalesce_dates(date_posted, created_at) DESC);
|