PgRest.StatementCache (PgRest v0.2.0)

Copy Markdown View Source

Promotes hot SQL texts to named prepared statements.

A node-wide ETS table (owned by PgRest.Cache) counts how often each SQL text is executed, keyed by SQL text and database role (SHA-256). After promote_after sightings the text is promoted. Later executions carry cache_statement: "pgrest_<32 hex chars>", so Postgrex prepares it once per connection. At most max texts are promoted node-wide; once the cap is reached other texts stay unnamed, with no eviction churn. Request-controlled aliases and select shapes can mint unlimited SQL texts, so the cap is what bounds server-side prepared statements: settled promotions never exceed max. Concurrent claims can briefly overshoot the counter, and a claim that loses is rolled back (see confirm/3); a caller that read the loser's name in that window prepares one extra statement on its connection, so the transient excess is bounded by the number of concurrent callers, never by the number of distinct texts. The sightings table is bounded too: whenever a caller finds it above 10 * max entries, the counters of unpromoted texts are cleared.

The cap and the table are node-wide: every PgRest.Plug instance on the node shares them, and the first instance's max that fills the cap wins. The cap holds per lifetime of the table's owner: a restarted PgRest.Cache starts an empty table (and a fresh count), while connections keep the statements they already prepared.

Without the table (the :pgrest application is not started) nothing is promoted, and a warning is logged once.

Role partitions share the same node-wide bound. Prepared plans may fold or inline privileged functions, so a statement prepared for one role must never be reused by another role on the same connection.

With statement_cache: false nothing is promoted.

Differences from PostgREST

Prepared statements are partitioned by database role. PostgREST v14.18 can reuse a privileged role's folded function result for anon after plan caching.

Summary

Functions

The default statement_cache configuration.

Repo options for executing sql: [cache_statement: name] once the text is promoted, [] otherwise.

Types

config()

@type config() :: keyword() | false | nil

Functions

defaults()

@spec defaults() :: keyword()

The default statement_cache configuration.

query_opts(sql, config, role \\ nil)

@spec query_opts(String.t(), config(), String.t() | nil) :: keyword()

Repo options for executing sql: [cache_statement: name] once the text is promoted, [] otherwise.