Ecto

Vincent Nguyen 26 August 2017
elixir, ecto

When I start to learn and work on Elixir, I really impressive about Ecto.

Ecto is a database wrapper and language integrated query for Elixir.

My personal feeling is Ecto is not magically like ActiveRecord. For example, Ecto doesn't support Lazy-Load, you need to allow data to be preloaded into structs. Lazy loading is often a source of confusion and performance issues and Ecto pushes developers to do the proper thing. Sound good, huh?

Ecto also supports a mechanism to help you organize the schema across multiple contexts - break a large schema into smaller ones. Maybe one for reading data, another for writing. Or one for your database, another for your forms.

And did you know the Plataformatec? They wrote a cool free Ecto ebook and the book will be updated frequently when Ecto release new version.

After few days reading the book below is my summary and of course, from the book, I also had few things don't completely understand. I will deep dive it again in this September.


But Elixir fails the "coupling of state and behavior". Behavior in Elixir is always added to modules via functions. Elixir provides structs to help us work with structured data.

    defmodule Product do
      defstruct [:price, :title]
  
      def purchased?(product) do
        # Do Sth
      end
    end
  

The call will be

    product = Product.new(title: "iPhone 8", price: 1000)
    product.price
  
    Product.purchased?(product)
  

As you see, the schema types is the place you provide information for fields and set relationship to another model.

And a schema may be end-up with hundreds of fields, relationships - this is a very bad schema. Therefore, it's better to break schema across multiple contexts, this would lead to simpler and clearer solutions.