Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

foldl-like function that returns a struct #71

Open
macabeus opened this issue Feb 8, 2018 · 1 comment
Open

foldl-like function that returns a struct #71

macabeus opened this issue Feb 8, 2018 · 1 comment

Comments

@macabeus
Copy link
Contributor

macabeus commented Feb 8, 2018

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, "[email protected]", "1", 100000, true}, {Database.Account, 2, "[email protected]", "2", 100000, true}].

A possible better return is [%Database.Account{account_number: "1", amount: 100000, email: "[email protected]", id: 1}, %Database.Account{account_number: "2", amount: 100000, email: "[email protected]", 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.

@meh
Copy link
Owner

meh commented Feb 9, 2018

The problem is that foldl and such is supposed to allow you to play with the schema as well, for instance if you want to change a table up you'll need to do this.

Now this is undocumented, and it probably shouldn't be, but you can use Database.Account.coerce/1 to turn a tuple into a struct, and a struct into a tuple.

Keep in mind that foldl and friends are thin wrappers around mnesia functions, so you always need to coerce back and forth.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants