Thanks @wojtekmach.
For me, and possibly others, it helps to see the full example:
def new_merchant_transactions(merchant_id, date) do
sql = """
SELECT * from transactions
WHERE merchant_id = $1
"""
result = Ecto.Adapters.SQL.query!(MyApp.Repo, sql, [merchant_id])
Enum.map(result.rows, &MyApp.Repo.load(Transaction, {result.columns, &1}))
end
should return something like:
[debug] QUERY OK db=1.1ms
SELECT * from transactions
WHERE merchant_id = $1
[1]
[%Transaction{__meta__: #Ecto.Schema.Metadata<:loaded, "transactions">,
amount: %Money{amount: 1300, currency: :USD}, id: 70,
inserted_at: ~N[2018-01-09 16:53:48.964092],
merchant: #Ecto.Association.NotLoaded<association :merchant is not loaded>,
merchant_id: 1, reference_number: nil,
reward: #Ecto.Association.NotLoaded<association :reward is not loaded>,
reward_id: nil, type: "debit", updated_at: ~N[2018-01-09 16:53:48.964099],
user: #Ecto.Association.NotLoaded<association :user is not loaded>,
user_id: 45},
%Transaction{__meta__: #Ecto.Schema.Metadata<:loaded, "transactions">,
amount: %Money{amount: 1000, currency: :USD}, id: 69,
inserted_at: ~N[2017-11-12 22:30:03.972531],
merchant: #Ecto.Association.NotLoaded<association :merchant is not loaded>,
merchant_id: 1, reference_number: nil,
reward: #Ecto.Association.NotLoaded<association :reward is not loaded>,
reward_id: 3, type: "credit", updated_at: ~N[2017-11-12 22:30:03.972537],
user: #Ecto.Association.NotLoaded<association :user is not loaded>,
user_id: 13},
%Transaction{__meta__: #Ecto.Schema.Metadata<:loaded, "transactions">,
amount: %Money{amount: 1624, currency: :USD}, id: 68,
inserted_at: ~N[2017-10-15 01:46:18.689442],
merchant: #Ecto.Association.NotLoaded<association :merchant is not loaded>,
merchant_id: 1, reference_number: nil,
reward: #Ecto.Association.NotLoaded<association :reward is not loaded>,
reward_id: nil, type: "debit", updated_at: ~N[2017-10-15 01:46:18.689449],
user: #Ecto.Association.NotLoaded<association :user is not loaded>,
user_id: 30},
Converting the %Postgrex.Result{
to the right struct.
%Postgrex.Result{columns: ["id", "amount", "type", "user_id", "merchant_id",
"inserted_at", "updated_at", "reward_id", "reference_number"],
command: :select, connection_id: 26202, num_rows: 1,
rows: [[70, 1300, "debit", 45, 1, {{2018, 1, 9}, {16, 53, 48, 964092}},
{{2018, 1, 9}, {16, 53, 48, 964099}}, nil, nil]]}