-- PostgreSQL Performance Fix for Episode Queries
-- Run this script to add the missing index for PresentationUniqueKey
-- This will significantly speed up episode deduplication queries
\pset pager off

-- Create the index (CONCURRENTLY means it won't lock the table during creation)
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_baseitems_presentationuniquekey_episodes
ON library."BaseItems" ("PresentationUniqueKey", "TopParentId", "IsVirtualItem")
WHERE "Type" = 'MediaBrowser.Controller.Entities.TV.Episode' AND "PresentationUniqueKey" IS NOT NULL;

-- Verify the index was created
SELECT 
    schemaname,
    tablename,
    indexname,
    indexdef
FROM pg_indexes
WHERE schemaname = 'library' 
  AND indexname = 'idx_baseitems_presentationuniquekey_episodes';

-- Check index size
SELECT 
    pg_size_pretty(pg_relation_size('library.idx_baseitems_presentationuniquekey_episodes'::regclass)) AS index_size;
