Skip to content

Feat/upgrade prisma v7#600

Open
renatocron wants to merge 2 commits intohomolfrom
feat/upgrade-prisma-v7
Open

Feat/upgrade prisma v7#600
renatocron wants to merge 2 commits intohomolfrom
feat/upgrade-prisma-v7

Conversation

@renatocron
Copy link
Copy Markdown
Contributor

@renatocron renatocron commented Mar 3, 2026

Summary by CodeRabbit

Release Notes

  • Chores
    • Upgraded database ORM framework to the latest version with enhanced PostgreSQL adapter support
    • Updated database configuration management with environment-based settings
    • Refactored database service layer with improved transaction handling and retry logic
    • Established minimum runtime requirements: Node.js >=18.18.0 and npm >=9.0.0
    • Enhanced Docker containerization for improved deployment compatibility

lucasansei and others added 2 commits February 25, 2026 14:05
…ortações de Decimal

A atualização garante compatibilidade com o Prisma 7, melhorando a estabilidade e
compatibilidade do projeto, além de corrigir importações de Decimal para o pacote
runtime do Prisma, evitando problemas de compatibilidade.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 3, 2026

📝 Walkthrough

Walkthrough

This PR upgrades Prisma from v6.12.0 to v7.4.2, introducing PrismaPg adapter support, a new Prisma configuration file, and migration of import paths from runtime/library to runtime/client. Views lose primary key annotations, PrismaService is refactored with proxy-based transaction retry logic, and a postinstall patch script ensures runtime compatibility.

Changes

Cohort / File(s) Summary
Build & Configuration Setup
backend/Dockerfile, backend/package.json, backend/prisma.config.ts
Added Docker file copying for patch script, vendor directory, and Prisma config. Added engine requirements (Node >=18.18.0, npm >=9.0.0), postinstall script, and upgraded prisma/adapter packages to v7.4.2. Introduced new prisma.config.ts with environment-based datasource configuration.
Prisma Schema Updates
backend/prisma/schema.prisma
Removed DATABASE_URL from datasource block. Stripped @id and @default(autoincrement()) annotations from 15+ view models (ViewProjetoMDO, ViewProjetoV2, ViewVariavelGlobal, view_meta_pessoa_responsavel, view_pdm_meta_iniciativa_atividade, view_painel_estrategico_projetos, etc.), converting them from primary keys to regular fields.
Prisma Patching Script
backend/scripts/patch-prisma-exports.js
New Node.js script that patches @prisma/client-runtime-utils package.json to export ./dist subpath with require/import configurations, ensuring Node 24+ compatibility for NestJS Swagger plugin metadata.
PrismaService Refactor
backend/src/prisma/prisma.service.ts
Major refactoring: replaced PrismaServiceBase with direct PrismaClient extension, integrated PrismaPg adapter, added Proxy-wrapped instance for lazy connection and custom transaction handling with RetryPromise retries and configurable timeouts (default 60s). Consolidated logging and removed legacy middleware patterns.
Transaction Client Type Update
backend/src/api-logs/backup-scheduler.service.ts
Updated import to include Prisma type and changed scheduleApiLogBackupTasks parameter type from Omit<PrismaService, ...> to Prisma.TransactionClient.
Decimal Import Path Corrections
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/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/.../*, backend/src/pp/.../*, backend/src/reports/relatorios/helpers/reports.params-processado.ts, backend/src/variavel/.../*
Updated import paths for Decimal from @prisma/client/runtime/library to @prisma/client/runtime/client across 16+ files. Also updated InputJsonValue import path in reports helper. No functional logic changes.

Sequence Diagram

sequenceDiagram
    participant App as Application
    participant Proxy as PrismaService<br/>(Proxy)
    participant Adapter as PrismaPg<br/>Adapter
    participant DB as Database

    App->>Proxy: onModuleInit()
    Proxy->>Adapter: $connect()
    Adapter->>DB: Establish connection
    DB-->>Adapter: Connected
    Adapter-->>Proxy: Ready

    App->>Proxy: $transaction(fn or array)
    Proxy->>Proxy: Intercept via Proxy trap
    alt Array-based transaction
        Proxy->>Adapter: Execute batch with RetryPromise
    else Function-based transaction
        Proxy->>Adapter: Execute with timeout (60s default)<br/>and RetryPromise retries
    end
    Adapter->>DB: Execute queries
    DB-->>Adapter: Results
    Adapter-->>Proxy: Transaction complete
    Proxy-->>App: Results with retry logic applied
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • robsonsobral
  • GustavoFSoares

Poem

🐰 Prisma hops from six to seven,
Views shed their IDs (oh what a heaven!),
Adapters dance with Postgres grace,
Proxy transactions keep pace,
From runtime/library to runtime/client we strive,
The schema evolves—and hopping thrives! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: upgrading Prisma to version 7, which is the primary objective reflected throughout the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/upgrade-prisma-v7

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


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 and usage tips.

@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud bot commented Mar 3, 2026

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

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 (3)
backend/src/reports/relatorios/helpers/reports.params-processado.ts (1)

1-1: Use Prisma.InputJsonValue from @prisma/client instead of runtime internals.

Line 1 should avoid @prisma/client/runtime/client for type imports; this path is not a stable public API.

♻️ Proposed fix
-import { InputJsonValue } from '@prisma/client/runtime/client';
+import { FonteRelatorio, ParlamentarCargo, Prisma, TipoRelatorio } from '@prisma/client';
...
-import { FonteRelatorio, ParlamentarCargo, TipoRelatorio } from '@prisma/client';
...
-): Promise<InputJsonValue | undefined> => {
+): Promise<Prisma.InputJsonValue | undefined> => {
...
-            return report.parametros_processados.valueOf() as InputJsonValue;
+            return report.parametros_processados.valueOf() as Prisma.InputJsonValue;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/reports/relatorios/helpers/reports.params-processado.ts` at line
1, Replace the runtime-internal import of InputJsonValue with the public Prisma
type: remove the import from '@prisma/client/runtime/client' and instead import
Prisma (or directly Prisma.InputJsonValue) from '@prisma/client', then update
any usages to reference Prisma.InputJsonValue (or the imported alias) so the
code uses the stable public API rather than runtime internals (update the import
statement that currently brings in InputJsonValue).
backend/src/orcamento-planejado/entities/orcamento-planejado.entity.ts (1)

1-8: Use public Prisma API (Prisma.Decimal) instead of internal runtime import.

The import from @prisma/client/runtime/client is an internal implementation detail that is not covered by Prisma's semantic versioning and can change between versions. The Decimal type is available through the public Prisma namespace.

♻️ Proposed fix
-import { Decimal } from '@prisma/client/runtime/client';
+import { Prisma } from '@prisma/client';
...
-    valor_planejado: number | Decimal;
+    valor_planejado: number | Prisma.Decimal;

This pattern is already used elsewhere in the codebase (e.g., variavel.service.ts).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/orcamento-planejado/entities/orcamento-planejado.entity.ts`
around lines 1 - 8, Replace the internal runtime Decimal import with the public
Prisma API: remove the import of Decimal from '@prisma/client/runtime/client'
and instead reference Prisma.Decimal from the public '@prisma/client' package;
update the OrcamentoPlanejado type for the valor_planejado property to use
number | Prisma.Decimal and ensure the module imports Prisma (import { Prisma }
from '@prisma/client') so the OrcamentoPlanejado class and its valor_planejado
field compile against the supported public Prisma type.
backend/src/casa-civil/dash/transferencia.service.ts (1)

26-26: Use public Prisma.Decimal instead of internal runtime import for upgrade safety.

Line 26 imports Decimal from @prisma/client/runtime/client, which is Prisma's internal/private API and unsupported across upgrades. Prisma explicitly recommends using Prisma.Decimal from @prisma/client instead. Update the import and adjust usages from Decimal(0) to new Prisma.Decimal(0).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/casa-civil/dash/transferencia.service.ts` at line 26, The current
import pulls Decimal from Prisma's internal runtime; replace that with the
public API by importing Prisma from '@prisma/client' (remove the import from
'@prisma/client/runtime/client') and update any constructions like Decimal(0) to
use new Prisma.Decimal(0) (or Prisma.Decimal as appropriate) in
transferencia.service.ts so the code uses the supported public Prisma.Decimal
type instead of the internal runtime symbol.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/src/prisma/prisma.service.ts`:
- Around line 33-34: PrismaService is passing an undefined DATABASE_URL into new
PrismaPg which delays failure; update the PrismaService
initialization/constructor to validate process.env.DATABASE_URL immediately
(similar to the SESSION_JWT_SECRET check in jwt.strategy.ts) and throw a clear
error if missing, then construct new PrismaPg({ connectionString: databaseUrl })
using the validated value (reference symbols: PrismaService, PrismaPg,
process.env.DATABASE_URL).

---

Nitpick comments:
In `@backend/src/casa-civil/dash/transferencia.service.ts`:
- Line 26: The current import pulls Decimal from Prisma's internal runtime;
replace that with the public API by importing Prisma from '@prisma/client'
(remove the import from '@prisma/client/runtime/client') and update any
constructions like Decimal(0) to use new Prisma.Decimal(0) (or Prisma.Decimal as
appropriate) in transferencia.service.ts so the code uses the supported public
Prisma.Decimal type instead of the internal runtime symbol.

In `@backend/src/orcamento-planejado/entities/orcamento-planejado.entity.ts`:
- Around line 1-8: Replace the internal runtime Decimal import with the public
Prisma API: remove the import of Decimal from '@prisma/client/runtime/client'
and instead reference Prisma.Decimal from the public '@prisma/client' package;
update the OrcamentoPlanejado type for the valor_planejado property to use
number | Prisma.Decimal and ensure the module imports Prisma (import { Prisma }
from '@prisma/client') so the OrcamentoPlanejado class and its valor_planejado
field compile against the supported public Prisma type.

In `@backend/src/reports/relatorios/helpers/reports.params-processado.ts`:
- Line 1: Replace the runtime-internal import of InputJsonValue with the public
Prisma type: remove the import from '@prisma/client/runtime/client' and instead
import Prisma (or directly Prisma.InputJsonValue) from '@prisma/client', then
update any usages to reference Prisma.InputJsonValue (or the imported alias) so
the code uses the stable public API rather than runtime internals (update the
import statement that currently brings in InputJsonValue).

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d6e108a and 2dd6751.

⛔ Files ignored due to path filters (1)
  • backend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (26)
  • backend/Dockerfile
  • backend/package.json
  • backend/prisma.config.ts
  • backend/prisma/schema.prisma
  • backend/scripts/patch-prisma-exports.js
  • backend/src/api-logs/backup-scheduler.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/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/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/prisma/prisma.service.ts
  • backend/src/reports/relatorios/helpers/reports.params-processado.ts
  • backend/src/variavel/dto/list-variavel.dto.ts
  • backend/src/variavel/entities/variavel.entity.ts
  • backend/vendor/prisma-field-encryption.tgz

Comment on lines +33 to +34
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
super({ adapter, log: logConfig });
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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the prisma service file
head -50 backend/src/prisma/prisma.service.ts

Repository: AppCivico/smae

Length of output: 1856


🏁 Script executed:

# Check if PATTERNS.md exists and review it for environment validation guidance
cat backend/PATTERNS.md 2>/dev/null || echo "File not found, checking for similar pattern docs"

Repository: AppCivico/smae

Length of output: 22118


🏁 Script executed:

# Search for DATABASE_URL references throughout the codebase to understand how it's typically handled
rg "DATABASE_URL" --type ts --type tsx -B 2 -A 2

Repository: AppCivico/smae

Length of output: 85


🏁 Script executed:

# Check if there's any environment validation at app startup/module level
rg "validate.*env|process.env\." backend --type ts --type tsx | head -20

Repository: AppCivico/smae

Length of output: 85


🏁 Script executed:

# Look for main.ts and app bootstrap
fd -e ts -e tsx "main\.|app\.module" backend/src --type f

Repository: AppCivico/smae

Length of output: 480


🏁 Script executed:

# Check for environment validation patterns in the codebase
rg "process\.env\." backend/src --type ts -B 1 -A 1 | head -40

Repository: AppCivico/smae

Length of output: 2781


🏁 Script executed:

# Look specifically for error handling or validation related to DATABASE_URL
rg "DATABASE_URL|connectionString" backend --type ts -B 2 -A 2

Repository: AppCivico/smae

Length of output: 1487


🏁 Script executed:

# Check if there's an environment validation module or config
fd -e ts -e tsx "env|config" backend/src --type f | grep -E "(env|config)" | head -20

Repository: AppCivico/smae

Length of output: 1392


🏁 Script executed:

# Check main.ts for bootstrap/validation
cat -n backend/src/main.ts

Repository: AppCivico/smae

Length of output: 3705


🏁 Script executed:

# Check prisma.config.ts to see how env() function works
cat -n backend/prisma.config.ts

Repository: AppCivico/smae

Length of output: 406


🏁 Script executed:

# Search for env validation utility
rg "function env|const env|export.*env" backend --type ts -B 1 -A 3 | head -50

Repository: AppCivico/smae

Length of output: 1932


🏁 Script executed:

# Check how DATABASE_URL is used in other parts - specifically in bin/pgsql-migrate.ts
sed -n '1,30p' backend/bin/pgsql-migrate.ts

Repository: AppCivico/smae

Length of output: 926


🏁 Script executed:

# Look for any environment validation or checks that happen before PrismaService is instantiated
rg "DATABASE_URL" backend/prisma --type ts -B 3 -A 3

Repository: AppCivico/smae

Length of output: 40


🏁 Script executed:

# Check if there are any error patterns when DATABASE_URL is missing in the prisma logs or tests
fd -e ts -e tsx "test|spec" backend/src --type f | xargs grep -l "DATABASE_URL" 2>/dev/null | head -5

Repository: AppCivico/smae

Length of output: 40


🏁 Script executed:

# Look at how the PrismaService is used - when is it first instantiated?
rg "PrismaService" backend/src/app.module.ts -B 2 -A 5

Repository: AppCivico/smae

Length of output: 40


🏁 Script executed:

# Look at app.module.ts to understand when PrismaService is instantiated
head -100 backend/src/app.module.ts

Repository: AppCivico/smae

Length of output: 3966


🏁 Script executed:

# Check the PrismaModule to see how it provides PrismaService
fd -e ts "prisma.module" backend/src --type f

Repository: AppCivico/smae

Length of output: 93


🏁 Script executed:

# Search for any error handling or documentation about DATABASE_URL requirement
rg "DATABASE_URL" backend --type ts --type md -B 5 -A 2 | head -60

Repository: AppCivico/smae

Length of output: 2395


🏁 Script executed:

# Check the prisma.module.ts file
cat -n backend/src/prisma/prisma.module.ts

Repository: AppCivico/smae

Length of output: 309


🏁 Script executed:

# Check if there's any .env file documentation or requirements
fd -e md "README|SETUP|ENV|.env" backend --type f | head -10

Repository: AppCivico/smae

Length of output: 157


🏁 Script executed:

# Look for any CI/CD configuration that might validate DATABASE_URL before startup
fd -e yml -e yaml ".github|docker" backend --type f | head -10

Repository: AppCivico/smae

Length of output: 40


🏁 Script executed:

# Check the backend README for setup/environment documentation
head -150 backend/README.md

Repository: AppCivico/smae

Length of output: 3851


🏁 Script executed:

# Search for any .env.example or similar files
fd -e example -e sample "env" backend --type f

Repository: AppCivico/smae

Length of output: 78


🏁 Script executed:

# Look at the full PrismaService to understand the complete picture
cat -n backend/src/prisma/prisma.service.ts

Repository: AppCivico/smae

Length of output: 3362


🏁 Script executed:

# Check the .env.example to see if DATABASE_URL is documented
cat backend/.env.example | head -50

Repository: AppCivico/smae

Length of output: 1813


🏁 Script executed:

# Search for how other critical environment variables are handled
rg "SESSION_JWT_SECRET|CLOAK_KEY" backend/src --type ts -B 2 -A 2

Repository: AppCivico/smae

Length of output: 10456


Validate DATABASE_URL at service initialization for fail-fast error reporting.

The service currently passes an undefined connection string to PrismaPg, which defers the error until connection attempt and produces opaque failures. This mirrors the validation pattern already used in jwt.strategy.ts for SESSION_JWT_SECRET, ensuring critical infrastructure setup errors are caught immediately at bootstrap time.

Proposed fix
     constructor() {
-        const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
+        const connectionString = process.env.DATABASE_URL;
+        if (!connectionString) {
+            throw new Error('DATABASE_URL must be defined');
+        }
+        const adapter = new PrismaPg({ connectionString });
         super({ adapter, log: logConfig });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
super({ adapter, log: logConfig });
constructor() {
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error('DATABASE_URL must be defined');
}
const adapter = new PrismaPg({ connectionString });
super({ adapter, log: logConfig });
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/prisma/prisma.service.ts` around lines 33 - 34, PrismaService is
passing an undefined DATABASE_URL into new PrismaPg which delays failure; update
the PrismaService initialization/constructor to validate
process.env.DATABASE_URL immediately (similar to the SESSION_JWT_SECRET check in
jwt.strategy.ts) and throw a clear error if missing, then construct new
PrismaPg({ connectionString: databaseUrl }) using the validated value (reference
symbols: PrismaService, PrismaPg, process.env.DATABASE_URL).

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