-- Add slug column to news table if it doesn't exist ALTER TABLE public.news ADD COLUMN IF NOT EXISTS slug TEXT; -- Generate slugs for existing records using simple SQL replace functions -- Update records where slug is null UPDATE public.news SET slug = LOWER( REGEXP_REPLACE( REGEXP_REPLACE( title, '[^a-zA-Z0-9\s]', -- Remove special characters except spaces '', 'g' ), '\s+', -- Replace spaces with hyphens '-', 'g' ) ) || '-' || id WHERE slug IS NULL; -- Add a unique constraint to the slug column if it doesn't exist DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM pg_constraint WHERE conname = 'news_slug_unique' ) THEN ALTER TABLE public.news ADD CONSTRAINT news_slug_unique UNIQUE (slug); END IF; IF NOT EXISTS ( SELECT 1 FROM pg_indexes WHERE indexname = 'idx_news_slug' ) THEN CREATE INDEX idx_news_slug ON public.news (slug); END IF; END $$; -- Make slug NOT NULL if it's nullable DO $$ BEGIN IF EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'news' AND column_name = 'slug' AND is_nullable = 'YES' ) THEN ALTER TABLE public.news ALTER COLUMN slug SET NOT NULL; END IF; END $$;