Ecto: Microseconds not being discarded

Created on 22 Oct 2018  路  6Comments  路  Source: elixir-ecto/ecto

Environment

  • Elixir version (elixir -v): 1.7
  • Database and version (PostgreSQL 9.4, MongoDB 3.2, etc.): PostgreSQL 10
  • Ecto version (mix deps): 3.0-rc.1
  • Database adapter and version (mix deps): Postgrex 2.0-rc
  • Operating system: Mac OS X

Current behavior

Trying out ecto 3 and running my test suite I get hundreds of those errors:

** (Ecto.ChangeError) value `#DateTime<2018-10-21 23:32:31.464747Z>` for `Connect.Authentication.User.reset_sent_at`in `update` does not match type :utc_datetime

     Microseconds must be empty. Use `DateTime.truncate(utc_datetime, :second)` (available in Elixir v1.6+) to remove microseconds.

Expected behavior

Microseconds just being discarded without manual intervention.

Most helpful comment

I can see the reasoning behind the decision to have it that way, but as I said above it might be good to make people aware of that. At least in my application there where quite a bunch of the following functions, which were raising errors for a reason I though I wouldn't have to deal with.

def mark_published(struct), do: change(struct, %{published: DateTime.utc_now()})

All 6 comments

As mentioned here this seems to be expected behavior. If so I'd suggest making the changelog more clear about it. Currently it says:

To uniformly support microseconds across all databases, the types :time, :naive_datetime, :utc_datetime will now discard any microseconds information.

This seems to be true for casting datetimes, but not when directly changing datetimes in the system without going through a casting process.

@LostKobrakai they are discarded if you use changeset (in cast/2), once you use something like Ecto.Changeset.change/2 or put_change/3 then Ecto assumes you work with an internal data structure and then it's up to you to discard microseconds.

I can see the reasoning behind the decision to have it that way, but as I said above it might be good to make people aware of that. At least in my application there where quite a bunch of the following functions, which were raising errors for a reason I though I wouldn't have to deal with.

def mark_published(struct), do: change(struct, %{published: DateTime.utc_now()})

I think if you submit a PR to the changelog Core Team would be happy to merge it :).

I've added a PR #2765 for changing the changelog here, but there are a few other places as well like the plataformatec blogposts, which would be nice if updated.

As the error message says, this is by design. You either have to truncate

it or move to usec.

Jos茅 Valim
www.plataformatec.com.br
Skype: jv.ptec
Founder and Director of R&D

Was this page helpful?
0 / 5 - 0 ratings

Related issues

stavro picture stavro  路  4Comments

kelostrada picture kelostrada  路  3Comments

alaadahmed picture alaadahmed  路  4Comments

ericmj picture ericmj  路  3Comments

atsheehan picture atsheehan  路  4Comments