agentleFS
diegovasquez-aidiegovasquez-ai/builder-crm/.claude/skills/supabase/SKILL.md

supabase

Skill40 starsChanged 2 months agoMITView on GitHub

Todo lo relacionado con Supabase: crear tablas, migraciones, RLS, queries, metricas, CRUD, auth, storage, logs, y operaciones de datos. Activar cuando el usuario dice: necesito una tabla, crear tabla, base de datos, guardar datos, proteger datos, RLS, migracion, query, cuantos usuarios, metricas, revenue, dame los datos, consulta supabase, cuantos registros, analiza los datos, estadisticas, reportes, churn, funnel, storage, auth, configurar permisos, o cualquier operacion de BD.

  • Reads credentials
  • Sends data out

67 other projects use a version of this, 2 of them edited.

Adopted by

Most recently taken up by

Used with

Projects with it also use firebase, vercel and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • xfstudioSkill

    firebase

    Firebase gives you a complete backend in minutes - auth, database, storage, functions, hosting. But the ease of setup hides real complexity. Security rules are your last line of defense, and they're often wrong. Firestore queries are limited, and you learn this after you've designed your data model. This skill covers Firebase Authentication, Firestore, Realtime Database, Cloud Functions, Cloud Storage, and Firebase Hosting. Key insight: Firebase is optimized for read-heavy, denormalized data. I

    Also in 5 projects that use this

  • SentrySkill

    vercel

    Deploy and inspect Vercel apps, assign aliases, delete deployments, investigate logs, and monitor deployment outcomes. Use for Vercel deployment and log requests, not GitHub code changes or other cloud providers.

    Also in 4 projects that use this

  • ffsshhttiikkSkill

    flutter

    Flutter cross-platform framework

    Also in 3 projects that use this

  • VercelSkill

    react-native

    React Native renderer for json-render that turns JSON specs into native mobile UIs. Use when working with @json-render/react-native, building React Native UIs from JSON, creating mobile component catalogs, or rendering AI-generated specs on mobile.

    Also in 3 projects that use this

  • VercelSkill

    vercel-optimize

    Use for Vercel cost and performance optimization on deployed projects, especially Next.js, SvelteKit, Nuxt, and limited Astro apps. Collect Vercel metrics, usage, project config, and code scan results first; investigate only metric-backed candidates; produce ranked recommendations grounded in verified files and version-aware Vercel/framework docs. Trigger for Vercel bill reduction, slow or expensive routes, caching opportunities, Function Invocations, Build Minutes, Fast Data Transfer, Core Web Vitals, Bot Management, Fluid compute, or cost breakdown requests.

    Also in 3 projects that use this

  • wewpellex21Skill

    backend

    Servers, routes, APIs, and backend architecture. Activated when Claude creates server-side code, API routes, or Express/Fastify/Next.js API handlers.

    Also in 3 projects that use this

  • +2 more from vercel-labs

The file

We split this skill into the rules it gives an agent

2 rules. 0 are common, 2 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 65 edited versions we read keep these.

  • 2

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    apply_migration para DDL: CREATE, ALTER, DROP

    line 400
  2. Distinctive:

    Verificar con queries reales: No confiar en docs desactualizados

    line 405

“Common” is measured: kept by at least 6 in 10 of the 65 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Supabase — Tu Base de Datos Completa

Estructura, datos, seguridad, y metricas. Todo en un solo lugar.


Setup Inicial (Una Sola Vez)

Paso 1: Credenciales

KeyDonde encontrarlaPara que
Service Role KeyDashboard → Settings → API → service_roleQueries directos (bypassa RLS)
Personal Access Tokensupabase.com/dashboard/account/tokensManagement API (SQL raw, logs)

Paso 2: Guardar en .env

SUPABASE_URL=https://TU_PROJECT_REF.supabase.co
SUPABASE_SERVICE_KEY=eyJhbGci...tu_service_role_key
SUPABASE_PAT=sbp_...tu_personal_access_token
SUPABASE_PROJECT_REF=tu_project_ref

Paso 3: Documentar tu schema

Ejecuta el MEGAPROMPT al final de este archivo para generar references/schema.md automaticamente.


Cargar Credenciales

SIEMPRE ejecutar antes de cualquier query:

export SUPABASE_URL=$(grep '^SUPABASE_URL=' .env | cut -d= -f2)
export SUPABASE_SERVICE_KEY=$(grep '^SUPABASE_SERVICE_KEY=' .env | cut -d= -f2)
export SUPABASE_PAT=$(grep '^SUPABASE_PAT=' .env | cut -d= -f2)
export SUPABASE_PROJECT_REF=$(grep '^SUPABASE_PROJECT_REF=' .env | cut -d= -f2)

MCP: Estructura y Exploracion

Si tienes @supabase/mcp-server-supabase en .mcp.json:

Explorar

list_tables                    -- Ver estructura de BD
execute_sql("SELECT ...")      -- Consultar datos
get_logs(service: "auth")      -- Depurar auth
get_logs(service: "postgres")  -- Depurar BD

Crear/Modificar Estructura (DDL)

apply_migration(
  name: "nombre_descriptivo",
  query: "CREATE TABLE | ALTER TABLE | CREATE INDEX"
)

Verificar Seguridad

get_advisors(type: "security") -- Detecta tablas sin RLS
search_docs("consulta aqui")   -- Buscar en docs oficiales

HTTP: Datos y Operaciones

PostgREST (CRUD rapido)

curl -s "$SUPABASE_URL/rest/v1/TABLA?FILTROS" \
  -H "apikey: $SUPABASE_SERVICE_KEY" \
  -H "Authorization: Bearer $SUPABASE_SERVICE_KEY"

Management API (SQL raw)

curl -s -X POST "https://api.supabase.com/v1/projects/$SUPABASE_PROJECT_REF/database/query" \
  -H "Authorization: Bearer $SUPABASE_PAT" \
  -H "Content-Type: application/json" \
  -d '{"query": "TU SQL AQUI"}'

Cuando usar cada uno:

  • MCP → explorar, migraciones, verificar seguridad
  • PostgREST → CRUD, filtros, paginacion, scripts
  • Management API → JOINs, aggregations, SQL complejo, logs

Patron: Crear Tabla con RLS

-- 1. Crear la tabla
apply_migration(
  name: "create_profiles",
  query: "
    CREATE TABLE profiles (
      id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
      username TEXT UNIQUE,
      avatar_url TEXT,
      created_at TIMESTAMPTZ DEFAULT now(),
      updated_at TIMESTAMPTZ DEFAULT now()
    )
  "
)

-- 2. Habilitar RLS
apply_migration(
  name: "enable_rls_profiles",
  query: "ALTER TABLE profiles ENABLE ROW LEVEL SECURITY"
)

-- 3. Politicas
apply_migration(
  name: "profiles_select_own",
  query: "
    CREATE POLICY profiles_select_own ON profiles
    FOR SELECT USING (auth.uid() = id)
  "
)

apply_migration(
  name: "profiles_update_own",
  query: "
    CREATE POLICY profiles_update_own ON profiles
    FOR UPDATE USING (auth.uid() = id)
  "
)

-- 4. Verificar
get_advisors(type: "security")

Claves Foraneas

apply_migration(
  name: "create_posts",
  query: "
    CREATE TABLE posts (
      id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
      user_id UUID REFERENCES profiles(id) ON DELETE CASCADE NOT NULL,
      title TEXT NOT NULL,
      content TEXT,
      published BOOLEAN DEFAULT false,
      created_at TIMESTAMPTZ DEFAULT now()
    )
  "
)

Indices

-- Simple
apply_migration(name: "idx_posts_user_id", query: "CREATE INDEX idx_posts_user_id ON posts(user_id)")

-- Compuesto
apply_migration(name: "idx_posts_user_published", query: "CREATE INDEX idx_posts_user_published ON posts(user_id, published)")

-- Parcial
apply_migration(name: "idx_posts_published", query: "CREATE INDEX idx_posts_published ON posts(created_at) WHERE published = true")

PostgREST — Referencia Rapida

Filtros

OperadorSignificadoEjemplo
eqIgualstatus=eq.active
neqNo igualstatus=neq.deleted
gt / gteMayor / mayor-igualprice_cents=gt.1000
lt / lteMenor / menor-igualcreated_at=lte.2026-01-01
like / ilikePatronemail=ilike.*@gmail.com
inEn listastatus=in.(active,trialing)
isNull checkdeleted_at=is.null
notNegacionstatus=not.eq.canceled
csContains (arrays)tags=cs.{premium}

Ordenar y Paginar

ParametroEjemplo
Ordenarorder=created_at.desc
Limitarlimit=10
Offsetoffset=20
Seleccionar columnasselect=id,name,email
Contar totalHeader: Prefer: count=exact + -I

CRUD Completo

Listar:

curl -s "$SUPABASE_URL/rest/v1/users?select=id,email,created_at&status=eq.active&order=created_at.desc&limit=20" \
  -H "apikey: $SUPABASE_SERVICE_KEY" \
  -H "Authorization: Bearer $SUPABASE_SERVICE_KEY"

Contar:

curl -s "$SUPABASE_URL/rest/v1/users?select=id&status=eq.active" \
  -H "apikey: $SUPABASE_SERVICE_KEY" \
  -H "Authorization: Bearer $SUPABASE_SERVICE_KEY" \
  -H "Prefer: count=exact,head=true" -I 2>/dev/null | grep -i content-range

Insertar:

curl -s -X POST "$SUPABASE_URL/rest/v1/users" \
  -H "apikey: $SUPABASE_SERVICE_KEY" \
  -H "Authorization: Bearer $SUPABASE_SERVICE_KEY" \
  -H "Content-Type: application/json" \
  -H "Prefer: return=representation" \
  -d '{"email": "test@example.com", "name": "Test User"}'

Actualizar:

curl -s -X PATCH "$SUPABASE_URL/rest/v1/users?id=eq.UUID_AQUI" \
  -H "apikey: $SUPABASE_SERVICE_KEY" \
  -H "Authorization: Bearer $SUPABASE_SERVICE_KEY" \
  -H "Content-Type: application/json" \
  -H "Prefer: return=representation" \
  -d '{"status": "inactive"}'

Upsert:

curl -s -X POST "$SUPABASE_URL/rest/v1/metrics" \
  -H "apikey: $SUPABASE_SERVICE_KEY" \
  -H "Authorization: Bearer $SUPABASE_SERVICE_KEY" \
  -H "Content-Type: application/json" \
  -H "Prefer: resolution=merge-duplicates,return=representation" \
  -d '{"date": "2026-03-16", "value": 100}'

Filtrar por fecha (ultimos 7 dias):

curl -s "$SUPABASE_URL/rest/v1/events?created_at=gte.$(date -u -v-7d +%Y-%m-%dT00:00:00Z)&order=created_at.desc" \
  -H "apikey: $SUPABASE_SERVICE_KEY" \
  -H "Authorization: Bearer $SUPABASE_SERVICE_KEY"

Management API — SQL Raw

Usuarios por dia:

curl -s -X POST "https://api.supabase.com/v1/projects/$SUPABASE_PROJECT_REF/database/query" \
  -H "Authorization: Bearer $SUPABASE_PAT" \
  -H "Content-Type: application/json" \
  -d '{"query": "SELECT date_trunc('\''day'\'', created_at)::date as day, count(*) FROM users WHERE created_at >= now() - interval '\''30 days'\'' GROUP BY 1 ORDER BY 1"}'

Revenue total:

curl -s -X POST "https://api.supabase.com/v1/projects/$SUPABASE_PROJECT_REF/database/query" \
  -H "Authorization: Bearer $SUPABASE_PAT" \
  -H "Content-Type: application/json" \
  -d '{"query": "SELECT sum(price_cents)/100.0 as revenue_usd, count(*) as total FROM purchases WHERE status = '\''completed'\''"}'

Top N con JOIN:

curl -s -X POST "https://api.supabase.com/v1/projects/$SUPABASE_PROJECT_REF/database/query" \
  -H "Authorization: Bearer $SUPABASE_PAT" \
  -H "Content-Type: application/json" \
  -d '{"query": "SELECT u.email, count(o.id) as orders FROM users u JOIN orders o ON o.user_id = u.id GROUP BY u.email ORDER BY orders DESC LIMIT 10"}'

Logs:

curl -s "https://api.supabase.com/v1/projects/$SUPABASE_PROJECT_REF/analytics/endpoints/logs.all?iso_timestamp_start=$(date -u -v-1d +%Y-%m-%dT00:00:00Z)" \
  -H "Authorization: Bearer $SUPABASE_PAT"

Patron: Metricas de Negocio

Adapta nombres de tabla y columnas a tu schema:

MRR (Monthly Recurring Revenue)

curl -s "$SUPABASE_URL/rest/v1/purchases?select=price_cents,billing_interval&status=eq.completed&cancel_at_period_end=eq.false" \
  -H "apikey: $SUPABASE_SERVICE_KEY" \
  -H "Authorization: Bearer $SUPABASE_SERVICE_KEY" | python3 -c "
import sys,json; data=json.load(sys.stdin)
mrr=sum(r['price_cents']/(12 if r.get('billing_interval')=='year' else 1) for r in data)
print(f'MRR: \${mrr/100:,.2f} USD ({len(data)} suscripciones activas)')
"

Churn Signal

curl -s "$SUPABASE_URL/rest/v1/purchases?select=id&status=eq.completed&cancel_at_period_end=eq.true" \
  -H "apikey: $SUPABASE_SERVICE_KEY" \
  -H "Authorization: Bearer $SUPABASE_SERVICE_KEY" | python3 -c "
import sys,json; print(f'Van a cancelar: {len(json.load(sys.stdin))}')
"

Funnel de Conversion

curl -s "$SUPABASE_URL/rest/v1/funnel_events?select=event_name&created_at=gte.$(date -u -v-7d +%Y-%m-%dT00:00:00Z)" \
  -H "apikey: $SUPABASE_SERVICE_KEY" \
  -H "Authorization: Bearer $SUPABASE_SERVICE_KEY" | python3 -c "
import sys,json,collections; data=json.load(sys.stdin)
counts=collections.Counter(r['event_name'] for r in data)
for k,v in counts.most_common(): print(f'{k}: {v}')
"

Patron: BI Snapshot (Metricas Diarias)

Tabla que se llena cada noche con un snapshot de tus KPIs:

CREATE TABLE daily_metrics (
  date DATE PRIMARY KEY,
  total_users INTEGER,
  active_users INTEGER,
  new_signups INTEGER,
  revenue_cents INTEGER,
  mrr_cents INTEGER,
  churned INTEGER,
  snapshot_at TIMESTAMPTZ DEFAULT now()
);

Script de snapshot:

TOTAL=$(curl -s "$SUPABASE_URL/rest/v1/users?select=id" -H "apikey: $SUPABASE_SERVICE_KEY" -H "Authorization: Bearer $SUPABASE_SERVICE_KEY" -H "Prefer: count=exact,head=true" -I 2>/dev/null | grep -i content-range | sed 's/.*\///')

curl -s -X POST "$SUPABASE_URL/rest/v1/daily_metrics" \
  -H "apikey: $SUPABASE_SERVICE_KEY" \
  -H "Authorization: Bearer $SUPABASE_SERVICE_KEY" \
  -H "Content-Type: application/json" \
  -H "Prefer: resolution=merge-duplicates,return=representation" \
  -d "{\"date\": \"$(date +%Y-%m-%d)\", \"total_users\": $TOTAL}"

MEGAPROMPT: Documentar tu Schema

Copia y pega en Claude Code:

Documenta el schema completo de mi base de datos Supabase.

1. Ejecuta: list_tables
2. Para cada tabla: execute_sql("SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'NOMBRE_TABLA' ORDER BY ordinal_position")
3. Genera references/schema.md con formato:

# [Mi Proyecto] -- Database Schema
## Project: [project_ref]
## Tables ([N] total)

### nombre_tabla (CRITICAL - [dominio])
- columna1: tipo, columna2: tipo, ...

Marca CRITICAL las tablas mas importantes (usuarios, compras, contenido).
Agrupa por dominio (Core, Content, Analytics, etc.).

Principios

  1. RLS Siempre: Toda tabla con datos de usuario debe tener RLS habilitado
  2. Migraciones Nombradas: Nombres descriptivos para tracking
  3. apply_migration para DDL: CREATE, ALTER, DROP
  4. execute_sql para DML: SELECT, INSERT, UPDATE, DELETE
  5. get_advisors despues de crear tablas: Verificar seguridad
  6. NUNCA fabricar datos: Si un query falla, decirlo
  7. NUNCA mezclar ventanas de tiempo: Advertir si se comparan periodos incompatibles
  8. Verificar con queries reales: No confiar en docs desactualizados
  9. Service Role Key bypassa RLS: Solo en desarrollo/admin
  10. Documentar tu schema: Claude es 10x mas util cuando conoce tus tablas

Flujo de Trabajo

Estructura:
  list_tables → disenar → apply_migration → RLS → policies → get_advisors → test data

Datos:
  Cargar credenciales → PostgREST (CRUD) o Management API (SQL) → verificar resultado

Referencia: Tu Schema

Si documentaste tu schema, esta en references/schema.md. Leelo antes de cualquier query.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.