8000 Opt-in trim_scale for decimal fields · Issue #414 · romeerez/orchid-orm · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Opt-in trim_scale for decimal fields #414
Open
@IlyaSemenov

Description

@IlyaSemenov

The default Postgres behavior for decimal fields math operations is that the result has the precision of the maximum precision of its elements. That means, 0.333 + 0.367 is not 0.7 but 0.700:

await db.user.insert({ balance: 0.333 })
await db.user.find(1).increment({ balance: 0.367 })
console.log(await db.user.find(1).get("balance")) // Expected 0.7, actual result 0.700

This is inconvenient for real use. I end up using raw SQL for all math operations:

await db.user.insert({ balance: 0.333 })
await db.user.find(1).update({ balance: sql`trim_scale(balance + (${0.367}))` })
console.log(await db.user.find(1).get("balance")) // 0.7

The same problem is with aggregates:

await db.user.insertMany([{ balance: 0.333 }, { balance: 0.367 }])
console.log(await db.user.sum("balance")) // Expected 0.7, actual result 0.700

Question, would it be somehow possible to automatically apply trim_scale on the ORM level in increment/decrement and aggregate operations? Perhaps t.decimal() options could be changed to be an object with optional keys, including the new flag:

{
  balance: t.decimal({ precision, scale, trimScale: true })
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0