PgRest.Plug (PgRest v0.2.0)

Copy Markdown View Source

Phoenix Plug that serves registered PgRest resources, PostgREST style.

Usage

# In your router:
forward "/api", PgRest.Plug, repo: MyApp.Repo

Routes are /<table> and /rpc/<function>. A POST is an insert (PgRest.Write.Insert), a PUT a single-row upsert (PgRest.Write.Put); PATCH and DELETE act on the rows the query-string filters select (PgRest.Write.Modify). /rpc/<function> calls a registered PgRest.Function: GET/HEAD read-only with the query string's arguments, POST with the body's (PgRest.Planner.plan_call/3). A read (GET, HEAD) flows PgRest.Request -> PgRest.Planner -> PgRest.SQL.Read -> PgRest.Executor -> PgRest.Responder: one SQL statement inside one short transaction.

Options

  • :repo (required) - the Ecto repo module
  • :registry - the PgRest.Registry whose resources the plug serves (default PgRest.Registry). Requests pick a schema of that registry with Accept-Profile (reads) or Content-Profile (writes); without one they get its default schema.
  • :context_builder - (conn, opts) -> context_map for the context passed to scope/2, after_load/2 and the authorization module (default: the repo plus user_id, role, tenant_id and assigns from conn.assigns). It runs once per served request after parsing, with the schema graph in opts; only RLS mode with jwt: :context needs it before routing (without graph). The plug overrides repo, authorization, max_limit, max_embed_depth, aggregates, plan_enabled, count_modes, graph and authenticated?; only RLS mode also sets jwt_claims and db_role.
  • :authorization - a PgRest.Authorization module (default nil)
  • :require_filters_for_mutations - true (default) rejects PATCH/DELETE without a filter
  • :max_limit - clamps every node's row count, like PostgREST's db-max-rows (default nil)
  • :max_embed_depth - deepest embed nesting (default 8)
  • :max_body_bytes - request body limit (default 8_000_000)
  • :max_bulk_rows - rows accepted in one bulk write (default 10_000)
  • :count_modes - allowed Prefer: count= modes (default [:exact, :planned, :estimated])
  • :tx_end - :commit (default) ignores Prefer: tx=; :commit_allow_override honors it
  • :statement_cache - [promote_after: 3, max: 500] (default) or false, see PgRest.StatementCache
  • :statement_timeout - a Postgres interval such as "5s" (default nil). Set inside every request transaction. Reads run in a transaction too, but a dedicated repo configured with parameters: [statement_timeout: ...] is the belt and braces.
  • :aggregates - true allows aggregate functions in select= (count(), col.sum(), ...), like PostgREST's db-aggregates-enabled; false (default) makes any aggregate, at any depth, a 400 PGRST123. The legacy bare count column is no aggregate, as upstream.
  • :plan_enabled - serves application/vnd.pgrst.plan (execution plans, which show bound values), like PostgREST's db-plan-enabled: false (default), true, or a (conn, context -> boolean) function. Otherwise a 406 PGRST107. See PgRest.Negotiate for the :explain and analyze gates.
  • :rls - RLS mode (default nil): every request runs as a database role from its JWT, with PostgREST's request GUCs and an optional pre_request function. See PgRest.Auth.
  • :anonymous? - without :rls, (conn, context -> boolean) deciding whether a request is anonymous, so a 42501 is a 401, else a 403 (default &PgRest.Auth.default_anonymous?/2).

A request for an operation the resource's allow: excludes is a 42501 (401, or 403 when authenticated), but only after the query string is parsed (a malformed filter is a PGRST100 first, as in PostgREST); a denied request still reads a bounded body (at most :max_body_bytes).

init/1 validates every key and value and raises ArgumentError otherwise.

OPTIONS answers with an Allow header and no body, from the registry alone: no transaction, no authorization, no [:pgrest, :query] event. It checks the profile and the filters and order of the query string first, as PostgREST does. /<table> allows the methods the resource's allow: permits (OPTIONS, GET and HEAD always, PUT only with a primary key), / allows OPTIONS,GET,HEAD, and /rpc/<function> allows OPTIONS,POST for a volatile function and OPTIONS,GET,HEAD,POST otherwise. Any other method is a 405 PGRST117.

Differences from PostgREST

  • OPTIONS sends no CORS headers: PostgREST always adds Access-Control-Allow-Origin: *, and Access-Control-Allow-Methods/Max-Age on a preflight (Access-Control-Request-*), which PgRest does not treat specially. Serve CORS from the host app.
  • Allow is narrowed by allow: (a resource with allow: [:read] answers OPTIONS,GET,HEAD); PostgREST has no allow: and narrows it for views without the matching trigger. The authorization module is not consulted, as in PostgREST.
  • OPTIONS /rpc/<f> with select= does not resolve the select's embeds: ?select=*,nope(*) is a 200, where PostgREST plans it and answers 400 PGRST200. ?select=id&clients.id=eq.1 and ?select=&a.b=eq.1 also return 200 instead of PostgREST's 400 PGRST108: PgRest skips embed-path checks when select is present.

Summary

Functions

Serves /<table> requests; any other path is a 404.

The default of an option (see the moduledoc), delegated to the shared options table.

Validates the options and fills the defaults.

Functions

call(conn, opts)

@spec call(Plug.Conn.t(), map()) :: Plug.Conn.t()

Serves /<table> requests; any other path is a 404.

default(key)

@spec default(atom()) :: term()

The default of an option (see the moduledoc), delegated to the shared options table.

init(opts)

@spec init(keyword()) :: map()

Validates the options and fills the defaults.

Raises ArgumentError for an unknown key or an invalid value.