SeaQL / sea-orm

🐚 An async & dynamic ORM for Rust
https://www.sea-ql.org/SeaORM/
Apache License 2.0
7.3k stars 513 forks source link

Cast unsigned integers to PostgreSQL compatible types #1082

Closed laralove143 closed 2 years ago

laralove143 commented 2 years ago

Motivation

Right now if we want to insert an unsigned integer to our Postgres database we have to add an as i8/16/32/64, and when fetching it we have to do as u8/16/32/64

When working with a lot of unsigned integers this can be lots of boilerplate

Proposed Solutions

Although integer casting is usually dangerous, doing uN as iN to insert and iN as uN to fetch is entirely lossless, see the test here

Additional Information

frederikhors commented 2 years ago

Does https://github.com/SeaQL/sea-orm/issues/1068 help this, what do you think @laralove143?

laralove143 commented 2 years ago

I don't think this is possible without some sort of casting for u64, for other integers it'd be possible to include it in a bigger integer at the cost of wasted space (i64::from(1_u32))

But since Postgres actually doesn't support unsigned integers I think it may be a bit misleading to allow methods made for unsigned integer SQL data types

billy1624 commented 2 years ago

But since Postgres actually doesn't support unsigned integers I think it may be a bit misleading to allow methods made for unsigned integer SQL data types

Hey @laralove143, same thing applied to integer casting. If we cast the integer internally some unexpected behavior might occur.

laralove143 commented 2 years ago

What unexpected behavior, as long as you always cast back and forth you'll get the same integer

If you really want to put it in a complete test, you can run this but it'll take like hours, if not days, to complete...

tyt2y3 commented 2 years ago

uN as iN to insert and iN as uN

That's a really neat idea, however it only makes sense if you disregard the data inside the DB . Say, you ran a SUM function on the column, the outcome would be completely wrong.

In this case I suggest you to use a wrapper type. Let me know if SeaORM can make wrapper types more accessible.

laralove143 commented 2 years ago

That is correct, but if users do it manually instead of SeaORM, they're much more likely to cause UB, since it's an ORM couldn't it ensure it stays correct by disallowing users from calling such functions (or cast correctly for you when possible, for example for WHERE = or < or >)

tyt2y3 commented 2 years ago

I don't think it's something we will support in SeaORM. You can also use bytea may be. Please open another issue if SeaORM can make wrapper types more accessible.