mathieuprog
QueryBuilder - Compose Ecto queries without effort
I’ll start right with an example ![]()
User
|> QueryBuilder.where(firstname: "John", city: "Anytown")
|> QueryBuilder.where({:age, :gt, 30})
|> QueryBuilder.order_by(lastname: :asc)
|> QueryBuilder.preload([:role, authored_articles: :comments])
|> Repo.all()
With associations:
User
|> QueryBuilder.where([role: :permissions], name@permissions: "delete")
|> Repo.all()
Query Builder allows to build and compose Ecto queries based on data.
Concise, no need to deal with bindings and macros.
Its primary goal is to allow Context functions to receive a set of filters and options:
# in a Controller
Blog.list_articles(preload: [:comments], order_by: [title: :asc])
Blog.list_articles(preload: [:category, comments: :user])
This avoids having to create many different functions in the Context for every combination of filters and options, or to create one general function that does too much to satisfy all the consumers.
The calling code (e.g. the Controllers), can now retrieve the list of articles with different options. In some part of the application, the category is needed; in other parts it is not; sometimes the articles must be sorted based on their title; other times it doesn’t matter, etc.
The options may be added to the query as shown below:
# in the Blog context
def get_article_by_id(id, opts \\ []) do
QueryBuilder.where(Article, id: id)
|> QueryBuilder.from_list(opts)
|> Repo.one!()
end
Inspired by the libraries token_operator and ecto_filter.
More examples are available in the doc:
Trending in Announcing
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #performance
- #security










First 10 of 21 Posts!
wolfiton
Hi,
Did you checked your library with a security package for elixir for sql injections or other problems?
Also is it compatible with absinthe and absinthe_ecto?
Thanks in advance
mathieuprog
The library makes use of
Ecto.Queryto build queries, so it comes with the same security features asEcto. SQL injection is impossible;Ectoalways uses parameterized queries which prevent SQL injection attacks.I still have to gain more knowledge about Absinthe, which I plan to delve into in the coming months. So I can’t comment about that now sorry:) But I will look into that, thank you for the idea.
wolfiton
Thanks for the replay.
Also if you have time:
Does your library make the queries less costly or it just replaces Ecto queries?
mathieuprog
It only does a small optimization for you when you want to preload data.
Imagine a User has one Role and many Articles.
If you want to preload the user with its associated role and articles, it’s better to join user and role table (as it is a one-to-one association); but it is better to execute a separate query for loading the articles (the cost of executing a separate SQL query to the DB for loading a one-to-many association is lower than Ecto’s processing if all the rows are in the result of one single query).
If you execute the following:
It will generate something like:
As you can see above, the library has joined user and role as it is a one-to-one association, but didn’t join articles with user (as long as there are no where clauses on articles, in which case there will be of course a join).
That’s the only optimization regarding queries it does for you. But you could write those queries directly with Ecto.Query’s API of course. The purpose of the library is really to work with data instead of macros, which allows you to
QueryBuilder;There’s still a lot of work to be done, and the library will be updated progressively according to my needs or other library users’ need. Currently supported are basic
whereclauses:QueryBuilder.where(User, age: 30)( == )same as:
QueryBuilder.where(User, {:age , :eq, 30})QueryBuilder.where(User, {:age, :ne, 30})( != )QueryBuilder.where(User, {:age, :gt, 30})( > )QueryBuilder.where(User, {:age, :ge, 30})( >= )QueryBuilder.where(User, {:age, :lt, 30})( < )QueryBuilder.where(User, {:age, :le, 30})( <= )You can pass a list with multiple filters:
QueryBuilder.where(User, name: "Bob", age: 30)With associations:
QueryBuilder.where(User, :role, name@role: "author")QueryBuilder.where(User, [role: :permissions], name@permissions: "write")Order by:
QueryBuilder.order_by(User, age: :desc)QueryBuilder.order_by(User, :articles, title@articles: :asc)The functions above will make the necessary joins automatically, but sometimes you need to left join:
QueryBuilder.join(User, :articles, :left)And of course, preload:
QueryBuilder.preload(User, :articles, role: :permissions)wolfiton
Thank you for providing examples and explanations of your libraries features.
The way you design it it looks very refreshing form the traditional Ecto queries and it looks a lot more human friendly and short.
Also i think will help other team members to understand easily the code base.
I will give it a try and come back with the results in a couple of days.
Thanks for sharing it.
mathieuprog
Here are some new convenient features in
QueryBuilder:Grouped OR expressions:
maybe_where/3for easier piping:dalerka
Hey, thanks for sharing your work!
How about supporting aggregate functions, like
count? i.e. How to do it with QueryBuilder without making extra DB calls?Also, do you plan to add support for pagination-related queries?
I really like how Flop library simplifies some things returning the
metainfo, but unfortunately it lacks some features that QueryBuilder or ExSieve have, eg. forcontainsoperations.mathieuprog
I add features according to my needs or others’ demands. For example, someone asked support for
IN, so I added:in,:not_in,:include,:excludeoperations.Latest update with support for grouped OR expressions and
maybe_wherewere added for my own project’s need.I have personally no experience yet with pagination in Ecto, so I will have to wait that I encounter the need of such operations in my project.
Thank you for bringing that up:)
onomated
First off, thanks for an awesome library.
Any guidance on how to support fragments in where queries? So I’m implementing text search, and needs some logic similar to this:
Notice the fragment needs to access columns bound to the queryable object.
I’m extending QueryBuilder with my own app module to add the search function, which should just work with
from_list. Something like:Is there a way to support custom sql fragments? Or looks like one approach would be to break down the
QueryBuilder.Querydown toecto_query? Any guidance on extending would be appreciated!mathieuprog
Here is an example of how to extend the query with Ecto when using QueryBuilder:
How does it work?
where/2. That function will be called by QueryBuilder and the library will pass a function that allows you to get the right binding for a field.dynamicexpression and you add fields with their bindings (by calling the function that the library provides you with):I noticed that this works for
wherebut not fororder_byyet, becausedynamichasn’t been used fororder_by. However I guess it will be easy to add.By the way, it would be nice to add your module in the doc for demonstrating how to extend QueryBuilder. Would you be able to past a working code of the module once you’re done (and a sample calling code)?
Last Post!
mathieuprog
QueryBuilder v1.0.0 has been released!
New features:
Extensionmodule allowing to easily extend QueryBuilder with user’s own functions:<field_name>@selfvs:<atom_value>Thanks to @onomated that did all of the work, of high quality!
Because QueryBuilder is considered stable and there have been breaking changes, it has been bumped to 1.0.
Breaking changes:
.1.
QueryBuilder.order_by(User, lastname: :asc)becomesQueryBuilder.order_by(User, asc: :lastname).2.
QueryBuilder.where(User, {:name, :eq, :nickname})becomesQueryBuilder.where(User, {:name, :eq, :nickname@self})(concerns a comparison of two fields of the root schema)