@vsrepo/prisma7-adapter 1.3.2 → 2.0.0-dev.1

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.
Files changed (79) hide show
  1. package/CHANGELOG.md +535 -0
  2. package/LICENSE +20 -20
  3. package/README.md +394 -299
  4. package/README.pt-BR.md +394 -299
  5. package/dist/constants/provider-capabilities.constant.d.ts +17 -0
  6. package/dist/constants/provider-capabilities.constant.js +27 -0
  7. package/dist/index.d.ts +9 -8
  8. package/dist/index.js +1 -7
  9. package/dist/parsers/data.parser.d.ts +3 -33
  10. package/dist/parsers/data.parser.js +70 -69
  11. package/dist/parsers/include.parser.d.ts +1 -1
  12. package/dist/parsers/include.parser.js +3 -7
  13. package/dist/parsers/order-by.parser.d.ts +1 -10
  14. package/dist/parsers/order-by.parser.js +3 -16
  15. package/dist/parsers/select.parser.d.ts +1 -1
  16. package/dist/parsers/select.parser.js +3 -7
  17. package/dist/parsers/where.parser.d.ts +4 -29
  18. package/dist/parsers/where.parser.js +49 -148
  19. package/dist/prisma7.adapter.d.ts +116 -81
  20. package/dist/prisma7.adapter.js +345 -362
  21. package/dist/resolvers/map-prisma-error.resolver.d.ts +0 -11
  22. package/dist/resolvers/map-prisma-error.resolver.js +48 -72
  23. package/dist/resolvers/merge-entities.resolver.d.ts +11 -15
  24. package/dist/resolvers/merge-entities.resolver.js +29 -38
  25. package/dist/resolvers/resolve-provider.resolver.d.ts +2 -22
  26. package/dist/resolvers/resolve-provider.resolver.js +10 -33
  27. package/dist/types/adapter-config.type.d.ts +21 -10
  28. package/dist/types/adapter-config.type.js +1 -3
  29. package/dist/types/adapter-relations.type.d.ts +14 -8
  30. package/dist/types/adapter-relations.type.js +1 -3
  31. package/dist/types/plain-object.type.js +1 -3
  32. package/dist/types/prisma-arg-like.type.js +1 -3
  33. package/dist/types/prisma-client-models.type.d.ts +4 -4
  34. package/dist/types/prisma-client-models.type.js +1 -3
  35. package/dist/types/prisma-provider.type.d.ts +1 -1
  36. package/dist/types/prisma-provider.type.js +1 -3
  37. package/dist/types/prisma-repository-like.type.d.ts +1 -1
  38. package/dist/types/prisma-repository-like.type.js +1 -3
  39. package/dist/types/prisma7-client-like.type.d.ts +1 -8
  40. package/dist/types/prisma7-client-like.type.js +1 -3
  41. package/dist/types/prisma7-global-config.type.d.ts +17 -0
  42. package/dist/types/prisma7-global-config.type.js +1 -0
  43. package/dist/types/prisma7-orm-types.type.d.ts +2 -2
  44. package/dist/types/prisma7-orm-types.type.js +1 -3
  45. package/dist/types/relation.type.d.ts +119 -25
  46. package/dist/types/relation.type.js +1 -3
  47. package/dist/validators/is-decimal.validator.d.ts +2 -5
  48. package/dist/validators/is-decimal.validator.js +3 -6
  49. package/dist/validators/is-plain-object.validator.d.ts +1 -1
  50. package/dist/validators/is-plain-object.validator.js +3 -7
  51. package/dist/validators/validate-prisma-client.validator.d.ts +1 -14
  52. package/dist/validators/validate-prisma-client.validator.js +7 -24
  53. package/package.json +108 -91
  54. package/dist/index.js.map +0 -1
  55. package/dist/parsers/data.parser.js.map +0 -1
  56. package/dist/parsers/include.parser.js.map +0 -1
  57. package/dist/parsers/order-by.parser.js.map +0 -1
  58. package/dist/parsers/select.parser.js.map +0 -1
  59. package/dist/parsers/where.parser.js.map +0 -1
  60. package/dist/prisma7.adapter.js.map +0 -1
  61. package/dist/resolvers/map-prisma-error.resolver.js.map +0 -1
  62. package/dist/resolvers/merge-entities.resolver.js.map +0 -1
  63. package/dist/resolvers/resolve-provider.resolver.js.map +0 -1
  64. package/dist/types/adapter-config.type.js.map +0 -1
  65. package/dist/types/adapter-relations.type.js.map +0 -1
  66. package/dist/types/plain-object.type.js.map +0 -1
  67. package/dist/types/prisma-arg-like.type.js.map +0 -1
  68. package/dist/types/prisma-client-models.type.js.map +0 -1
  69. package/dist/types/prisma-provider.type.js.map +0 -1
  70. package/dist/types/prisma-repository-like.type.js.map +0 -1
  71. package/dist/types/prisma7-client-like.type.js.map +0 -1
  72. package/dist/types/prisma7-orm-types.type.js.map +0 -1
  73. package/dist/types/relation.type.js.map +0 -1
  74. package/dist/validators/is-decimal.validator.js.map +0 -1
  75. package/dist/validators/is-plain-object.validator.js.map +0 -1
  76. package/dist/validators/validate-adapter-config.validator.d.ts +0 -8
  77. package/dist/validators/validate-adapter-config.validator.js +0 -78
  78. package/dist/validators/validate-adapter-config.validator.js.map +0 -1
  79. package/dist/validators/validate-prisma-client.validator.js.map +0 -1
package/CHANGELOG.md ADDED
@@ -0,0 +1,535 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ (Português) Todas as mudanças notáveis neste projeto serão documentadas neste arquivo.
6
+
7
+ ---
8
+
9
+ ## [2.0.0-dev.1] - 2026-11-08
10
+
11
+ ### Added
12
+
13
+ - **`VSRepoPrisma7Adapter.setGlobalConfig`** (static) — sets defaults (`provider`, `logLevel`, `allowOmitPk`) for every adapter created after the call. Each call replaces the previous global config, and the adapter's own config always wins. The `Prisma7GlobalConfig` type is exported
14
+ - **`onUpdate` and `onDisconnect` in the `relations` config**, replacing `restriction` and `nullable`:
15
+ - `onUpdate` for to-one relations (`oto`/`mto`) is `"connect"` (default), `"connectOrCreate"` or `"upsert"` (`ToOneStrategy`)
16
+ - `onUpdate` for to-many relations (`otm`/`mtm`) is `"add"` (default) or `"set"` (`ToManyStrategy`)
17
+ - `onDisconnect` (what `null` does on a to-one relation) is `"disconnect"` (default) or `"delete"` (`DisconnectStrategy`)
18
+ - **`"ignore"` as a relation config** — leaves the field out of every write. Since the relation object is dropped, a scalar FK in the payload goes through together with the primary key, which makes it the simplest way around the `allowOmitPk` problem when you only want to keep the FK
19
+ - **`fkHere` and `fkThere` in the `relations` config** — tell the adapter which side of a to-one relation keeps the foreign key. `fkThere` (FK in the related entity) is stripped from the related payload(s) before the nested write is built; `fkHere` (FK in the entity itself) is dropped from `create`/`update` when the relation is in the payload, since Prisma doesn't accept the scalar FK next to the relation object
20
+ - **`allowOmitPk` option** (adapter config and global config) — lets the adapter drop the primary key from a write that also has an `fkHere` relation. Off by default: read the README before enabling it, since a record that doesn't exist yet is then created with a database-generated key instead of the one you sent
21
+ - `RelationMode`, `ToOneStrategy`, `ToManyStrategy` and `DisconnectStrategy` types are exported
22
+ - JSDoc for the new options and types, and README (EN and pt-BR) sections on the global config, `onUpdate`, `onDisconnect`, `"ignore"`, `fkHere`/`fkThere` and `allowOmitPk` (what it is for, when to turn it on, and how to work around it)
23
+
24
+ ### Changed
25
+
26
+ - **`Relation` is now a union discriminated by `mode`**: each mode only accepts its own options (`fkHere` and `onDisconnect` for `oto`/`mto` only, the to-one and to-many strategies for their own modes). Invalid combinations no longer compile
27
+ - **`restriction` was removed** (it drove three unrelated behaviors). Use `onUpdate`: `"add"`/`"set"` keep their meaning for to-many relations; for to-one relations `restriction: "add"` is now the default `onUpdate: "connect"` and `restriction: "set"` is `onUpdate: "upsert"`
28
+ - **`nullable` was removed.** Sending `null` to a to-one relation now always disconnects it (or deletes it with `onDisconnect: "delete"`, on an `oto` or `mto`); the adapter no longer throws `INVALID_DATA` for it, and a required relation is rejected by Prisma itself
29
+ - **A to-one relation with the related `pk` now defaults to `connect` on update** (it used to be `connectOrCreate`), so the related record is no longer created when it is missing (the write fails with `NOT_FOUND`). Use `onUpdate: "connectOrCreate"` to get it back
30
+ - A write whose payload has the primary key **and** an `fkHere` relation now throws `INVALID_DATA` (a `VSRepoAdapterError` explaining `allowOmitPk`) instead of being sent to Prisma, unless `allowOmitPk` is enabled. Payloads without the primary key are not affected
31
+ - The `@prisma/client` peer dependency is now `^7.10.1` (was `^7.10.0`)
32
+ - `vsrepo` peer dependency bumped to `^3.0.0-dev.3`
33
+
34
+ ### Fixed
35
+
36
+ - **`save`/`create`/`update` failed with Prisma's `Unknown argument` validation error on to-one relations whose foreign key lives in the entity itself** (e.g. saving an `Address` loaded with its `user`), because the payload mixed the scalar FK and the primary key with the relation object. Relations configured with `fkHere`/`fkThere` now build a valid nested write
37
+ - Unit tests migrated to the new options, type-level tests added for the `Relation` union, and integration tests added for `fkHere`/`fkThere`, `allowOmitPk`, `"ignore"` and the `onUpdate` strategies
38
+
39
+ ---
40
+
41
+ ## [2.0.0-dev.1] - 2026-11-08 (Português)
42
+
43
+ ### Adicionado
44
+
45
+ - **`VSRepoPrisma7Adapter.setGlobalConfig`** (estático) — define defaults (`provider`, `logLevel`, `allowOmitPk`) pra todo adapter criado depois da chamada. Cada chamada substitui a config global anterior, e a config do próprio adapter sempre vence. O tipo `Prisma7GlobalConfig` é exportado
46
+ - **`onUpdate` e `onDisconnect` na config `relations`**, no lugar de `restriction` e `nullable`:
47
+ - `onUpdate` pra relations to-one (`oto`/`mto`) é `"connect"` (default), `"connectOrCreate"` ou `"upsert"` (`ToOneStrategy`)
48
+ - `onUpdate` pra relations to-many (`otm`/`mtm`) é `"add"` (default) ou `"set"` (`ToManyStrategy`)
49
+ - `onDisconnect` (o que o `null` faz numa relation to-one) é `"disconnect"` (default) ou `"delete"` (`DisconnectStrategy`)
50
+ - **`"ignore"` como config de relation** — deixa o campo fora de toda escrita. Como o objeto de relation é descartado, uma FK escalar no payload passa junto da primary key, o que faz dele a forma mais simples de contornar o problema do `allowOmitPk` quando você só quer manter a FK
51
+ - **`fkHere` e `fkThere` na config `relations`** — informam ao adapter qual lado de uma relation to-one guarda a foreign key. O `fkThere` (FK na entidade relacionada) é removido do(s) payload(s) relacionado(s) antes de montar o nested write; o `fkHere` (FK na própria entidade) é removido do `create`/`update` quando a relation está no payload, já que o Prisma não aceita a FK escalar junto do objeto de relation
52
+ - **Opção `allowOmitPk`** (config do adapter e config global) — permite que o adapter remova a primary key de uma escrita que também tem uma relation `fkHere`. Desativada por padrão: leia o README antes de ativar, pois um registro que ainda não existe passa a ser criado com uma key gerada pelo banco, e não a que você enviou
53
+ - Os tipos `RelationMode`, `ToOneStrategy`, `ToManyStrategy` e `DisconnectStrategy` são exportados
54
+ - JSDoc das novas opções e tipos, e seções nos READMEs (EN e pt-BR) sobre a config global, `onUpdate`, `onDisconnect`, `"ignore"`, `fkHere`/`fkThere` e `allowOmitPk` (pra que serve, quando ativar e como contornar)
55
+
56
+ ### Alterado
57
+
58
+ - **`Relation` agora é uma união discriminada por `mode`**: cada modo só aceita as suas opções (`fkHere` e `onDisconnect` só pra `oto`/`mto`, as estratégias to-one e to-many cada uma no seu modo). Combinações inválidas não compilam mais
59
+ - **`restriction` foi removido** (ele controlava três comportamentos sem relação entre si). Use `onUpdate`: `"add"`/`"set"` mantêm o significado nas relations to-many; nas to-one, `restriction: "add"` virou o `onUpdate: "connect"` default e `restriction: "set"` virou `onUpdate: "upsert"`
60
+ - **`nullable` foi removido.** Enviar `null` pra uma relation to-one agora sempre desconecta (ou apaga, com `onDisconnect: "delete"`, num `oto` ou `mto`); o adapter não lança mais `INVALID_DATA` por isso, e uma relation obrigatória é rejeitada pelo próprio Prisma
61
+ - **Uma relation to-one com a `pk` do relacionado agora usa `connect` por padrão no update** (antes era `connectOrCreate`), então o relacionado não é mais criado quando não existe (a escrita falha com `NOT_FOUND`). Use `onUpdate: "connectOrCreate"` pra recuperar o comportamento antigo
62
+ - Uma escrita cujo payload tem a primary key **e** uma relation `fkHere` agora lança `INVALID_DATA` (um `VSRepoAdapterError` explicando o `allowOmitPk`) em vez de ser enviada ao Prisma, a menos que `allowOmitPk` esteja ativado. Payloads sem a primary key não são afetados
63
+ - A peer dependency `@prisma/client` agora é `^7.10.1` (era `^7.10.0`)
64
+ - Peer dependency `vsrepo` elevada pra `^3.0.0-dev.3`
65
+
66
+ ### Corrigido
67
+
68
+ - **`save`/`create`/`update` falhavam com o erro de validação `Unknown argument` do Prisma em relations to-one cuja foreign key fica na própria entidade** (ex.: salvar um `Address` carregado com seu `user`), porque o payload misturava a FK escalar e a primary key com o objeto de relation. Relations configuradas com `fkHere`/`fkThere` agora montam um nested write válido
69
+ - Testes unitários migrados pras novas opções, testes de tipos adicionados pra união `Relation`, e testes de integração adicionados pra `fkHere`/`fkThere`, `allowOmitPk`, `"ignore"` e as estratégias de `onUpdate`
70
+
71
+ ---
72
+
73
+ ## [2.0.0-dev] - 2026-10-29
74
+
75
+ > Development version of the adapter for **VSRepository v3** (`vsrepo` `^3.0.0-dev.2`). The 1.x line keeps targeting VSRepository v2.
76
+
77
+ ### Breaking changes
78
+
79
+ - **Now targets VSRepository v3** — the `vsrepo` peer dependency is `^3.0.0-dev.2` (was `^2.7.2`) and the adapter implements the new `VSRepoAdapter` contract. It is not compatible with VSRepository v2: stay on 1.x there
80
+ - **ESM package, Node `>=22`** — the package is now `"type": "module"` (it was CommonJS) and `engines.node` went from `>=18` to `>=22`
81
+ - **`tableName` renamed to `modelName`** in the constructor config
82
+ - **`VSRepoPrisma7AdapterConfig` renamed to `Prisma7AdapterConfig`** — the adapter class is still exported as both `VSRepoPrisma7Adapter` and `Prisma7Adapter`
83
+ - **`merge` removed** — it was discontinued from the `VSRepoAdapter` contract (`VSRepository` now merges in memory by itself, on top of the adapter's `findOne`). The constructor `relations` config now only drives `create`/`update`/`upsert`/`save`
84
+ - **`logSlowThresholdMs` removed** from the constructor config
85
+ - **The constructor config is no longer validated at runtime** — the `INVALID_ADAPTER_CONFIG` errors for `tableName`/`pkName`/`relations`/`logLevel`/`provider` are gone, so those fields are now checked by TypeScript only. The constructor still validates the Prisma client and the model, with `MISSING_DB_CLIENT` (client is `null`/`undefined`) and `MODEL_NOT_FOUND` (no `prisma[modelName]` delegate)
86
+ - **The provider is resolved in the constructor** — when it can't be detected and no `provider` was set, construction throws a `VSRepoAdapterError` (`NOT_SUPPORTED`) asking for `provider`. Before, construction never threw and only `getPlaceholder` threw, when called
87
+ - **What the provider can't run now throws `NOT_SUPPORTED` upfront**, instead of being left to Prisma: `ignoreCase` outside PostgreSQL/CockroachDB, `createManyReturning`/`updateManyReturning` on MySQL and SQL Server, and `ignoreConflicts` (Prisma's `skipDuplicates`) on `createMany`/`createManyReturning` on SQL Server and SQLite. The `like` operator also throws `NOT_SUPPORTED` on every provider (use `contains`/`startsWith`/`endsWith`)
88
+
89
+ ### Added
90
+
91
+ - **`incrementMany`, `decrementMany`, `multiplyMany` and `divideMany`** — the multi-record counterparts of the `*One` atomic methods: they apply the operation, server-side, to every record matching `where` through Prisma's `updateMany` (`{ field: { increment | decrement | multiply | divide: value } }`) and return a `CountResult`
92
+ - **Integration tests against real databases** — PostgreSQL, MySQL, SQLite, SQL Server and CockroachDB share one suite (`test/shared`) and run in CI, each provider with its own Prisma schema, migrations and config under `prisma/<provider>`. Run them with `test:integration` or `test:integration:<provider>`
93
+ - **Unit tests** for the adapter and for the parsers, resolvers and validators (colocated `*.spec.ts` files)
94
+ - **Publish workflow** — pushing a `v*` tag runs the whole CI (lint, unit tests, integration tests, build) and then publishes; pre-release tags publish under their pre-release dist-tag (`2.0.0-dev` → `dev`)
95
+
96
+ ### Changed
97
+
98
+ - `where` is now optional on `findOne`, `findOneOrThrow`, `findMany`, `count` and `exists`
99
+ - `count` only forwards `where` to Prisma, and every method now forwards only the read options its typing accepts (`select`, `relations`, `order`, `pagination`)
100
+ - `createManyReturning` and `updateManyReturning` now run a **single** query (`createManyAndReturn`/`updateManyAndReturn`) unless `select` or `relations` is given; only then do they run the 2 queries (the write returning primary keys + a `findMany`), inside a transaction
101
+ - `deleteManyReturning` now deletes the records by the primary keys it fetched, instead of re-applying the `where` in the `deleteMany` — so a row inserted after the `findMany` is no longer deleted by mistake. When `select` leaves the primary key out, it is added internally and stripped from the result
102
+ - `update` and `upsert` no longer drop the primary key from the update payload — only `save` omits it, in its update branch (`parsePrismaWriteData` got the `omitPkInUpdate` argument)
103
+ - `isDecimal` validation is stricter
104
+ - Clearer errors from `parseFieldValue` and `resolveProvider`; JSDoc added for the atomic `*Many` methods and the public types
105
+ - Tooling: Jest + Babel → Vitest, npm (`package-lock.json`) → Bun (`bun.lock`), oxlint added, and `tests/` replaced by colocated specs + `test/`. `example.ts` was removed
106
+
107
+ ### Fixed
108
+
109
+ - **Relation filters (`_some`/`_every`/`_none`/`_with`/`_without`) are now parsed as nested `where`s** — the filter body goes through the same recursive parser as the root `where`, so logical operators and the `ignoreCase`/`like` checks also apply inside relation filters
110
+ - `PrismaClientModels` no longer includes numeric keys, so the `modelName` autocomplete only lists real models
111
+
112
+ ---
113
+
114
+ ## [2.0.0-dev] - 2026-10-29 (Português)
115
+
116
+ > Versão de desenvolvimento do adapter para o **VSRepository v3** (`vsrepo` `^3.0.0-dev.2`). A linha 1.x continua mirando o VSRepository v2.
117
+
118
+ ### Mudanças incompatíveis (breaking)
119
+
120
+ - **Agora mira o VSRepository v3** — a peer dependency `vsrepo` é `^3.0.0-dev.2` (era `^2.7.2`) e o adapter implementa o novo contrato do `VSRepoAdapter`. Não é compatível com o VSRepository v2: fique na 1.x nele
121
+ - **Pacote ESM, Node `>=22`** — o pacote agora é `"type": "module"` (era CommonJS) e o `engines.node` passou de `>=18` pra `>=22`
122
+ - **`tableName` renomeado pra `modelName`** na config do construtor
123
+ - **`VSRepoPrisma7AdapterConfig` renomeado pra `Prisma7AdapterConfig`** — a classe do adapter continua exportada como `VSRepoPrisma7Adapter` e `Prisma7Adapter`
124
+ - **`merge` removido** — ele foi descontinuado do contrato do `VSRepoAdapter` (o `VSRepository` agora faz o merge em memória por conta própria, em cima do `findOne` do adapter). A config `relations` do construtor agora só guia `create`/`update`/`upsert`/`save`
125
+ - **`logSlowThresholdMs` removido** da config do construtor
126
+ - **A config do construtor não é mais validada em runtime** — os erros `INVALID_ADAPTER_CONFIG` pra `tableName`/`pkName`/`relations`/`logLevel`/`provider` saíram, então esses campos agora são checados só pelo TypeScript. O construtor continua validando o client do Prisma e o model, com `MISSING_DB_CLIENT` (client `null`/`undefined`) e `MODEL_NOT_FOUND` (sem delegate `prisma[modelName]`)
127
+ - **O provider é resolvido no construtor** — quando não dá pra detectar e nenhum `provider` foi informado, a construção lança um `VSRepoAdapterError` (`NOT_SUPPORTED`) pedindo o `provider`. Antes, a construção nunca lançava e só o `getPlaceholder` lançava, quando chamado
128
+ - **O que o provider não suporta agora lança `NOT_SUPPORTED` antecipadamente**, em vez de ficar por conta do Prisma: `ignoreCase` fora de PostgreSQL/CockroachDB, `createManyReturning`/`updateManyReturning` em MySQL e SQL Server, e `ignoreConflicts` (o `skipDuplicates` do Prisma) no `createMany`/`createManyReturning` em SQL Server e SQLite. O operador `like` também lança `NOT_SUPPORTED` em todo provider (use `contains`/`startsWith`/`endsWith`)
129
+
130
+ ### Adicionado
131
+
132
+ - **`incrementMany`, `decrementMany`, `multiplyMany` e `divideMany`** — as versões pra vários registros dos métodos atômicos `*One`: aplicam a operação, server-side, em todo registro que casa com `where` através do `updateMany` do Prisma (`{ campo: { increment | decrement | multiply | divide: valor } }`) e retornam um `CountResult`
133
+ - **Testes de integração com bancos de verdade** — PostgreSQL, MySQL, SQLite, SQL Server e CockroachDB compartilham uma mesma suíte (`test/shared`) e rodam no CI, cada provider com seu próprio schema do Prisma, migrations e config em `prisma/<provider>`. Rode com `test:integration` ou `test:integration:<provider>`
134
+ - **Testes unitários** pro adapter e pros parsers, resolvers e validators (arquivos `*.spec.ts` ao lado do código)
135
+ - **Workflow de publicação** — dar push numa tag `v*` roda o CI inteiro (lint, testes unitários, testes de integração, build) e só então publica; tags de pré-release publicam na dist-tag da pré-release (`2.0.0-dev` → `dev`)
136
+
137
+ ### Alterado
138
+
139
+ - `where` agora é opcional em `findOne`, `findOneOrThrow`, `findMany`, `count` e `exists`
140
+ - `count` só repassa o `where` pro Prisma, e todo método agora repassa só as opções de leitura que a sua tipagem aceita (`select`, `relations`, `order`, `pagination`)
141
+ - `createManyReturning` e `updateManyReturning` agora rodam **uma única** query (`createManyAndReturn`/`updateManyAndReturn`), a não ser que `select` ou `relations` seja informado; só aí rodam as 2 queries (a escrita retornando as primary keys + um `findMany`), dentro de uma transaction
142
+ - `deleteManyReturning` agora deleta os registros pelas primary keys que buscou, em vez de re-aplicar o `where` no `deleteMany` — então uma linha inserida depois do `findMany` não é mais deletada por engano. Quando o `select` deixa a primary key de fora, ela é adicionada internamente e removida do resultado
143
+ - `update` e `upsert` não removem mais a primary key do payload de update — só o `save` a omite, no branch de update (o `parsePrismaWriteData` ganhou o argumento `omitPkInUpdate`)
144
+ - A validação do `isDecimal` ficou mais rígida
145
+ - Erros mais claros no `parseFieldValue` e no `resolveProvider`; JSDoc adicionado para os métodos atômicos `*Many` e para os tipos públicos
146
+ - Tooling: Jest + Babel → Vitest, npm (`package-lock.json`) → Bun (`bun.lock`), oxlint adicionado, e `tests/` substituído por specs ao lado do código + `test/`. O `example.ts` foi removido
147
+
148
+ ### Corrigido
149
+
150
+ - **Filtros de relation (`_some`/`_every`/`_none`/`_with`/`_without`) agora são parseados como `where`s aninhados** — o corpo do filtro passa pelo mesmo parser recursivo do `where` raiz, então operadores lógicos e as checagens de `ignoreCase`/`like` também valem dentro de filtros de relation
151
+ - `PrismaClientModels` não inclui mais chaves numéricas, então o autocomplete do `modelName` lista só models de verdade
152
+
153
+ ---
154
+
155
+ ## [1.3.2] - 2026-09-30
156
+
157
+ ### Fixed
158
+
159
+ - **`mode: "insensitive"` is now always applied when `ignoreCase` is `true`** – prior to this fix, `mode: "insensitive"` was only applied to fields within a specific list; it did not cover the `in` and `notIn` fields, nor others that also support case-insensitivity
160
+ - **`is` and `isNot` can now be applied together** – prior to this fix, _parseObjectRelationFilter_ applied only one or the other, potentially silently ignoring user filters
161
+
162
+ ---
163
+
164
+ ## [1.3.2] - 2026-09-30 (Português)
165
+
166
+ ### Corrigido
167
+
168
+ - **`mode: "insensitive"` agora é sempre aplicado quando `ignoreCase` for `true`** - antes desse fix o `mode: "insensitive"` só era aplicado em campos dentro de uma lista específica, porém não cobria os campos `in` e `notIn`, e outros que também podem aceitar o insensitive
169
+ - **`is` e `isNot` agora podem ser aplicados juntos** - antes desse fix o _parseObjectRelationFilter_ só aplicava um ou outro, podendo silenciosamente ignorar filtros do usuário
170
+
171
+ ---
172
+
173
+ ## [1.3.1] - 2026-09-29
174
+
175
+ ### Fixed
176
+
177
+ - **`saveMany` no longer runs the individual `save` calls in parallel inside the transaction** — previously, all records were dispatched at once with `Promise.all(objs.map(...))` against the same transaction client, but a Prisma/pg transaction client cannot execute concurrent queries: it emitted `DeprecationWarning: Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.` and would break outright on `pg@9`. Records are now saved sequentially (`await` inside a `for` loop), still inside the same transaction, reusing an active `options.db` transaction client when one is given
178
+
179
+ ### Changed
180
+
181
+ - `vsrepo` peer dependency bumped to `^2.7.2`
182
+
183
+ ---
184
+
185
+ ## [1.3.1] - 2026-09-29 (Português)
186
+
187
+ ### Corrigido
188
+
189
+ - **`saveMany` não executa mais os `save` individuais em paralelo dentro da transação** — anteriormente, todos os registros eram disparados de uma vez com `Promise.all(objs.map(...))` contra o mesmo transaction client, mas um transaction client do Prisma/pg não pode executar queries concorrentes: ele emitia `DeprecationWarning: Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.` e passaria a quebrar de vez no `pg@9`. Agora os registros são salvos sequencialmente (`await` dentro de um `for`), ainda dentro da mesma transação, reaproveitando um transaction client já ativo em `options.db` quando fornecido
190
+
191
+ ### Alterado
192
+
193
+ - Peer dependency `vsrepo` elevada pra `^2.7.2`
194
+
195
+ ---
196
+
197
+ ## [1.3.0] - 2026-09-26
198
+
199
+ ### Added
200
+
201
+ - **Provider detection** — detection order: the new `provider` constructor option (overrides) → the generated client's `_engineConfig.activeProvider` → the driver adapter's `provider`. Never throws, even when nothing can be detected
202
+ - **`getPlaceholder(index)`** — implements the new optional `VSRepoAdapter.getPlaceholder?` method released with `vsrepo` 2.7.0: returns the raw-query placeholder syntax for the `index`-th (0-based) bound parameter (`$${index + 1}` for `postgresql`/`cockroachdb`, `?` for `mysql`/`sqlite`, `@P${index + 1}` for `sqlserver`). This is what enables `VSSql` fragments and `vsPlaceholders` in `VSRepository`. When the provider can't be resolved, it throws a `VSRepoAdapterError` (code `NOT_SUPPORTED`) only when actually called — never at construction
203
+
204
+ ### Changed
205
+
206
+ - New optional `provider` field in the constructor config, validated at construction time against the provider picklist
207
+ - `vsrepo` peer dependency bumped to `^2.7.0`
208
+
209
+ ---
210
+
211
+ ## [1.3.0] - 2026-09-26 (Português)
212
+
213
+ ### Adicionado
214
+
215
+ - **Detecção de provider** — ordem de detecção: a nova opção `provider` do construtor (sobrescreve) → o `_engineConfig.activeProvider` do client gerado → o `provider` do driver adapter. Nunca lança, mesmo quando nada é detectável
216
+ - **`getPlaceholder(index)`** — implementa o novo método opcional `VSRepoAdapter.getPlaceholder?` lançado junto com a `vsrepo` 2.7.0: retorna a sintaxe de placeholder de query raw pro N-ésimo (base 0) parâmetro ligado (`$${index + 1}` pra `postgresql`/`cockroachdb`, `?` pra `mysql`/`sqlite`, `@P${index + 1}` pra `sqlserver`). É o que habilita os fragmentos `VSSql` e o `vsPlaceholders` no `VSRepository`. Quando o provider não é resolvível, lança um `VSRepoAdapterError` (code `NOT_SUPPORTED`) somente quando é de fato chamado — nunca na construção
217
+
218
+ ### Alterado
219
+
220
+ - Nova opção opcional `provider` na config do construtor, validada na construção contra o picklist de providers
221
+ - Peer dependency `vsrepo` elevada pra `^2.7.0`
222
+
223
+ ---
224
+
225
+ ## [1.2.0] - 2026-09-19
226
+
227
+ ### Added
228
+
229
+ - `VSRepoPrisma7Adapter` now implements the new optional `getPkName()` adapter method
230
+ - Now `logSlowThresholdMs` accepts a `number` (ms) **or** a `boolean` — `false` disables slow-operation warnings entirely, `true`/omitted falls back to the default `300`ms
231
+
232
+ ### Changed
233
+
234
+ - `vsrepo` peer dependency bumped to `^2.5.0`
235
+
236
+ ---
237
+
238
+ ## [1.2.0] - 2026-09-19 (Português)
239
+
240
+ ### Adicionado
241
+
242
+ - `VSRepoPrisma7Adapter` agora implementa o novo método opcional `getPkName()` dos adapters
243
+ - Agora `logSlowThresholdMs` aceita um `number` (ms) **ou** um `boolean` — `false` desativa os warnings de operação lenta por completo, `true`/omitido cai pro default de `300`ms
244
+
245
+ ### Alterado
246
+
247
+ - Peer dependency `vsrepo` elevada pra `^2.5.0`
248
+
249
+ ---
250
+
251
+ ## [1.1.6] - 2026-09-16
252
+
253
+ ### Added
254
+
255
+ - **`PrismaClientModels` type is now exported from the package index** — it is now part of the public API surface with full JSDoc, making it easier to reference the model delegate map type directly from userland
256
+ - **Improved `VSRepoPrisma7AdapterConfig` typings for better auto-complete** — the config type now provides more precise generic constraints, improving IDE auto-complete and type inference when instantiating the adapter
257
+
258
+ ### Changed
259
+
260
+ - **Removed `valibot` runtime dependency — constructor validation is now done manually** — `valibot` has been removed from `dependencies`; all constructor config validation (previously delegated to valibot schemas) is now performed through hand-written checks in `validate-adapter-config.validator.ts`. This eliminates an external runtime dependency without any change to the validation behavior or error surface (`VSRepoAdapterError` codes remain the same)
261
+
262
+ ---
263
+
264
+ ## [1.1.6] - 2026-09-16 (Português)
265
+
266
+ ### Adicionado
267
+
268
+ - **O tipo `PrismaClientModels` agora é exportado pelo index do pacote** — agora faz parte da API pública com JSDoc completa, facilitando o uso direto do tipo de mapa de delegates do Prisma no código do usuário
269
+ - **Tipagem do `VSRepoPrisma7AdapterConfig` melhorada para facilitar o auto-complete** — o tipo de config agora possui restrições genéricas mais precisas, melhorando o auto-complete da IDE e a inferência de tipos ao instanciar o adapter
270
+
271
+ ### Alterado
272
+
273
+ - **Removida a dependência runtime `valibot` — validações do construtor agora são feitas manualmente** — o `valibot` foi removido das `dependencies`; toda a validação da config do construtor (antes delegada aos schemas do valibot) agora é feita por verificações escritas à mão em `validate-adapter-config.validator.ts`. Isso elimina uma dependência externa de runtime sem nenhuma mudança no comportamento de validação ou na superfície de erros (os códigos de `VSRepoAdapterError` permanecem os mesmos)
274
+
275
+ ---
276
+
277
+ ## [1.1.5] - 2026-09-14
278
+
279
+ ### Added
280
+
281
+ - **`nullable` support for `oto` (one-to-one) relations** — `nullable: true` is now permitted and validated for `oto` relations (previously restricted to `mto`), allowing optional one-to-one relationships to be configured
282
+
283
+ ### Fixed
284
+
285
+ - **Robust `null` handling and validation in to-one relations (`oto` / `mto`)**:
286
+ - Providing `null` for a to-one relation when `nullable` is omitted or `false` now explicitly throws a `VSRepoAdapterError` (code `INVALID_DATA`), preventing silent unexpected behaviors or unintended deletions
287
+ - When `nullable: true`:
288
+ - For `oto` with `restriction: "set"`, passing `null` resolves to `{ delete: true }` on update (the owned row is removed)
289
+ - For `oto` with `restriction: "add"` or `mto`, passing `null` resolves to `{ disconnect: true }` on update
290
+ - In `parseToOneRelation`, primary key existence is now checked against `undefined` (`pkValue == undefined`) instead of `null`, preventing false positives when evaluating the relation payload's identifier
291
+
292
+ ---
293
+
294
+ ## [1.1.5] - 2026-09-14 (Português)
295
+
296
+ ### Adicionado
297
+
298
+ - **Suporte a `nullable` para relações `oto` (one-to-one)** — a opção `nullable: true` agora é permitida e validada também para relações `oto` (anteriormente restrita a `mto`), possibilitando a configuração de relações um-para-um opcionais
299
+
300
+ ### Corrigido
301
+
302
+ - **Tratamento e validação robusta de `null` em relações to-one (`oto` / `mto`)**:
303
+ - Enviar `null` para uma relação to-one quando `nullable` estiver ausente ou `false` agora lança explicitamente um `VSRepoAdapterError` (código `INVALID_DATA`), evitando comportamentos inesperados ou deleções não intencionais
304
+ - Quando `nullable: true`:
305
+ - Para `oto` com `restriction: "set"`, passar `null` resolve para `{ delete: true }` no update (a linha dependente é removida)
306
+ - Para `oto` com `restriction: "add"` ou `mto`, passar `null` resolve para `{ disconnect: true }` no update
307
+ - No `parseToOneRelation`, a verificação da presença de chave primária agora compara com `undefined` (`pkValue == undefined`) em vez de `null`, prevenindo falsos positivos na avaliação do identificador do payload da relação
308
+
309
+ ---
310
+
311
+ ## [1.1.4] - 2026-09-12
312
+
313
+ ### Added
314
+
315
+ - **The `Prisma7OrmTypes` utility type now only requires the `PrismaClient` type to infer ORM types** – previously, it required both `PrismaClient` and `Prisma.TransactionClient` types; now, the transaction type is inferred from the `PrismaClient`'s `$transaction` method
316
+ - **New alias `Prisma7Adapter` for `VSRepoPrisma7Adapter`** - `VSRepoPrisma7Adapter` can now _also_ be imported as `Prisma7Adapter`
317
+
318
+ ### Performance
319
+
320
+ - **The payload calculation for `to-many` relations now only calculates the `upsert` for `one-to-many` relations** – previously, the `upsert` was also calculated for `many-to-many` relations but was not used.
321
+
322
+ ---
323
+
324
+ ## [1.1.4] - 2026-09-12 (Português)
325
+
326
+ ### Adicionado
327
+
328
+ - **O tipo utilitário `Prisma7OrmTypes` agora só precisa da tipagem do PrismaClient para inferir as tipagens do ORM** - antes precisava da tipagem do PrismaClient e do Prisma.TransactionClient, agora o tipo da transaction é inferido pelo método `$transaction` do PrismaClient
329
+ - **Novo alias `Prisma7Adapter` para o `VSRepoPrisma7Adapter`** - agora o `VSRepoPrisma7Adapter` _também_ pode ser importado como `Prisma7Adapter`
330
+
331
+ ### Desempenho
332
+
333
+ - **Agora o cálculo do payload de relações `to-many` só calcula o `upsert` para relações `one-to-many`** - antes o `upsert` era calculado pro `many-to-many` também, mas não era utilizado
334
+
335
+ ---
336
+
337
+ ## [1.1.3] - 2026-09-10
338
+
339
+ ### Fixed
340
+
341
+ - **`runInTransaction` now correctly forwards the `timeoutMs` option to Prisma** — previously, the method passed the whole options object straight to `$transaction`, which only recognizes `isolationLevel`/`maxWait`/`timeout`, so a `timeoutMs` passed through `VSRepository.transaction()` — documented as an adapter option — never reached Prisma. The signature now types options as `VSRepoTransactionOptions` and explicitly maps `timeoutMs` to Prisma's `timeout` (alongside `isolationLevel`), so interactive transactions actually respect the configured timeout
342
+
343
+ ---
344
+
345
+ ## [1.1.3] - 2026-09-10 (Português)
346
+
347
+ ### Corrigido
348
+
349
+ - **`runInTransaction` agora repassa corretamente a opção `timeoutMs` pro Prisma** — anteriormente, o método passava o objeto de options inteiro direto pro `$transaction`, que só reconhece `isolationLevel`/`maxWait`/`timeout`, então um `timeoutMs` passado via `VSRepository.transaction()` — documentado como opção do adapter — nunca chegava no Prisma. A assinatura agora tipa as options como `VSRepoTransactionOptions` e mapeia explicitamente `timeoutMs` pro `timeout` do Prisma (junto do `isolationLevel`), fazendo as transactions interativas respeitarem de fato o timeout configurado
350
+
351
+ ---
352
+
353
+ ## [1.1.2] - 2026-09-09
354
+
355
+ ### Fixed
356
+
357
+ - **`count` now correctly passes `readArg` (pagination, order, select, relations, distinct) to Prisma** — previously, `count` only forwarded `{ where }`, silently ignoring any `pagination` or `order` options passed through `AdapterMethodOptions`. The method now calls `resolveReadArg(options)` and spreads the result into the Prisma arg, enabling pagination (`offset`/`limit`) and ordering to work as expected with `count`
358
+
359
+ ---
360
+
361
+ ## [1.1.2] - 2026-09-09 (Português)
362
+
363
+ ### Corrigido
364
+
365
+ - **`count` agora repassa corretamente o `readArg` (pagination, order, select, relations, distinct) pro Prisma** — anteriormente, o `count` só encaminhava `{ where }`, ignorando silenciosamente quaisquer opções de `pagination` ou `order` passadas via `AdapterMethodOptions`. O método agora chama `resolveReadArg(options)` e espalha o resultado no arg do Prisma, habilitando paginação (`offset`/`limit`) e ordenação no `count`
366
+
367
+ ---
368
+
369
+ ## [1.1.1] - 2026-09-07
370
+
371
+ ### Added
372
+
373
+ - **Stronger constructor validation**, catching more misconfigurations at construction time instead of on the first query:
374
+ - The Prisma client (first constructor argument) is now validated: passing `null`/`undefined` throws a `VSRepoAdapterError` (code `MISSING_DB_CLIENT`) immediately, instead of failing later with a raw `Cannot read properties of undefined`
375
+ - `tableName` is now checked against the provided Prisma client: if `prisma[tableName]` doesn't exist as a delegate (e.g. a typo, or a model name that doesn't exist in the generated client), the constructor throws a `VSRepoAdapterError` (code `MODEL_NOT_FOUND`) naming the missing delegate, instead of failing on the first `save`/`get`/etc.
376
+ - `relations[field].nullable: true` is now rejected when `mode` is not `mto` — `nullable` only applies to `mto`. Validated with a new `VSRepoAdapterError` (code `INVALID_ADAPTER_CONFIG`), same as the rest of the relation schema
377
+ - New `validators/validate-prisma-client.validator.ts`, plus tests covering all three new validations (`tests/config-validation.test.ts`)
378
+
379
+ ---
380
+
381
+ ## [1.1.1] - 2026-09-07 (Português)
382
+
383
+ ### Adicionado
384
+
385
+ - **Validação mais forte no construtor**, pegando mais erros de configuração já na construção em vez de na primeira query:
386
+ - O client Prisma (primeiro argumento do construtor) agora é validado: passar `null`/`undefined` lança um `VSRepoAdapterError` (code `MISSING_DB_CLIENT`) imediatamente, em vez de falhar depois com um `Cannot read properties of undefined` genérico
387
+ - `tableName` agora é conferido contra o client Prisma fornecido: se `prisma[tableName]` não existir como delegate (ex.: um typo, ou um nome de model que não existe no client gerado), o construtor lança um `VSRepoAdapterError` (code `MODEL_NOT_FOUND`) nomeando o delegate ausente, em vez de falhar no primeiro `save`/`get`/etc.
388
+ - `relations[campo].nullable: true` agora é rejeitado quando `mode` é diferente de `mto` — `nullable` só se aplica a `mto`. Validado com um novo `VSRepoAdapterError` (code `INVALID_ADAPTER_CONFIG`), igual ao resto do schema de relation
389
+ - Novo `validators/validate-prisma-client.validator.ts`, além de testes cobrindo as três novas validações (`tests/config-validation.test.ts`)
390
+
391
+ ---
392
+
393
+ ## [1.1.0] - 2026-09-04
394
+
395
+ ### Added
396
+
397
+ - **Atomic and aggregation methods** — implements the 8 new abstract methods added to the `VSRepoAdapter` contract by `vsrepo` 2.1.0: `incrementOne`, `decrementOne`, `multiplyOne`, `divideOne`, `sum`, `average`, `min` and `max`
398
+ - `incrementOne`/`decrementOne`/`multiplyOne`/`divideOne` translate directly into Prisma's native single-field atomic write (`data: { [field]: { increment: value } }`, etc.), evaluated server-side against the row's _current_ value, not as a client-side read-modify-write. Prisma's `update()` already returns the row reflecting the state _after_ the write, so no follow-up read is issued
399
+ - `sum`/`average`/`min`/`max` translate into Prisma's `aggregate()` (`_sum`/`_avg`/`_min`/`_max`); the raw result (`number`, `bigint`, `Decimal`, or `null`) is normalized to `number | null`, returning `null` (not `0`) when no record matches, mirroring SQL's `SUM()`/`AVG()`/`MIN()`/`MAX()`
400
+ - `Decimal` fields are fully supported: atomic `value`s are passed through to Prisma as-is, and aggregate results are always normalized to `number` via `.toNumber()`, never returned as a `Decimal` instance
401
+ - New "Atomic and aggregation methods" section in `README.md`/`README.pt-BR.md`, plus JSDoc on every new method
402
+
403
+ ### Changed
404
+
405
+ - **BREAKING (peer dependency):** the `vsrepo` peer dependency was bumped from `^2.0.0` to `^2.1.0` — the adapter now imports `NumericKeys`/`DecimalLike` types that only exist starting in `vsrepo` 2.1.0, and implements the new abstract methods required by that version's `VSRepoAdapter` contract
406
+
407
+ ---
408
+
409
+ ## [1.1.0] - 2026-09-04 (Português)
410
+
411
+ ### Adicionado
412
+
413
+ - **Métodos atômicos e de agregação** — implementa os 8 novos métodos abstratos adicionados ao contrato do `VSRepoAdapter` pela `vsrepo` 2.1.0: `incrementOne`, `decrementOne`, `multiplyOne`, `divideOne`, `sum`, `average`, `min` e `max`
414
+ - `incrementOne`/`decrementOne`/`multiplyOne`/`divideOne` traduzem direto pra escrita atômica nativa de campo único do Prisma (`data: { [field]: { increment: value } }`, etc.), avaliada server-side contra o valor _atual_ do registro, e não como um read-modify-write no cliente. O `update()` do Prisma já retorna a linha refletindo o estado _após_ a escrita, então nenhuma leitura extra é feita
415
+ - `sum`/`average`/`min`/`max` traduzem pro `aggregate()` do Prisma (`_sum`/`_avg`/`_min`/`_max`); o resultado bruto (`number`, `bigint`, `Decimal`, ou `null`) é normalizado pra `number | null`, retornando `null` (não `0`) quando nenhum registro casa, espelhando o `SUM()`/`AVG()`/`MIN()`/`MAX()` do SQL
416
+ - Campos `Decimal` são totalmente suportados: os `value`s atômicos são repassados pro Prisma como estão, e os resultados de agregação são sempre normalizados pra `number` via `.toNumber()`, nunca retornados como uma instância de `Decimal`
417
+ - Nova seção "Métodos atômicos e de agregação" no `README.md`/`README.pt-BR.md`, além de JSDoc em cada novo método
418
+
419
+ ### Alterado
420
+
421
+ - **BREAKING (peer dependency):** a peer dependency `vsrepo` foi elevada de `^2.0.0` pra `^2.1.0` — o adapter agora importa os tipos `NumericKeys`/`DecimalLike`, que só existem a partir da `vsrepo` 2.1.0, e implementa os novos métodos abstratos exigidos pelo contrato `VSRepoAdapter` dessa versão
422
+
423
+ ---
424
+
425
+ ## [1.0.3] - 2026-09-03
426
+
427
+ ### Fixed
428
+
429
+ - `logSlowThresholdMs` option was missing from the runtime validation schema (`adapterConfigSchema`) — although the option was documented and consumed in the constructor since v1.0.1, it was not declared in the valibot schema, which could cause validation issues; the field is now properly validated as an optional positive number, and a default value of `300` is applied before passing it to `VSLogger`
430
+
431
+ ---
432
+
433
+ ## [1.0.3] - 2026-09-03 (Português)
434
+
435
+ ### Corrigido
436
+
437
+ - A opção `logSlowThresholdMs` estava faltando no schema de validação em runtime (`adapterConfigSchema`) — embora a opção fosse documentada e consumida no construtor desde a v1.0.1, ela não estava declarada no schema valibot, o que poderia causar problemas de validação; o campo agora é validado corretamente como um número positivo opcional, e um valor padrão de `300` é aplicado antes de passá-lo ao `VSLogger`
438
+
439
+ ---
440
+
441
+ ## [1.0.2] - 2026-09-02
442
+
443
+ ### Docs
444
+
445
+ - Documented how `deleteManyReturning` works — it fetches the records matching `where` via a `findMany` and then **re-applies the same `where`** to a `deleteMany` (Prisma has no native `deleteManyAndReturn`). Because the delete is driven by the `where` rather than the fetched records, a concurrent change between the two operations can make the returned records and the actually-deleted rows diverge (e.g. a row inserted after the `findMany` still gets deleted even though it wasn't returned; a row that stops matching before the `deleteMany` isn't deleted even though it was returned). Added guidance in the `README.md`/`README.pt-BR.md` (Transactions section) on running the method inside a `repository.transaction()` at a higher isolation level (e.g. `TransactionIsolationLevel.SERIALIZABLE`) to guarantee no concurrency issues, and updated the JSDoc of `deleteManyReturning` accordingly
446
+
447
+ ---
448
+
449
+ ## [1.0.2] - 2026-09-02 (Português)
450
+
451
+ ### Documentação
452
+
453
+ - Documentado o funcionamento do `deleteManyReturning` — ele busca os registros que batem com o `where` via um `findMany` e depois **re-aplica o mesmo `where`** num `deleteMany` (o Prisma não tem um `deleteManyAndReturn` nativo). Como o delete é guiado pelo `where` — e não pelos registros buscados — uma alteração concorrente entre as duas operações pode fazer os registros retornados e as linhas realmente deletadas divergirem (ex.: uma linha inserida depois do `findMany` ainda é deletada mesmo sem ter sido retornada; uma linha que deixa de bater antes do `deleteMany` não é deletada mesmo tendo sido retornada). Adicionada orientação no `README.md`/`README.pt-BR.md` (seção Transactions) para rodar o método dentro de um `repository.transaction()` num nível de isolamento mais alto (ex.: `TransactionIsolationLevel.SERIALIZABLE`) para garantir que não haverá problemas de concorrência, e atualizado o JSDoc do `deleteManyReturning` de acordo
454
+
455
+ ---
456
+
457
+ ## [1.0.1] - 2026-09-02
458
+
459
+ ### Fixed
460
+
461
+ - `merge` method now strips `undefined` fields from the source object before merging — previously, when merging entities without `relations` (`relations` config absent), `undefined` values from the source object were carried into the result, which could overwrite existing fields of the stored record with `undefined`
462
+ - Corrected the performance log texts — the start/end logs now read `run <method>` (e.g. `run findOne`) consistently across every method instead of the method name alone
463
+
464
+ ### Added
465
+
466
+ - Documented provider-specific limitations in `README.md`/`README.pt-BR.md` — a table covering which Prisma features this adapter relies on aren't available on every provider (`mode: "insensitive"` for case-insensitive filters, `createManyReturning`/`updateManyReturning` for returning writes, and `skipDuplicates` on the `IgnoreConflicts` variants), noting these come from Prisma itself, not from the adapter
467
+ - Added a new `logSlowThresholdMs` option to the `VSRepoPrisma7Adapter` constructor config — the duration (in ms) above which a finished operation is logged as potentially slow, passed through to the internal `VSLogger`; defaults to `300ms`, complementing the existing `logLevel` option for performance monitoring
468
+
469
+ ---
470
+
471
+ ## [1.0.1] - 2026-09-02 (Português)
472
+
473
+ ### Corrigido
474
+
475
+ - O método `merge` agora remove campos com valor `undefined` do objeto de origem antes de mesclar — antes, ao mesclar entidades sem `relations` (config de `relations` ausente), valores `undefined` do objeto de origem eram propagados para o resultado, o que poderia sobrescrever campos existentes do registro salvo com `undefined`
476
+ - Corrigidos os textos dos logs de performance — os logs de início/fim agora leem `run <método>` (ex.: `run findOne`) de forma consistente em todos os métodos, em vez de apenas o nome do método
477
+
478
+ ### Adicionado
479
+
480
+ - Documentadas as limitações por provider no `README.md`/`README.pt-BR.md` — uma tabela cobrindo quais recursos do Prisma que esse adapter usa não estão disponíveis em todos os bancos (`mode: "insensitive"` para filtros case-insensitive, `createManyReturning`/`updateManyReturning` para escritas com retorno, e `skipDuplicates` nas variantes `IgnoreConflicts`), destacando que essas limitações vêm do próprio Prisma, não do adapter
481
+ - Adicionada uma nova opção `logSlowThresholdMs` na config do construtor do `VSRepoPrisma7Adapter` — a duração (em ms) acima da qual uma operação finalizada é logada como potencialmente lenta, repassada ao `VSLogger` interno; o default é `300ms`, complementando a opção `logLevel` já existente para monitoramento de performance
482
+
483
+ ---
484
+
485
+ ## [1.0.0] - 2026-08-31
486
+
487
+ > First official release. `@vsrepo/prisma7-adapter` is the officially published `VSRepoAdapter` implementation for [VSRepository v2](https://github.com/VSRepository/VSRepository), backed by [Prisma 7](https://www.prisma.io/).
488
+
489
+ ### Added
490
+
491
+ - **Full `VSRepoAdapter` implementation** — translates every `VSRepository` operation into Prisma Client calls, backed by Prisma 7
492
+ - **Where/ordering parsing** — resolves `VSRepoWhere`, `Ordering` and case-insensitive filters (`IgnoreCase`) through dedicated parsers (`parsePrismaWhere`)
493
+ - **`select` support** — transforms method-options `select` into a Prisma `select` in read operations (`parsePrismaSelect`)
494
+ - **`relations` in method options (read)** — eager loading shape `{ field: true }` / `{ field: { sub: true } }` (nested) transformed into a Prisma `include` (`parsePrismaInclude`); the `include` is discarded when a `select` is provided (Prisma doesn't combine `include` and `select`)
495
+ - **`relations` in the constructor (write)** — describes each relation field (`mode: "oto" | "mto" | "otm" | "mtm"`, `restriction: "add" | "set"`, `pk`, `nullable`) so `create`/`update`/`upsert`/`save`/`merge` payload relation fields are resolved into Prisma nested writes (`create`/`connectOrCreate`/`upsert`/`disconnect`/`delete`/`deleteMany`/`set`) — the same behavior the v1 of VSRepository had
496
+ - **Full base method support** — `findOne`, `findOneOrThrow`, `findMany`, `save` (create/upsert), `saveMany`, `delete`, `deleteMany`, `deleteManyReturning`, `update`, `updateMany`, `updateManyReturning`, `count`, `exists`, `create`, `createMany`, `createManyReturning`, `merge`, `upsert`
497
+ - **`createManyReturning` / `updateManyReturning` / `deleteManyReturning`** — returning writes built on Prisma's `createManyAndReturn`/`updateManyAndReturn`, re-querying the affected rows by primary key via a second `findMany`, with `select`/`include` support and respect for the `order` option
498
+ - **Error mapping** — every Prisma/ORM error is mapped and always re-thrown as `VSRepoAdapterError`, carrying the original ORM error and a dedicated `AdapterErrorCode`
499
+ - **Config validation** — the constructor config (`tableName`, `pkName`, `relations`, `logLevel`) is validated at runtime with [valibot](https://valibot.dev/); an invalid value throws a `VSRepoPrisma7AdapterError` naming the offending field
500
+ - **Transactions** — every method accepts `options.db`; multi-operation methods (`saveMany`, `updateManyReturning`, `createManyReturning`, `deleteManyReturning`) go through `runTransactional`, reusing an already-active transaction client (detected by the `$on` method) instead of nesting a new one
501
+ - **`Prisma7OrmTypes<DB, TX>` / `Prisma7ClientLike`** — type helpers that tie `VSRepository`'s `getDbClient()`/`transaction()` return types to your real, generated Prisma types
502
+ - **Logging** — uses `VSLogger` internally: a `DEBUG` line with the resolved Prisma arg per method plus start/end performance logs (WARN on slow operations), controlled by the `logLevel` constructor option
503
+ - **Nested-write validation** — `createMany`/`createManyReturning`/`updateMany`/`updateManyReturning` only accept scalar fields; a payload containing a configured relation field throws a `VSRepoPrisma7AdapterError`
504
+ - **Build & pack** — `tsc` build to `dist/`, npm `prepack` build, `clean`/`build`/`typecheck` scripts, and `files` whitelisting for publishing (commonly CommonJS output)
505
+ - **CI workflow** — GitHub Actions (`.github/workflows/ci.yml`)
506
+ - **Tests** — implementation tests for the adapter and integration tests with `VSRepository` (including dynamic and query methods), plus `example.ts` usage example
507
+ - **Documentation** — `README.md`/`README.pt-BR.md` (English + Portuguese) covering installation, basic usage, the constructor config, the two `relations` (`write` vs `read`), `merge`, transactions, logging, requirements, and full JSDoc on the public API surface (marked `@publicApi`), plus a downloads badge
508
+
509
+ ---
510
+
511
+ ## [1.0.0] - 2026-08-31 (Português)
512
+
513
+ > Primeira release oficial. `@vsrepo/prisma7-adapter` é a implementação oficial publicada de `VSRepoAdapter` para o [VSRepository v2](https://github.com/VSRepository/VSRepository), usando [Prisma 7](https://www.prisma.io/).
514
+
515
+ ### Adicionado
516
+
517
+ - **Implementação completa de `VSRepoAdapter`** — traduz toda operação do `VSRepository` em chamadas do Prisma Client, usando Prisma 7
518
+ - **Parsing de where/ordering** — resolve `VSRepoWhere`, `Ordering` e filtros case-insensitive (`IgnoreCase`) através de parsers dedicados (`parsePrismaWhere`)
519
+ - **Suporte a `select`** — transforma o `select` das options dos métodos num `select` do Prisma nas operações de leitura (`parsePrismaSelect`)
520
+ - **`relations` nas options (leitura)** — eager loading com a forma `{ campo: true }` / `{ campo: { sub: true } }` (aninhado) transformado num `include` do Prisma (`parsePrismaInclude`); o `include` é descartado quando um `select` é fornecido (o Prisma não combina `include` e `select`)
521
+ - **`relations` no construtor (escrita)** — descreve cada campo de relação (`mode: "oto" | "mto" | "otm" | "mtm"`, `restriction: "add" | "set"`, `pk`, `nullable`) para que os campos de relação dos payloads de `create`/`update`/`upsert`/`save`/`merge` sejam resolvidos em nested writes do Prisma (`create`/`connectOrCreate`/`upsert`/`disconnect`/`delete`/`deleteMany`/`set`) — o mesmo comportamento que a v1 do VSRepository tinha
522
+ - **Suporte completo aos métodos base** — `findOne`, `findOneOrThrow`, `findMany`, `save` (create/upsert), `saveMany`, `delete`, `deleteMany`, `deleteManyReturning`, `update`, `updateMany`, `updateManyReturning`, `count`, `exists`, `create`, `createMany`, `createManyReturning`, `merge`, `upsert`
523
+ - **`createManyReturning` / `updateManyReturning` / `deleteManyReturning`** — escritas com retorno baseadas nos `createManyAndReturn`/`updateManyAndReturn` do Prisma, re-buscando as linhas afetadas pela primary key num segundo `findMany`, com suporte a `select`/`include` e respeito à opção `order`
524
+ - **Mapeamento de erros** — todo erro de Prisma/ORM é mapeado e sempre relançado como `VSRepoAdapterError`, carregando o erro original do ORM e um `AdapterErrorCode` dedicado
525
+ - **Validação de config** — a config do construtor (`tableName`, `pkName`, `relations`, `logLevel`) é validada em runtime com [valibot](https://valibot.dev/); um valor inválido lança um `VSRepoPrisma7AdapterError` apontando o campo problemático
526
+ - **Transactions** — todos os métodos aceitam `options.db`; métodos com múltiplas operações (`saveMany`, `updateManyReturning`, `createManyReturning`, `deleteManyReturning`) passam por `runTransactional`, reaproveitando um transaction client já ativo (detectado pelo método `$on`) em vez de aninhar uma nova
527
+ - **`Prisma7OrmTypes<DB, TX>` / `Prisma7ClientLike`** — helpers de tipo que amarram os tipos de retorno de `getDbClient()`/`transaction()` do `VSRepository` aos seus tipos reais e gerados do Prisma
528
+ - **Logging** — usa o `VSLogger` internamente: uma linha `DEBUG` com o arg resolvido do Prisma por método e logs de performance de início/fim (WARN pra operações lentas), controlado pela opção `logLevel` do construtor
529
+ - **Validação de nested writes** — `createMany`/`createManyReturning`/`updateMany`/`updateManyReturning` só aceitam campos escalares; um payload contendo um campo de relação configurado lança um `VSRepoPrisma7AdapterError`
530
+ - **Build & pack** — build com `tsc` para `dist/`, `prepack` de build no npm, scripts `clean`/`build`/`typecheck`, e whitelist de `files` para publicação (saída CommonJS)
531
+ - **Workflow de CI** — GitHub Actions (`.github/workflows/ci.yml`)
532
+ - **Testes** — testes de implementação para o adapter e testes de integração com o `VSRepository` (incluindo dynamic e query methods), além do exemplo de uso `example.ts`
533
+ - **Documentação** — `README.md`/`README.pt-BR.md` (inglês + português) cobrindo instalação, uso básico, config do construtor, os dois `relations` (escrita vs leitura), `merge`, transactions, logging, requisitos e JSDoc completa na API pública (marcada com `@publicApi`), além do badge de downloads
534
+
535
+ ---
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 João Pedro Azevedo Freire Mecenas
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Copyright (c) 2026 João Pedro Azevedo Freire Mecenas
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.