← Tutoriales por extra

🗄️ SQL custom · reportes ad-hoc

Editor SQL read-only en tu panel · ejecuta SELECT/WITH sobre tu schema de tenant · útil reports custom no cubiertos por dashboards · audit trail · sandboxed.

1. ¿Qué resuelve?

2. Cuándo activarlo

3. Setup

  1. Activar extra tenant.custom_sql desde /extras.
  2. Ve a /custom-sql · editor abre.
  3. Solo owner + admin pueden ejecutar. Manager/user/viewer ven 403.

4. Restricciones obligatorias (security)

5. Flujo típico

  1. Editor pre-llenado con ejemplo:
    SELECT id, full_name, email, created_at
    FROM contacts
    ORDER BY created_at DESC
    LIMIT 50
  2. Modificar query · ejecutar · resultados aparecen tabla.
  3. Guardar query · nombre + categoría + descripción · re-ejecutas con 1 click después.
  4. Export CSV · descarga resultados · útil compartir CFO/contador.
  5. Compartir · query guardada visible owner + admin · NO compartido con ningún rol inferior.

6. Queries útiles ejemplo

Top 10 clientes por revenue

SELECT c.full_name, COUNT(i.id) AS num_invoices, SUM(i.total) AS revenue
FROM contacts c
JOIN invoices i ON i.contact_id = c.id
WHERE i.status IN ('issued', 'paid')
  AND i.created_at > NOW() - INTERVAL '6 months'
GROUP BY c.id, c.full_name
ORDER BY revenue DESC
LIMIT 10

Citas canceladas por médico mes pasado

SELECT a.resource_id, COUNT(*) AS cancelled
FROM appointments a
WHERE a.status = 'cancelled'
  AND a.starts_at >= date_trunc('month', NOW() - INTERVAL '1 month')
  AND a.starts_at < date_trunc('month', NOW())
GROUP BY a.resource_id
ORDER BY cancelled DESC

Productos sin venta últimos 90 días

SELECT p.id, p.sku, p.name, p.price
FROM products p
WHERE p.active = true
  AND p.id NOT IN (
    SELECT (jsonb_array_elements(metadata->'lines')->>'productId')::uuid
    FROM invoices
    WHERE created_at > NOW() - INTERVAL '90 days'
      AND jsonb_typeof(metadata->'lines') = 'array'
  )
ORDER BY p.name
LIMIT 50

7. Troubleshooting

8. Audit + compliance

Cada query queda en custom_sql_runs con texto · actor · timestamp · duración. Owner puede revisar trail en /custom-sql/audit · cumple ISO/SOC2 read-only access requirement. Logs retention según plan tenant.

Reference: apps/web/app/custom-sql/ · módulo tenant.custom_sql + validator @vertix/core/sql-validator.