opendoor / pggen

A database first code generator focused on postgres
MIT License
58 stars 9 forks source link

DB type numeric translates to string #75

Open NickPPC opened 4 years ago

NickPPC commented 4 years ago

DB schema: material_quantity numeric,

Pggened model: MaterialQuantity *string gorm:"column:material_quantity"

ethanpailes commented 4 years ago

This is actually working as intended. numeric is a somewhat weird type because the math is done in terms of decimal numbers rather than using floating point. It is designed for representing something like money where you want to round at exactly 2 base 10 decimal places.

Unfortunately, go does not have a type that can conveniently represent this sort of thing. In 95% of cases just marshaling to a float would be what people want, but I really don't want to leave people up a creek if they actually want the real semantics of numeric. Presumably if they want floating point semantics they would be using a real type anyway.

If go did have a decimal number type, we could marshal to that, but as is the best we could do is pull in some third party decimal numeric type that has the right semantics and I'd rather not take a public dependency on anything except the standard library.

I think the best policy for using numeric with is:

I'm going to close this for now, but if you can find a good third party number type with the right semantics, I would be open to using that and wrapping it with a new type so that we don't depend on it publicly.

ethanpailes commented 4 years ago

Thinking about this as little more, it might make sense to expose a configuration option to allow people to ask pggen to generate a float instead. I'm sure there are cases where people don't really care about 100% correct semantics, and just want to get the number into an easy to work with type quickly.