Ecto.Repo behaviour

This module is used to define a repository. A repository maps to a data store, for example an SQL database. A repository must implement conf/0 and set an adapter (see Ecto.Adapter) to be used for the repository.

When used, the following options are allowed:

Example

defmodule MyRepo do
  use Ecto.Repo, adapter: Ecto.Adapters.Postgres

  def conf do
    parse_url "ecto://postgres:postgres@localhost/postgres"
  end
end

Most of the time, we want the repository to work with different environments. In such cases, we can pass an :env option:

defmodule MyRepo do
  use Ecto.Repo, adapter: Ecto.Adapters.Postgres, env: Mix.env

  def conf(env), do: parse_url url(env)

  defp url(:dev),  do: "ecto://postgres:postgres@localhost/postgres_dev"
  defp url(:test), do: "ecto://postgres:postgres@localhost/postgres_test?size=1"
  defp url(:prod), do: "ecto://postgres:postgres@localhost/postgres_prod"
end

Notice that, when using the environment, developers should implement conf/1 which automatically passes the environment instead of conf/0.

Note the environment is only used at compilation time. That said, make sure the :build_per_environment option is set to true (the default) in your Mix project configuration.

Source

Types

t :: module

Callbacks

adapter/0

Specs:

Returns the adapter tied to the repository.

Source
all/2

Specs:

Fetches all results from the data store based on the given query. May raise Ecto.QueryError if query validation fails. Ecto.AdapterError will be raised if there is an adapter error.

Options

:timeout - The time in milliseconds to wait for the call to finish,

`:infinity` will wait indefinitely (default: 5000);

Example

# Fetch all post titles
query = from p in Post,
     select: p.title
MyRepo.all(query)
Source
conf/0

Specs:

Should return the database options that will be given to the adapter. Often used in conjunction with parse_url/1. This function must be implemented by the user.

Source
delete/2

Specs:

Deletes an model using the primary key as key. If the model has no primary key Ecto.NoPrimaryKey will be raised. Ecto.AdapterError will be raised if there is an adapter error.

Options

:timeout - The time in milliseconds to wait for the call to finish,

`:infinity` will wait indefinitely (default: 5000);

Example

[post] = MyRepo.all(from(p in Post, where: p.id == 42))
MyRepo.delete(post)
Source
delete_all/2

Specs:

Deletes all entities matching the given query with the given values. Ecto.AdapterError will be raised if there is an adapter error.

Options

:timeout - The time in milliseconds to wait for the call to finish,

`:infinity` will wait indefinitely (default: 5000);

Examples

MyRepo.delete_all(Post)

from(p in Post, where: p.id < 10) |> MyRepo.delete_all
Source
get/3

Specs:

Fetches a single model from the data store where the primary key matches the given id. Returns nil if no result was found. If the model in the queryable has no primary key Ecto.NoPrimaryKey will be raised. Ecto.AdapterError will be raised if there is an adapter error.

Options

:timeout - The time in milliseconds to wait for the call to finish,

`:infinity` will wait indefinitely (default: 5000);
Source
insert/2

Specs:

Stores a single new model in the data store and returns its stored representation. May raise Ecto.AdapterError if there is an adapter error.

Options

:timeout - The time in milliseconds to wait for the call to finish,

`:infinity` will wait indefinitely (default: 5000);

Example

post = %Post{title: "Ecto is great", text: "really, it is"}
       |> MyRepo.insert
Source
log/2

Specs:

  • log(any, (() -> any)) :: any

Enables logging and debugging of adapter actions such as sending queries to the database. Should be overridden to customize behaviour.

Examples

def log({:query, sql}, fun) do
  {time, result} = :timer.tc(fun)
  Logger.log({sql, time})
  result
end

def log(_arg, fun), do: fun.()
Source
query_apis/0

Specs:

  • query_apis :: [module]

Returns the supported query APIs. Should be overridden to customize.

Source
rollback/0

Specs:

  • rollback :: no_return

Rolls back the current transaction. See rollback/1.

Source
rollback/1

Specs:

  • rollback(any) :: no_return

Rolls back the current transaction. The transaction will return the value given as {:error, value}.

Source
start_link/0

Specs:

  • start_link :: {:ok, pid} | :ok | {:error, {:already_started, pid}} | {:error, term}

Starts any connection pooling or supervision and return {:ok, pid} or just :ok if nothing needs to be done.

Returns {:error, {:already_started, pid}} if the repo already started or {:error, term} in case anything else goes wrong.

Source
stop/0

Specs:

  • stop :: :ok

Stops any connection pooling or supervision started with start_link/1.

Source
transaction/2

Specs:

  • transaction(Keyword.t, (... -> any)) :: {:ok, any} | {:error, any}

Runs the given function inside a transaction. If an unhandled error occurs the transaction will be rolled back. If no error occurred the transaction will be commited when the function returns. A transaction can be explicitly rolled back by calling rollback, this will immediately leave the function and return the value given to rollback as {:error, value}. A successful transaction returns the value returned by the function wrapped in a tuple as {:ok, value}. Transactions can be nested.

Options

:timeout - The time in milliseconds to wait for the call to finish,

`:infinity` will wait indefinitely (default: 5000);

Examples

MyRepo.transaction(fn ->
  MyRepo.update(alice.update_balance(&(&1 - 10))
  MyRepo.update(bob.update_balance(&(&1 + 10))
end)

# In the following example only the comment will be rolled back
MyRepo.transaction(fn ->
  MyRepo.insert(%Post{})

  MyRepo.transaction(fn ->
    MyRepo.insert(%Comment{})
    raise "error"
  end)
end)

# Roll back a transaction explicitly
MyRepo.transaction(fn ->
  p = MyRepo.insert(%Post{})
  if not Editor.post_allowed?(p) do
    MyRepo.rollback
  end
end)
Source
update/2

Specs:

Updates an model using the primary key as key. If the model has no primary key Ecto.NoPrimaryKey will be raised. Ecto.AdapterError will be raised if there is an adapter error.

Options

:timeout - The time in milliseconds to wait for the call to finish,

`:infinity` will wait indefinitely (default: 5000);

Example

[post] = from p in Post, where: p.id == 42
post = post.title("New title")
MyRepo.update(post)
Source
update_all/3

Updates all entities matching the given query with the given values. Ecto.AdapterError will be raised if there is an adapter error.

Options

:timeout - The time in milliseconds to wait for the call to finish,

`:infinity` will wait indefinitely (default: 5000);

Examples

MyRepo.update_all(Post, title: "New title")

MyRepo.update_all(p in Post, visits: p.visits + 1)

from(p in Post, where: p.id < 10)
|> MyRepo.update_all(title: "New title")
Source