This article was originally published on Serokell's blog – https://serokell.io/blog/ecto-guide-for-beginners.
If you have tried your hand at doing web development with Phoenix, you have definitely run into Ecto. It’s the go-to database library for Elixir programmers. Unfortunately, Phoenix tutorials usually don’t cover Ecto deeply enough to develop an intuition of why things are the way they are.
In this article, we’ll instead try to understand how Ecto works. First, we’ll use Ecto to play around with a basic blog database. After that, we’ll dive deeper into different Ecto’s modules and what they offer.
If this is the first time you encounter Elixir (or Phoenix), I suggest you start slow and check out our guides to Elixir and Phoenix.
What is Ecto?
Ecto is the go-to database toolkit in the Elixir ecosystem, usually used to interact with SQL databases like Postgres and MySQL. It is very powerful and can be used for all the interaction with databases you need, such as inserting, validating, changing, and querying data.
It has four main components:
Schema. Schemas are maps from database tables into Elixir structs; the module provides everything you need to create them.
Changeset. Changesets help validate the data that you want to insert into the database or modify.
Repo. This is the main point through which any interaction with the database is called.
Query. A macro-powered DSL for doing composable queries with Elixir-like syntax.
You are free to use any combination of these modules in your application, according to your requirements. There is no need to use all of them.
What are the benefits of using Ecto?
Most likely, the choice of using Ecto will come as a consequence of other choices that you’ve made. If you are using Phoenix and Elixir, the chance is you will use Ecto. 🙃