Types and schemaless queries

is there a way to use a ecto type to “load” a certain field when using schemaless queries?

Ecto.Query.from(o in "orders", select: o.inserted_at) |> MyApp.Repo.all

This returns a list of datetime tuples, [{2017, 10, 02}, {10, 11, 32}]. I can manually map the result to DateTime afterwards, but I’m wondering if there is some magic that I can put in :select that I’m missing? Like type(o, MyEctoType) but on the way out of the database.

1 Like

From Ecto 2.2 you can do this:

Ecto.Query.from(o in "orders", select: type(o.inserted_at, :naive_datetime)) |> MyApp.Repo.all

Excellent! That was exactly what I was looking for! Who would have guessed this info was hiding in the manual all the time :open_mouth:
Thanks a lot!

Can this be done dinamically like so:?

field_list = [type(o.inserted_at, :naive_datetime), type(o.updated_at, :naive_datetime)]
Ecto.Query.from(o in "orders", select: field_list) |> MyApp.Repo.all

Any of these depending on what you want it to return:



Or literals.

Yes but I want them to have the type(o. inside them, I don’t think that will work. But I was just wondering that maybe there is a solution.

You can have a type in them as long as the type call is within the macro call.

1 Like