Vetspire.Repo (vetspire v3.0.0)

View Source

Summary

Functions

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.delete/2.

Callback implementation for Ecto.Repo.delete!/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.load/2.

Fetch a single row by id with a row lock applied. Allowed locks

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.

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.

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.

Runs the given closure with the server-side statement_timeout disabled.

Functions

aggregate(queryable, aggregate, field, opts)

Callback implementation for Ecto.Repo.aggregate/4.

all_by(queryable, clauses, opts \\ [])

Callback implementation for Ecto.Repo.all_by/3.

as_virtual_table!(schema, query)

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.

checked_out?()

Callback implementation for Ecto.Repo.checked_out?/0.

checkout(fun, opts \\ [])

Callback implementation for Ecto.Repo.checkout/2.

child_spec(opts)

config()

Callback implementation for Ecto.Repo.config/0.

current_wal_lsn()

@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.

cursor_stream(query, opts \\ [])

See Elixir.Vetspire.Repo.CursorStream.cursor_stream/2 for more information.

default_lock_timeout_ms()

@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.

default_options(operation)

Callback implementation for Ecto.Repo.default_options/1.

delete(struct, opts \\ [])

Callback implementation for Ecto.Repo.delete/2.

delete!(struct, opts \\ [])

Callback implementation for Ecto.Repo.delete!/2.

delete_all(queryable, opts \\ [])

Callback implementation for Ecto.Repo.delete_all/2.

disconnect_all(interval, opts \\ [])

@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.

dry_run!(closure)

Runs the given closure inside a transaction and returns the result without persisting

ecto_middleware()

explain(operation, queryable, opts \\ [])

@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:

AdapterSupported opts
Postgrexanalyze, verbose, costs, settings, buffers, timing, summary, format, plan, wrap_in_transaction
MyXQLformat, wrap_in_transaction

All options except format are boolean valued and default to false.

The allowed format values are :map, :yaml, and :text:

  • :map is the deserialized JSON encoding.
  • :yaml and :text return the result as a string.

The built-in adapters support the following formats:

  • Postgrex: :map, :yaml and :text
  • MyXQL: :map and :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:

explain_query(query, opts \\ [])

@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()

force_read_replica(enabled? \\ true)

@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.

forget(struct, fields, cardinality \\ :one)

@spec forget(map(), atom() | [atom()], :one | :many) :: map()

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)

get_dynamic_repo()

Callback implementation for Ecto.Repo.get_dynamic_repo/0.

get_lock_for_update(schema, id, lock \\ :nowait, opts \\ [])

@spec get_lock_for_update(module(), integer() | binary(), :nowait | :wait, keyword()) ::
  struct() | nil | {:error, term()}

in_transaction?()

Callback implementation for Ecto.Repo.in_transaction?/0.

init(_, opts)

Dynamically loads the repository url from the DATABASE_URL environment variable.

insert(struct, opts \\ [])

Callback implementation for Ecto.Repo.insert/2.

insert!(struct, opts \\ [])

Callback implementation for Ecto.Repo.insert!/2.

insert_all(schema_or_source, entries, opts \\ [])

Callback implementation for Ecto.Repo.insert_all/3.

insert_or_update(changeset, opts \\ [])

Callback implementation for Ecto.Repo.insert_or_update/2.

insert_or_update!(changeset, opts \\ [])

Callback implementation for Ecto.Repo.insert_or_update!/2.

list_preloads(struct)

load(schema_or_types, data)

Callback implementation for Ecto.Repo.load/2.

lock_for_update!(schema, id, lock \\ :nowait, opts \\ [])

@spec lock_for_update!(module(), integer() | binary(), :nowait | :wait, keyword()) ::
  struct()

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.

paginate(queryable, opts \\ [], repo_opts \\ [])

prepare_query(operation, query, opts)

Callback implementation for Ecto.Repo.prepare_query/3.

prepare_transaction(fun_or_multi, opts)

Callback implementation for Ecto.Repo.prepare_transaction/2.

put_dynamic_repo(dynamic)

Callback implementation for Ecto.Repo.put_dynamic_repo/1.

query(sql, params \\ [], opts \\ [])

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. nil may 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 a delete command 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}}

query!(sql, params \\ [], opts \\ [])

Same as query/3 but returns result directly without :ok tuple and raises on invalid queries

query_many(sql, params \\ [], opts \\ [])

@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. nil may 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 a delete command 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}]}

query_many!(sql, params \\ [], opts \\ [])

Same as query_many/4 but returns result directly without :ok tuple and raises on invalid queries

reload(queryable, opts \\ [])

Callback implementation for Ecto.Repo.reload/2.

reload!(queryable, opts \\ [])

Callback implementation for Ecto.Repo.reload!/2.

replica()

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.

replica_caught_up?(repo, lsn)

@spec replica_caught_up?(module(), String.t()) :: boolean()

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.

rollback(value)

@spec rollback(term()) :: no_return()

Callback implementation for Ecto.Repo.rollback/1.

start_link(opts \\ [])

Callback implementation for Ecto.Repo.start_link/1.

stop(timeout \\ 5000)

Callback implementation for Ecto.Repo.stop/1.

to_sql(operation, queryable)

@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", []}

transact(fun_or_multi, opts \\ [])

Callback implementation for Ecto.Repo.transact/2.

transaction_with_lock_retry(schema, id, fun, opts \\ [])

@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).

update(struct, opts \\ [])

Callback implementation for Ecto.Repo.update/2.

update!(struct, opts \\ [])

Callback implementation for Ecto.Repo.update!/2.

update_all(queryable, updates, opts \\ [])

Callback implementation for Ecto.Repo.update_all/3.

use_read_replica?()

@spec use_read_replica?() :: boolean()

without_statement_timeout(repo \\ __MODULE__, fun)

@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.