Skip to content

Fix insert of BigDecimal with config - #695

Merged
DZakh merged 4 commits into
mainfrom
dz/fix-configured-bigdecimal-write
Aug 20, 2025
Merged

Fix insert of BigDecimal with config#695
DZakh merged 4 commits into
mainfrom
dz/fix-configured-bigdecimal-write

Conversation

@DZakh

@DZakh DZakh commented Aug 19, 2025

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Added BigDecimal fields with precision/scale configuration to public types and test data.
  • Improvements

    • Numeric custom types now emit proper NUMERIC(p,s)[] array representations for database compatibility; public APIs unchanged.
  • Tests

    • Updated tests, fixtures, and handlers to include the new BigDecimal-with-config fields and validate serialization and unnest insert behavior.

@DZakh
DZakh requested a review from JonoPrest August 19, 2025 12:14
@coderabbitai

coderabbitai Bot commented Aug 19, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a NUMERIC(...) special-case in Table.toSqlParams for Custom types so array types emit NUMERIC(p, s)[] directly; updates GraphQL test schema, event handlers, and SerDe/SQL tests to add a BigDecimal field with precision/scale and assert NUMERIC(10, 8) typing in DDL and unnest paths.

Changes

Cohort / File(s) Summary
SQL param handling (Table.toSqlParams)
codegenerator/cli/npm/envio/src/db/Table.res
Adds a guard for Custom(fieldType) when fieldType startsWith "NUMERIC(", returning the raw NUMERIC(...)[] for arrays instead of the previous text[] with schema-qualified cast; API unchanged.
Test schema updates
scenarios/test_codegen/schema.graphql
Adds bigDecimalWithConfig: BigDecimal! @config(precision: 10, scale: 8) to EntityWithAllTypes and EntityWithAllNonArrayTypes.
Test event handlers
scenarios/test_codegen/src/EventHandlers.ts
Sets bigDecimalWithConfig to new BigDecimal("1.1") in two EntityWithAllTypes records used by the loader handler.
SerDe and SQL tests
scenarios/test_codegen/test/SerDe_Test.res, scenarios/test_codegen/test/lib_tests/PgStorage_test.res
Adds bigDecimalWithConfig to test entities; updates table DDL to NUMERIC(10, 8) NOT NULL, adjusts unnest INSERT parameter lists to include NUMERIC(10, 8)[], and updates ON CONFLICT DO UPDATE assignments and expected ordering accordingly.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Schema as GraphQL Schema
  participant Codegen as Code Generator
  participant Table as Table.toSqlParams
  participant Tests as SQL Tests

  Schema->>Codegen: Add BigDecimal field with @config(precision:10, scale:8)
  Codegen->>Table: toSqlParams(fieldType="NUMERIC(10, 8)", isArray=true)
  alt fieldType startsWith "NUMERIC("
    Table-->>Codegen: return "NUMERIC(10, 8)[]"
  else
    Table-->>Codegen: return previous array typing (text[] cast path)
  end
  Codegen->>Tests: Emit DDL and UNNEST bindings using NUMERIC(10, 8) / NUMERIC(10, 8)[]
  Tests-->>Codegen: Assert expected DDL / unnest parameter types
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • moose-code
  • JonoPrest

Poem

I nibble bytes and hop through rows,
NUMERIC arrays where the tall grass grows.
Precision snug, scale set right,
I bound the schema through the night.
Thump-thump—tests pass at first daylight. 🐰✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 305571d and 29fe9f7.

📒 Files selected for processing (1)
  • codegenerator/cli/npm/envio/src/db/Table.res (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • codegenerator/cli/npm/envio/src/db/Table.res
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dz/fix-configured-bigdecimal-write

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
codegenerator/cli/npm/envio/src/db/Table.res (1)

241-247: Fix is correct: avoid schema-qualifying parameterized NUMERIC types

Handling Custom(fieldType) when it starts with "NUMERIC(" to produce NUMERIC(...)[] prevents generating invalid casts like TEXT[]::"schema".NUMERIC(10, 8) and matches the tests’ expectation ($n::NUMERIC(10, 8)[]). Boolean and enum branches remain intact.

To make this more robust and future-proof:

  • Make the check case-insensitive and accept DECIMAL(…) as a synonym.
  • Trim leading spaces before the check to avoid issues if formatting changes upstream.

Proposed change within this switch (keeps behavior identical for NUMERIC, but expands support):

-            | Custom(fieldType) if fieldType->Js.String2.startsWith("NUMERIC(") => fieldType
+            | Custom(fieldType) if fieldType->isNumericParamType => fieldType

Add this helper near the top of the file (outside the selected range):

let isNumericParamType = (t: string) => {
  let u = t->Js.String2.trim->Js.String2.toUpperCase
  u->Js.String2.startsWith("NUMERIC(") || u->Js.String2.startsWith("DECIMAL(")
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a021fd1 and 568968c.

📒 Files selected for processing (4)
  • codegenerator/cli/npm/envio/src/db/Table.res (1 hunks)
  • scenarios/test_codegen/schema.graphql (2 hunks)
  • scenarios/test_codegen/src/EventHandlers.ts (2 hunks)
  • scenarios/test_codegen/test/SerDe_Test.res (4 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
scenarios/test_codegen/**/schema.graphql

📄 CodeRabbit Inference Engine (scenarios/test_codegen/.cursor/rules/hyperindex.mdc)

scenarios/test_codegen/**/schema.graphql: After changing schema.graphql, run: pnpm codegen
Do not add the @entity decorator to GraphQL schema types
Avoid time-series aggregate fields (e.g., dailyVolume) in the GraphQL schema
Never use arrays of entities in the schema (e.g., [User!]!)
Model relationships using *_id fields in the schema (e.g., user_id: String!) instead of entity references

Files:

  • scenarios/test_codegen/schema.graphql
scenarios/test_codegen/**/*.ts

📄 CodeRabbit Inference Engine (scenarios/test_codegen/.cursor/rules/hyperindex.mdc)

scenarios/test_codegen/**/*.ts: After changing any TypeScript files, run: pnpm tsc --noEmit to ensure successful compilation
When updating existing entities in handlers, always use the spread operator to create updated objects before persisting
For any external call (e.g., fetch), wrap it in an Effect via experimental_createEffect and consume via context.effect
Use !context.isPreload to skip logic that should not run during preload
In TypeScript, set relationship fields using *_id properties (e.g., token_id) rather than object references
Always cast timestamps from events to BigInt (e.g., BigInt(event.block.timestamp))
When matching addresses in configuration objects within code, ensure keys are lowercase and compare using address.toLowerCase()
Use string | undefined for optional string fields instead of string | null
Always normalize token amounts to a standard decimal (e.g., 18) before addition across tokens; use helpers like normalizeAmountToUSD()

Files:

  • scenarios/test_codegen/src/EventHandlers.ts
**/*.{res,resi}

📄 CodeRabbit Inference Engine (.cursor/rules/rescript.mdc)

**/*.{res,resi}: Never use [| item |] to create an array. Use [ item ] instead.
Must always use = for setting value to a field. Use := only for ref values created using ref function.
ReScript has record types which require a type definition before hand. You can access record fields by dot like foo.myField.
It's also possible to define an inline object, it'll have quoted fields in this case.
Use records when working with structured data, and objects to conveniently pass payload data between functions.
Never use %raw to access object fields if you know the type.

Files:

  • codegenerator/cli/npm/envio/src/db/Table.res
  • scenarios/test_codegen/test/SerDe_Test.res
codegenerator/cli/npm/envio/**

📄 CodeRabbit Inference Engine (.cursor/rules/navigation.mdc)

Library-fied runtime shared across indexers lives in codegenerator/cli/npm/envio.

Files:

  • codegenerator/cli/npm/envio/src/db/Table.res
🧠 Learnings (4)
📚 Learning: 2025-08-11T08:49:57.399Z
Learnt from: CR
PR: enviodev/hyperindex#0
File: scenarios/test_codegen/.cursor/rules/hyperindex.mdc:0-0
Timestamp: 2025-08-11T08:49:57.399Z
Learning: Applies to scenarios/test_codegen/**/schema.graphql : Do not add the entity decorator to GraphQL schema types

Applied to files:

  • scenarios/test_codegen/schema.graphql
📚 Learning: 2025-08-11T08:49:57.399Z
Learnt from: CR
PR: enviodev/hyperindex#0
File: scenarios/test_codegen/.cursor/rules/hyperindex.mdc:0-0
Timestamp: 2025-08-11T08:49:57.399Z
Learning: Applies to scenarios/test_codegen/**/schema.graphql : Avoid time-series aggregate fields (e.g., dailyVolume) in the GraphQL schema

Applied to files:

  • scenarios/test_codegen/schema.graphql
📚 Learning: 2025-08-11T08:49:57.399Z
Learnt from: CR
PR: enviodev/hyperindex#0
File: scenarios/test_codegen/.cursor/rules/hyperindex.mdc:0-0
Timestamp: 2025-08-11T08:49:57.399Z
Learning: Applies to scenarios/test_codegen/**/*.ts : When updating existing entities in handlers, always use the spread operator to create updated objects before persisting

Applied to files:

  • scenarios/test_codegen/src/EventHandlers.ts
📚 Learning: 2025-08-11T08:49:57.399Z
Learnt from: CR
PR: enviodev/hyperindex#0
File: scenarios/test_codegen/.cursor/rules/hyperindex.mdc:0-0
Timestamp: 2025-08-11T08:49:57.399Z
Learning: Applies to scenarios/test_codegen/**/*.ts : Always cast timestamps from events to BigInt (e.g., BigInt(event.block.timestamp))

Applied to files:

  • scenarios/test_codegen/src/EventHandlers.ts
🔇 Additional comments (6)
scenarios/test_codegen/src/EventHandlers.ts (1)

543-543: LGTM: new non-null BigDecimal field is set in both entities

Both inserts now populate bigDecimalWithConfig, aligning with the schema change making it non-nullable. No logic side-effects.

Per repo guidelines for scenarios/test_codegen:

  • After TS changes: run pnpm tsc --noEmit
  • After schema changes: run pnpm codegen

Also applies to: 567-567

scenarios/test_codegen/schema.graphql (1)

117-117: Schema addition looks correct; remember to regenerate types

bigDecimalWithConfig: BigDecimal! @config(precision: 10, scale: 8) is correctly added to both types. This will drive NUMERIC(10, 8) in SQL and affects generated TS types.

Run pnpm codegen to update generated types used in handlers/tests.

Also applies to: 145-145

scenarios/test_codegen/test/SerDe_Test.res (4)

37-38: LGTM: entity test data includes configured BigDecimal

Adding bigDecimalWithConfig to the all-types entity mirrors the schema and ensures SerDe coverage.


127-127: LGTM: CREATE TABLE expectation includes NUMERIC(10, 8) column

The expected DDL for EntityWithAllNonArrayTypes now includes "bigDecimalWithConfig" NUMERIC(10, 8) NOT NULL, consistent with the schema directive.


138-140: LGTM: UNNEST query casts use NUMERIC(10, 8)[]

The INSERT … SELECT FROM unnest expectation correctly uses $2::NUMERIC(10, 8)[], validating the generator change in Table.res.


160-161: LGTM: non-array entity test data includes configured BigDecimal

This ensures the non-array code path and history serialization also cover the new field.

switch field {
| Field(f) =>
switch f.fieldType {
| Custom(fieldType) if fieldType->Js.String2.startsWith("NUMERIC(") => fieldType

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can you just add a comment above this when it would start with Numeric? It's obviously an edge case

Comment thread codegenerator/cli/npm/envio/src/db/Table.res
@DZakh
DZakh enabled auto-merge (squash) August 20, 2025 12:24
@DZakh
DZakh merged commit c1be236 into main Aug 20, 2025
2 checks passed
@DZakh
DZakh deleted the dz/fix-configured-bigdecimal-write branch August 20, 2025 12:32
@coderabbitai coderabbitai Bot mentioned this pull request Nov 13, 2025
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