About
Ecto is a toolkit for data mapping and language integrated query for Elixir. Here is an example:
# In your config/config.exs file
config :my_app, ecto_repos: [Sample.Repo]
config :my_app, Sample.Repo,
database: "ecto_simple",
username: "postgres",
password: "postgres",
hostname: "localhost",
port: "5432"
# In your application code
defmodule Sample.Repo do
use Ecto.Repo,
otp_app: :my_app,
adapter: Ecto.Adapters.Postgres
end
defmodule Sample.Weather do
use Ecto.Schema
schema "weather" do
field :city # Defaults to type :string
field :temp_lo, :integer
field :temp_hi, :integer
field :prcp, :float, default: 0.0
end
end
defmodule Sample.App do
import Ecto.Query
alias Sample.{Weather, Repo}
def keyword_query do
query =
from w in Weather,
where: w.prcp > 0 or is_nil(w.prcp),
select: w
Repo.all(query)
end
def pipe_query do
Weather
|> where(city: "Kraków")
|> order_by(:temp_lo)
|> limit(10)
|> Repo.all
end
end
Ecto is commonly used to interact with databases, such as PostgreSQL and MySQL via Ecto.Adapters.SQL (source code). Ecto is also commonly used to map data from any source into Elixir structs, whether they are backed by a database or not.
See the getting started guide and the online documentation for more information. Other resources available are:
Programming Ecto, by Darin Wilson and Eric Meadows-Jönsson, which guides you from fundamentals up to advanced concepts
The Little Ecto Cookbook, a free ebook by Dashbit, which is a curation of the existing Ecto guides with some extra contents
Important links
Running tests
Clone the repo and fetch its dependencies:
$ git clone https://github.com/elixir-ecto/ecto.git
$ cd ecto
$ mix deps.get
$ mix test
Note that mix test
does not run the tests in the integration_test
folder. To run integration tests, you can clone ecto_sql
in a sibling directory and then run its integration tests with the ECTO_PATH
environment variable pointing to your Ecto checkout:
$ cd ..
$ git clone https://github.com/elixir-ecto/ecto_sql.git
$ cd ecto_sql
$ mix deps.get
$ ECTO_PATH=../ecto mix test.all
Running containerized tests
It is also possible to run the integration tests under a containerized environment using earthly:
$ earthly -P +all
You can also use this to interactively debug any failing integration tests using:
$ earthly -P -i --build-arg ELIXIR_BASE=1.8.2-erlang-21.3.8.21-alpine-3.13.1 +integration-test
Then once you enter the containerized shell, you can inspect the underlying databases with the respective commands:
PGPASSWORD=postgres psql -h 127.0.0.1 -U postgres -d postgres ecto_test
MYSQL_PASSWORD=root mysql -h 127.0.0.1 -uroot -proot ecto_test
sqlcmd -U sa -P 'some!Password'
Logo
“Ecto” and the Ecto logo are Copyright © 2020 Dashbit.
The Ecto logo was designed by Dane Wesolko.