Skip to content

feat(prisma): migra para Prisma 7 sem engine Rust (prisma-client-js +… - #637

Merged
renatocron merged 2 commits into
homolfrom
feat/prisma-v7-rustfree
Jul 25, 2026
Merged

renatocron merged 2 commits into
homolfrom
feat/prisma-v7-rustfree

Conversation

@renatocron

@renatocron renatocron commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Migração Prisma 6.19 → 7.8 (sem engine Rust)

Migra o backend para o Prisma 7 usando o driver adapter (@prisma/adapter-pg) e mantendo o generator prisma-client-js. No Prisma 7 o cliente é Rust-free de qualquer forma (o pacote não distribui mais o query-engine Rust — só o schema-engine, usado apenas em migrate/introspect), então continuamos sem engine Rust em runtime.

Branch base: homol.


O que muda

  • Dependências: @prisma/client e prisma → ^7.8.0; adiciona @prisma/adapter-pg@^7.8.0 (pg já existia) e decimal.js@^10.6.0 (ver ponto 2 abaixo).
  • Driver adapter obrigatório: new PrismaPg({ connectionString: process.env.DATABASE_URL }) em PrismaService, prisma/seed.ts e bin/pgsql-migrate.ts.
  • prisma.config.ts (novo): no v7 a url sai do bloco datasource do schema. O datasource é condicional a DATABASE_URL — assim prisma generate roda no build do Docker (sem banco) sem estourar PrismaConfigEnvError.
  • Imports de runtime: @prisma/client/runtime/library → @prisma/client/runtime/client em 18 arquivos (só InputJsonValue; o Decimal migrou para decimal.js — ver ponto 2).
  • field-encryption: passa a usar o build da PR 47ng/prisma-field-encryption#144 via https://pkg.pr.new/47ng/prisma-field-encryption@151. A v1.6.0 publicada quebra no v7 (mudança de formato do DMMF); o build da PR lê o schema por AST (@mrleebo/prisma-ast) e funciona. Além disso, a extensão agora fica isolada em um client dedicado (ver ponto 3).
  • scripts/postinstall.js: reduzido a só prisma generate condicional (o patch de node_modules foi eliminado — ver ponto 2).
  • Dockerfile: reestruturado para cache de layers (ver abaixo).
  • Correções do #27823 em queries $queryRaw (ver abaixo).

⚠️ O que pode falhar / pontos de atenção

1. prisma/issues/27823 — arrays de ENUM em SQL cru (o "bug que é feature")
Com o driver adapter, o pg não desserializa arrays de tipos custom (enums). Arrays de int/text continuam OK (inclusive array_agg); o problema é só com enums, nos dois sentidos:

  • Saída (SELECT ... enum[] / array_agg(enum)): volta como string '{SMAE,PDM}' em vez de array JS. Corrigido com jsonb_agg(...) / to_jsonb(...) no SELECT (o jsonb_agg mantém NULL em conjunto vazio, igual ao array_agg).
  • Entrada (ARRAY[${arrayJs}]::"Enum"[]): o pg serializa o array JS como um único parâmetro '{a,b}', então ARRAY[$1] vira array aninhado e dá 22P02 invalid input value for enum. Corrigido removendo o ARRAY[] e fazendo cast direto: ${arrayJs}::"Enum"[].

A entrada do listaPrivilegiosModulos (caminho de autenticação) estava nesse caso — toda requisição autenticada dava 401 até o fix. Só foi pego no teste de fumaça com dump real (a auditoria estática não pegou o lado de entrada).

Queries do ORM (findMany etc.) não são afetadas — o Prisma já faz cast ::text[] nas colunas enum. Só SQL cru ($queryRaw/$queryRawUnsafe) precisa de atenção. Ao mexer em SQL cru, faça grep por array_agg, colunas enum[] no SELECT e ARRAY[${...}].

2. Node 24 — ERR_PACKAGE_PATH_NOT_EXPORTED (tipo Decimal)
O plugin do @nestjs/swagger, ao rastrear o tipo Decimal em propriedades de DTO/entity, gerava type: () => require("@prisma/client-runtime-utils/dist").Decimal no metadata compilado. Esse pacote não expõe ./dist no seu exports, e o Node 24 aplica exports estritamente → quebrava no boot ao montar o documento Swagger (que executa esses thunks).

Solução (sem patch de node_modules): o Decimal do Prisma É a classe do decimal.js por baixo. Trocando o import Decimal de @prisma/client/runtime/client para decimal.js em 17 arquivos (mesma classe, estruturalmente compatível — sem instanceof/estáticos no código), o plugin passa a emitir require("decimal.js") / require("decimal.js/decimal"), ambos com exports válidos. Isso eliminou o antigo scripts/patch-prisma-exports.js.

3. field-encryption + views → client dedicado prisma.encrypted
A extensão prisma-field-encryption envolve todas as operações e desreferencia o modelo no mapa DMMF sem null-guard. Como as views do Prisma não entram em datamodel.models, qualquer query numa das 22 views do schema quebrava com Cannot read properties of undefined (reading 'fields') (ex.: /indicador, /variavel que usam view_pdm_meta_iniciativa_atividade / ViewVariavelGlobal). Não tinha sido pego porque a árvore projeto/tarefa não toca views.

Solução: só um model tem colunas @encrypted (api_request_log). Então o PrismaService principal (usado em todo o app, inclusive views) não aplica a extensão; um client derivado via $extends (que compartilha a conexão/pool) é exposto em prisma.encrypted e usado apenas nos 4 pontos que leem/escrevem api_request_log (logger middleware, backup, restore, request-log). Confirmado round-trip: escrita cifra em repouso (v1.aesgcm256…), leitura decifra.

4. postinstall roda prisma generate
O client v7 não é gerado automaticamente no install, então o postinstall dispara prisma generate (~40s no primeiro npm install após o pull). No Docker o generate é pulado no npm ci (schema ainda não copiado, guard por schema.prisma existir) e roda numa layer própria — preservando o cache de deps.


Trade-off: por que prisma-client-js e não o novo prisma-client

Tentamos o novo generator prisma-client (o caminho "oficial" do futuro). Ele emite o cliente como código-fonte TS dentro de src/, que o tsc type-checa junto com o app. Medido, com o nosso schema (~300 models):

prisma-client-js novo prisma-client
tsc (type instantiations) 3,0 M 65,0 M
memória de pico do build ~2,8 GB 9,3 GB (precisa de heap de 12 GB)
tsc check time ~10 s ~76 s
prisma generate ~40 s ~146 s (e em todo npm install)
engine Rust nenhum nenhum
status deprecado atual

É uma regressão conhecida do Prisma 7 (prisma#29011, ~3× mais type-instantiations). Testamos as mitigações e não resolvem para o nosso caso: // @ts-nocheck nos arquivos gerados → continua OOM a 4 GB (o custo é a instanciação de tipos nos ~2400 call-sites de query, não a checagem dos arquivos gerados); o truque oficial typeof client (convertidos os 560 Prisma.TransactionClient) → 0 de diferença (65 M idênticos).

Prós de prisma-client-js: build ~22× mais leve, cabe no heap padrão (4 GB), sem .ts gerado no repo, diff pequeno (imports continuam @prisma/client), igualmente Rust-free.
Contra: está deprecado (será removido em versão futura do v7 — sem data). Plano: revisitar o novo generator quando o #29011 for resolvido; a troca será barata (basicamente o generator block + reapontar imports).


Docker — cache de layers

Reestruturado para que mudanças que não são no schema reaproveitem cache:

  1. COPY package*.json + COPY scripts/ → RUN npm ci (postinstall pula o generate pois o schema ainda não foi copiado) — layer só invalida quando muda dependência.
  2. COPY prisma/schema.prisma + prisma.config.ts → RUN npx prisma generate — layer própria, só invalida quando schema/config mudam (~40s).
  3. COPY . . → npm run build — mudança de código não re-roda npm ci nem prisma generate.

Heap do build voltou ao padrão (--max-old-space-size=4096).


Verificação já feita (contra dump real restaurado localmente)

  • tsc --noEmit + nest build: 0 erros com heap padrão (4 GB).
  • Boot da API compilada: sobe limpo, 0 ERR_PACKAGE_PATH_NOT_EXPORTED, com o node_modules sem nenhum patch (exports map de @prisma/client-runtime-utils no estado original).
  • Views: /api/variavel (ViewVariavelGlobal, 750 registros), /api/indicador, /api/variavel-categorica → 200 (antes: 500 decryptOnRead).
  • Auth: guard JWT → listaPrivilegiosModulos roda sem erro (respostas 200/403, não 401/500).
  • field-encryption: round-trip via prisma.encrypted — create grava cifrado em repouso, findMany decifra de volta ao original; /api/request-log → 200.
  • Login + árvore de tarefas (sessão anterior): GET /projeto/:id/tarefa e /tarefas-hierarquia (até 155 tarefas, 5 níveis) → 200.

Não testado / follow-up

  • Testes automatizados (a suíte já estava quebrada antes desta branch).
  • Recomendado subir o null-guard na PR do field-encryption (if (!model) return; em decryptOnRead/encryptOnWrite) para robustez, mesmo com o isolamento em prisma.encrypted.
  • Módulos além de projeto/tarefa, auth, indicador/variável e logs não foram exercitados manualmente (geo do painel-estratégico, orçamento, relatórios).

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability of database-backed backup/restore and request-log workflows by consistently using the encrypted data path.
    • Fixed several raw-query and aggregation responses so array results are returned correctly to the app.
    • Standardized numeric handling by using a consistent decimal library across multiple calculations and DTOs.
  • Chores
    • Streamlined backend install/build behavior to ensure Prisma client generation runs correctly and more efficiently in container builds.

… driver adapter)

Migra o backend do Prisma 6.19 para o 7.8, mantendo o generator `prisma-client-js`
(deprecado, porém ~22x mais leve no tsc que o novo `prisma-client` — ver prisma#29011).
No Prisma 7 nenhum dos generators distribui o query-engine Rust, então continua Rust-free.

Principais mudanças:
- Driver adapter obrigatório: `@prisma/adapter-pg` (PrismaPg) em PrismaService, seed e
  bin/pgsql-migrate.
- `prisma.config.ts`: a `url` sai do datasource do schema; datasource condicional a
  DATABASE_URL para o `prisma generate` rodar no build do Docker (sem banco).
- field-encryption: build da PR 47ng/prisma-field-encryption#144
  (pkg.pr.new@151), que lê o schema por AST e funciona no v7.

Correções de comportamento do driver adapter (prisma#27823 — arrays de ENUM em SQL cru):
- Saída: `jsonb_agg`/`to_jsonb` no lugar de `array_agg(enum)` / colunas enum[]
  (pessoa listaPrivilegiosModulos + 6 sites defensivos).
- Entrada: cast direto `${arr}::"Enum"[]` no lugar de `ARRAY[${arr}]::"Enum"[]`
  (evita 22P02 no caminho de auth).

Tipo Decimal em DTOs -> decimal.js (em vez de @prisma/client/runtime/client):
- O plugin do @nestjs/swagger emitia `require("@prisma/client-runtime-utils/dist")`,
  subpath ausente no `exports` -> ERR_PACKAGE_PATH_NOT_EXPORTED no boot (Node 24).
  Importando `Decimal` de `decimal.js` (mesma classe por baixo), o emit vira
  `require("decimal.js")`, que tem exports válido. Elimina o patch de node_modules.

field-encryption isolado em um client dedicado (`prisma.encrypted`):
- A extensão envolvia TODAS as operações e desreferencia o modelo no mapa sem null-guard,
  quebrando qualquer query em `view` (as 22 views do schema) com
  "Cannot read properties of undefined (reading 'fields')".
- Agora o client principal (usado em todo o app, inclusive views) NÃO tem a extensão;
  um client derivado via `$extends` (compartilha a conexão) é exposto em `prisma.encrypted`
  e usado só nos 4 pontos que leem/escrevem colunas @Encrypted de `api_request_log`.

Docker: layers de cache — `npm ci` (deps) independente do schema; `prisma generate` em
layer própria; build em NODE_OPTIONS padrão (4GB). postinstall reduzido a só o
`prisma generate` condicional (client v7 não gera no install).
@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ec85d783-c920-4043-8ffd-42987e5739c6

📥 Commits

Reviewing files that changed from the base of the PR and between df6d655 and d9b9618.

⛔ Files ignored due to path filters (1)
  • backend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • backend/package.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/package.json

📝 Walkthrough

Walkthrough

This PR upgrades the backend to Prisma 7 with PostgreSQL driver adapters, restructures Docker build layers, and adds conditional Prisma client generation. It introduces encrypted log access, updates raw SQL JSON serialization, and replaces Prisma runtime imports for decimal and JSON types.

Changes

Prisma 7 migration

Layer / File(s) Summary
Prisma dependency and configuration
backend/package.json, backend/prisma.config.ts, backend/prisma/schema.prisma
Upgrades Prisma packages to ^7.9.0, adds adapter and decimal dependencies, moves Prisma settings into prisma.config.ts, and removes the schema datasource URL.
Docker generation workflow
backend/Dockerfile, backend/scripts/postinstall.js
Reorders Docker installation layers and runs prisma generate conditionally when the schema is present.
PostgreSQL adapter and encrypted Prisma client
backend/src/prisma/prisma.service.ts, backend/prisma/seed.ts, backend/bin/pgsql-migrate.ts
Configures Prisma clients with PrismaPg and exposes an encrypted client through PrismaService.
Encrypted API log access
backend/src/api-logs/..., backend/src/common/middleware/logger.middleware.ts, backend/src/request_log/request_log.service.ts
Routes API request-log reads, writes, backups, and restores through prisma.encrypted.api_request_log.
Raw SQL JSON result shapes
backend/src/gestao-projetos/..., backend/src/pdm/..., backend/src/pessoa/..., backend/src/pp/tarefa/..., backend/src/variavel/...
Replaces selected PostgreSQL array aggregations with jsonb_agg or to_jsonb, and adjusts enum-array parameter casting.
Decimal and InputJsonValue imports
backend/src/**/*.entity.ts, *.dto.ts, *.service.ts, backend/src/reports/...
Moves Decimal imports to decimal.js and InputJsonValue to @prisma/client/runtime/client.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: migrating the backend to Prisma 7 without the Rust engine.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/prisma-v7-rustfree

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@renatocron
renatocron force-pushed the feat/prisma-v7-rustfree branch from d5d7d73 to df6d655 Compare July 7, 2026 21:46
Comment thread backend/scripts/postinstall.js Fixed
@renatocron

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (4)
backend/scripts/postinstall.js (1)

7-9: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Prefer node: prefixed imports for built-in modules.

Static analysis flags using child_process, fs, and path without the node: prefix. The node: prefix is a Node.js best practice that prevents shadowing by same-named local modules and makes built-in usage explicit.

♻️ Proposed refactor
-const { execSync } = require('child_process');
-const fs = require('fs');
-const path = require('path');
+const { execSync } = require('node:child_process');
+const fs = require('node:fs');
+const path = require('node:path');
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/scripts/postinstall.js` around lines 7 - 9, Update the built-in
module imports in postinstall.js to use the node: prefix for child_process, fs,
and path. Keep the same require assignments, but change the module specifiers in
the top-level import statements so the script clearly references Node’s built-in
modules and avoids potential shadowing.

Source: Linters/SAST tools

backend/src/prisma/prisma.service.ts (1)

64-78: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Encrypted client won't participate in $transaction.

The proxy intercepts $transaction on the base target, but encrypted is a separate $extends client. Any future use of this.prisma.encrypted.* inside a this.prisma.$transaction(cb) callback will run on a connection outside that transaction (no atomicity/rollback with the surrounding tx). Today's callers use encrypted outside transactions, so this is a forward-looking caveat worth a short comment near the encrypted getter.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/prisma/prisma.service.ts` around lines 64 - 78, Add a short
comment near the `encrypted` branch in `PrismaService`’s proxy `get` handler
clarifying that `this.encrypted` is a separate `$extends` client and does not
join `this.prisma.$transaction` callbacks. Keep the note focused on the
`encrypted` getter and the proxy that intercepts `onModuleInit`/`$transaction`,
so future callers know not to use `encrypted` for work that must be atomic with
the surrounding transaction.
backend/src/gestao-projetos/painel-estrategico/painel-estrategico.service.ts (1)

1094-1095: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

jsonb_agg over a LEFT JOIN emits [null] for rows without camadas.

When glc has no match, jsonb_agg(glc.geo_camada_id) returns [null] (the old array_agg had the same quirk), so camadas carries a spurious null element instead of an empty array. Consider filtering nulls to return [].

♻️ Filter nulls out of the aggregate
-                -- jsonb_agg: driver adapter (Prisma 7) devolve array_agg de $queryRaw como string; JSON volta como array JS
-                jsonb_agg(glc.geo_camada_id) as camadas,
+                -- jsonb_agg: driver adapter (Prisma 7) devolve array_agg de $queryRaw como string; JSON volta como array JS
+                COALESCE(jsonb_agg(glc.geo_camada_id) FILTER (WHERE glc.geo_camada_id IS NOT NULL), '[]'::jsonb) as camadas,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/gestao-projetos/painel-estrategico/painel-estrategico.service.ts`
around lines 1094 - 1095, The `jsonb_agg(glc.geo_camada_id)` aggregation in
`painel-estrategico.service.ts` is producing `[null]` for `LEFT JOIN` rows
without matches, so `camadas` ends up with a spurious null entry instead of an
empty array. Update the aggregate in the query used by this service to ignore
null `glc.geo_camada_id` values (for example by applying a null filter inside
the aggregate) so the result for missing camadas is `[]` and not `[null]`.
backend/src/reports/relatorios/helpers/reports.params-processado.ts (1)

1-1: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Import InputJsonValue from @prisma/client The runtime path is internal; Prisma 7.8 exposes this type from the public package, so this import can move there for stability.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/reports/relatorios/helpers/reports.params-processado.ts` at line
1, The import in the reports params helper is using Prisma’s internal runtime
path for InputJsonValue, which should be switched to the public package export.
Update the import in reports.params-processado.ts to use InputJsonValue from
`@prisma/client` so the type comes from the stable public API and not the internal
client runtime path.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/package.json`:
- Line 90: The backend/package.json dependency for prisma-field-encryption is
still pinned to a pkg.pr.new preview tarball, so update the package reference to
the published npm release unless this PR specifically depends on the Prisma 7
fix. Also refresh the lockfile so it no longer resolves prisma-field-encryption
from the external preview artifact, keeping the dependency on a stable registry
source.

---

Nitpick comments:
In `@backend/scripts/postinstall.js`:
- Around line 7-9: Update the built-in module imports in postinstall.js to use
the node: prefix for child_process, fs, and path. Keep the same require
assignments, but change the module specifiers in the top-level import statements
so the script clearly references Node’s built-in modules and avoids potential
shadowing.

In
`@backend/src/gestao-projetos/painel-estrategico/painel-estrategico.service.ts`:
- Around line 1094-1095: The `jsonb_agg(glc.geo_camada_id)` aggregation in
`painel-estrategico.service.ts` is producing `[null]` for `LEFT JOIN` rows
without matches, so `camadas` ends up with a spurious null entry instead of an
empty array. Update the aggregate in the query used by this service to ignore
null `glc.geo_camada_id` values (for example by applying a null filter inside
the aggregate) so the result for missing camadas is `[]` and not `[null]`.

In `@backend/src/prisma/prisma.service.ts`:
- Around line 64-78: Add a short comment near the `encrypted` branch in
`PrismaService`’s proxy `get` handler clarifying that `this.encrypted` is a
separate `$extends` client and does not join `this.prisma.$transaction`
callbacks. Keep the note focused on the `encrypted` getter and the proxy that
intercepts `onModuleInit`/`$transaction`, so future callers know not to use
`encrypted` for work that must be atomic with the surrounding transaction.

In `@backend/src/reports/relatorios/helpers/reports.params-processado.ts`:
- Line 1: The import in the reports params helper is using Prisma’s internal
runtime path for InputJsonValue, which should be switched to the public package
export. Update the import in reports.params-processado.ts to use InputJsonValue
from `@prisma/client` so the type comes from the stable public API and not the
internal client runtime path.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 493a8096-5211-40ab-9e5c-eb8d12ee5930

📥 Commits

Reviewing files that changed from the base of the PR and between 7f6e998 and df6d655.

⛔ Files ignored due to path filters (1)
  • backend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (35)
  • backend/Dockerfile
  • backend/bin/pgsql-migrate.ts
  • backend/package.json
  • backend/prisma.config.ts
  • backend/prisma/schema.prisma
  • backend/prisma/seed.ts
  • backend/scripts/postinstall.js
  • backend/src/api-logs/backup/api-log-backup.service.ts
  • backend/src/api-logs/restore/api-log-restore.service.ts
  • backend/src/casa-civil/dash/transferencia.service.ts
  • backend/src/casa-civil/distribuicao-recurso/entities/distribuicao-recurso.entity.ts
  • backend/src/casa-civil/transferencia/entities/transferencia.dto.ts
  • backend/src/casa-civil/vinculo/entities/vinculo.entity.ts
  • backend/src/common/middleware/logger.middleware.ts
  • backend/src/gestao-projetos/painel-estrategico/painel-estrategico.service.ts
  • backend/src/indicador/entities/indicador.entity.ts
  • backend/src/orcamento-planejado/entities/orcamento-planejado.entity.ts
  • backend/src/orcamento-planejado/orcamento-planejado.service.ts
  • backend/src/orcamento-realizado/orcamento-realizado.service.ts
  • backend/src/painel/dto/detalhe-painel.dto.ts
  • backend/src/painel/painel.service.ts
  • backend/src/pdm/pdm.service.ts
  • backend/src/pessoa/pessoa.service.ts
  • backend/src/pp/contrato-aditivo/entities/contrato-aditivo.entity.ts
  • backend/src/pp/contrato/contrato.service.ts
  • backend/src/pp/contrato/entities/contrato.entity.ts
  • backend/src/pp/orcamento-planejado/orcamento-planejado.service.ts
  • backend/src/pp/orcamento-realizado/orcamento-realizado.service.ts
  • backend/src/pp/tarefa/tarefa.service.ts
  • backend/src/prisma/prisma.service.ts
  • backend/src/reports/relatorios/helpers/reports.params-processado.ts
  • backend/src/request_log/request_log.service.ts
  • backend/src/variavel/dto/list-variavel.dto.ts
  • backend/src/variavel/entities/variavel.entity.ts
  • backend/src/variavel/variavel.service.ts
💤 Files with no reviewable changes (1)
  • backend/prisma/schema.prisma

Comment thread backend/package.json Resolved
@renatocron

Copy link
Copy Markdown
Contributor Author

Atualização: bump para Prisma 7.9.0 + decisão sobre o generator

Saiu o 7.9.0 e ele fecha o #29011 — a única razão pela qual esta PR ficou no generator (deprecado) prisma-client-js. Remedi para decidir se valia trocar para o novo prisma-client.

Decisão: mantém prisma-client-js, sobe para ^7.9.0

O novo prisma-client ficou viável no 7.9.0 (cabe no heap padrão de 4 GB), mas ainda é mais trabalho (repontar 286 imports de @prisma/client + ajuste do generic no PrismaService) para um ganho que não justifica agora. Ficamos com prisma-client-js; revisitamos quando/if for removido de fato.

Números (medição no 7.9.0, tsc a frio, heap padrão 4 GB, mesma árvore de código)

Métrica prisma-client-js (atual) novo prisma-client (7.9.0) novo generator no 7.8.0 (histórico)
Type instantiations 2,98 M 4,31 M 65 M
Total types 547 k 747 k —
Check time 11,8 s 14,0 s 76 s
tsc total 20,5 s 22,7 s —
Peak RSS 2,85 GB 3,44 GB 9,3 GB
Cabe no heap padrão (4 GB)? ✅ ✅ ❌ (exigia 12 GB)
prisma generate ~20 s 26,7 s 146 s
Erros de tipo no código-fonte 0 2 (mesma causa) —

O fix do #29592 (restaura o default do generic OmitOpts) derrubou o novo generator de 65 M → 4,3 M instantiations (~15×) e 9,3 GB → 3,44 GB de pico. O gap que resta pro prisma-client-js é modesto (~1,45× instantiations, +0,6 GB de pico, +2 s de check, +7 s de generate) — custo normal de o generator novo emitir TS checável, não patologia.

Único bloqueio de código encontrado ao testar o novo generator: prisma.service.ts faz cast pra PrismaClient<{ log: typeof logConfig }>, mas no generator novo o 1º parâmetro do generic é LogLevel (fix de 1 linha). Os outros 285 importadores type-checaram limpos via alias de paths.

Por que subir pro 7.9.0 de qualquer forma

Além do #29011, o 7.9.0 traz um fix que bate direto no que esta PR adota — o @prisma/adapter-pg:

  • #29727: vazamento de conexão quando uma transação interativa estoura o maxWait durante o start — nos adapters adapter-pg/adapter-neon a próxima query na conexão reusada podia falhar com "there is already a transaction in progress" ou silenciosamente commitar o trabalho da transação vazada. Faz ROLLBACK explícito agora.
  • #29697: $queryRaw/$executeRaw com Date inválida falha rápido em vez de serializar como null (corrupção silenciosa) — relevante pelo volume de SQL cru.
  • #29512: erros não-mapeados do driver adapter viram P2039 (debugável) em vez de falha opaca.

Verificação feita nesta branch (7.9.0)

  • Deps @prisma/client / @prisma/adapter-pg / prisma → ^7.9.0; .prisma/client regenerado em 7.9.0.
  • tsc --noEmit: limpo no código-fonte, heap padrão, pico ~2,88 GB (o único erro é test/lib/common.ts, pré-existente) — sem regressão de tipos no 7.9.0.
  • Smoke do adapter-pg contra smae_dev (mesma fiação do PrismaService): conectividade $queryRaw, query ORM, jsonb_agg(enum) voltando como array JS (#27823 saída), param ::"Enum"[] sem 22P02 (#27823 entrada), $transaction interativa e reuso de conexão pós-tx — todos OK.

⚠️ Heads-up operacional (7.9.0, #29684/#29691/#29713): o guard de comandos destrutivos agora dispara ao detectar agente de IA (inclui env genérico AI_AGENT/AGENT e db push --accept-data-loss), e migrate-reset saiu do MCP. Nosso bin/pgsql-migrate.ts não passa pela CLI (não afetado) e migrate deploy não é destrutivo, mas vale conferir que o env de CI não dispara a detecção no db:reset.

@sonarqubecloud

Copy link
Copy Markdown

@renatocron
renatocron merged commit 60f0c98 into homol Jul 25, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants