edgedb / edgedb-rust

The official Rust binding for EdgeDB
https://edgedb.com
Apache License 2.0
208 stars 26 forks source link

to_unix_micros fix + test #273

Closed Dhghomon closed 11 months ago

Dhghomon commented 11 months ago

This is a fix for issue #267 where the .to_unix_micros() method returns an unexpected negative number.

Some context:

When a Datetime is created using .from_unix_micros(), it calls a method called _from_micros that takes the number of micros and adds it to a negative number:

micros.checked_add(Self::UNIX_EPOCH.micros)?;

This UNIX_EPOCH is defined as -946684800000000, which is the number of negative microseconds to get from 2000 to 1970 (Postgres epoch to Unix epoch). The Datetime struct then holds this number as its micros parameter. So if a Datetime is constructed using .from_unix_micros(0), it should have -946684800000000 micros.

But when .to_unix_micros() is called, it returns the number of micros plus this negative number:

self.micros + Datetime::UNIX_EPOCH.micros

So the solution is simply to change to

self.micros - Datetime::UNIX_EPOCH, bringing it back to zero.

I think. Was confused for a while as there is a typo (I assume) in a comment in the same file stating that the Postgres epoch is 2020, have changed that to 2000. I've added a test to assert that the round trip works and that the unix seconds and postgres seconds are what they are expected to be.