💧 Elixir Beginner

What is Ecto in Elixir?

Answer

Ecto is Elixir's database library — it is not just an ORM but a comprehensive toolkit for working with data. Key components: Repo: the database interface. Repo.insert(changeset), Repo.all(query), Repo.get(Model, id). Schema: defines the data model and its database mapping: schema "users" do field :name, :string; field :age, :integer; timestamps() end. Changeset: validates and transforms data before insertion/update. def changeset(user, attrs) do user |> cast(attrs, [:name, :age]) |> validate_required([:name]) |> validate_number(:age, greater_than: 0) end. Query DSL: composable, safe queries: from u in User, where: u.age > 18, select: u. Migrations: version-controlled schema changes. Ecto separates the database concern (Schema) from validation (Changeset) — a design that prevents common bugs where validation is bypassed by going directly to the database.