Manage Apple Reminders via the `remindctl` CLI on macOS (list, add, edit, complete, delete)....
npx skills add TrenzaCR/trenzaos-config --skill "trenza-database"
Install specific skill from multi-skill repository
# Description
>
# SKILL.md
name: trenza-database
description: >
Modelo de datos y convenciones de base de datos para TrenzaOS.
Trigger: Al crear tablas, migraciones, o definir esquemas de datos.
license: MIT
metadata:
author: trenza
version: "1.0"
TrenzaOS Database Skills
Purpose
Este skill enforce el modelo de datos multi-tenant de TrenzaOS.
Core Rules
1. Estructura de Tablas
Toda tabla de negocio DEBE seguir este patrón:
CREATE TABLE products (
-- Primary Key
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- Aislamiento (OBLIGATORIO)
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
-- Datos de negocio
name TEXT NOT NULL,
sku TEXT NOT NULL,
-- Auditoría (OBLIGATORIO)
created_by UUID REFERENCES users(id),
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
-- Soft delete (recomendado)
status TEXT DEFAULT 'active' -- 'active', 'archived'
);
-- Índice para tenant_id
CREATE INDEX idx_products_tenant ON products(tenant_id);
-- SKU único por tenant
CREATE UNIQUE INDEX idx_products_sku_tenant ON products(tenant_id, sku);
-- RLS
ALTER TABLE products ENABLE ROW LEVEL SECURITY;
CREATE POLICY "products_tenant_isolation" ON products
FOR ALL
USING (tenant_id = current_setting('app.current_tenant_id', true)::uuid)
WITH CHECK (tenant_id = current_setting('app.current_tenant_id', true)::uuid);
2. Convenciones de Naming
| Tipo | Convention | Ejemplo |
|---|---|---|
| Tablas | snake_case, plural |
user_sessions |
| Columnas | snake_case |
created_at |
| FK | {table}_id |
tenant_id |
| Índices | idx_{table}_{columns} |
idx_products_tenant |
| Políticas | {table}_{action}_{scope} |
products_tenant_isolation |
3. Tipos de Datos
-- Fechas: SIEMPRE timestamptz (UTC absoluto)
created_at TIMESTAMPTZ DEFAULT NOW()
-- UUIDs
id UUID PRIMARY KEY DEFAULT gen_random_uuid()
-- Dinero: NUMERIC con precisión fija
amount NUMERIC(12, 2) -- 12 dígitos, 2 decimales
-- JSONB para datos flexibles
metadata JSONB DEFAULT '{}'
4. Migraciones
Flujo de trabajo:
# 1. Crear migración
npx supabase migration new add_invoice_status
# 2. Editar SQL
# 3. Probar localmente
npx supabase db push
# 4. Generar tipos
npm run gen:types
# 5. Commit
git add . && git commit -m "feat: add invoice status"
Checklist de migración:
- [ ] Agregar tenant_id si es tabla de negocio
- [ ] Agregar columnas auditoras
- [ ] Crear índices necesarios
- [ ] Crear política RLS
- [ ] Ejecutar npm run gen:types
- [ ] Actualizar tipos Zod
5. Patrón Outbox
Para operaciones asíncronas:
CREATE TABLE outbox (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID REFERENCES tenants(id),
aggregate_type TEXT NOT NULL,
aggregate_id UUID NOT NULL,
event_type TEXT NOT NULL,
payload JSONB NOT NULL,
status TEXT DEFAULT 'pending',
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Trigger para automático
CREATE OR REPLACE FUNCTION publish_to_outbox()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO outbox (aggregate_type, aggregate_id, event_type, payload)
VALUES (
TG_TABLE_NAME,
NEW.id,
TG_OP,
to_jsonb(NEW)
);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
6. Extensiones Especiales
pgvector (AI)
-- CRÍTICO: Filtrar ANTES de similarity search
SELECT * FROM document_embeddings
WHERE tenant_id = current_setting('app.current_tenant_id', true)::uuid
ORDER BY embedding <=> query_embedding
LIMIT 10;
PostGIS (Geoespacial)
-- Índice GIST obligatorio
CREATE INDEX idx_locations_geom ON locations USING GIST (geom);
-- Query con bounds
SELECT * FROM locations
WHERE ST_DWithin(geom, ST_MakePoint(lon, lat)::geography, 5000)
AND tenant_id = current_setting('app.current_tenant_id', true)::uuid;
Database Checklist
Antes de crear/modificar tablas:
- [ ] ¿Tiene
tenant_id? - [ ] ¿Tiene columnas auditoras?
- [ ] ¿Tiene RLS?
- [ ] ¿Tiene índices apropiados?
- [ ] ¿Usa UUIDs, no IDs secuenciales?
- [ ] ¿Tiene soft delete?
References
# Supported AI Coding Agents
This skill is compatible with the SKILL.md standard and works with all major AI coding agents:
Learn more about the SKILL.md standard and how to use these skills with your preferred AI coding agent.