Skip to content

feature: prisma ast - #144

Open
Lqm1 wants to merge 6 commits into
47ng:nextfrom
Lqm1:feature/prisma-ast
Open

Lqm1 wants to merge 6 commits into
47ng:nextfrom
Lqm1:feature/prisma-ast

Conversation

@Lqm1

@Lqm1 Lqm1 commented Sep 16, 2025

Copy link
Copy Markdown

Resolves: #143 #142

This pull request refactors the codebase to use Prisma schema AST parsing instead of the Prisma DMMF format, simplifying model analysis and removing dependencies on Prisma internals. It introduces a new AST-based analysis module, updates dependencies, and migrates tests and core logic to use the new approach. The changes improve maintainability and compatibility with Prisma by relying on the open-source @mrleebo/prisma-ast library.

Migration to AST-based schema analysis:

  • Replaced the DMMF-based model analysis in src/dmmf.ts with a new AST-based implementation in src/ast.ts, using @mrleebo/prisma-ast for parsing Prisma schema files. The new analyseSchema and analyseSchemaFile functions provide model analysis based on schema comments and attributes, and the types were updated from DMMFModels to ASTModels. [1] [2] [3]

  • Updated all usages of the model analysis types and functions in src/encryption.ts and other modules to use the new AST-based types and functions (ASTModels instead of DMMFModels). [1] [2] [3]

Dependency updates and cleanup:

  • Removed the dependency on @prisma/internals and added @mrleebo/prisma-ast to package.json. Also updated the bin field for correct CLI usage. [1] [2]

  • Changed the Yarn node linker to node-modules for compatibility. (.yarnrc.yml)

Test migration and improvements:

  • Removed the old DMMF-based tests in src/dmmf.test.ts and added new, comprehensive AST-based tests in src/ast.test.ts, covering annotation parsing and schema analysis. [1] [2]

File renaming and code organization:

  • Renamed src/dmmf.ts to src/ast.ts to reflect the new AST-based approach.

References:
[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

- Replaced DMMFModels with ASTModels in encryption and middleware logic.
- Updated schema analysis to use @mrleebo/prisma-ast for parsing Prisma schemas.
- Introduced new functions for parsing encrypted and hash annotations.
- Adjusted tests to reflect changes in schema parsing and model descriptors.
- Deprecated DMMFDocument in favor of schemaPath in Configuration.
- Enhanced error handling for cursor and field types in schema analysis.
@franky47

Copy link
Copy Markdown
Member

Looks like the GitHub Actions workflow needs a little update before we can run it..

@Lqm1

Lqm1 commented Sep 16, 2025

Copy link
Copy Markdown
Author

I don't know if it will be solved, but I upgraded it to v4 anyway.

Comment thread .github/workflows/ci.yml Resolved
Co-authored-by: François Best <github@francoisbest.com>
@Lqm1
Lqm1 requested a review from franky47 September 16, 2025 10:55
@coveralls

coveralls commented Sep 16, 2025 •

Copy link
Copy Markdown

Pull Request Test Coverage Report for Build 17791208893

Details

  • 36 of 43 (83.72%) changed or added relevant lines in 3 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage increased (+0.4%) to 79.65%

Changes Missing Coverage Covered Lines Changed/Added Lines %
src/extension.ts 3 4 75.0%
src/middleware.ts 3 4 75.0%
src/ast.ts 30 35 85.71%
Totals Coverage Status
Change from base Build 13069234660: 0.4%
Covered Lines: 277
Relevant Lines: 330

💛 - Coveralls

@franky47 franky47 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, this will be a breaking change though, could you add a migration step in the docs please?

I'll have to do a pass on the CI process separately, I recently hardened my NPM account due to the supply chain attacks and I need to update this project's settings accordingly.

@Lqm1

Lqm1 commented Sep 17, 2025

Copy link
Copy Markdown
Author

LGTM, this will be a breaking change though, could you add a migration step in the docs please?

I'll have to do a pass on the CI process separately, I recently hardened my NPM account due to the supply chain attacks and I need to update this project's settings accordingly.

Edited how to migrate from v1.x to v2.x and how to use it
If you release these changes as v1.x, please let me know as I will revise them again.

@Lqm1
Lqm1 requested a review from franky47 September 17, 2025 11:51

@franky47 franky47 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, I'll see if I can setup pkg.pr.new here to give you a preview build to play with.

@franky47 franky47 added the deploy:preview Deploy a preview version of this PR on pkg.pr.new label Sep 18, 2025
@franky47

franky47 commented Sep 18, 2025 •

Copy link
Copy Markdown
Member

The automatic comment from pkg.pr.new failed, but here is the preview build:

npm install https://pkg.pr.new/prisma-field-encryption@f84e373

Hopefully subsequent pushes will be enough to trigger it.

@bryan-hunter

Copy link
Copy Markdown

any updates on this?

@hrueger

hrueger commented Oct 13, 2025

Copy link
Copy Markdown

We recently tried this pull request, but we had some problem with it. I believe it didn't handle multi-file schemas correctly, I'll ask my colleague for futher info.

@bryan-hunter

Copy link
Copy Markdown

We recently tried this pull request, but we had some problem with it. I believe it didn't handle multi-file schemas correctly, I'll ask my colleague for futher info.

ahh, thanks for the response!

@hrueger

hrueger commented Oct 14, 2025

Copy link
Copy Markdown

Hi all,
I made a reproduction repository: https://github.com/hrueger/prisma-encrypted-fields-test
When trying to insert the user, it fails with

/home/me/source/prisma-encrypted-fields-test/node_modules/prisma-field-encryption/dist/encryption.js:93
    if (Object.keys(model.fields).length === 0 &&
                          ^

TypeError: Cannot read properties of undefined (reading 'fields')
    at decryptOnRead (/home/me/source/prisma-encrypted-fields-test/node_modules/prisma-field-encryption/dist/encryption.js:93:27)
    at Array.$allOperations (/home/me/source/prisma-encrypted-fields-test/node_modules/prisma-field-encryption/dist/extension.js:36:52)
    at async a (/home/me/source/prisma-encrypted-fields-test/node_modules/@prisma/client/src/runtime/getPrismaClient.ts:833:24)
    at async <anonymous> (/home/me/source/prisma-encrypted-fields-test/index.ts:19:5)

Node.js v22.20.0

Hope that helps!

@batkedev

This comment was marked as off-topic.

@renatocron

Copy link
Copy Markdown

Hello @hrueger i've tested your repo agianst this #151 an it' working

I only had to change to add back again the "@" on the encryption settings

diff --git a/prisma/models/order.prisma b/prisma/models/order.prisma
index 5f9d6e4..416b880 100644
--- a/prisma/models/order.prisma
+++ b/prisma/models/order.prisma
@@ -1,4 +1,4 @@
 model Order {
     id             Int    @id @default(autoincrement())
-    paymentDetails String @unique /// encrypted
+    paymentDetails String @unique /// @encrypted
 }
diff --git a/prisma/models/user.prisma b/prisma/models/user.prisma
index 49b40b6..1292803 100644
--- a/prisma/models/user.prisma
+++ b/prisma/models/user.prisma
@@ -1,5 +1,5 @@
 model User {
     id    Int    @id @default(autoincrement())
-    email String /// encrypted
-    name  String /// encrypted
+    email String /// @encrypted
+    name  String /// @encrypted
 }

@DimosthenisK

Copy link
Copy Markdown

Any further updates on this? We're currently blocked from upgrading to Prisma v7 due to the prisma-field-encryption dependency.

@franky47

Copy link
Copy Markdown
Member

For what it's worth, it looks like Prisma is going a whole new direction now: https://www.prisma.io/blog/the-next-evolution-of-prisma-orm

@DimosthenisK

Copy link
Copy Markdown

For what it's worth, it looks like Prisma is going a whole new direction now: prisma.io/blog/the-next-evolution-of-prisma-orm

I'd say that this raises the importance of the update even more with Prisma 7 becoming extra-long term LTS. I foresee a ton of projects staying in Prisma v7 due to the extreme amount of effort updating to v8 would take.

At least that's the case for us - I'm disappointed in Prisma's decision but this isn't the place to discuss it.

@geosigno

geosigno commented Apr 3, 2026

Copy link
Copy Markdown

Can we expect the fix for v7 soon?

@renatocron

Copy link
Copy Markdown

Can we expect the fix for v7 soon?

https://pkg.pr.new/prisma-field-encryption@151
For now

@geosigno

Copy link
Copy Markdown

any update ?

renatocron added a commit to AppCivico/smae that referenced this pull request Jul 7, 2026
… 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).
@huksley

huksley commented Jul 12, 2026 •

Copy link
Copy Markdown

Any updates to field encryption for prisma v7?

renatocron added a commit to AppCivico/smae that referenced this pull request Jul 25, 2026
#637)

## 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](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 + `view`s → 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 `view`s
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](prisma/orm#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).


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## 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.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@DimosthenisK

Copy link
Copy Markdown

Hey folks - circling back on this as it's still blocking us since March. There are a few PRs for this and a fork that seems to have resolved the issues - any chance they can be merged in to the main repo?

@renatocron

Copy link
Copy Markdown

Hey folks - circling back on this as it's still blocking us since March. There are a few PRs for this and a fork that seems to have resolved the issues - any chance they can be merged in to the main repo?

the closest think to this official release is npm install https://pkg.pr.new/prisma-field-encryption@f84e373 that i'm using, but IDK for how long this works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

deploy:preview Deploy a preview version of this PR on pkg.pr.new

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Prisma 6.16.0 — dmmf shape changed: documentation missing and field-encryption breaks in prisma-client-js

10 participants