Branchwell

AI Resource Pro / website / scripts / add-slug-to-learning.sql

1-- Create a function to generate a slug from a title
2CREATE OR REPLACE FUNCTION generate_slug(title TEXT) RETURNS TEXT AS $$
3BEGIN
4 RETURN LOWER(
5 REGEXP_REPLACE(
6 REGEXP_REPLACE(
7 title,
8 '[^a-zA-Z0-9\s]', '', 'g'
9 ),
10 '\s+', '-', 'g'
11 )
12 );
13END;
14$$ LANGUAGE plpgsql;
15
16-- Add slug column to learning table if it doesn't exist
17DO $$
18BEGIN
19 IF NOT EXISTS (
20 SELECT 1
21 FROM information_schema.columns
22 WHERE table_schema = 'public'
23 AND table_name = 'learning'
24 AND column_name = 'slug'
25 ) THEN
26 ALTER TABLE public.learning ADD COLUMN slug TEXT;
27
28 -- Generate slugs for existing records
29 UPDATE public.learning
30 SET slug = generate_slug(title) || '-' || id;
31
32 -- Add a unique constraint to the slug column
33 ALTER TABLE public.learning ADD CONSTRAINT learning_slug_unique UNIQUE (slug);
34
35 -- Add an index for faster lookups
36 CREATE INDEX idx_learning_slug ON public.learning (slug);
37
38 -- Make slug NOT NULL
39 ALTER TABLE public.learning ALTER COLUMN slug SET NOT NULL;
40 END IF;
41END $$;