|
| 1 | +--- |
| 2 | +description: Database schema design patterns for Supabase with proper types and relationships |
| 3 | +globs: ["**/*.sql", "**/supabase/**", "**/types/**"] |
| 4 | +alwaysApply: false |
| 5 | +--- |
| 6 | + |
| 7 | +# Database Design Patterns |
| 8 | + |
| 9 | +## Table Naming |
| 10 | +- Use `snake_case` for tables and columns: `user_profiles`, `created_at` |
| 11 | +- NEVER use camelCase in SQL: `userId` → WRONG, `user_id` → CORRECT |
| 12 | +- Use plural table names: `profiles`, `posts`, `comments` |
| 13 | + |
| 14 | +## Required Columns (Every Table) |
| 15 | +```sql |
| 16 | +CREATE TABLE public.example ( |
| 17 | + id UUID DEFAULT gen_random_uuid() PRIMARY KEY, |
| 18 | + -- your columns here |
| 19 | + created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL, |
| 20 | + updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL |
| 21 | +); |
| 22 | +``` |
| 23 | +ALWAYS include `id`, `created_at`, and `updated_at`. |
| 24 | +ALWAYS use UUID for primary keys (not serial/integer). |
| 25 | +ALWAYS use TIMESTAMPTZ (not TIMESTAMP) for timezone safety. |
| 26 | + |
| 27 | +## Foreign Key Pattern |
| 28 | +```sql |
| 29 | +-- Always reference auth.users for user ownership |
| 30 | +user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE NOT NULL |
| 31 | +``` |
| 32 | +Use `ON DELETE CASCADE` for user-owned data. |
| 33 | +Use `ON DELETE SET NULL` for optional relationships. |
| 34 | + |
| 35 | +## RLS Template (Copy This Every Time) |
| 36 | +```sql |
| 37 | +ALTER TABLE public.example ENABLE ROW LEVEL SECURITY; |
| 38 | + |
| 39 | +-- Users can only see their own data |
| 40 | +CREATE POLICY "Users own data" ON public.example |
| 41 | + FOR ALL USING (auth.uid() = user_id); |
| 42 | + |
| 43 | +-- Or for public read + owner write: |
| 44 | +CREATE POLICY "Public read" ON public.example |
| 45 | + FOR SELECT USING (true); |
| 46 | +CREATE POLICY "Owner write" ON public.example |
| 47 | + FOR INSERT WITH CHECK (auth.uid() = user_id); |
| 48 | +CREATE POLICY "Owner update" ON public.example |
| 49 | + FOR UPDATE USING (auth.uid() = user_id); |
| 50 | +CREATE POLICY "Owner delete" ON public.example |
| 51 | + FOR DELETE USING (auth.uid() = user_id); |
| 52 | +``` |
| 53 | + |
| 54 | +## Type Generation |
| 55 | +After schema changes, regenerate types: |
| 56 | +```bash |
| 57 | +npx supabase gen types typescript --project-id YOUR_PROJECT_REF > src/types/database.ts |
| 58 | +``` |
| 59 | +ALWAYS use generated types — NEVER manually type database schemas. |
| 60 | + |
| 61 | +## Anti-Patterns |
| 62 | +- NEVER use `TEXT` for fields that should be enums — use PostgreSQL enums or CHECK constraints |
| 63 | +- NEVER store JSON blobs when structured columns work — use `JSONB` only for truly dynamic data |
| 64 | +- NEVER create tables without RLS — see `supabase-rls.mdc` |
| 65 | +- NEVER use `SERIAL` for IDs — use `UUID` for security (prevents enumeration attacks) |
0 commit comments