Vetspire. Repo
(vetspire v3.0.0)
View Source
Summary
Functions
Callback implementation for Ecto.Repo.aggregate/4.
Callback implementation for Ecto.Repo.all_by/3.
Given a schema to map onto, and a query which could be used to Vetspire.Repo.insert_all/3 into
said schema, uses a CTE to create a "virtual" table which can be queried as though it were
any other.
Callback implementation for Ecto.Repo.checked_out?/0.
Callback implementation for Ecto.Repo.checkout/2.
Callback implementation for Ecto.Repo.config/0.
Returns the primary's current write position in the write-ahead log.
See Elixir.Vetspire.Repo.CursorStream.cursor_stream/2 for more information.
Default bounded lock_timeout (ms) for :wait row locks on billing orders.
Callback implementation for Ecto.Repo.default_options/1.
Callback implementation for Ecto.Repo.delete/2.
Callback implementation for Ecto.Repo.delete!/2.
Callback implementation for Ecto.Repo.delete_all/2.
Forces all connections in the repo pool to disconnect within the given interval.
Runs the given closure inside a transaction and returns the result without persisting
Executes an EXPLAIN statement or similar for the given query according to its kind and the adapter in the given repository.
Helper util for SQL EXPLAIN statements. This accepts, and returns an Ecto.Query, allowing this
to part of a query pipe chain.
Helper functions to force queries to read from the replica. Used in vetspire_web/context.ex to push all API users to do so.
Helpers for removing preloaded fields from exmachina insertions. https://github.com/thoughtbot/ex_machina/issues/295
Callback implementation for Ecto.Repo.get_dynamic_repo/0.
Callback implementation for Ecto.Repo.in_transaction?/0.
Dynamically loads the repository url from the DATABASE_URL environment variable.
Callback implementation for Ecto.Repo.insert/2.
Callback implementation for Ecto.Repo.insert!/2.
Callback implementation for Ecto.Repo.insert_all/3.
Callback implementation for Ecto.Repo.insert_or_update/2.
Callback implementation for Ecto.Repo.insert_or_update!/2.
Callback implementation for Ecto.Repo.load/2.
Fetch a single row by id with a row lock applied. Allowed locks
Callback implementation for Ecto.Repo.prepare_query/3.
Callback implementation for Ecto.Repo.prepare_transaction/2.
Callback implementation for Ecto.Repo.put_dynamic_repo/1.
Runs a custom SQL query.
Same as query/3 but returns result directly without :ok tuple
and raises on invalid queries
Runs a custom SQL query that returns multiple results on the given repo.
Same as query_many/4 but returns result directly without :ok tuple
and raises on invalid queries
Callback implementation for Ecto.Repo.reload/2.
Callback implementation for Ecto.Repo.reload!/2.
Returns the module for the configured read replica. Based on https://hexdocs.pm/ecto/replicas-and-dynamic-repositories.html
Says whether the replica has replayed the write-ahead log up to lsn.
Callback implementation for Ecto.Repo.rollback/1.
Callback implementation for Ecto.Repo.start_link/1.
Callback implementation for Ecto.Repo.stop/1.
Converts the given query to SQL according to its kind and the adapter in the given repository.
Callback implementation for Ecto.Repo.transact/2.
Locks a row FOR UPDATE, then runs fun with it inside a transaction, retrying the lock a
bounded number of times when the row is already locked.
Callback implementation for Ecto.Repo.update/2.
Callback implementation for Ecto.Repo.update!/2.
Callback implementation for Ecto.Repo.update_all/3.
Runs the given closure with the server-side statement_timeout disabled.
Functions
Callback implementation for Ecto.Repo.aggregate/4.
Callback implementation for Ecto.Repo.all_by/3.
Given a schema to map onto, and a query which could be used to Vetspire.Repo.insert_all/3 into
said schema, uses a CTE to create a "virtual" table which can be queried as though it were
any other.
Callback implementation for Ecto.Repo.checked_out?/0.
Callback implementation for Ecto.Repo.checkout/2.
Callback implementation for Ecto.Repo.config/0.
@spec current_wal_lsn() :: String.t()
Returns the primary's current write position in the write-ahead log.
Pair it with replica_caught_up?/2 to make a read on the replica wait for a write
that the primary has just committed.
See Elixir.Vetspire.Repo.CursorStream.cursor_stream/2 for more information.
@spec default_lock_timeout_ms() :: pos_integer()
Default bounded lock_timeout (ms) for :wait row locks on billing orders.
ponytail: single calibration knob shared by the encounter add/edit/delete and reopen paths. Ceiling = how long a concurrent finalize/payment realistically holds the order lock before we give up (fork a new billable, or fail the edit/delete). Raise if forks/drops are too frequent.
Callback implementation for Ecto.Repo.default_options/1.
Callback implementation for Ecto.Repo.delete/2.
Callback implementation for Ecto.Repo.delete!/2.
Callback implementation for Ecto.Repo.delete_all/2.
@spec disconnect_all(non_neg_integer(), opts :: Keyword.t()) :: :ok
Forces all connections in the repo pool to disconnect within the given interval.
Once this function is called, the pool will disconnect all of its connections
as they are checked in or as they are pinged. Checked in connections will be
randomly disconnected within the given time interval. Pinged connections are
immediately disconnected - as they are idle (according to :idle_interval).
If the connection has a backoff configured (which is the case by default), disconnecting means an attempt at a new connection will be done immediately after, without starting a new process for each connection. However, if backoff has been disabled, the connection process will terminate. In such cases, disconnecting all connections may cause the pool supervisor to restart depending on the max_restarts/max_seconds configuration of the pool, so you will want to set those carefully.
Runs the given closure inside a transaction and returns the result without persisting
@spec explain( :all | :update_all | :delete_all, Ecto.Queryable.t(), opts :: Keyword.t() ) :: String.t() | Exception.t() | [map()]
Executes an EXPLAIN statement or similar for the given query according to its kind and the adapter in the given repository.
Examples
# Postgres
iex> MyRepo.explain(:all, Post)
"Seq Scan on posts p0 (cost=0.00..12.12 rows=1 width=443)"
iex> Ecto.Adapters.SQL.explain(Repo, :all, Post)
"Seq Scan on posts p0 (cost=0.00..12.12 rows=1 width=443)"
# MySQL
iex> MyRepo.explain(:all, from(p in Post, where: p.title == "title")) |> IO.puts()
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------------+
| 1 | SIMPLE | p0 | NULL | ALL | NULL | NULL | NULL | NULL | 1 | 100.0 | Using where |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------------+
# Shared opts
iex> MyRepo.explain(:all, Post, analyze: true, timeout: 20_000)
"Seq Scan on posts p0 (cost=0.00..11.70 rows=170 width=443) (actual time=0.013..0.013 rows=0 loops=1)\nPlanning Time: 0.031 ms\nExecution Time: 0.021 ms"It's safe to execute it for updates and deletes, no data change will be committed:
iex> MyRepo.explain(Repo, :update_all, from(p in Post, update: [set: [title: "new title"]]))
"Update on posts p0 (cost=0.00..11.70 rows=170 width=449)\n -> Seq Scan on posts p0 (cost=0.00..11.70 rows=170 width=449)"This function is also available under the repository with name explain:
iex> MyRepo.explain(:all, from(p in Post, where: p.title == "title"))
"Seq Scan on posts p0 (cost=0.00..12.12 rows=1 width=443)\n Filter: ((title)::text = 'title'::text)"Options
Built-in adapters support passing opts to the EXPLAIN statement according to the following:
| Adapter | Supported opts |
|---|---|
| Postgrex | analyze, verbose, costs, settings, buffers, timing, summary, format, plan, wrap_in_transaction |
| MyXQL | format, wrap_in_transaction |
All options except format are boolean valued and default to false.
The allowed format values are :map, :yaml, and :text:
:mapis the deserialized JSON encoding.:yamland:textreturn the result as a string.
The built-in adapters support the following formats:
- Postgrex:
:map,:yamland:text - MyXQL:
:mapand:text
The wrap_in_transaction option is a boolean that controls whether the command is run inside of a
transaction that is rolled back. This is useful when, for example, you'd like to use analyze: true
on an update or delete query without modifying data. Defaults to true.
The :plan option in Postgrex can take the values :custom or :fallback_generic. When :custom
is specified, the explain plan generated will consider the specific values of the query parameters
that are supplied. When using :fallback_generic, the specific values of the query parameters will
be ignored. :fallback_generic does not use PostgreSQL's built-in support for a generic explain
plan (available as of PostgreSQL 16), but instead uses a special implementation that works for PostgreSQL
versions 12 and above. Defaults to :custom.
Any other value passed to opts will be forwarded to the underlying adapter query function, including
shared Repo options such as :timeout. Non built-in adapters may have specific behaviour and you should
consult their documentation for more details.
For version compatibility, please check your database's documentation:
- Postgrex: PostgreSQL doc.
- MyXQL: MySQL doc.
@spec explain_query( Ecto.Query.t(), keyword() ) :: Ecto.Query.t()
Helper util for SQL EXPLAIN statements. This accepts, and returns an Ecto.Query, allowing this
to part of a query pipe chain.
Note, you can pass any options that Ecto.Adapters.SQL.explain/4 accepts
Examples
some_query |> Vetspire.Repo.explain_query()
@spec force_read_replica(enabled? :: boolean()) :: :ok
Helper functions to force queries to read from the replica. Used in vetspire_web/context.ex to push all API users to do so.
This will only affect the current process, i.e. not anything spawned as Tasks or scheduled Oban jobs etc.
Helpers for removing preloaded fields from exmachina insertions. https://github.com/thoughtbot/ex_machina/issues/295
Examples
insert(:client)
|> Vetspire.Repo.forget(:org)
insert(:patient)
|> Vetspire.Repo.forget(:encounters, :many)
Callback implementation for Ecto.Repo.get_dynamic_repo/0.
Callback implementation for Ecto.Repo.in_transaction?/0.
Dynamically loads the repository url from the DATABASE_URL environment variable.
Callback implementation for Ecto.Repo.insert/2.
Callback implementation for Ecto.Repo.insert!/2.
Callback implementation for Ecto.Repo.insert_all/3.
Callback implementation for Ecto.Repo.insert_or_update/2.
Callback implementation for Ecto.Repo.insert_or_update!/2.
Callback implementation for Ecto.Repo.load/2.
Fetch a single row by id with a row lock applied. Allowed locks:
- :nowait -> FOR UPDATE NOWAIT (default)
- :wait -> FOR UPDATE
Raises RuntimeError if called outside a transaction.
Raises Vetspire.Error with code: :not_found if no record is found.
Raises Vetspire.Error with code: :locked if the row is already locked.
Callback implementation for Ecto.Repo.prepare_query/3.
Callback implementation for Ecto.Repo.prepare_transaction/2.
Callback implementation for Ecto.Repo.put_dynamic_repo/1.
@spec query(iodata(), Ecto.Adapters.SQL.query_params(), Keyword.t()) :: {:ok, Ecto.Adapters.SQL.query_result()} | {:error, Exception.t()}
Runs a custom SQL query.
If the query was successful, it will return an :ok tuple containing
a map with at least two keys:
:num_rows- the number of rows affected:rows- the result set as a list.nilmay be returned instead of the list if the command does not yield any row as result (but still yields the number of affected rows, like adeletecommand without returning would)
Options
:log- When false, does not log the query:timeout- Execute request timeout, accepts::infinity(default:15000);
Examples
iex> MyRepo.query("SELECT $1::integer + $2", [40, 2])
{:ok, %{rows: [[42]], num_rows: 1}}
iex> Ecto.Adapters.SQL.query(MyRepo, "SELECT $1::integer + $2", [40, 2])
{:ok, %{rows: [[42]], num_rows: 1}}
@spec query!(iodata(), Ecto.Adapters.SQL.query_params(), Keyword.t()) :: Ecto.Adapters.SQL.query_result()
Same as query/3 but returns result directly without :ok tuple
and raises on invalid queries
@spec query_many(iodata(), Ecto.Adapters.SQL.query_params(), Keyword.t()) :: {:ok, [Ecto.Adapters.SQL.query_result()]} | {:error, Exception.t()}
Runs a custom SQL query that returns multiple results on the given repo.
In case of success, it must return an :ok tuple containing a list of
maps with at least two keys:
:num_rows- the number of rows affected:rows- the result set as a list.nilmay be returned instead of the list if the command does not yield any row as result (but still yields the number of affected rows, like adeletecommand without returning would)
Options
:log- When false, does not log the query:timeout- Execute request timeout, accepts::infinity(default:15000);
Examples
iex> MyRepo.query_many("SELECT $1; SELECT $2;", [40, 2])
{:ok, [%{rows: [[40]], num_rows: 1}, %{rows: [[2]], num_rows: 1}]}
iex> Ecto.Adapters.SQL.query_many(MyRepo, "SELECT $1; SELECT $2;", [40, 2])
{:ok, [%{rows: [[40]], num_rows: 1}, %{rows: [[2]], num_rows: 1}]}
@spec query_many!(iodata(), Ecto.Adapters.SQL.query_params(), Keyword.t()) :: [ Ecto.Adapters.SQL.query_result() ]
Same as query_many/4 but returns result directly without :ok tuple
and raises on invalid queries
Callback implementation for Ecto.Repo.reload/2.
Callback implementation for Ecto.Repo.reload!/2.
Returns the module for the configured read replica. Based on https://hexdocs.pm/ecto/replicas-and-dynamic-repositories.html
There is a single replica repo because AlloyDB's read pool sits behind one endpoint and balances each connection across its nodes itself — a second Ecto repo pointed at the same host bought no extra parallelism, only double the connections.
Says whether the replica has replayed the write-ahead log up to lsn.
Call it on the connection that then does the read, because each node of the read pool
replays the log on its own and thus has its own replay position. Wrap both in
without_statement_timeout/2, which checks out one connection for the whole closure.
There is no replication to wait for when the repo is not a replica, which happens in
development, in test, and in a single node deployment. This returns true in that case.
pg_is_in_recovery() is what identifies a replica: a server that was promoted keeps
a pg_last_wal_replay_lsn() from before the promotion, thus a NULL check alone would
make a primary look like a replica that lags forever.
Callback implementation for Ecto.Repo.rollback/1.
Callback implementation for Ecto.Repo.start_link/1.
Callback implementation for Ecto.Repo.stop/1.
@spec to_sql(:all | :update_all | :delete_all, Ecto.Queryable.t()) :: {String.t(), Ecto.Adapters.SQL.query_params()}
Converts the given query to SQL according to its kind and the adapter in the given repository.
Examples
The examples below are meant for reference. Each adapter will return a different result:
iex> MyRepo.to_sql(:all, Post)
{"SELECT p.id, p.title, p.inserted_at, p.created_at FROM posts as p", []}
iex> MyRepo.to_sql(:update_all, from(p in Post, update: [set: [title: ^"hello"]]))
{"UPDATE posts AS p SET title = $1", ["hello"]}
iex> Ecto.Adapters.SQL.to_sql(:all, MyRepo, Post)
{"SELECT p.id, p.title, p.inserted_at, p.created_at FROM posts as p", []}
Callback implementation for Ecto.Repo.transact/2.
@spec transaction_with_lock_retry( module(), integer() | binary(), (struct() -> term()), keyword() ) :: {:ok, term()} | {:error, Vetspire.Error.t() | term()}
Locks a row FOR UPDATE, then runs fun with it inside a transaction, retrying the lock a
bounded number of times when the row is already locked.
The lock is the first statement, so a retry that never acquires the lock never runs fun -
there are no double effects to guard against.
Returns {:ok, result} on success (same shape as transaction/2). When the lock is still
held after the last retry, returns {:error, %Vetspire.Error{code: :locked}} - the shape the
billing callers already expect. A Repo.rollback from fun passes through unchanged. A
non-lock error is reraised.
Inside an outer transaction this never retries (see :retries below). A lock failure there
returns {:error, %Vetspire.Error{code: :locked}} for the caller to roll back. A retry would
be futile, because the failed lock statement already aborted the Postgres subtransaction.
Options:
:retries- lock retries after the first attempt (default 1). Forced to 0 inside an outer transaction, so a swallowed lock error cannot taint it.:sleep_ms- sleep between retries (default 100).:lock_timeout_ms- lock wait per attempt (default 50).
Callback implementation for Ecto.Repo.update/2.
Callback implementation for Ecto.Repo.update!/2.
Callback implementation for Ecto.Repo.update_all/3.
@spec use_read_replica?() :: boolean()
@spec without_statement_timeout(module(), (-> result)) :: result when result: var
Runs the given closure with the server-side statement_timeout disabled.
Each deployment caps statement_timeout via DB_STATEMENT_TIMEOUT_SECONDS so an
abandoned query stops burning database resources once nobody is waiting on it. A few
batch workloads — monthly subscription billing, accounts receivable reports — run past
that cap by design. A client-side :timeout cannot help them: it only stops the caller
waiting, it never cancels the query server-side, so lifting the server cap for the
duration is the only thing that lets one finish.
The connection is checked out for the whole closure so every query inside runs on the
same connection, and the previous timeout is restored afterwards even if the closure
raises. Pass replica/0 to lift the cap on the read replica rather than the primary;
because there is a single replica repo, nested replica/0 calls resolve to that same
repo and reuse the checked-out connection.
Queries issued from processes spawned inside the closure (Task, Oban jobs) check out
their own connections and are not covered.