PgRest.Executor (PgRest v0.2.0)

Copy Markdown View Source

Runs compiled statements against the repo: one statement per read, count modes, the request transaction, statement-cache promotion and error translation.

Every PgRest repo call goes through repo_opts/2, which merges log: false and telemetry_event: nil for statements (Ecto's query events carry the bind parameters, so they reach neither the logger nor repo telemetry handlers; [:pgrest, :query] replaces them), telemetry_options: [pgrest: true], the PgRest.StatementCache options and, when statement_timeout is set, a client timeout one second above it.

Config

A map with :statement_cache (see PgRest.StatementCache) and :statement_timeout (a Postgres interval string such as "5s"); missing keys take the plug defaults. config/3 adds the transaction setup (transaction/4) and :authenticated?, which decides a 42501's 401 or 403.

Telemetry

[:pgrest, :query] is a span around each statement with %{sql, params_count, prepared} metadata and %{rows, error_kind} added on stop (error_kind is nil, or :database, :connection or :internal for a failure). Parameter values are never included.

Summary

Functions

Runs a statement returning one integer (the write check's count).

Prefer: handling=strict, max-affected=n: {:error, PGRST124} when affected, the rows the statement affected, is over n (the caller's transaction then rolls back), else :ok. Lenient handling ignores max-affected. A write passes the rows it wrote (written), never the rows its select= returns, which an aggregate can collapse; a call passes its result rows.

The vnd.pgrst.object+json media type needs exactly one row: PGRST116 otherwise. Checked inside the request transaction (a write or a volatile call is then rolled back), before ensure_max_affected/2, as PostgREST orders them.

Runs an EXPLAIN statement (PgRest.SQL.Explain.wrap/2) and returns the plan as the response body: for FORMAT JSON the single QUERY PLAN value re-encoded with Jason ([{"Plan":...}]), for FORMAT TEXT the rows joined with a newline. Like every statement it passes log: false (repo_opts/2); the plan shows the bound values, which is why the plan media type is gated (PgRest.Negotiate). Meant for the request transaction, so that ANALYZE of a write is rolled back with it.

The request transaction around explain/3 of statement explained as spec (PgRest.SQL.Explain.wrap/2): an analyze of a write rolls back with it under Prefer: tx=rollback, and none of a result's checks run.

Milliseconds of a Postgres interval string ("50ms", "5s", "2min", "1h", "1d"; a bare integer is milliseconds): {:ok, ms}, or :error for anything else.

Runs a read statement and resolves the total for count.

Runs fun in a transaction opened with one setup statement, SELECT set_config(...), that sets search_path (config :search_path, a list of schemas), then config :role_settings ([{name, value}], both bound) and :gucs ([{name, value}]: RLS mode's role and request.*, PgRest.Auth), transaction_read_only when config :read_only? is true, statement_timeout when configured and timezone for a Prefer: timezone (config :timezone), all transaction-local, every value a bind parameter. There is never a separate SET TRANSACTION: a write under read_only? fails with Postgres' 25006. Config :pre_request (a SELECT "schema"."fn"() statement) then runs before fun.

Runs a write statement (see PgRest.SQL.Write), which returns one row of total, page_total, body, pgrst_keys (the written keys as JSON text, or nil) and pgrst_inserted (the rows an upsert really inserted, or nil) and pgrst_written (rows the mutation wrote, whatever the representation then shows), pgrst_matched (the payload elements a PUT matched, or nil), then the decoded response GUCs (PgRest.ResponseGucs).

Types

result()

@type result() :: %{
  body: String.t(),
  page_total: non_neg_integer(),
  total: non_neg_integer() | nil,
  gucs: PgRest.ResponseGucs.decoded()
}

Functions

count(repo, arg, config)

@spec count(module(), {String.t(), [term()]}, map()) ::
  {:ok, non_neg_integer()} | {:error, PgRest.Error.t()}

Runs a statement returning one integer (the write check's count).

ensure_max_affected(prefer, affected)

@spec ensure_max_affected(PgRest.Prefer.t(), non_neg_integer()) ::
  :ok | {:error, PgRest.Error.t()}

Prefer: handling=strict, max-affected=n: {:error, PGRST124} when affected, the rows the statement affected, is over n (the caller's transaction then rolls back), else :ok. Lenient handling ignores max-affected. A write passes the rows it wrote (written), never the rows its select= returns, which an aggregate can collapse; a call passes its result rows.

ensure_single(arg1, arg2)

@spec ensure_single(PgRest.MediaType.t(), %{
  :page_total => non_neg_integer(),
  optional(atom()) => term()
}) :: :ok | {:error, PgRest.Error.t()}

The vnd.pgrst.object+json media type needs exactly one row: PGRST116 otherwise. Checked inside the request transaction (a write or a volatile call is then rolled back), before ensure_max_affected/2, as PostgREST orders them.

explain(repo, arg, config \\ %{})

@spec explain(module(), {String.t(), [term()]}, map()) ::
  {:ok, String.t()} | {:error, PgRest.Error.t()}

Runs an EXPLAIN statement (PgRest.SQL.Explain.wrap/2) and returns the plan as the response body: for FORMAT JSON the single QUERY PLAN value re-encoded with Jason ([{"Plan":...}]), for FORMAT TEXT the rows joined with a newline. Like every statement it passes log: false (repo_opts/2); the plan shows the bound values, which is why the plan media type is gated (PgRest.Negotiate). Meant for the request transaction, so that ANALYZE of a write is rolled back with it.

explain_transaction(repo, prefer, statement, spec, config)

@spec explain_transaction(
  module(),
  PgRest.Prefer.t(),
  {String.t(), [term()]},
  map(),
  map()
) ::
  {:ok, String.t()} | {:error, PgRest.Error.t()}

The request transaction around explain/3 of statement explained as spec (PgRest.SQL.Explain.wrap/2): an analyze of a write rolls back with it under Prefer: tx=rollback, and none of a result's checks run.

interval_ms(interval)

@spec interval_ms(String.t()) :: {:ok, pos_integer()} | :error

Milliseconds of a Postgres interval string ("50ms", "5s", "2min", "1h", "1d"; a bare integer is milliseconds): {:ok, ms}, or :error for anything else.

read(repo, arg, count, plan, config \\ %{})

@spec read(
  module(),
  {String.t(), [term()]},
  atom() | nil,
  PgRest.Plan.Read.t(),
  map()
) ::
  {:ok, result()} | {:error, PgRest.Error.t()}

Runs a read statement and resolves the total for count.

planned runs EXPLAIN (FORMAT JSON) on the count subquery. estimated follows PostgREST: the exact count is bounded by max_limit + 1; above max_limit (or with no max_limit) the larger of the exact count and the planner's estimate is used. An RPC runs no further query: its estimated total is exact and its planned total is nil.

transaction(repo, prefer, fun, config \\ %{})

@spec transaction(module(), PgRest.Prefer.t(), (-> result), map()) ::
  result | {:error, PgRest.Error.t()}
when result: term()

Runs fun in a transaction opened with one setup statement, SELECT set_config(...), that sets search_path (config :search_path, a list of schemas), then config :role_settings ([{name, value}], both bound) and :gucs ([{name, value}]: RLS mode's role and request.*, PgRest.Auth), transaction_read_only when config :read_only? is true, statement_timeout when configured and timezone for a Prefer: timezone (config :timezone), all transaction-local, every value a bind parameter. There is never a separate SET TRANSACTION: a write under read_only? fails with Postgres' 25006. Config :pre_request (a SELECT "schema"."fn"() statement) then runs before fun.

fun returns the response. An {:error, _} result, or prefer.tx == :rollback, rolls the transaction back and still returns the computed result. A database or connection failure becomes {:error, %PgRest.Error{}}.

write(repo, arg, config)

@spec write(module(), {String.t(), [term()]}, map()) ::
  {:ok,
   %{
     body: String.t() | nil,
     page_total: non_neg_integer(),
     keys: String.t() | nil,
     inserted: integer() | nil,
     written: non_neg_integer(),
     matched: non_neg_integer() | nil,
     gucs: PgRest.ResponseGucs.decoded()
   }}
  | {:error, PgRest.Error.t()}

Runs a write statement (see PgRest.SQL.Write), which returns one row of total, page_total, body, pgrst_keys (the written keys as JSON text, or nil) and pgrst_inserted (the rows an upsert really inserted, or nil) and pgrst_written (rows the mutation wrote, whatever the representation then shows), pgrst_matched (the payload elements a PUT matched, or nil), then the decoded response GUCs (PgRest.ResponseGucs).

A :query_meta map in config is merged into the [:pgrest, :query] metadata.