Computer Science and the craft of programming. • Back-end with Elixir; • Increasingly learning Erlang/OTP. Trying to make the world a better place to live, through technology.
should be available together. It’s different State and Behaviour should be syntactically spoke differently. At it’s core, Objects couple State and Behaviour together.
Map, Tuples, etc... Behaviour Behaviour cannot be attached to data structures. Always added to modules through functions. Elixir fails in the “coupling state and behaviour”.
struct must be explicitly given as an argument. Behaviour There is not structural coupling between the user and the functions in the User module. It’s impossible to call user.confirm()
language. Also, take a look at Embedded Schemas. Relational While Ecto is not Relational Mapper, it contains a Relational Mapper. How it is achieved using Ecto?
may end up with “God Schemas”, “Fat Models”, etc... Excessively rely on schemas when sometimes the best way is using a map, tuple, etc... Using the same Schema for all operations that may end up with point one. BOOM!
your relations to Elixir data Schemas Like structs, but a really relation mapper from DB State Modules does not have behaviour behaviour Usually attached through functions to modules
Most queries in Ecto are written using schemas. To retrieve all users from a database for example: MyApp.Repo.all(User) As Ecto knows all the fields that a schema has, it is simple to use: query = from p in Post, select: %Post{title: p.title, body: p.body} MyApp.Repo.all(query)
schemas We can select all desired fields without any conformation with any schema. from “posts”, select: [:title, :body] With that, Ecto will automatically convert a list of fields to a struct or a map.
take a look on a example where we increment a page view from a website: def increment_page_view(post) do query = from “posts”, where: [id: ^post.id], update: [inc: [page_views: 1]] MyApp.Repo.update_all(query, []) end
a schema and rely on pre-defined shape of data. Ecto make query with and without schemas more accessible. The function above doesn’t rely on schemas It enable developers to write dynamic queries.
because it is not our intent to persist it anywhere. defmodule Registration do use Ecto.Schema embedded_schema do field :first_name field :last_name field :email end end
if you want to use the same mapping on different places. Understand when a big problem can be broken into smaller parts. Using schemas didn’t affect the solution at all.
by Flaticon, and infographics & images by Freepik and illustrations by Stories THANKS Do you have any questions? orandson@gmail.com https://rands0n.com