Custom fields with naive_datetime type report difference in microseconds on tests

ecto

#1

Hi everyone,

I added two custom fields with naive_datetime type to one of my schemas and even though everything seems right (inserting, loading data), when i run tests against it, it gives an error comparing values on microseconds (0 != 6).

An example of the difference:
lhs: %NaiveDateTime{calendar: Calendar.ISO, day: 10, hour: 0, minute: 0, month: 11, second: 0, year: 2018, microsecond: {0, 6}}
rhs: %NaiveDateTime{calendar: Calendar.ISO, day: 10, hour: 0, minute: 0, month: 11, second: 0, year: 2018, microsecond: {0, 0}}

I saw someone mentioning to add @timestamps_opts [usec: false] before your schema settings but that only applies to the timestamps fields AFAIK.

Am i missing something simple here ?

Note: I’m using Phoenix 1.3, Ecto 2.2, PostgreSQL as DB and creating simple fixtures functions on the tests.

Thank you


Strange error comparing NaiveDatetime in ecto
#2

IIRC (and I may not) Ecto will set the microsecond precision to 6 because thats what Postgres will return whereas the default NaiveDateTime will set the precision to 0.

If you use NaiveDateTime.compare/2 I think you’ll find they’ll be :eq meaning equal.


#3

In Ecto master we will have naive_datetime and naive_datetime_usec, exactly to solve issues like this. Elixir v1.6 will also include a NaiveDateTime.truncate function, which makes it easier to set a given precision.


#4

Thank you for feedback Kip, i used compare, but i was having issues in matching operations on my tests, at the point where i felt, there should be a better way to handle this :wink:

That’s great news José, thank you for the great work put on those projects, and the feedback of course :smile:


#5

This might be related.

I noticed an oddity in the timestamps during insertion versus lookup:

My tests were failing in serialization of the naive_datetime. After I used the value from db lookup, tests ran fine.

> res = Repo.insert!(%Model{})
> res.inserted_at
~N[2018-01-10 13:25:52.122046]
> res_load = Repo.get!(res.id)
~N[2018-01-10 13:25:52.122000]

Not clear how it is possible for the actual insertion time to be later than reported by insert.

Stack: mongodb 3.4 / Ecto 2.1


#6

It is possible that Mongo only has milliseconds precision and truncated the value.


#7

Yes, unfortunately there is an issue at the moment with how the mongo ecto adapter handles the precision. It is something that is on my todo list.