How do i produce an elixir struct from erlang

The API for query creation is exactly what we have today. You are thinking about using the internals but it is not necessary to fiddle with them all. Our query api supports both interpolation and dynamic values. For example, imagine you have to parse “foo:43” and convert it to a query. You can do this:

query = "table" # or Schema
[field, value] = String.split("foo:43", ":")
field = String.to_existing_atom(field)
query = from q in querry, field(q, ^field) == ^value

And so on. Ben mentioned the correct way to solve this in the forum here: How to produce executable code using yecc? - In a nutshell, you shouldn’t build the query inside the parser because the parser goal is to return an AST. Then, in Elixir code, you traverse the AST, building the Ecto query.

For example, for “foo:43”, your parser should return something like:

{:where, :foo, "43"}

Then you can traverse this AST and convert it into an Ecto query.

As a good exercise, I would suggest for you to implement a calculator using yecc. Do not have yecc perform the computations. Instead you should have yecc return an AST (so 1 + 2 returns {:+, 1, 2}) and then you traverse this AST in Elixir computing the final result.

4 Likes