According to documentation: Ecto.Query – Ecto v2.2.11
It is also possible to select a struct and limit the returned fields at the same time:
from(City, select: [:name])
I have really hard time understanding this. How are those fields limited? I got the feeling the docs are misleading, because I expect, especially looking at SQL generated, this:
iex(10)> from(c in Client, select: [:name]) |> Repo.all
[debug] QUERY OK source="clients" db=5.6ms decode=0.4ms queue=0.3ms
SELECT c0."name" FROM "clients" AS c0 []
Would return this:
[
%Office.Litigation.Schemas.Client{
name: "Dean",
},
%Office.Litigation.Schemas.Client{
name: "John"
}
....
]
But because Structs are Structs and there are some rules, it actually returns this:
[
%Office.Litigation.Schemas.Client{
__meta__: #Ecto.Schema.Metadata<:loaded, "clients">,
address: #Ecto.Association.NotLoaded<association :address is not loaded>,
address_id: nil,
clients_emails: #Ecto.Association.NotLoaded<association :clients_emails is not loaded>,
clients_phones: #Ecto.Association.NotLoaded<association :clients_phones is not loaded>,
company: nil,
defendant_cases: #Ecto.Association.NotLoaded<association :defendant_cases is not loaded>,
emails: #Ecto.Association.NotLoaded<association :emails is not loaded>,
id: nil,
inserted_at: nil,
krs: nil,
name: "Dean",
nip: nil,
phones: #Ecto.Association.NotLoaded<association :phones is not loaded>,
plaintiff_cases: #Ecto.Association.NotLoaded<association :plaintiff_cases is not loaded>,
surname: nil,
updated_at: nil
},
%Office.Litigation.Schemas.Client{
__meta__: #Ecto.Schema.Metadata<:loaded, "clients">,
address: #Ecto.Association.NotLoaded<association :address is not loaded>,
address_id: nil,
clients_emails: #Ecto.Association.NotLoaded<association :clients_emails is not loaded>,
clients_phones: #Ecto.Association.NotLoaded<association :clients_phones is not loaded>,
company: nil,
defendant_cases: #Ecto.Association.NotLoaded<association :defendant_cases is not loaded>,
emails: #Ecto.Association.NotLoaded<association :emails is not loaded>,
id: nil,
inserted_at: nil,
krs: nil,
name: "Alycia",
nip: nil,
phones: #Ecto.Association.NotLoaded<association :phones is not loaded>,
plaintiff_cases: #Ecto.Association.NotLoaded<association :plaintiff_cases is not loaded>,
surname: nil,
updated_at: nil
}
...
]
It took me quite a lot of time trying to debug, and until I realized why what I expected is impossible to achieve i simply did Client |> select([client], %{name: client.name}) |> Repo.all()
And now, is it me who has hard time grasping what’s in the documentation? Should documentation be maybe improved somehow? Or am I totally missing something?