A Swiss Army knife for your Ecto schemas
SwissSchema is a query toolkit for Ecto schemas. It makes it easy to manipulate data using Ecto schemas by implementing relevant Ecto.Repo Query API and Schema API functions, pre-configured to work specifically with the given Ecto schema.
Add swiss_schema
as a dependency in mix.exs
:
def deps do
[
# ...
{:swiss_schema, "~> 0.6"}
]
end
Then, use SwissSchema
in your Ecto schemas:
# lib/my_app/accounts/user.ex
defmodule MyApp.Accounts.User do
use Ecto.Schema
use SwissSchema, repo: MyApp.Repo
def changeset(%User{} = user, params) do
# here you set up your schema's changeset as usual
end
end
That's it, you should be good to go.
When you use SwissSchema
, a collection of pre-configured functions will be added to your Ecto schema module. The functions are equivalent to two important Ecto.Repo APIs: the Query API and the Schema API.
iex> User.get(1)
{:ok, %User{id: 1, ...}}
iex> User.get_by(email: "john@smiths.net")
{:ok, %User{id: 2, email: "john@smiths.net", ...}}
The motivation to have such API directly in your Ecto schema is to make function calls more idiomatic.
Check the docs for a complete list of available functions.
See CONTRIBUTING.md.
See: FAQ.md.
It seems that I'm not the only person in the world trying to improve this immediate Ecto's querying DX. Recently, I found some other projects similar to SwissSchema that creates some sort of querying tools out of Ecto schemas:
- Bee by Helder de Sousa 🇧🇷
- Ecto.Entity by Kamaro Lambert 🇰🇪
- EctoQuerify by Marko Bogdanović 🇷🇸
© 2023 Joel Jucá. Licensed under Apache License 2.0