solnic

solnic

Drops.Relation - High-Level Relation Abstraction on top of Ecto

Hey folks,

I’m back with a new library for y’all :slight_smile: Gonna x-post from my blog:


I’m excited to announce the latest addition to the Elixir Drops suite of libraries: Drops.Relation. This new library provides a high-level API for defining database relations with automatic schema inference and composable queries, simplifying database interactions when developing applications in Elixir.

Drops.Relation is based on 10 years of my work on the Ruby Object Mapper project and brings the most powerful features of ROM to Elixir.

What is Drops.Relation?

Drops.Relation bridges the gap between Ecto and application-level data handling and management. It automatically introspects your database tables, generates Ecto schemas, and provides a convenient query API that feels like working directly with Ecto.Repo while adding powerful composition features.

To put it simply it makes you develop applications faster and simplifies maintanance.

Think of it as a smart wrapper around Ecto that eliminates boilerplate while adding sophisticated query composition capabilities, while preserving your full control over your relations and their schemas.

Getting Started

Add it to your mix.exs:

def deps do
  [
    {:drops_relation, "~> 0.1.0"}
  ]
end

Configure it in your config.exs:

config :my_app, :drops,
  relation: [
    repo: MyApp.Repo
  ]

Then run the installation task:

mix drops.relation.install

This should create aliases for ecto tasks that will ensure that schemas are refreshed whenever you run migrations.

To test it out, just run migrations:

mix ecto.migrate

If things go well, you will see this at the end of the output:

Cache refresh completed

From there, you can start defining your relations with inferred schemas :sparkles:

Automatic Schema Inference

One of Drops.Relation’s standout features is automatic schema inference. Instead of manually defining every field, type, and constraint, you can let the library introspect your database:

defmodule MyApp.Users do
  use Drops.Relation, otp_app: :my_app

  schema("users", infer: true)
end

The library automatically discovers:

  • Column names and types
  • Primary and foreign keys
  • Indexes and constraints
  • Default values and nullability

You can access the generated schema programmatically:

schema = MyApp.Users.schema()
schema[:email]
# %Drops.Relation.Schema.Field{
#   name: :email,
#   type: :string,
#   source: :email,
#   meta: %{
#     default: nil,
#     index: true,
#     type: :string,
#     primary_key: false,
#     foreign_key: false,
#     nullable: false
#   }
# }

Familiar Repository API

Drops.Relation provides all the familiar Ecto.Repo functions you’re used to but makes them more accessible:

# Reading data
user = Users.get(1)
user = Users.get_by(email: "john@example.com")
users = Users.all()
users = Users.all_by(active: true)

# Writing data
{:ok, user} = Users.insert(%{name: "John", email: "john@example.com"})
{:ok, user} = Users.update(user, %{name: "Jane"})
{:ok, user} = Users.delete(user)

# Aggregations
count = Users.count()
avg_age = Users.aggregate(:avg, :age)

Composable Queries

Where Drops.Relation really shines is in query composition. You can chain query operations together to build complex queries:

# Basic composition
active_users = Users
|> Users.restrict(active: true)
|> Users.order(:name)
|> Enum.to_list()

# Complex restrictions with multiple conditions
admins = Users
|> Users.restrict(role: ["admin", "super_admin"])
|> Users.restrict(active: true)
|> Users.order([{:last_login, :desc}, :name])

# Works seamlessly with Enum functions
user_names = Users
|> Users.restrict(active: true)
|> Enum.map(& &1.name)

In the first release Drops.Relation provides 3 high-level query operations:

  • Drops.Relation.restrict - filters data based on conditions
  • Drops.Relation.order - sets ordering
  • Drops.Relation.preload - preloads associations

More operations will be added in future releases.

Custom Queries with defquery

For more complex scenarios, you can define reusable query functions using the defquery macro:

defmodule MyApp.Users do
  use Drops.Relation, otp_app: :my_app

  schema("users", infer: true)

  defquery active() do
    from(u in relation(), where: u.active == true)
  end

  defquery by_role(role) when is_binary(role) do
    from(u in relation(), where: u.role == ^role)
  end

  defquery by_role(roles) when is_list(roles) do
    from(u in relation(), where: u.role in ^roles)
  end

  defquery recent(days \\ 7) do
    cutoff = DateTime.utc_now() |> DateTime.add(-days, :day)
    from(u in relation(), where: u.inserted_at >= ^cutoff)
  end

  defquery with_posts() do
    from(u in relation(),
         join: p in assoc(u, :posts),
         distinct: u.id)
  end
end

These custom queries are fully composable with built-in operations:

# Compose custom queries
recent_admins = Users
|> Users.active()
|> Users.by_role("admin")
|> Users.recent(30)
|> Users.order(:name)
|> Enum.to_list()

# Mix with restrict operations
active_users_with_email = Users
|> Users.active()
|> Users.restrict(email: {:not, nil})
|> Users.order(:email)

Advanced Feature: Boolean Query Logic

For complex query logic involving multiple conditions, Drops.Relation provides a powerful query macro with boolean operations:

import Drops.Relation.Query

# Simple AND operation
adult_active_users = Users
|> query([u], u.active() and u.adult())
|> Enum.to_list()

# Complex nested conditions
complex_query = Users
|> query([u],
    (u.active() and u.adult()) or
    (u.inactive() and u.with_email())
  )
|> Users.order(:name)
|> Enum.to_list()

# Mix built-in and custom operations
filtered_users = Users
|> query([u],
    u.active() and
    u.restrict(role: ["admin", "user"])
  )
|> Enum.to_list()

What’s Next?

Future releases will include:

  • Enhanced association handling
  • Type-safe high-level query handling
  • More composable query operations
  • Integration with other Elixir Drops libraries
  • Generators for Phoenix

Try It!

Drops.Relation is available on Hex.pm and the source code is on GitHub.

The library is currently in its early stages, testing and feedback are welcome!

Give it a try and let me know what you think! I’m always interested in feedback and contributions from the community :purple_heart:


https://github.com/solnic/drops_relation

Where Next?

Popular in Announcing Top

tmbb
PhoenixWS - Websockets over Phoenix Channels Source code on Github here: GitHub - tmbb/phoenix_ws: Websockets implemented over Phoenix Ch...
New
asiniy
Hey there! I wrote a download elixir package which does exactly what its name about - an easy way to download files. I saw solutions ab...
New
gabrielpoca
Hello everyone! I want to share with you something that I’m really proud of: https://stillstatic.io/ Still is a static site builder for...
New
Crowdhailer
I have been updating a library that allows you to pipe between functions that use the erlang result tuple convention. Assuming you have ...
New
brainlid
LangChain is short for Language Chain. An LLM, or Large Language Model, is the “Language” part. This library makes it easier for Elixir a...
New
Flo0807
Hello everyone! I am excited to share our heart project Backpex with you. After building several Phoenix applications, we realized that...
New
achempion
Hi, I would like to tell about my initiative to further maintain and develop Waffle project which is the fork of Arc library. The progre...
New
mplatts
With HEEX released we decided to start a components library using Tailwind CSS - check it out here: Petal Components. We also have a boi...
New
wfgilman
I’ve cleaned up and open sourced three financial libraries I was using for my company. They are bindings for the APIs of these three comp...
New
pkrawat1
Hey guyz We at @aviabird are working on a payment library in elixir/phoenix. We are targeting March 2018 to add 56 Gateways to it. Have...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31142 143
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement