Skip to content

foldl-like function that returns a struct #71

@macabeus

Description

@macabeus

As far as I understand, if we want to run a function on each record on table (to filter, or map...), we could use the foldl/3 function.

But, it's hard to use, because the value passed to function isn't a struct, for example, if we have

defdatabase Database do
  deftable Account, [{:id, autoincrement}, :email, :account_number :amount],
  ...

and use

Amnesia.transaction do
  Database.Account.foldl([], &([&1 | &2]))
end

The return is something like [{Database.Account, 1, "account_a@gmail.com", "1", 100000, true}, {Database.Account, 2, "account_bb@gmail.com", "2", 100000, true}].

A possible better return is [%Database.Account{account_number: "1", amount: 100000, email: "account_a@gmail.com", id: 1}, %Database.Account{account_number: "2", amount: 100000, email: "account_bb@gmail.com", id: 2}].

Currently, I'm using a workaround to return an array of structs:

Amnesia.transaction do
  Database.Account.keys
  |> Enum.map(&Database.Account.read!/1)
end

But, maybe exists a better solution, and I think that it's useful to add on Amnesia.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions