acalejos

acalejos

Flint - Drop-In Utilities / Enhancement for Ecto Schemas

Hey all,

I originally made this for my project Merquery and decided to extract it to its own library. The README is below if you’re interested. It’s still very early in development, but I felt that it was far enough along to be worth sharing.

There are many reasons I made this instead of using any of the many existing libraries out there, but the main reasons were:

  • I wanted to take advatage of Ecto.Type, which lets you define how types are both cast and dumped, meaning you can have separate representations of the data between client and server, and the type servers as the adapter.
  • I wanted the API to look like Ecto so that it can look better coexisting with Ecto code, be converted to/from Flint ↔ Ecto fairly easily, and take advantage of all of Ecto’s APIs

All schemas defined using Flint are stlil Ecto schemas under the hood, and I’ve attempted to make the API as idiomatic to Ecto as I could (e.g. even though validation are colocated inline with the schema, they’re still enforced on the call to changeset, new reflection functions are added using the __schema__(:atom) API, etc.)

Repo:


README

Flint

Practical Ecto embedded_schemas for data validation, coercion, and manipulation.

Features

  • ! Variants of Ecto field, embeds_one, and embeds_many macros to mark a field as required (see. Required Fields)
  • Colocated validations, so you can define common validations alongside field declarations (see Validations)
  • Adds Access implementation to all schemas
  • Adds Jason.Encoder implementation to all schemas
  • New Ecto.Schema Reflection Functions
    • __schema__(:required) - Returns list of fields marked as required (from ! macros)
    • __schema__(:validations) - Keyword mapping of fields to validations
  • Convenient generated function (changeset,new,new!,…) (see. Generated Functions)
  • Configurable Application-wide defaults for Ecto.Schema API (see. Config)

Installation

def deps do
  [
    {:flint, github: "acalejos/flint"}
  ]
end

Motivation

Flint is built on top of Ecto and is meant to provide good defaults for using embedded_schemas for use outside of a database.
It also adds a bevy of convenient features to the existing Ecto API to make writing schemas and validations much quicker.

Of course, since you’re using Ecto, you can use this for use as an ORM, but this is emphasizing the use of embedded_schemas as just more expressive and powerful maps while keeping compatibility with Ecto.Changeset, Ecto.Type, and all of the other benefits Ecto has to offer.

In particular, Flint focuses on making it more ergonomic to use embedded_schemas as a superset of Maps, so a Flint.Schema by default implements the Access behaviour and implements the Jason.Encoder protocol.

Flint also was made to leverage the distinction Ecto makes between the embedded representation of the schema and the dumped representation. This means that you can dictate how you want the Elixir-side representation to look, and then provide transformations
for how it should be dumped, which helps when you want the serialized representation to look different.

This is useful if you want to make changes in the server-side code without needing to change the client-side (or vice-versa). Or perhaps you want a mapped representation, where instead of an Ecto.Enum just converting its atom key to a string when dumped, it gets mapped to an integer, etc.

Usage

If you want to declare a schema with Flint, just use Flint within your module, and now you have access to Flint’s implementation of the
embedded_schema/1 macro. You can declare an embedded_schema within your module as you otherwise would with Ecto. Within the embedded_schema/1 block, you also have access to Flints implementations of embeds_one,embeds_one!,embeds_many, embeds_many!, field, and field!.

You can also use the shorthand notation, where you pass in your schema definition as an argument to the use/2 macro. Flint.__using__/1 also
accepts the following options which will be passed as module attributes to the Ecto embedded_schema. Refer to the Ecto.Schema docs for more about these options.

  • primary_key (default false)
  • schema_prefix (default nil)
  • schema_context (default nil)
  • timestamp_opts (default [type: :naive_datetime])

So these two are equivalent:

defmodule User do
  use Flint

  embedded_schema do
    field! :username, :string
    field! :password, :string, redacted: true
    field :nickname, :string
  end
end

is equivalent to:

defmodule User do
  use Flint, schema: [
    field!(:username, :string)
    field!(:password, :string, redacted: true)
    field(:nickname, :string)
  ]
end

If you’re starting with Flint and you know you will stick with it, the shorthand might make more sense. But if you want to be able to quickly
change between use Ecto.Schem and use Flint, or you’re converting some existing Ecto embedded_schemas to Flint, the latter might be
preferable.

Since a call to Flint’s embedded_schema or use Flint, schema: [] just creates an Ecto embedded_schema you can use them just as you would any other Ecto schemas. You can compose them, apply changesets to them, etc.

Required Fields

Flint adds the convenience bang (!) macros (embed_one!,embed_many!, field!) for field declarations within your struct to declare a field as required within its changeset function.

Flint schemas also have a new reflection function in addition to the normal Ecto reflection functions.

  • __schema__(:required) – Returns a list of all fields that were marked as required.

Field Validations

Basic Validations

Flint allows you to colocate schema definitions and validations.

defmodule Person do
  use Flint

  embedded_schema do
    field! :first_name, :string,  max: 10, min: 5
    field! :last_name, :string, min: 5, max: 10
    field :favorite_colors, {:array, :string}, subset_of: ["red", "blue", "green"]
    field! :age, :integer, greater_than: 0, less_than: 100
  end
end

Parameterized Validations

You can even parameterize the options passed to the validations:

defmodule Person do
  use Flint

  embedded_schema do
    field! :first_name, :string,  max: 10, min: 5
    field! :last_name, :string, min: 5, max: 10
    field :favorite_colors, {:array, :string}, subset_of: ["red", "blue", "green"]
    field! :age, :integer, greater_than: 0, less_than: max_age
  end
end

If you do this, make sure to pass the options as a keyword list into the call to changeset:

Person.changeset(
  %Person{},
  %{first_name: "Bob", last_name: "Smith", favorite_colors: ["red", "blue", "pink"], age: 101},
  [max_age: 100]
)
#Ecto.Changeset<
  action: nil,
  changes: %{
    age: 101,
    first_name: "Bob",
    last_name: "Smith",
    favorite_colors: ["red", "blue", "pink"]
  },
  errors: [
    first_name: {"should be at least %{count} character(s)",
     [count: 5, validation: :length, kind: :min, type: :string]},
    favorite_colors: {"has an invalid entry", [validation: :subset, enum: ["red", "blue", "green"]]},
    age: {"must be less than %{number}", [validation: :number, kind: :less_than, number: 100]}
  ],
  data: #Person<>,
  valid?: false,
  ...
>

This lets you change the parameters of the validations for each call to changeset for more flexibility

Options

Currently, the options / validations supported out of the box with Flint are all based on validation functions
defined in Ecto.Changeset:

Aliases

If you don’t like the name of an option, you can provide a compile-time list of aliases to map new option names to existing options.

In your config, add an :aliases key with a Keyword value, where each key is the new alias, and the value is an existing option name.

For example, these are default aliases implemented in Flint:

config Flint, aliases: [
    lt: :less_than,
    gt: :greater_than,
    le: :less_than_or_equal_to,
    ge: :greater_than_or_equal_to,
    eq: :equal_to,
    neq: :not_equal_to
  ]

NOTE If you add your own aliases and want to keep these above defaults, you will have to add them manually to your aliases.

__schema__(:validations)

Since validations are enforced through the generated changeset functions, if you override this function you will not get the benefits
of the validations.

If you want to implement your own, you can use __schema__(:validations) which is an added reflection function that stores validations.

NOTE These are stored as their quoted representation to support passing bindings, so make sure to account for this if implementing yourself.

If you want to override changeset but want to keep the default validation behavior, there is also the Flint.Schema.validate_fields function,
which accepts an %Ecto.Changetset{} and optionally bindings, and performs validations using the information stored in __schema__(:validations).

Generated Functions

Flint provides default implementations for the following functions for any schema declaration. Each of these is overridable.

  • changeset - Creates a changeset by casting all fields and validating all that were marked as required. If a :default key is provided for a field, then any use of a bang (!) declaration will essentially be ignored since the cast will fall back to the default before any valdiations are performed.
  • new - Creates a new changeset from the empty module struct and applies the changes (regardless of whether the changeset was valid).
  • new! - Same as new, except raises if the changeset is not valid.

Config

You can configure the default options set by Flint.

  • embeds_one: The default arguments when using embeds_one. Defaults to [defaults_to_struct: true, on_replace: :delete]
  • embeds_one!: The default arguments when using embeds_one!. Defaults to [on_replace: :delete]
  • embeds_many: The default arguments when using embeds_many or embeds_many!. Defaults to [on_replace: :delete]
  • embeds_many!: The default arguments when using embeds_many!. Defaults to [on_replace: :delete]
  • :enum: The default arguments for an Ecto.Enum field. Defaults to [embed_as: :dumped].
  • :aliases: See Aliases

You can also configure any aliases you want to use for schema validations.

Embedded vs Dumped Representations

Flint takes advantage of the distinction Ecto makes between an embedded_schema’s embedded and dumped representations.

For example, by default in Flint, Ecto.Enums that are Keyword (rather than just lists of atoms) will have their keys
be the embedded representation, and will have the values be the dumped representation.

defmodule Book do
  use Flint, schema: [
    field(:genre, Ecto.Enum, values: [biography: 0, science_fiction: 1, fantasy: 2, mystery: 3])
  ]
end

book = Book.new(%{genre: "biography"})
# %Book{genre: :biography}

Flint.Schema.dump(book)
# %{genre: 0}

In this example, you can see how you can share multiple representations of the same data using this distinction.

You can also implement your own Ecto.Type and further customize this:

defmodule ContentType do
  use Ecto.Type
  def type, do: :atom

  def cast("application/json"), do: {:ok, :json}

  def cast(_), do: :error
  def load(_), do: :error

  def dump(:json), do: {:ok, "application/json"}
  def dump(_), do: :error

  def embed_as(_) do
    :dump
  end
end

Here, cast will be called when creating a new Flint schema from a map, and dump will be used
when calling Flint.Schema.dump/1.

defmodule URL do
  use Flint, schema: [
    field(:content_type, ContentType)
  ]
end
url = URL.new(%{content_type: "application/json"})
# %URL{content_type: :json}

Flint.Schema.dump(url)
# %{content_type: "application/json"}

Examples

You can view the Notebooks folder for some examples in LIivebook.

You can also look at Merquery for a real, comprehensive
example of how to use Flint.

Most Liked

acalejos

acalejos

New v0.3.0 pushed to Hex. Main addition is the new Flint.Type module that makes writing custom Ecto types a breeze!

Video Demo: https://x.com/ac_alejos/status/1833720091013185898

Flint.Type

Flint.Type is meant to make writing new Ecto types require much less boilerplate, because you can base your
type off of an existing type and only modify the callbacks that have different behavior.

Simply use Flint.Type and pass the :extends option which says which type module to inherit callbacks
from. This will delegate all required callbacks and any implemented optional callbacks and make them
overridable.

It also lets you make a type from an Ecto.ParameterizedType with default parameter values.
You may supply any number of default parameters. This essentially provides a new
init/1 implementation for the type, supplying the default values, while not affecting any of the
other Ecto.ParameterizedType callbacks. You may still override the newly set defaults at the local level.

Just supply all options that you wish to be defaults as extra options when using Flint.Type.

You may override any of the inherited callbacks inherity from the extended module
in the case that you wish to customize the module further.

Examples

defmodule Category do
  use Flint.Type, extends: Ecto.Enum, values: [:folder, :file]
end

This will apply default values to Ecto.Enum when you supply a Category type
to an Ecto schema. You may still override the values if you supply the :values
option for the field.

import Flint.Type
deftype NewUID, extends: Ecto.UUID, dump: &String.length/1

This will create a new NewUID type that behaves exactly like an Ecto.UUID except it dumps
its string length.

Schultzer

Schultzer

Would love to see some of this end up, upstream in Ecto, I’ve always felt it was missing.

Eiji

Eiji

Oh, I see … In that case I have a better solution:

field! :type, :string do
  type not in ~w[elf human] -> "Expected elf or human, got: #{type}"
end

field! :age, :integer do
  age < 0 -> "Nobody can have a negative age"
  type == "elf" and age > max_elf_age -> "Attention! The elf has become a bug! Should be dead already!"
  type == "human" and age > max_human_age -> "Expected human to have up to #{max_human_age}, got: #{age}"
end

If remember correctly (writing from memory) the AST should look like:

[do: [
  {:->, ast_meta, [validation_expression, error_message_or_data]},
  # …
]]

Pros of this solution:

  1. The AST like expr1 -> expr2 is simple to parse.
  2. You can return more than one error easily (simply filter only matching validations on left side and return error messages on the right side)
  3. Allows to return something like:
    {:error, field_name: ["first error message", "second error message", …], …}
  4. Custom error messages or even custom data (as there is no need to validate collected data on right side), for example:
    {:error, field_name: [{500, "Internal human error"}]}
Eiji

Eiji

Yes and no. Yes as value generation and transformation are often desired. No for making it part of validations which could be confusing for developers and harder to implement.

For a value generation you could write other macro which have one more argument. Let’s call it vritual_field (following ecto’s naming). Having a separate macro would cause less trouble (default values in macro definition) and would be documented separately with a note like:

Works like a field, but generates a value based on other fields

For a transformation we could simply use a map option. This could be supported in both field and virtual_field as it could simplify implementation of generic stuff like a prettify.

field :name, :string, map: &do_something/1

def do_something(name) do
  # no need to validate and return ok/error tuples
  name
end

Here is a list of expressions to support:

  1. simple expression i.e. a + b
  2. function calls like func_name(first_field, second_field)
  3. 1-arity anonymous function like &(&1 + 1) or &do_something/1
  4. anonymous function like &do_something(second_field, &1)

In all cases of anonymous functions you have to ensure that &1 is a current field value (only for field macro). The rest cases are expressions with or without function call where you simply have to support field names just like in validations.

If I did not made a mistake here is a list of macro definitions you should support:

  1. defmacro field(name, type, do: block)
  2. defmacro field(name, type, opts \\ []):map support in opts
  3. defmacro field(name, type, opts, do: block):map support in opts
  4. defmacro field!(name, type, do: block)
  5. defmacro field!(name, type, opts \\ []):map support in opts
  6. defmacro field!(name, type, opts, do: block):map support in opts
  7. defmacro virtual_field(name, type, expr, do: block)
  8. defmacro virtual_field(name, type, expr, opts \\ []):map support in opts
  9. defmacro virtual_field(name, type, expr, opts, do: block):map support in opts
acalejos

acalejos

v0.4 available now on Hex.

Big refactor adding Flint.Extension module. Now most of the features are packaged as extensions, making it easier to enable or disable features per schema.

Extensions also allows you to register new options to the field macro in Flint.Schema.

Extension Docs: Flint.Extension — Flint v0.4.2

Demos:
x.com - v0.4 release demo
x.com - Demo with Instructor pt. 1
x.com - Demo with Instructor pt. 2

Where Next?

Popular in Libraries Top

RobertDober
Earmark is a pure-Elixir Markdown converter. It is intended to be used as a library (just call Earmark.as_html), but can also be used as...
239 11851 134
New
deadtrickster
I’ve just released stable versions of my Prometheus Elixir libs: Elixir client [docs]; Ecto collector [docs]; Plugs instrumenter/Export...
New
cjen07
parameterized pipe in elixir: |n&gt; edit: negative index in |n&gt; and mixed usage with |&gt; are supported example: use ParamP...
New
josevalim
EDIT: since Ecto 3.0 final version is out, this post was amended to use the final versions in the instructions below. Hi everyone, We a...
New
blatyo
https://www.conduitframework.com/ The best overview for how things are tied together is this presentation. Modules and functions are pre...
New
danschultzer
In short Plug n’ play OAuth 2.0 provider library. Just set up a resource owner schema with Ecto (your user schema), install the dependen...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
ahamez
Hi everyone, I’ve been working on this protobuf library for 3 years. We use it in the company I work for, EasyMile, to communicate with ...
New
KallDrexx
For a good number of months I've been working on creating a very basic RTMP live video streaming server. Now that I have a very, very ba...
New
versilov
Could not wait for the missing Elixir ML libraries to appear, so, I wrote one myself, taking https://github.com/sdwolfz/exlearn as a foun...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New

Sub Categories:

We're in Beta

About us Mission Statement