Syntax error in query

I have this query I wrote for testing the library.

   expect = from j in Test.JoinModel, join: e in assoc(j, :example),
   preload: [example:  from w in Test.WhereModel,  limit: ^3 , offset: ^0]

It throws this error while compiling:

         unexpected comma. Parentheses are required to solve ambiguity inside containers

Any help will be appreciated.
Thanks

You need to add parentheses to resolve ambiguity. I tend to add them around the whole from, like so:

   expect = from(
      j in Test.JoinModel,
      join: e in assoc(j, :example),
      preload: [example:  from(w in Test.WhereModel,  limit: ^3 , offset: ^0)]
   )

Strictly speaking only the parentheses around the inner from are required, because without them Elixir doesn’t know if you are adding more options for the from or the preload.

1 Like

Thanks for you reply .It still throws an error. This time this one:

    from(w in Test.WhereModel, limit: 3, offset: 0)` is not a valid preload expression. preload expects an atom,a list of atoms or a keyword list with more preloads as values. Use ^ on the outermost preload to interpolate a value

I’m not that well versed with assocs and preloads so hope someone else can respond about that.

Hi, if you are playing with ecto, try better schema names, it truly helps.

You don’t need ^ for numbers, only for named variables like ^limit or ^offset.

If you want to preload an association with a join you should:

from(user in User,
     join: posts in assoc(user, :posts),
     preload: [posts: posts],
     limit: 3,
     offset: 0)

And if you want to do with a query (this performs two queries in the database):

post_query = from(post in Post, limit: 3, offset: 0)
from(user in User,
     preload: [posts: ^post_query],
     limit: 3,
     offset: 0)

However, take a look at the ecto documentation:

Note: keep in mind operations like limit and offset in the preload query will affect the whole result set and not each association. For example, the query below:

comments_query = from c in Comment, order_by: c.popularity, limit: 5
Repo.all from p in Post, preload: [comments: ^comments_query]

won’t bring the top of comments per post. Rather, it will only bring the 5 top comments across all posts.

1 Like

Thanks for your feedback.

1 Like