Composite - a library for writing dynamic queries

Hey
I want to introduce you a small utility that may help in writing dynamic queries :slight_smile:

In a few words, this code:

blank_string? = fn string -> String.trim(string) == "" end
query = some_complex_query()

query =
  if not is_binary(params[:some_field1]) or blank_string?.(params[:some_field1]) do
    query
  else
    query |> where(some_field1: ^params[:some_field1])
  end

query =
  if is_nil(params[:some_field2]) do
    query
  else
    query |> where(some_field2: ^params[:some_field2])
  end

query |> Repo.all()

can be reorganzied to this:

blank_string? = fn string -> String.trim(string) == "" end

some_complex_query()
|> Composite.new(params)
|> Composite.param(:somefield1, &where(&1, some_field1: ^&2),
  ignore?: &(not is_binary(&1) or blank_string?.(&1))
)
|> Composite.param(:some_field2, &where(&1, some_field2: ^&2))
|> Repo.all()

However, library can be used not only with Ecto.
For more complex example with joins check test file.

Currently, it is not published to hex and available only on Github

Any feedback is welcome! :slight_smile:

Aren’t Changesets used for parameter validations?

For validation - yes, but this library is about optional application.

1 Like

One and a half years have passed, the library has version 0.4 and has better docs with examples.
Check it out here composite v0.4.0 β€” Documentation

Published an article about the library