Ecto v2.1.0-rc.5 Ecto.Repo behaviour
Defines a repository.
A repository maps to an underlying data store, controlled by the adapter. For example, Ecto ships with a Postgres adapter that stores data into a PostgreSQL database.
When used, the repository expects the :otp_app
as option.
The :otp_app
should point to an OTP application that has
the repository configuration. For example, the repository:
defmodule Repo do
use Ecto.Repo, otp_app: :my_app
end
Could be configured with:
config :my_app, Repo,
adapter: Ecto.Adapters.Postgres,
database: "ecto_simple",
username: "postgres",
password: "postgres",
hostname: "localhost"
Most of the configuration that goes into the config
is specific
to the adapter, so check Ecto.Adapters.Postgres
documentation
for more information. However, some configuration is shared across
all adapters, they are:
:priv
- the directory where to keep repository data, like migrations, schema and more. Defaults to “priv/YOUR_REPO”. It must always point to a subdirectory inside the priv directory.:url
- an URL that specifies storage information. Read below for more information:loggers
- a list of{mod, fun, args}
tuples that are invoked by adapters for logging queries and other events. The given module and function will be called with a log entry (seeEcto.LogEntry
) and the given arguments. The invoked function must return theEcto.LogEntry
as result. The default value is:[{Ecto.LogEntry, :log, []}]
, which will callEcto.LogEntry.log/1
that will use Elixir’sLogger
in:debug
mode. You may pass any desired mod-fun-args triplet or[{Ecto.LogEntry, :log, [:info]}]
if you want to keep the current behaviour but use another log level.
URLs
Repositories by default support URLs. For example, the configuration above could be rewritten to:
config :my_app, Repo,
url: "ecto://postgres:postgres@localhost/ecto_simple"
The schema can be of any value. The path represents the database name while options are simply merged in.
URLs also support {:system, "KEY"}
to be given, telling Ecto to load
the configuration from the system environment instead:
config :my_app, Repo,
url: {:system, "DATABASE_URL"}
Shared options
Almost all of the repository operations below accept the following options:
:timeout
- The time in milliseconds to wait for the query call to finish,:infinity
will wait indefinitely (default: 15000);:pool_timeout
- The time in milliseconds to wait for calls to the pool to finish,:infinity
will wait indefinitely (default: 5000);:log
- When false, does not log the query
Such cases will be explicitly documented as well as any extra option.
Summary
Callbacks
Returns the adapter tied to the repository
A callback invoked by adapters that logs the given action
Calculate the given aggregate
over the given field
Fetches all entries from the data store matching the given query
Returns the adapter configuration stored in the :otp_app
environment
Deletes a struct using its primary key
Same as delete/2
but returns the struct or raises if the changeset is invalid
Deletes all entries matching the given query
Fetches a single struct from the data store where the primary key matches the given id
Similar to get/3
but raises Ecto.NoResultsError
if no record was found
Fetches a single result from the query
Similar to get_by/3
but raises Ecto.NoResultsError
if no record was found
Returns true if the current process is inside a transaction
A callback executed when the repo starts or when configuration is read
Inserts a struct or a changeset
Same as insert/2
but returns the struct or raises if the changeset is invalid
Inserts all entries into the repository
Inserts or updates a changeset depending on whether the struct is persisted or not
Same as insert_or_update/2
but returns the struct or raises if the changeset
is invalid
Loads data
into a struct or a map
Fetches a single result from the query
Similar to one/2
but raises Ecto.NoResultsError
if no record was found
Preloads all associations on the given struct or structs
Rolls back the current transaction
Starts any connection pooling or supervision and return {:ok, pid}
or just :ok
if nothing needs to be done
Shuts down the repository represented by the given pid
Returns a lazy enumerable that emits all entries from the data store matching the given query. SQL adapters, such as Postgres and MySQL, can only enumerate a stream inside a transaction
Runs the given function or Ecto.Multi
inside a transaction
Updates a changeset using its primary key
Same as update/2
but returns the struct or raises if the changeset is invalid
Updates all entries matching the given query with the given values
Types
Callbacks
Returns the adapter tied to the repository.
A callback invoked by adapters that logs the given action.
See Ecto.LogEntry
for more information and Ecto.Repo
module
documentation on setting up your own loggers.
aggregate(queryable :: Ecto.Queryable.t, aggregate :: :avg | :count | :max | :min | :sum, field :: atom, opts :: Keyword.t) :: term | nil
Calculate the given aggregate
over the given field
.
If the query has a limit, offset or distinct set, it will be automatically wrapped in a subquery in order to return the proper result.
Any preload or select in the query will be ignored in favor of the column being aggregated.
The aggregation will fail if any group_by
field is set.
Options
See the “Shared options” section at the module documentation.
Examples
# Returns the number of visits per blog post
Repo.aggregate(Post, :count, :visits)
# Returns the average number of visits for the top 10
query = from Post, limit: 10
Repo.aggregate(query, :avg, :visits)
all(queryable :: Ecto.Query.t, opts :: Keyword.t) :: [Ecto.Schema.t] | no_return
Fetches all entries from the data store matching the given query.
May raise Ecto.QueryError
if query validation fails.
Options
:prefix
- The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the query.
See the “Shared options” section at the module documentation.
Example
# Fetch all post titles
query = from p in Post,
select: p.title
MyRepo.all(query)
Returns the adapter configuration stored in the :otp_app
environment.
Dynamic configuration is not reflected on this value.
delete(struct_or_changeset :: Ecto.Schema.t | Ecto.Changeset.t, opts :: Keyword.t) :: {:ok, Ecto.Schema.t} | {:error, Ecto.Changeset.t}
Deletes a struct using its primary key.
If the struct has no primary key, Ecto.NoPrimaryKeyFieldError
will be raised.
It returns {:ok, struct}
if the struct has been successfully
deleted or {:error, changeset}
if there was a validation
or a known constraint error.
Options
:prefix
- The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the struct.
See the “Shared options” section at the module documentation.
Example
post = MyRepo.get!(Post, 42)
case MyRepo.delete post do
{:ok, struct} -> # Deleted with success
{:error, changeset} -> # Something went wrong
end
delete!(struct_or_changeset :: Ecto.Schema.t | Ecto.Changeset.t, opts :: Keyword.t) :: Ecto.Schema.t | no_return
Same as delete/2
but returns the struct or raises if the changeset is invalid.
delete_all(queryable :: Ecto.Queryable.t, opts :: Keyword.t) :: {integer, nil | [term]} | no_return
Deletes all entries matching the given query.
It returns a tuple containing the number of entries
and any returned result as second element. If the database
does not support RETURNING in DELETE statements or no
return result was selected, the second element will be nil
.
Options
:returning
- selects which fields to return. Whentrue
, returns all fields in the given struct. May be a list of fields, where a struct is still returned but only with the given fields. Orfalse
, where nothing is returned (the default). This option is not supported by all databases.:prefix
- The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the query.
See the “Shared options” section at the module documentation for remaining options.
Examples
MyRepo.delete_all(Post)
from(p in Post, where: p.id < 10) |> MyRepo.delete_all
get(queryable :: Ecto.Queryable.t, id :: term, opts :: Keyword.t) :: Ecto.Schema.t | nil | no_return
Fetches a single struct from the data store where the primary key matches the given id.
Returns nil
if no result was found. If the struct in the queryable
has no or more than one primary key, it will raise an argument error.
Options
See the “Shared options” section at the module documentation.
Example
MyRepo.get(Post, 42)
get!(queryable :: Ecto.Queryable.t, id :: term, opts :: Keyword.t) :: Ecto.Schema.t | nil | no_return
Similar to get/3
but raises Ecto.NoResultsError
if no record was found.
Options
See the “Shared options” section at the module documentation.
Example
MyRepo.get!(Post, 42)
get_by(queryable :: Ecto.Queryable.t, clauses :: Keyword.t | map, opts :: Keyword.t) :: Ecto.Schema.t | nil | no_return
Fetches a single result from the query.
Returns nil
if no result was found.
Options
See the “Shared options” section at the module documentation.
Example
MyRepo.get_by(Post, title: "My post")
get_by!(queryable :: Ecto.Queryable.t, clauses :: Keyword.t | map, opts :: Keyword.t) :: Ecto.Schema.t | nil | no_return
Similar to get_by/3
but raises Ecto.NoResultsError
if no record was found.
Options
See the “Shared options” section at the module documentation.
Example
MyRepo.get_by!(Post, title: "My post")
Returns true if the current process is inside a transaction.
Examples
MyRepo.in_transaction?
#=> false
MyRepo.transaction(fn ->
MyRepo.in_transaction? #=> true
end)
A callback executed when the repo starts or when configuration is read.
The first argument is the context the callback is being invoked. If it
is called because the Repo supervisor is starting, it will be :supervisor
.
It will be :dry_ryn
if it is called for reading configuration without
actually starting a process.
The second argument is the repository configuration as stored in the
application environment. It must return {:ok, keyword}
with the updated
list of configuration or :ignore
(only in the :supervisor
case).
insert(struct_or_changeset :: Ecto.Schema.t | Ecto.Changeset.t, opts :: Keyword.t) :: {:ok, Ecto.Schema.t} | {:error, Ecto.Changeset.t}
Inserts a struct or a changeset.
In case a struct is given, the struct is converted into a changeset with all non-nil fields as part of the changeset.
In case a changeset is given, the changes in the changeset are merged with the struct fields, and all of them are sent to the database.
It returns {:ok, struct}
if the struct has been successfully
inserted or {:error, changeset}
if there was a validation
or a known constraint error.
Options
:prefix
- The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the struct.:on_conflict
- How to react if the entry violates a primary key, unique or exclusion constraint. It may be:raise
(the default),:nothing
which will ignore any error, a keyword list of update instructions (such as the one given toupdate_all/3
or anEcto.Query
which will act as anUPDATE
statement. It maps to “ON CONFLICT” on databases like Postgres and “ON DUPLICATE KEY” on databases such as MySQL.:conflict_target
- Which columns to verify for conflicts. If none is specified, the conflict target is left up to the database and is usually made of primary keys and/or unique/exclusion constraints.
See the “Shared options” section at the module documentation.
Examples
A typical example is calling MyRepo.insert/1
with a struct
and acting on the return value:
case MyRepo.insert %Post{title: "Ecto is great"} do
{:ok, struct} -> # Inserted with success
{:error, changeset} -> # Something went wrong
end
“Upsert” is also supported by passing the :on_conflict
option:
# Insert it once
{:ok, inserted} = MyRepo.insert(%Post{title: "inserted"})
# Insert with the same ID but do nothing on conflicts.
# Keep in mind that, although this returns :ok, the returned
# struct may not necessarily reflect the data in the database.
{:ok, upserted} = MyRepo.insert(%Post{id: inserted.id, title: "updated"}, on_conflict: :nothing)
# Now let's insert with the same ID but use a query to update
# a column on conflicts. As before, although this returns :ok,
# the returned struct may not necessarily reflect the data in
# the database. In fact, any operation done on `:on_conflict`
# won't be automatically mapped to the struct.
# In Postgres:
on_conflict = [set: [title: "updated"]]
{:ok, updated} = MyRepo.insert(%Post{id: inserted.id, title: "updated"},
on_conflict: on_conflict, conflict_target: :id)
# In MySQL:
on_conflict = [set: [title: "updated"]]
{:ok, updated} = MyRepo.insert(%Post{id: inserted.id, title: "updated"},
on_conflict: on_conflict)
insert!(struct_or_changeset :: Ecto.Schema.t | Ecto.Changeset.t, opts :: Keyword.t) :: Ecto.Schema.t | no_return
Same as insert/2
but returns the struct or raises if the changeset is invalid.
insert_all(schema_or_source :: binary | {binary, Ecto.Schema.t} | Ecto.Schema.t, entries :: [map | Keyword.t], opts :: Keyword.t) :: {integer, nil | [term]} | no_return
Inserts all entries into the repository.
It expects a schema (MyApp.User
) or a source ("users"
) or
both ({"users", MyApp.User}
) as the first argument. The second
argument is a list of entries to be inserted, either as keyword
lists or as maps.
It returns a tuple containing the number of entries
and any returned result as second element. If the database
does not support RETURNING in UPDATE statements or no
return result was selected, the second element will be nil
.
When a schema is given, the values given will be properly dumped
before being sent to the database. If the schema contains an
autogenerated ID field, it will be handled either at the adapter
or the storage layer. However any other autogenerated value, like
timestamps, won’t be autogenerated when using insert_all/3
.
This is by design as this function aims to be a more direct way
to insert data into the database without the conveniences of
insert/2
. This is also consistent with update_all/3
that
does not handle timestamps as well.
If a source is given, without a schema, the given fields are passed as is to the adapter.
Options
:returning
- selects which fields to return. Whentrue
, returns all fields in the given struct. May be a list of fields, where a struct is still returned but only with the given fields. Orfalse
, where nothing is returned (the default). This option is not supported by all databases.:prefix
- The prefix to run the query on (such as the schema path in Postgres or the database in MySQL).:on_conflict
- How to react if the entry violates a primary key, unique or exclusion constraint. It may be:raise
(the default),:nothing
which will ignore any error, a keyword list of update instructions (such as the one given toupdate_all/3
or anEcto.Query
which will act as anUPDATE
statement. It maps to “ON CONFLICT” on databases like Postgres and “ON DUPLICATE KEY” on databases such as MySQL.:conflict_target
- Which columns to verify for conflicts. If none is specified, the conflict target is left up to the database and is usually made of primary keys and/or unique/exclusion constraints.
See the “Shared options” section at the module documentation for remaining options.
Examples
MyRepo.insert_all(Post, [[title: "My first post"], [title: "My second post"]])
MyRepo.insert_all(Post, [%{title: "My first post"}, %{title: "My second post"}])
Return values
By default, both Postgres and MySQL return the amount of entries
inserted on insert_all
. However, when the :on_conflict
option
is specified, Postgres will only return a row if it was affected
while MySQL returns at least the number of entries attempted.
For example, if :on_conflict
is set to :nothing
, Postgres will
return 0 if no new entry was added while MySQL will still return
the amount of entries attempted to be inserted, even if no entry
was added. Even worse, if :on_conflict
is query, MySQL will return
the number of attempted entries plus the number of entries modified
by the UPDATE query.
insert_or_update(struct_or_changeset :: Ecto.Schema.t | Ecto.Changeset.t, opts :: Keyword.t) :: {:ok, Ecto.Schema.t} | {:error, Ecto.Changeset.t}
Inserts or updates a changeset depending on whether the struct is persisted or not.
The distinction whether to insert or update will be made on the
Ecto.Schema.Metadata
field :state
. The :state
is automatically set by
Ecto when loading or building a schema.
Please note that for this to work, you will have to load existing structs from the database. So even if the struct exists, this won’t work:
struct = %Post{id: 'existing_id', ...}
MyRepo.insert_or_update changeset
# => {:error, "id already exists"}
Options
:prefix
- The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the struct.
See the “Shared options” section at the module documentation.
Example
result =
case MyRepo.get(Post, id) do
nil -> %Post{id: id} # Post not found, we build one
post -> post # Post exists, let's use it
end
|> Post.changeset(changes)
|> MyRepo.insert_or_update
case result do
{:ok, struct} -> # Inserted or updated with success
{:error, changeset} -> # Something went wrong
end
insert_or_update!(struct_or_changeset :: Ecto.Schema.t | Ecto.Changeset.t, opts :: Keyword.t) :: Ecto.Schema.t | no_return
Same as insert_or_update/2
but returns the struct or raises if the changeset
is invalid.
Loads data
into a struct or a map.
The first argument can be a schema, or a map (of types) and determines the return value: a struct or a map, respectively.
The second argument data
specifies fields and values that are to be loaded.
It can be a map, a keyword list, or a {fields, values}
tuple.
Fields can be atoms or strings.
Fields that are not present in the schema (or types
map) are ignored.
If any of the values has invalid type, an error is raised.
Examples
iex> MyRepo.load(User, %{name: "Alice", age: 25})
%User{name: "Alice", age: 25}
iex> MyRepo.load(User, [name: "Alice", age: 25])
%User{name: "Alice", age: 25}
data
can also take form of {fields, values}
:
iex> MyRepo.load(User, {[:name, :age], ["Alice", 25]})
%User{name: "Alice", age: 25, ...}
The first argument can also be a types
map:
iex> types = %{name: :string, age: :integer}
iex> MyRepo.load(types, %{name: "Alice", age: 25})
%{name: "Alice", age: 25}
This function is especially useful when parsing raw query results:
iex> result = Ecto.Adapters.SQL.query!(MyRepo, "SELECT * FROM users", [])
iex> Enum.map(result.rows, &MyRepo.load(User, {result.columns, &1}))
[%User{...}, ...]
one(queryable :: Ecto.Queryable.t, opts :: Keyword.t) :: Ecto.Schema.t | nil | no_return
Fetches a single result from the query.
Returns nil
if no result was found. Raises if more than one entry.
Options
See the “Shared options” section at the module documentation.
one!(queryable :: Ecto.Queryable.t, opts :: Keyword.t) :: Ecto.Schema.t | no_return
Similar to one/2
but raises Ecto.NoResultsError
if no record was found.
Raises if more than one entry.
Options
See the “Shared options” section at the module documentation.
preload(struct_or_structs, preloads :: term, opts :: Keyword.t) :: struct_or_structs when struct_or_structs: [Ecto.Schema.t] | Ecto.Schema.t
Preloads all associations on the given struct or structs.
This is similar to Ecto.Query.preload/3
except it allows
you to preload structs after they have been fetched from the
database.
In case the association was already loaded, preload won’t attempt to reload it.
Options
Besides the “Shared options” section at the module documentation, it accepts:
:force
- By default, Ecto won’t preload associations that are already loaded. By setting this option to true, any existing association will be discarded and reloaded.:in_parallel
- If the preloads must be done in parallel. It can only be performed when we have more than one preload and the repository is not in a transaction. Defaults totrue
.:prefix
- the prefix to fetch preloads from. By default, queries will use the same prefix as the one in the given collection. This option allows the prefix to be changed.
Examples
posts = Repo.preload posts, :comments
posts = Repo.preload posts, comments: :permalinks
posts = Repo.preload posts, comments: from(c in Comment, order_by: c.published_at)
Rolls back the current transaction.
The transaction will return the value given as {:error, value}
.
start_link(opts :: Keyword.t) :: {:ok, pid} | {: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 is already
started or {:error, term}
in case anything else goes wrong.
Options
See the configuration in the moduledoc for options shared between adapters, for adapter-specific configuration see the adapter’s documentation.
Shuts down the repository represented by the given pid.
Returns a lazy enumerable that emits all entries from the data store matching the given query. SQL adapters, such as Postgres and MySQL, can only enumerate a stream inside a transaction.
May raise Ecto.QueryError
if query validation fails.
Options
:prefix
- The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the query:max_rows
- The number of rows to load from the database as we stream. It is supported at least by Postgres and MySQL and defaults to 500.
See the “Shared options” section at the module documentation.
Example
# Fetch all post titles
query = from p in Post,
select: p.title
stream = MyRepo.stream(query)
MyRepo.transaction(fn() ->
Enum.to_list(stream)
end)
transaction(fun_or_multi :: (... -> any) | Ecto.Multi.t, opts :: Keyword.t) :: {:ok, any} | {:error, any} | {:error, atom, any, %{optional(atom) => any}}
Runs the given function or Ecto.Multi
inside a transaction.
Use with function
If an unhandled error occurs the transaction will be rolled back
and the error will bubble up from the transaction function.
If no error occurred the transaction will be committed when the
function returns. A transaction can be explicitly rolled back
by calling rollback/1
, 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}
.
If transaction/2
is called inside another transaction, the function
is simply executed, without wrapping the new transaction call in any
way. If there is an error in the inner transaction and the error is
rescued, or the inner transaction is rolled back, the whole outer
transaction is marked as tainted, guaranteeing nothing will be committed.
Use with Ecto.Multi
Besides functions transaction can be used with an Ecto.Multi struct.
Transaction will be started, all operations applied and in case of
success committed returning {:ok, changes}
. In case of any errors
the transaction will be rolled back and
{:error, failed_operation, failed_value, changes_so_far}
will be
returned.
You can read more about using transactions with Ecto.Multi
as well as
see some examples in the Ecto.Multi
documentation.
Options
See the “Shared options” section at the module documentation.
Examples
MyRepo.transaction(fn ->
MyRepo.update!(%{alice | balance: alice.balance - 10})
MyRepo.update!(%{bob | balance: bob.balance + 10})
end)
# Roll back a transaction explicitly
MyRepo.transaction(fn ->
p = MyRepo.insert!(%Post{})
if not Editor.post_allowed?(p) do
MyRepo.rollback(:posting_not_allowed)
end
end)
# With Ecto.Multi
Ecto.Multi.new
|> Ecto.Multi.insert(:post, %Post{})
|> MyRepo.transaction
update(changeset :: Ecto.Changeset.t, opts :: Keyword.t) :: {:ok, Ecto.Schema.t} | {:error, Ecto.Changeset.t}
Updates a changeset using its primary key.
A changeset is required as it is the only mechanism for
tracking dirty changes. Only the fields present in the changes
part
of the changeset are sent to the database. Any other, in-memory
changes done to the schema are ignored.
If the struct has no primary key, Ecto.NoPrimaryKeyFieldError
will be raised.
It returns {:ok, struct}
if the struct has been successfully
updated or {:error, changeset}
if there was a validation
or a known constraint error.
Options
Besides the “Shared options” section at the module documentation, it accepts:
:force
- By default, if there are no changes in the changeset,update!/2
is a no-op. By setting this option to true, update callbacks will always be executed, even if there are no changes (including timestamps).:prefix
- The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the struct.
Example
post = MyRepo.get!(Post, 42)
post = Ecto.Changeset.change post, title: "New title"
case MyRepo.update post do
{:ok, struct} -> # Updated with success
{:error, changeset} -> # Something went wrong
end
update!(changeset :: Ecto.Changeset.t, opts :: Keyword.t) :: Ecto.Schema.t | no_return
Same as update/2
but returns the struct or raises if the changeset is invalid.
update_all(queryable :: Ecto.Queryable.t, updates :: Keyword.t, opts :: Keyword.t) :: {integer, nil | [term]} | no_return
Updates all entries matching the given query with the given values.
It returns a tuple containing the number of entries
and any returned result as second element. If the database
does not support RETURNING in UPDATE statements or no
return result was selected, the second element will be nil
.
Keep in mind this update_all
will not update autogenerated
fields like the updated_at
columns.
See Ecto.Query.update/3
for update operations that can be
performed on fields.
Options
:returning
- selects which fields to return. Whentrue
, returns all fields in the given struct. May be a list of fields, where a struct is still returned but only with the given fields. Orfalse
, where nothing is returned (the default). This option is not supported by all databases.:prefix
- The prefix to run the query on (such as the schema path in Postgres or the database in MySQL). This overrides the prefix set in the query.
See the “Shared options” section at the module documentation for remaining options.
Examples
MyRepo.update_all(Post, set: [title: "New title"])
MyRepo.update_all(Post, inc: [visits: 1])
from(p in Post, where: p.id < 10)
|> MyRepo.update_all(set: [title: "New title"])
from(p in Post, where: p.id < 10, update: [set: [title: "New title"]])
|> MyRepo.update_all([])
from(p in Post, where: p.id < 10, update: [set: [title: fragment("?", new_title)]])
|> MyRepo.update_all([])