Branchwell

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

1-- Add slug column to learning table if it doesn't exist
2ALTER TABLE public.learning ADD COLUMN IF NOT EXISTS slug TEXT;
3
4-- Generate slugs for existing records using simple SQL replace functions
5-- Update records where slug is null
6UPDATE public.learning
7SET slug =
8 LOWER(
9 REGEXP_REPLACE(
10 REGEXP_REPLACE(
11 title,
12 '[^a-zA-Z0-9\s]',
13 '',
14 'g'
15 ),
16 '\s+',
17 '-',
18 'g'
19 )
20 ) || '-' || id
21WHERE slug IS NULL;
22
23-- Add a unique constraint to the slug column if it doesn't exist
24DO $$
25BEGIN
26 IF NOT EXISTS (
27 SELECT 1
28 FROM pg_constraint
29 WHERE conname = 'learning_slug_unique'
30 ) THEN
31 ALTER TABLE public.learning ADD CONSTRAINT learning_slug_unique UNIQUE (slug);
32 END IF;
33END $$;
34
35-- Add an index for faster lookups if it doesn't exist
36DO $$
37BEGIN
38 IF NOT EXISTS (
39 SELECT 1
40 FROM pg_indexes
41 WHERE indexname = 'idx_learning_slug'
42 ) THEN
43 CREATE INDEX idx_learning_slug ON public.learning (slug);
44 END IF;
45END $$;
46
47-- Make slug NOT NULL if it's nullable
48DO $$
49BEGIN
50 IF EXISTS (
51 SELECT 1
52 FROM information_schema.columns
53 WHERE table_schema = 'public'
54 AND table_name = 'learning'
55 AND column_name = 'slug'
56 AND is_nullable = 'YES'
57 ) THEN
58 ALTER TABLE public.learning ALTER COLUMN slug SET NOT NULL;
59 END IF;
60END $$;