Open
Description
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
Labels
No labels