Flexible and dynamic Ecto query builder for Elixir applications, allowing developers to retrieve data flexibly without writing custom queries for each use case.
Add bind
to your list of dependencies in mix.exs
:
def deps do
[
{:bind, "~> 0.1.1"}
]
end
Bind.query(schema, params)
Parameters:
schema
: The Ecto schema module (e.g.,MyApp.User
).params
: Either a map of query parameters or a query string.
Returns: An Ecto query.
Create Ecto query:
query = Bind.query(MyApp.User, %{ "name[eq]" => "Alice", "age[gte]" => 30 })
Alternatively, with a query string:
query = Bind.query(MyApp.User, "?name[eq]=Alice&age[gte]=30")
And finally run the query to get results from the database:
results = Repo.all(query)
Error handling
case Bind.query(MyApp.User, %{ "name[eq]" => "Alice", "age[gte]" => 30 }) do
{:error, reason} ->
IO.puts("Error building query: #{reason}")
query ->
results = Repo.all(query)
end
Examples:
%{"name[eq]" => "Alice", "age[gte]" => 30}
%{
"name[starts_with]" => "A",
"age[gte]" => 18,
"role[in]" => "superuser,admin,mod",
"is_active[true]" => "",
"last_login[nil]" => false
}
List of comparison operators supported:
eq
: Equal toneq
: Not equal togt
: Greater thangte
: Greater than or equal tolt
: Less thanlte
: Less than or equal totrue
: Boolean truefalse
: Boolean falsestarts_with
: String starts withends_with
: String ends within
: In a list of valuescontains
: String containsnil
: Is nil (or is not nil)
Use the sort
parameter to specify sorting order:
- Prefix with
-
for descending order - No prefix for ascending order
%{"sort" => "-age"} # Sort by age descending
%{"sort" => "age"} # Sort by age ascending
If nothing specified, sorts by ID field ascending.
limit
: Specify the maximum number of results (default: 10)start
: Specify the starting ID for pagination
Example:
%{"limit" => 20, "start" => 100}
Bind can also pass URL query strings:
query_string = "?name[eq]=Alice&age[gte]=30&sort=-age&limit=10"
query = Bind.query(MyApp.User, query_string)
When using with Phoenix, use raw query string instead of params and decode it first; URI.decode_query(conn.query_string)
.
Example controller method:
def index(conn, params) do
query = Bind.query(Waitlist, URI.decode_query(conn.query_string))
requests = Mitte.Repo.all(query)
render(conn, :index, requests: requests)
end