@maestro-ai/cli 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -0
- package/content/guides/Cat/303/241logo de Stacks para Cloud Moderna.md" +119 -0
- package/content/guides/Cat/303/241logo de Stacks para Hospedagem Compartilhada.md" +147 -0
- package/content/guides/Checklist Mestre de Entrega.md +68 -0
- package/content/guides/Gates de Qualidade.md +209 -0
- package/content/guides/Guia de Adi/303/247/303/243o de Novas Funcionalidades.md" +355 -0
- package/content/guides/Guia de Chaos Engineering.md +267 -0
- package/content/guides/Guia de Debugging com IA.md +135 -0
- package/content/guides/Guia de Estrat/303/251gias de Cache.md" +352 -0
- package/content/guides/Guia de Migrations Zero-Downtime.md +311 -0
- package/content/guides/Guia de Multi-tenancy.md +368 -0
- package/content/guides/Guia de Otimiza/303/247/303/243o de Custos Cloud.md" +195 -0
- package/content/guides/Guia de Refatora/303/247/303/243o de C/303/263digo Legado com IA.md" +162 -0
- package/content/guides/Guia de SLOs e Error Budgets.md +315 -0
- package/content/guides/M/303/251tricas de Efici/303/252ncia do Desenvolvimento com IA.md" +93 -0
- package/content/guides/Rules base.md +90 -0
- package/content/prompts/README.md +203 -0
- package/content/prompts/acessibilidade/analise-acessibilidade.md +257 -0
- package/content/prompts/apis/design-api-rest.md +303 -0
- package/content/prompts/apis/idempotencia.md +254 -0
- package/content/prompts/apis/versionamento.md +313 -0
- package/content/prompts/arquitetura/arquitetura-c4-completo.md +190 -0
- package/content/prompts/arquitetura/clean-architecture.md +151 -0
- package/content/prompts/arquitetura/ddd-bounded-contexts.md +183 -0
- package/content/prompts/arquitetura/ddd-cqrs.md +176 -0
- package/content/prompts/arquitetura/modelo-dominio.md +207 -0
- package/content/prompts/arquitetura/multi-tenancy.md +235 -0
- package/content/prompts/database/migrations-zero-downtime.md +192 -0
- package/content/prompts/database/otimizacao-queries.md +296 -0
- package/content/prompts/desenvolvimento/code-review.md +301 -0
- package/content/prompts/desenvolvimento/gerar-servico.md +271 -0
- package/content/prompts/devops/docker-compose.md +336 -0
- package/content/prompts/devops/feature-flags.md +374 -0
- package/content/prompts/devops/kubernetes-deploy.md +460 -0
- package/content/prompts/devops/pipeline-cicd.md +358 -0
- package/content/prompts/devops/terraform-iac.md +502 -0
- package/content/prompts/escalabilidade/analise-performance.md +240 -0
- package/content/prompts/escalabilidade/analise-performance.txt +94 -0
- package/content/prompts/escalabilidade/caching.md +255 -0
- package/content/prompts/observabilidade/chaos-testing.md +237 -0
- package/content/prompts/observabilidade/estrategia-observabilidade.md +263 -0
- package/content/prompts/observabilidade/estrategia-observabilidade.txt +134 -0
- package/content/prompts/observabilidade/slos.md +215 -0
- package/content/prompts/produto/discovery-inicial.md +203 -0
- package/content/prompts/produto/discovery-inicial.txt +33 -0
- package/content/prompts/requisitos/refinar-requisitos.md +232 -0
- package/content/prompts/requisitos/refinar-requisitos.txt +40 -0
- package/content/prompts/seguranca/analise-seguranca.md +243 -0
- package/content/prompts/seguranca/pentest-checklist.md +333 -0
- package/content/prompts/seguranca/rate-limiting.md +356 -0
- package/content/prompts/seguranca/revisao-lgpd.md +227 -0
- package/content/prompts/seguranca/threat-modeling.md +224 -0
- package/content/prompts/testes/contract-testing.md +340 -0
- package/content/prompts/testes/gerar-testes-unitarios.md +474 -0
- package/content/prompts/testes/testes-e2e.md +460 -0
- package/content/prompts/testes/testes-integracao.md +418 -0
- package/content/prompts/testes/testes-performance.md +458 -0
- package/content/prompts/ux/gerar-ui-stitch.md +151 -0
- package/content/skills/api-patterns/SKILL.md +81 -0
- package/content/skills/api-patterns/api-style.md +42 -0
- package/content/skills/api-patterns/auth.md +24 -0
- package/content/skills/api-patterns/documentation.md +26 -0
- package/content/skills/api-patterns/graphql.md +41 -0
- package/content/skills/api-patterns/rate-limiting.md +31 -0
- package/content/skills/api-patterns/response.md +37 -0
- package/content/skills/api-patterns/rest.md +40 -0
- package/content/skills/api-patterns/scripts/api_validator.py +211 -0
- package/content/skills/api-patterns/security-testing.md +122 -0
- package/content/skills/api-patterns/trpc.md +41 -0
- package/content/skills/api-patterns/versioning.md +22 -0
- package/content/skills/app-builder/SKILL.md +75 -0
- package/content/skills/app-builder/agent-coordination.md +71 -0
- package/content/skills/app-builder/feature-building.md +53 -0
- package/content/skills/app-builder/project-detection.md +34 -0
- package/content/skills/app-builder/scaffolding.md +118 -0
- package/content/skills/app-builder/tech-stack.md +40 -0
- package/content/skills/app-builder/templates/SKILL.md +39 -0
- package/content/skills/app-builder/templates/astro-static/TEMPLATE.md +76 -0
- package/content/skills/app-builder/templates/chrome-extension/TEMPLATE.md +92 -0
- package/content/skills/app-builder/templates/cli-tool/TEMPLATE.md +88 -0
- package/content/skills/app-builder/templates/electron-desktop/TEMPLATE.md +88 -0
- package/content/skills/app-builder/templates/express-api/TEMPLATE.md +83 -0
- package/content/skills/app-builder/templates/flutter-app/TEMPLATE.md +90 -0
- package/content/skills/app-builder/templates/monorepo-turborepo/TEMPLATE.md +90 -0
- package/content/skills/app-builder/templates/nextjs-fullstack/TEMPLATE.md +82 -0
- package/content/skills/app-builder/templates/nextjs-saas/TEMPLATE.md +100 -0
- package/content/skills/app-builder/templates/nextjs-static/TEMPLATE.md +106 -0
- package/content/skills/app-builder/templates/nuxt-app/TEMPLATE.md +101 -0
- package/content/skills/app-builder/templates/python-fastapi/TEMPLATE.md +83 -0
- package/content/skills/app-builder/templates/react-native-app/TEMPLATE.md +93 -0
- package/content/skills/architecture/SKILL.md +55 -0
- package/content/skills/architecture/context-discovery.md +43 -0
- package/content/skills/architecture/examples.md +94 -0
- package/content/skills/architecture/pattern-selection.md +68 -0
- package/content/skills/architecture/patterns-reference.md +50 -0
- package/content/skills/architecture/trade-off-analysis.md +77 -0
- package/content/skills/bash-linux/SKILL.md +199 -0
- package/content/skills/behavioral-modes/SKILL.md +242 -0
- package/content/skills/brainstorming/SKILL.md +163 -0
- package/content/skills/brainstorming/dynamic-questioning.md +350 -0
- package/content/skills/clean-code/SKILL.md +201 -0
- package/content/skills/code-review-checklist/SKILL.md +109 -0
- package/content/skills/database-design/SKILL.md +52 -0
- package/content/skills/database-design/database-selection.md +43 -0
- package/content/skills/database-design/indexing.md +39 -0
- package/content/skills/database-design/migrations.md +48 -0
- package/content/skills/database-design/optimization.md +36 -0
- package/content/skills/database-design/orm-selection.md +30 -0
- package/content/skills/database-design/schema-design.md +56 -0
- package/content/skills/database-design/scripts/schema_validator.py +172 -0
- package/content/skills/deployment-procedures/SKILL.md +241 -0
- package/content/skills/doc.md +177 -0
- package/content/skills/documentation-templates/SKILL.md +194 -0
- package/content/skills/frontend-design/SKILL.md +396 -0
- package/content/skills/frontend-design/animation-guide.md +331 -0
- package/content/skills/frontend-design/color-system.md +311 -0
- package/content/skills/frontend-design/decision-trees.md +418 -0
- package/content/skills/frontend-design/motion-graphics.md +306 -0
- package/content/skills/frontend-design/scripts/accessibility_checker.py +183 -0
- package/content/skills/frontend-design/scripts/ux_audit.py +722 -0
- package/content/skills/frontend-design/typography-system.md +345 -0
- package/content/skills/frontend-design/ux-psychology.md +541 -0
- package/content/skills/frontend-design/visual-effects.md +383 -0
- package/content/skills/game-development/2d-games/SKILL.md +119 -0
- package/content/skills/game-development/3d-games/SKILL.md +135 -0
- package/content/skills/game-development/SKILL.md +167 -0
- package/content/skills/game-development/game-art/SKILL.md +185 -0
- package/content/skills/game-development/game-audio/SKILL.md +190 -0
- package/content/skills/game-development/game-design/SKILL.md +129 -0
- package/content/skills/game-development/mobile-games/SKILL.md +108 -0
- package/content/skills/game-development/multiplayer/SKILL.md +132 -0
- package/content/skills/game-development/pc-games/SKILL.md +144 -0
- package/content/skills/game-development/vr-ar/SKILL.md +123 -0
- package/content/skills/game-development/web-games/SKILL.md +150 -0
- package/content/skills/geo-fundamentals/SKILL.md +156 -0
- package/content/skills/geo-fundamentals/scripts/geo_checker.py +289 -0
- package/content/skills/i18n-localization/SKILL.md +154 -0
- package/content/skills/i18n-localization/scripts/i18n_checker.py +241 -0
- package/content/skills/intelligent-routing/SKILL.md +334 -0
- package/content/skills/lint-and-validate/SKILL.md +45 -0
- package/content/skills/lint-and-validate/scripts/lint_runner.py +172 -0
- package/content/skills/lint-and-validate/scripts/type_coverage.py +173 -0
- package/content/skills/mcp-builder/SKILL.md +176 -0
- package/content/skills/mobile-design/SKILL.md +394 -0
- package/content/skills/mobile-design/decision-trees.md +516 -0
- package/content/skills/mobile-design/mobile-backend.md +491 -0
- package/content/skills/mobile-design/mobile-color-system.md +420 -0
- package/content/skills/mobile-design/mobile-debugging.md +122 -0
- package/content/skills/mobile-design/mobile-design-thinking.md +357 -0
- package/content/skills/mobile-design/mobile-navigation.md +458 -0
- package/content/skills/mobile-design/mobile-performance.md +767 -0
- package/content/skills/mobile-design/mobile-testing.md +356 -0
- package/content/skills/mobile-design/mobile-typography.md +433 -0
- package/content/skills/mobile-design/platform-android.md +666 -0
- package/content/skills/mobile-design/platform-ios.md +561 -0
- package/content/skills/mobile-design/scripts/mobile_audit.py +670 -0
- package/content/skills/mobile-design/touch-psychology.md +537 -0
- package/content/skills/nextjs-best-practices/SKILL.md +203 -0
- package/content/skills/nodejs-best-practices/SKILL.md +333 -0
- package/content/skills/parallel-agents/SKILL.md +175 -0
- package/content/skills/performance-profiling/SKILL.md +143 -0
- package/content/skills/performance-profiling/scripts/lighthouse_audit.py +76 -0
- package/content/skills/plan-writing/SKILL.md +152 -0
- package/content/skills/powershell-windows/SKILL.md +167 -0
- package/content/skills/python-patterns/SKILL.md +441 -0
- package/content/skills/react-patterns/SKILL.md +198 -0
- package/content/skills/red-team-tactics/SKILL.md +199 -0
- package/content/skills/seo-fundamentals/SKILL.md +129 -0
- package/content/skills/seo-fundamentals/scripts/seo_checker.py +219 -0
- package/content/skills/server-management/SKILL.md +161 -0
- package/content/skills/systematic-debugging/SKILL.md +109 -0
- package/content/skills/tailwind-patterns/SKILL.md +269 -0
- package/content/skills/tdd-workflow/SKILL.md +149 -0
- package/content/skills/testing-patterns/SKILL.md +178 -0
- package/content/skills/testing-patterns/scripts/test_runner.py +219 -0
- package/content/skills/vulnerability-scanner/SKILL.md +276 -0
- package/content/skills/vulnerability-scanner/checklists.md +121 -0
- package/content/skills/vulnerability-scanner/scripts/security_scan.py +458 -0
- package/content/skills/webapp-testing/SKILL.md +187 -0
- package/content/skills/webapp-testing/scripts/playwright_runner.py +173 -0
- package/content/specialists/Especialista em Acessibilidade.md +266 -0
- package/content/specialists/Especialista em An/303/241lise de Testes.md" +434 -0
- package/content/specialists/Especialista em Arquitetura Avan/303/247ada.md" +358 -0
- package/content/specialists/Especialista em Arquitetura de Software.md +177 -0
- package/content/specialists/Especialista em Banco de Dados.md +260 -0
- package/content/specialists/Especialista em Contrato de API.md +172 -0
- package/content/specialists/Especialista em Dados e Analytics com IA.md +246 -0
- package/content/specialists/Especialista em Debugging e Troubleshooting.md +191 -0
- package/content/specialists/Especialista em Desenvolvimento Frontend.md +477 -0
- package/content/specialists/Especialista em Desenvolvimento Mobile.md +241 -0
- package/content/specialists/Especialista em Desenvolvimento e Vibe Coding Estruturado.md +417 -0
- package/content/specialists/Especialista em DevOps e Infraestrutura.md +294 -0
- package/content/specialists/Especialista em Documenta/303/247/303/243o T/303/251cnica.md" +227 -0
- package/content/specialists/Especialista em Engenharia de Requisitos com IA.md +299 -0
- package/content/specialists/Especialista em Explora/303/247/303/243o de Codebase.md" +179 -0
- package/content/specialists/Especialista em Gest/303/243o de Produto.md" +179 -0
- package/content/specialists/Especialista em Migra/303/247/303/243o e Moderniza/303/247/303/243o.md" +410 -0
- package/content/specialists/Especialista em Modelagem e Arquitetura de Dom/303/255nio com IA.md" +248 -0
- package/content/specialists/Especialista em Observabilidade.md +415 -0
- package/content/specialists/Especialista em Performance e Escalabilidade.md +373 -0
- package/content/specialists/Especialista em Plano de Execu/303/247/303/243o com IA.md" +341 -0
- package/content/specialists/Especialista em Prototipagem R/303/241pida com Google Stitch.md" +419 -0
- package/content/specialists/Especialista em Seguran/303/247a da Informa/303/247/303/243o.md" +508 -0
- package/content/specialists/Especialista em UX Design.md +453 -0
- package/content/specialists/INDEX.md +43 -0
- package/content/templates/PRD.md +165 -0
- package/content/templates/README.md +65 -0
- package/content/templates/adr.md +103 -0
- package/content/templates/arquitetura.md +279 -0
- package/content/templates/backlog.md +185 -0
- package/content/templates/checklist-seguranca.md +180 -0
- package/content/templates/contexto.md +120 -0
- package/content/templates/criterios-aceite.md +99 -0
- package/content/templates/design-banco.md +270 -0
- package/content/templates/design-doc.md +240 -0
- package/content/templates/feature.md +88 -0
- package/content/templates/historia-backend.md +84 -0
- package/content/templates/historia-frontend.md +75 -0
- package/content/templates/historia-usuario.md +125 -0
- package/content/templates/mapa-navegacao.md +133 -0
- package/content/templates/matriz-rastreabilidade.md +121 -0
- package/content/templates/modelo-dominio.md +219 -0
- package/content/templates/plano-testes.md +199 -0
- package/content/templates/prototipo-stitch.md +138 -0
- package/content/templates/requisitos.md +162 -0
- package/content/templates/slo-sli.md +197 -0
- package/content/workflows/README-MCP.md +363 -0
- package/content/workflows/brainstorm.md +113 -0
- package/content/workflows/create.md +59 -0
- package/content/workflows/debug.md +103 -0
- package/content/workflows/deploy.md +176 -0
- package/content/workflows/enhance.md +63 -0
- package/content/workflows/mcp-debug.md +506 -0
- package/content/workflows/mcp-feature.md +385 -0
- package/content/workflows/mcp-gate.md +413 -0
- package/content/workflows/mcp-next.md +388 -0
- package/content/workflows/mcp-refactor.md +600 -0
- package/content/workflows/mcp-start.md +304 -0
- package/content/workflows/mcp-status.md +400 -0
- package/content/workflows/orchestrate.md +237 -0
- package/content/workflows/plan.md +89 -0
- package/content/workflows/preview.md +81 -0
- package/content/workflows/status.md +86 -0
- package/content/workflows/test.md +144 -0
- package/content/workflows/ui-ux-pro-max.md +296 -0
- package/dist/commands/init.d.ts +6 -0
- package/dist/commands/init.js +138 -0
- package/dist/commands/update.d.ts +5 -0
- package/dist/commands/update.js +50 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +21 -0
- package/package.json +48 -0
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
# Prompt: Multi-tenancy
|
|
2
|
+
|
|
3
|
+
> **Prioridade**: 🟡 MÉDIA
|
|
4
|
+
> **Aplicável a**: SaaS, plataformas white-label, sistemas B2B
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Prompt Base: Projetar Multi-tenancy
|
|
9
|
+
|
|
10
|
+
```text
|
|
11
|
+
Atue como arquiteto de software especialista em SaaS.
|
|
12
|
+
|
|
13
|
+
Preciso implementar multi-tenancy para:
|
|
14
|
+
- Tipo de produto: [ex. CRM SaaS, e-commerce white-label]
|
|
15
|
+
- Número esperado de tenants: [ex. 100 / 10.000 / 1M]
|
|
16
|
+
- Isolamento necessário: [ex. dados apenas / compliance rígido]
|
|
17
|
+
- Customização por tenant: [ex. branding / features / workflows]
|
|
18
|
+
|
|
19
|
+
Constraints:
|
|
20
|
+
- Stack: [DESCREVA]
|
|
21
|
+
- Orçamento de infra: [DESCREVA]
|
|
22
|
+
- Time: [DESCREVA]
|
|
23
|
+
|
|
24
|
+
Projete:
|
|
25
|
+
|
|
26
|
+
1. **Modelo de Isolamento**
|
|
27
|
+
- Database per tenant, schema per tenant, ou row-level?
|
|
28
|
+
- Justificativa para o contexto
|
|
29
|
+
- Estratégia para tenants com necessidades especiais
|
|
30
|
+
|
|
31
|
+
2. **Identificação de Tenant**
|
|
32
|
+
- Como identificar o tenant em cada request
|
|
33
|
+
- Subdomain, header, JWT, ou combinação
|
|
34
|
+
- Fallback se não identificado
|
|
35
|
+
|
|
36
|
+
3. **Implementação de Dados**
|
|
37
|
+
- Schema das tabelas (com tenant_id)
|
|
38
|
+
- Middleware/interceptor para filtrar
|
|
39
|
+
- Como garantir que queries não vazem dados
|
|
40
|
+
|
|
41
|
+
4. **Customização**
|
|
42
|
+
- Configurações por tenant
|
|
43
|
+
- Feature flags por plano
|
|
44
|
+
- Branding (logo, cores)
|
|
45
|
+
|
|
46
|
+
5. **Operacional**
|
|
47
|
+
- Provisioning de novo tenant
|
|
48
|
+
- Migrations multi-tenant
|
|
49
|
+
- Backup/restore por tenant
|
|
50
|
+
- Monitoramento por tenant
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## Prompt: Migrar para Multi-tenant
|
|
56
|
+
|
|
57
|
+
```text
|
|
58
|
+
Tenho um sistema single-tenant que precisa virar multi-tenant:
|
|
59
|
+
[DESCREVA ESTRUTURA ATUAL]
|
|
60
|
+
|
|
61
|
+
Requisitos:
|
|
62
|
+
- Manter dados do tenant atual
|
|
63
|
+
- Adicionar suporte a novos tenants
|
|
64
|
+
- Mínimo de breaking changes
|
|
65
|
+
- Timeline: [PRAZO]
|
|
66
|
+
|
|
67
|
+
Gere um plano de migração com:
|
|
68
|
+
1. Alterações de schema (adicionar tenant_id)
|
|
69
|
+
2. Migrations de dados existentes
|
|
70
|
+
3. Mudanças de código (queries, middlewares)
|
|
71
|
+
4. Testes de validação
|
|
72
|
+
5. Rollout gradual
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## Prompt: Implementar Row-Level Security
|
|
78
|
+
|
|
79
|
+
```text
|
|
80
|
+
Preciso implementar isolamento por row-level security.
|
|
81
|
+
|
|
82
|
+
Stack: [ex. PostgreSQL + Prisma + Node.js]
|
|
83
|
+
|
|
84
|
+
Tabelas principais:
|
|
85
|
+
[LISTE TABELAS]
|
|
86
|
+
|
|
87
|
+
Gere:
|
|
88
|
+
1. Migrations para adicionar tenant_id
|
|
89
|
+
2. Policies RLS no PostgreSQL
|
|
90
|
+
3. Middleware para setar current_tenant
|
|
91
|
+
4. Repository base com tenant scope
|
|
92
|
+
5. Testes de isolamento
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## Prompt: Tenant Provisioning
|
|
98
|
+
|
|
99
|
+
```text
|
|
100
|
+
Preciso automatizar o onboarding de novos tenants.
|
|
101
|
+
|
|
102
|
+
Quando um novo tenant é criado, preciso:
|
|
103
|
+
- [ex. Criar registro no banco]
|
|
104
|
+
- [ex. Configurar subdomain no DNS]
|
|
105
|
+
- [ex. Criar usuário admin]
|
|
106
|
+
- [ex. Popular dados iniciais]
|
|
107
|
+
- [ex. Enviar email de boas-vindas]
|
|
108
|
+
|
|
109
|
+
Stack: [DESCREVA]
|
|
110
|
+
|
|
111
|
+
Gere:
|
|
112
|
+
1. Endpoint/workflow de provisioning
|
|
113
|
+
2. Jobs assíncronos necessários
|
|
114
|
+
3. Rollback se algum step falhar
|
|
115
|
+
4. Notificações de progresso
|
|
116
|
+
5. Documentação do processo
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## Prompt: Limites e Quotas por Tenant
|
|
122
|
+
|
|
123
|
+
```text
|
|
124
|
+
Preciso implementar limites por plano:
|
|
125
|
+
|
|
126
|
+
| Recurso | Free | Pro | Enterprise |
|
|
127
|
+
|---------|------|-----|------------|
|
|
128
|
+
| Usuários | 5 | 50 | Ilimitado |
|
|
129
|
+
| Storage | 1GB | 10GB | 100GB |
|
|
130
|
+
| API calls/dia | 1000 | 10000 | Ilimitado |
|
|
131
|
+
| Features | [X,Y] | [X,Y,Z] | Todas |
|
|
132
|
+
|
|
133
|
+
Stack: [DESCREVA]
|
|
134
|
+
|
|
135
|
+
Gere:
|
|
136
|
+
1. Schema para quotas e usage tracking
|
|
137
|
+
2. Service para verificar limites
|
|
138
|
+
3. Middleware para bloquear quando excede
|
|
139
|
+
4. Dashboard de usage para tenant admin
|
|
140
|
+
5. Alerts quando próximo do limite
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
## Exemplo: Tenant Context Completo
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
// src/tenancy/TenantContext.ts
|
|
149
|
+
import { AsyncLocalStorage } from 'async_hooks';
|
|
150
|
+
import { PrismaClient } from '@prisma/client';
|
|
151
|
+
|
|
152
|
+
interface TenantContext {
|
|
153
|
+
tenantId: string;
|
|
154
|
+
config: TenantConfig;
|
|
155
|
+
user?: User;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
interface TenantConfig {
|
|
159
|
+
id: string;
|
|
160
|
+
subdomain: string;
|
|
161
|
+
plan: 'free' | 'pro' | 'enterprise';
|
|
162
|
+
quotas: {
|
|
163
|
+
maxUsers: number;
|
|
164
|
+
maxStorage: number;
|
|
165
|
+
maxApiCalls: number;
|
|
166
|
+
};
|
|
167
|
+
features: string[];
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const storage = new AsyncLocalStorage<TenantContext>();
|
|
171
|
+
|
|
172
|
+
// Middleware
|
|
173
|
+
export async function tenantMiddleware(req, res, next) {
|
|
174
|
+
const tenantId = extractTenantIdFromRequest(req);
|
|
175
|
+
|
|
176
|
+
if (!tenantId) {
|
|
177
|
+
return res.status(400).json({ error: 'Tenant not found' });
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const config = await loadTenantConfig(tenantId);
|
|
181
|
+
|
|
182
|
+
storage.run({ tenantId, config }, next);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Getters
|
|
186
|
+
export function getTenant(): TenantContext {
|
|
187
|
+
const ctx = storage.getStore();
|
|
188
|
+
if (!ctx) throw new Error('No tenant context');
|
|
189
|
+
return ctx;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function getTenantId(): string {
|
|
193
|
+
return getTenant().tenantId;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function hasFeature(feature: string): boolean {
|
|
197
|
+
return getTenant().config.features.includes(feature);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Prisma extension para injetar tenant automaticamente
|
|
201
|
+
export const prisma = new PrismaClient().$extends({
|
|
202
|
+
query: {
|
|
203
|
+
$allModels: {
|
|
204
|
+
async findMany({ args, query }) {
|
|
205
|
+
args.where = { ...args.where, tenantId: getTenantId() };
|
|
206
|
+
return query(args);
|
|
207
|
+
},
|
|
208
|
+
async create({ args, query }) {
|
|
209
|
+
args.data = { ...args.data, tenantId: getTenantId() };
|
|
210
|
+
return query(args);
|
|
211
|
+
},
|
|
212
|
+
// ... outras operações
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
---
|
|
219
|
+
|
|
220
|
+
## Checklist
|
|
221
|
+
|
|
222
|
+
- [ ] Modelo de isolamento definido
|
|
223
|
+
- [ ] Identificação de tenant implementada
|
|
224
|
+
- [ ] Todas as queries filtram por tenant
|
|
225
|
+
- [ ] Testes de isolamento automatizados
|
|
226
|
+
- [ ] Provisioning automatizado
|
|
227
|
+
- [ ] Limites e quotas por plano
|
|
228
|
+
- [ ] Monitoramento por tenant
|
|
229
|
+
- [ ] Documentação de onboarding
|
|
230
|
+
|
|
231
|
+
---
|
|
232
|
+
|
|
233
|
+
## Referências
|
|
234
|
+
|
|
235
|
+
Consulte: [Guia de Multi-tenancy](../03-guias/Guia%20de%20Multi-tenancy.md)
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# Prompt: Database Migrations Zero-Downtime
|
|
2
|
+
|
|
3
|
+
> **Prioridade**: 🟠 ALTA
|
|
4
|
+
> **Aplicável a**: Sistemas em produção com tráfego contínuo
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Contexto
|
|
9
|
+
|
|
10
|
+
Migrations tradicionais podem causar downtime ou erros quando aplicadas em sistemas ativos. Este prompt ajuda a planejar migrations seguras.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## Prompt Base: Planejar Migration
|
|
15
|
+
|
|
16
|
+
```text
|
|
17
|
+
Atue como DBA especialista em migrations zero-downtime.
|
|
18
|
+
|
|
19
|
+
Preciso fazer a seguinte alteração no banco de dados:
|
|
20
|
+
[DESCREVA A ALTERAÇÃO: ex. renomear coluna, alterar tipo, adicionar índice]
|
|
21
|
+
|
|
22
|
+
Contexto:
|
|
23
|
+
- Banco: [PostgreSQL/MySQL/SQL Server]
|
|
24
|
+
- Tamanho da tabela: [ex. 5 milhões de registros]
|
|
25
|
+
- Tráfego: [ex. 100 writes/min]
|
|
26
|
+
- Deploy: [blue-green/rolling/single server]
|
|
27
|
+
|
|
28
|
+
Gere um plano de migration com:
|
|
29
|
+
|
|
30
|
+
1. **Análise de Risco**
|
|
31
|
+
- A operação bloqueia a tabela?
|
|
32
|
+
- Tempo estimado de execução
|
|
33
|
+
- Impacto em queries ativas
|
|
34
|
+
|
|
35
|
+
2. **Estratégia de Migration**
|
|
36
|
+
- Quantos deploys são necessários?
|
|
37
|
+
- Ordem das alterações
|
|
38
|
+
- Scripts SQL para cada step
|
|
39
|
+
|
|
40
|
+
3. **Backward Compatibility**
|
|
41
|
+
- Como manter código antigo funcionando?
|
|
42
|
+
- Triggers ou dual-write necessários?
|
|
43
|
+
|
|
44
|
+
4. **Rollback Plan**
|
|
45
|
+
- Como reverter cada step?
|
|
46
|
+
- Dados perdidos em rollback?
|
|
47
|
+
|
|
48
|
+
5. **Monitoramento**
|
|
49
|
+
- O que observar durante a migration?
|
|
50
|
+
- Alertas a configurar
|
|
51
|
+
|
|
52
|
+
Siga o padrão Expand-Contract quando aplicável.
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Prompt: Migrar Coluna com Dados
|
|
58
|
+
|
|
59
|
+
```text
|
|
60
|
+
Tenho uma coluna que precisa ser transformada:
|
|
61
|
+
- Tabela: [NOME]
|
|
62
|
+
- Coluna atual: [NOME, TIPO]
|
|
63
|
+
- Transformação: [ex. split em duas colunas, mudar encoding, converter unidade]
|
|
64
|
+
- Registros: [QUANTIDADE]
|
|
65
|
+
|
|
66
|
+
Stack: [DESCREVA ORM/Framework]
|
|
67
|
+
|
|
68
|
+
Gere:
|
|
69
|
+
1. Scripts SQL para cada fase (expand, migrate, contract)
|
|
70
|
+
2. Job de backfill com batches
|
|
71
|
+
3. Código para dual-write durante transição
|
|
72
|
+
4. Verificações de integridade após migration
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## Prompt: Adicionar Índice em Tabela Grande
|
|
78
|
+
|
|
79
|
+
```text
|
|
80
|
+
Preciso adicionar um índice para melhorar performance:
|
|
81
|
+
- Tabela: [NOME], [X milhões de registros]
|
|
82
|
+
- Índice: [COLUNAS, TIPO]
|
|
83
|
+
- Banco: [PostgreSQL/MySQL]
|
|
84
|
+
- Tolerância a downtime: [zero/alguns segundos]
|
|
85
|
+
|
|
86
|
+
Gere:
|
|
87
|
+
1. Comando para criar índice sem bloquear (CONCURRENTLY, ONLINE)
|
|
88
|
+
2. Estimativa de tempo baseada no tamanho
|
|
89
|
+
3. Monitoramento durante criação
|
|
90
|
+
4. Verificação de que o índice está sendo usado
|
|
91
|
+
5. Plano B se a criação falhar
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## Prompt: Revisar Migration Existente
|
|
97
|
+
|
|
98
|
+
```text
|
|
99
|
+
Tenho este script de migration:
|
|
100
|
+
[COLE O SCRIPT]
|
|
101
|
+
|
|
102
|
+
Contexto:
|
|
103
|
+
- Ambiente: produção com [X] req/s
|
|
104
|
+
- Deploy: [TIPO]
|
|
105
|
+
- Banco: [TIPO E VERSÃO]
|
|
106
|
+
|
|
107
|
+
Analise:
|
|
108
|
+
1. Há operações que bloqueiam tabelas?
|
|
109
|
+
2. É backward compatible?
|
|
110
|
+
3. O rollback é possível?
|
|
111
|
+
4. Há riscos de perda de dados?
|
|
112
|
+
|
|
113
|
+
Sugira versão zero-downtime se necessário.
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## Exemplo: Migration Segura Completa
|
|
119
|
+
|
|
120
|
+
### Cenário: Renomear `name` para `full_name`
|
|
121
|
+
|
|
122
|
+
```sql
|
|
123
|
+
-- DEPLOY 1: Expand
|
|
124
|
+
-- Adiciona nova coluna
|
|
125
|
+
ALTER TABLE users ADD COLUMN full_name VARCHAR(255);
|
|
126
|
+
|
|
127
|
+
-- Cria trigger para sincronizar
|
|
128
|
+
CREATE OR REPLACE FUNCTION sync_user_name()
|
|
129
|
+
RETURNS TRIGGER AS $$
|
|
130
|
+
BEGIN
|
|
131
|
+
IF NEW.full_name IS NULL THEN
|
|
132
|
+
NEW.full_name := NEW.name;
|
|
133
|
+
END IF;
|
|
134
|
+
IF NEW.name IS NULL THEN
|
|
135
|
+
NEW.name := NEW.full_name;
|
|
136
|
+
END IF;
|
|
137
|
+
RETURN NEW;
|
|
138
|
+
END;
|
|
139
|
+
$$ LANGUAGE plpgsql;
|
|
140
|
+
|
|
141
|
+
CREATE TRIGGER trg_sync_user_name
|
|
142
|
+
BEFORE INSERT OR UPDATE ON users
|
|
143
|
+
FOR EACH ROW EXECUTE FUNCTION sync_user_name();
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
# DEPLOY 1: Código dual-write
|
|
148
|
+
class User:
|
|
149
|
+
def save(self):
|
|
150
|
+
self.full_name = self.name # Sync
|
|
151
|
+
db.save(self)
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
```sql
|
|
155
|
+
-- DEPLOY 1: Backfill (pode rodar após deploy)
|
|
156
|
+
UPDATE users SET full_name = name WHERE full_name IS NULL;
|
|
157
|
+
-- Em batches para tabelas grandes:
|
|
158
|
+
-- UPDATE users SET full_name = name WHERE full_name IS NULL LIMIT 10000;
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
# DEPLOY 2: Código usa nova coluna
|
|
163
|
+
class User:
|
|
164
|
+
@property
|
|
165
|
+
def display_name(self):
|
|
166
|
+
return self.full_name # Usa nova coluna
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
```sql
|
|
170
|
+
-- DEPLOY 3: Contract (após confirmar que nenhum código antigo está ativo)
|
|
171
|
+
DROP TRIGGER trg_sync_user_name ON users;
|
|
172
|
+
DROP FUNCTION sync_user_name();
|
|
173
|
+
ALTER TABLE users DROP COLUMN name;
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
## Checklist
|
|
179
|
+
|
|
180
|
+
- [ ] Testei em staging com dados similares a produção
|
|
181
|
+
- [ ] Medi tempo de execução em tabela grande
|
|
182
|
+
- [ ] Documentei cada step e ordem de execução
|
|
183
|
+
- [ ] Preparei scripts de rollback
|
|
184
|
+
- [ ] Informei time sobre janela de migration
|
|
185
|
+
- [ ] Backup recente existe e foi testado
|
|
186
|
+
- [ ] Monitoramento configurado
|
|
187
|
+
|
|
188
|
+
---
|
|
189
|
+
|
|
190
|
+
## Referências
|
|
191
|
+
|
|
192
|
+
Consulte: [Guia de Migrations Zero-Downtime](../03-guias/Guia%20de%20Migrations%20Zero-Downtime.md)
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
# Prompt: Otimização de Queries e Banco de Dados
|
|
2
|
+
|
|
3
|
+
> **Quando usar**: Ao identificar queries lentas ou planejar schema de banco
|
|
4
|
+
> **Especialista**: DBA / [Performance e Escalabilidade](../../02-especialistas/Especialista%20em%20Performance%20e%20Escalabilidade.md)
|
|
5
|
+
> **Nível**: Médio a Complexo
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Fluxo de Contexto
|
|
10
|
+
|
|
11
|
+
Antes de usar este prompt, tenha em mãos:
|
|
12
|
+
- Schema atual do banco ou modelo de domínio
|
|
13
|
+
- Queries problemáticas (se houver)
|
|
14
|
+
- Volume de dados esperado
|
|
15
|
+
|
|
16
|
+
Após gerar, salve o resultado em:
|
|
17
|
+
- `docs/07-performance/otimizacao-database.md`
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## Prompt Completo
|
|
22
|
+
|
|
23
|
+
```text
|
|
24
|
+
Atue como DBA sênior especializado em otimização de banco de dados.
|
|
25
|
+
|
|
26
|
+
## Contexto do Projeto
|
|
27
|
+
|
|
28
|
+
[COLE BREVE DESCRIÇÃO DO SISTEMA]
|
|
29
|
+
|
|
30
|
+
## Banco de Dados
|
|
31
|
+
|
|
32
|
+
Tipo: [PostgreSQL/MySQL/MongoDB/etc]
|
|
33
|
+
Versão: [Versão]
|
|
34
|
+
Cloud: [RDS/Cloud SQL/Atlas/Self-hosted]
|
|
35
|
+
Tamanho atual: [XGB de dados]
|
|
36
|
+
Tamanho esperado: [X em 1 ano]
|
|
37
|
+
|
|
38
|
+
## Schema Atual
|
|
39
|
+
|
|
40
|
+
```sql
|
|
41
|
+
[COLE O SCHEMA DDL OU DESCREVA AS TABELAS]
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Queries Problemáticas (se houver)
|
|
45
|
+
|
|
46
|
+
```sql
|
|
47
|
+
-- Query 1: [Descrição]
|
|
48
|
+
[QUERY SQL]
|
|
49
|
+
-- Tempo atual: Xms
|
|
50
|
+
-- Frequência: Y vezes/dia
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Volume de Dados
|
|
54
|
+
|
|
55
|
+
- Tabela X: ~N registros, crescimento K/mês
|
|
56
|
+
- Tabela Y: ~N registros, crescimento K/mês
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## Sua Missão
|
|
61
|
+
|
|
62
|
+
Analise e otimize o banco de dados:
|
|
63
|
+
|
|
64
|
+
### 1. Análise de Schema
|
|
65
|
+
|
|
66
|
+
#### 1.1 Tipos de Dados
|
|
67
|
+
- Tipos apropriados para cada coluna?
|
|
68
|
+
- Tamanhos excessivos (VARCHAR(255) desnecessário)?
|
|
69
|
+
- Nullable vs NOT NULL corretos?
|
|
70
|
+
|
|
71
|
+
#### 1.2 Normalização
|
|
72
|
+
- Está na forma normal adequada (3NF)?
|
|
73
|
+
- Há desnormalização intencional justificada?
|
|
74
|
+
- Redundância de dados?
|
|
75
|
+
|
|
76
|
+
#### 1.3 Relacionamentos
|
|
77
|
+
- Foreign keys definidas?
|
|
78
|
+
- Cascade appropriado?
|
|
79
|
+
- Índices em FKs?
|
|
80
|
+
|
|
81
|
+
### 2. Análise de Índices
|
|
82
|
+
|
|
83
|
+
#### 2.1 Índices Existentes
|
|
84
|
+
- Estão sendo utilizados?
|
|
85
|
+
- Há índices duplicados?
|
|
86
|
+
- Ordem das colunas correta?
|
|
87
|
+
|
|
88
|
+
#### 2.2 Índices Sugeridos
|
|
89
|
+
Para cada índice sugerido:
|
|
90
|
+
- Colunas e ordem
|
|
91
|
+
- Tipo (B-tree, Hash, GIN, GiST)
|
|
92
|
+
- Justificativa (queries beneficiadas)
|
|
93
|
+
- Impacto em writes
|
|
94
|
+
|
|
95
|
+
#### 2.3 Índices para Remover
|
|
96
|
+
- Índices não utilizados
|
|
97
|
+
- Índices duplicados
|
|
98
|
+
|
|
99
|
+
### 3. Otimização de Queries
|
|
100
|
+
|
|
101
|
+
Para cada query problemática:
|
|
102
|
+
|
|
103
|
+
#### 3.1 EXPLAIN ANALYZE
|
|
104
|
+
```sql
|
|
105
|
+
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) [QUERY];
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
#### 3.2 Problemas Identificados
|
|
109
|
+
- Sequential scans em tabelas grandes?
|
|
110
|
+
- Nested loops com muitas iterações?
|
|
111
|
+
- Sort em memória vs disco?
|
|
112
|
+
- Hash joins custosos?
|
|
113
|
+
|
|
114
|
+
#### 3.3 Query Otimizada
|
|
115
|
+
```sql
|
|
116
|
+
-- Query original
|
|
117
|
+
[QUERY ORIGINAL]
|
|
118
|
+
|
|
119
|
+
-- Query otimizada
|
|
120
|
+
[QUERY OTIMIZADA]
|
|
121
|
+
|
|
122
|
+
-- Ganho: de Xms para Yms (Z% melhoria)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### 4. Design de Schema (se aplicável)
|
|
126
|
+
|
|
127
|
+
Para novas tabelas ou refatoração:
|
|
128
|
+
|
|
129
|
+
#### 4.1 DDL Otimizado
|
|
130
|
+
```sql
|
|
131
|
+
CREATE TABLE tabela (
|
|
132
|
+
-- colunas com tipos otimizados
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
-- Índices
|
|
136
|
+
CREATE INDEX ...;
|
|
137
|
+
|
|
138
|
+
-- Constraints
|
|
139
|
+
ALTER TABLE ...;
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
#### 4.2 Particionamento
|
|
143
|
+
- Candidatos a particionamento
|
|
144
|
+
- Estratégia (range, list, hash)
|
|
145
|
+
- Manutenção de partições
|
|
146
|
+
|
|
147
|
+
### 5. Connection Pooling
|
|
148
|
+
|
|
149
|
+
- Pool size recomendado
|
|
150
|
+
- Timeout configurations
|
|
151
|
+
- Tool recomendada (PgBouncer, ProxySQL)
|
|
152
|
+
|
|
153
|
+
### 6. Vacuum e Manutenção (PostgreSQL)
|
|
154
|
+
|
|
155
|
+
- Vacuum strategy
|
|
156
|
+
- autovacuum settings
|
|
157
|
+
- Bloat monitoring
|
|
158
|
+
- REINDEX frequency
|
|
159
|
+
|
|
160
|
+
### 7. Migrations
|
|
161
|
+
|
|
162
|
+
Se sugerir alterações de schema:
|
|
163
|
+
```sql
|
|
164
|
+
-- Migration up
|
|
165
|
+
ALTER TABLE ...;
|
|
166
|
+
|
|
167
|
+
-- Migration down (rollback)
|
|
168
|
+
ALTER TABLE ...;
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### 8. Métricas e Monitoramento
|
|
172
|
+
|
|
173
|
+
- Métricas essenciais
|
|
174
|
+
- Queries lentas (slow query log)
|
|
175
|
+
- Alertas recomendados
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
---
|
|
179
|
+
|
|
180
|
+
## Exemplo de Uso
|
|
181
|
+
|
|
182
|
+
```text
|
|
183
|
+
Atue como DBA sênior especializado em otimização de banco de dados.
|
|
184
|
+
|
|
185
|
+
## Contexto do Projeto
|
|
186
|
+
|
|
187
|
+
Sistema de agendamento para salões de beleza.
|
|
188
|
+
Consultas frequentes de disponibilidade.
|
|
189
|
+
|
|
190
|
+
## Banco de Dados
|
|
191
|
+
|
|
192
|
+
Tipo: PostgreSQL
|
|
193
|
+
Versão: 15
|
|
194
|
+
Cloud: AWS RDS (db.t3.medium)
|
|
195
|
+
Tamanho atual: 2GB
|
|
196
|
+
Tamanho esperado: 50GB em 1 ano
|
|
197
|
+
|
|
198
|
+
## Schema Atual
|
|
199
|
+
|
|
200
|
+
```sql
|
|
201
|
+
CREATE TABLE clientes (
|
|
202
|
+
id UUID PRIMARY KEY,
|
|
203
|
+
nome VARCHAR(255),
|
|
204
|
+
telefone VARCHAR(255),
|
|
205
|
+
email VARCHAR(255),
|
|
206
|
+
criado_em TIMESTAMP
|
|
207
|
+
);
|
|
208
|
+
|
|
209
|
+
CREATE TABLE agendamentos (
|
|
210
|
+
id UUID PRIMARY KEY,
|
|
211
|
+
cliente_id UUID REFERENCES clientes(id),
|
|
212
|
+
profissional_id UUID REFERENCES profissionais(id),
|
|
213
|
+
servico_id UUID REFERENCES servicos(id),
|
|
214
|
+
data_hora TIMESTAMP,
|
|
215
|
+
status VARCHAR(50),
|
|
216
|
+
criado_em TIMESTAMP
|
|
217
|
+
);
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
## Queries Problemáticas
|
|
221
|
+
|
|
222
|
+
```sql
|
|
223
|
+
-- Query 1: Buscar disponibilidade de um profissional
|
|
224
|
+
SELECT * FROM agendamentos
|
|
225
|
+
WHERE profissional_id = $1
|
|
226
|
+
AND data_hora BETWEEN $2 AND $3
|
|
227
|
+
AND status != 'CANCELADO';
|
|
228
|
+
-- Tempo atual: 800ms
|
|
229
|
+
-- Frequência: 1000 vezes/dia
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
## Volume de Dados
|
|
233
|
+
|
|
234
|
+
- clientes: ~10.000 registros, +500/mês
|
|
235
|
+
- agendamentos: ~100.000 registros, +5.000/mês
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
---
|
|
239
|
+
|
|
240
|
+
## Resposta Esperada
|
|
241
|
+
|
|
242
|
+
### Schema Otimizado
|
|
243
|
+
|
|
244
|
+
```sql
|
|
245
|
+
-- Problema: VARCHAR(255) excessivo e sem índices
|
|
246
|
+
-- Correção: tipos adequados e índices
|
|
247
|
+
|
|
248
|
+
ALTER TABLE clientes ALTER COLUMN telefone TYPE VARCHAR(20);
|
|
249
|
+
ALTER TABLE clientes ALTER COLUMN email TYPE VARCHAR(100);
|
|
250
|
+
ALTER TABLE agendamentos ALTER COLUMN status TYPE VARCHAR(20);
|
|
251
|
+
|
|
252
|
+
-- Índices para a query de disponibilidade
|
|
253
|
+
CREATE INDEX idx_agendamentos_disponibilidade
|
|
254
|
+
ON agendamentos (profissional_id, data_hora)
|
|
255
|
+
WHERE status != 'CANCELADO';
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
### Query Otimizada
|
|
259
|
+
|
|
260
|
+
```sql
|
|
261
|
+
-- EXPLAIN original: Seq Scan (800ms)
|
|
262
|
+
-- EXPLAIN otimizado: Index Scan (15ms)
|
|
263
|
+
|
|
264
|
+
-- Query otimizada (mesma, mas usando índice parcial)
|
|
265
|
+
SELECT id, cliente_id, servico_id, data_hora, status
|
|
266
|
+
FROM agendamentos
|
|
267
|
+
WHERE profissional_id = $1
|
|
268
|
+
AND data_hora >= $2
|
|
269
|
+
AND data_hora < $3
|
|
270
|
+
AND status != 'CANCELADO';
|
|
271
|
+
|
|
272
|
+
-- Ganho: de 800ms para 15ms (98% melhoria)
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
### Índices Recomendados
|
|
276
|
+
|
|
277
|
+
| Tabela | Índice | Tipo | Justificativa |
|
|
278
|
+
|--------|--------|------|---------------|
|
|
279
|
+
| agendamentos | (profissional_id, data_hora) | B-tree parcial | Query de disponibilidade |
|
|
280
|
+
| agendamentos | (cliente_id, data_hora) | B-tree | Histórico do cliente |
|
|
281
|
+
| agendamentos | (data_hora) | B-tree | Relatórios por período |
|
|
282
|
+
|
|
283
|
+
---
|
|
284
|
+
|
|
285
|
+
## Checklist Pós-Geração
|
|
286
|
+
|
|
287
|
+
- [ ] Tipos de dados otimizados
|
|
288
|
+
- [ ] Índices sugeridos com justificativa
|
|
289
|
+
- [ ] EXPLAIN ANALYZE das queries
|
|
290
|
+
- [ ] Queries otimizadas com ganho estimado
|
|
291
|
+
- [ ] Connection pooling configurado
|
|
292
|
+
- [ ] Particionamento avaliado (se dados grandes)
|
|
293
|
+
- [ ] Vacuum/maintenance configurado
|
|
294
|
+
- [ ] Métricas de monitoramento
|
|
295
|
+
- [ ] Migrations para alterações
|
|
296
|
+
- [ ] Salvar em `docs/07-performance/otimizacao-database.md`
|