Data is an integral part of virtually any web application, and a great persistence library make a huge difference in performance and maintainability.
Thankfully, the Elixir ecosystem has us covered in spades. Ecto is a thin layer of functions that allow us to build composable queries, validate fields, and seamlessly transform records between our DB and application representations.
Managing DataIntro to Ecto
Heavy persistence libraries like ActiveRecord offer convenience, but often become performance bottlenecks. We could make every DB query explicitly, but then we're trading in all of our ergonomics for performance.
Ecto manages to strike an enjoyable balance, where we are asked to be deliberate about the records we fetch from a database but (most of the time) aren't dragged into the world of writing SQL queries explicitly.
You'll be amazed at how much we can do with just simple functions, and will never look at other persistence frameworks quite the same way again.
Managing DataManaging Migrations
If you've never used code to manage changes to your database schema, you're missing out. Migrations allow us to change our schema in (ideally) reversible steps, so we can apply and un-apply a set of changes while building features. Even if you've seen migrations before, there are some useful things to know about how they work with Ecto, and in particular, Postgres. We'll look, specifically at:
- Postgres array and jsonb column types
- Changing column types, while remaining backwards compatible
Managing DataCracking Changesets
This is one of my favorite parts about Ecto, and one of the parts you'll be most often working with. In contrast to other persistence libraries, the concept of the shape of a record (schema) and the logic for checking the validity of values (validations) are decoupled. There are some incredibly exciting consequences of this design decision.
Ecto ships with a bunch of validations, and because it's so quick and easy, we'll write a few of our own.
Managing DataEXERCISE: Models & Validation
Create models and appropriate validations for a blog post/comment app.
Managing DataQuick Queries
While we could use SQL syntax to retrieve records from our database, doing so would open us up to a world of pain. Ecto provides an approachable and composable way of building queries, while stopping short of doing us any "automatic favors" (i.e., N+1 queries) that so often degrade performance.
Managing DataEXERCISE: Query Olympics
You'll be given a list of database queries for you and your classmates to make using Ecto. Each query is worth a certain number of points. Highest number of points after the exercise is done, wins!
Break for Lunch