# PgRest v0.3.0 - Table of Contents

> A PostgREST and Supabase-compatible REST API powered by Elixir and Ecto.

## Pages

- [PgRest](readme.md)
- [Changelog](changelog.md)

- Guides
  - [Configuration](configuration.md)
  - [Resources](resources.md)
  - [Functions and RPC](rpc.md)
  - [Filtering Ecto queries](ecto-filter.md)
  - [Authorization and RLS](authorization-and-rls.md)
  - [PostGIS and GeoJSON](postgis.md)
  - [Compatibility](compatibility.md)
  - [Telemetry](telemetry.md)
  - [Testing](testing.md)
  - [PG16 to PG17 recording drift](pg17-drift.md)
  - [Upgrading from 0.1 to 0.2](upgrading-0-1-to-0-2.md)

## Modules

- [PgRest](PgRest.md): PostgREST-compatible REST API and query-building engine for Elixir.

- [PgRest.AST](PgRest.AST.md): Structs produced by the PostgREST grammar parsers (filters, logic trees, select and order).

- [PgRest.AST.Aggregate](PgRest.AST.Aggregate.md): A `select=` aggregate: `count()`, `col.sum()`, `alias:col::text.avg()::int`.
- [PgRest.AST.Condition](PgRest.AST.Condition.md): A single `field op value` filter.
- [PgRest.AST.Embed](PgRest.AST.Embed.md): A `select=` embedded resource: `alias:rel!hint!inner(...)`, or a spread
(`...rel(...)`). An empty embed `rel()` has `select: []`.

- [PgRest.AST.Field](PgRest.AST.Field.md): A column reference with an optional JSON path, e.g. `data->a->>b` or `arr->0`.

- [PgRest.AST.Logic](PgRest.AST.Logic.md): An `and`/`or` node of a logic tree, optionally negated (`not.and`, `not.or`).

- [PgRest.AST.OrderTerm](PgRest.AST.OrderTerm.md): One `order=` term: `field.desc.nullsfirst`, or `rel(field).asc` which orders by a
column of the to-one embed `rel`.

- [PgRest.AST.SelectField](PgRest.AST.SelectField.md): A `select=` column: `alias:field::cast`, or `:star` for `*`.

- [PgRest.Auth](PgRest.Auth.md): Who a request runs as: RLS mode's bearer token, role allowlist and request GUCs
(`PgRest.Plug`'s `rls:` option), or, without it, the `anonymous?` predicate.
- [PgRest.Authorization](PgRest.Authorization.md): Behavior for pluggable authorization in PgRest.
- [PgRest.Authorization.Apply](PgRest.Authorization.Apply.md): Applies a policy to one scoped source. `Authorization.check/5` runs first; the query
callback can only narrow the base query. Columns are physical database column names.
- [PgRest.Authorization.State](PgRest.Authorization.State.md): Internal authorization data carried by requests and plans, never user context.
- [PgRest.BodyReader](PgRest.BodyReader.md): A `Plug.Parsers` body reader that keeps the raw request body.
- [PgRest.Cache](PgRest.Cache.md): Owns the node-wide ETS caches every `PgRest.Plug` and `PgRest.Registry` share: the
compiled scoped SQL (`PgRest.SQL.ScopedSource`) and the prepared-statement promotion
table (`PgRest.StatementCache`).
- [PgRest.Catalog](PgRest.Catalog.md): Reads metadata about registered tables from the PostgreSQL catalogs.
- [PgRest.Catalog.Facts](PgRest.Catalog.Facts.md): Server-wide facts `PgRest.Catalog.facts/1` reads once per repo: the timezone names
`Prefer: timezone` accepts, the server version, whether the login role bypasses RLS, the
`ALTER ROLE ... SET` settings of the roles it may switch to (`%{role => [{name, value}]}`),
and `postgis`: `%{schema: schema, version: version}` of the PostGIS extension, `nil`
without it (`application/geo+json` is offered only when it is set).

- [PgRest.Ecto.Filter](PgRest.Ecto.Filter.md): Compiles PostgREST filter AST nodes (`PgRest.AST.Condition`, `PgRest.AST.Logic`) into
`Ecto.Query.dynamic/2` expressions, for applications that parse PostgREST filters with
`PgRest.Grammar.Filter` and run the query through their own Ecto code instead of
`PgRest.Plug`.
- [PgRest.Error.Translate](PgRest.Error.Translate.md): Translates exceptions into `PgRest.Error`, mapping Postgres SQLSTATEs to HTTP
statuses the way PostgREST does.
- [PgRest.Executor](PgRest.Executor.md): Runs compiled statements against the repo: one statement per read, count modes,
the request transaction, statement-cache promotion and error translation.
- [PgRest.Function](PgRest.Function.md): A database function a `PgRest.Registry` exposes for RPC.
- [PgRest.Function.Introspect](PgRest.Function.Introspect.md): Loads `PgRest.Function`s from `pg_proc`, in one statement.
- [PgRest.Function.Param](PgRest.Function.Param.md): An input (`IN`, `INOUT` or `VARIADIC`) parameter of a `PgRest.Function`. `name` is `""`
for an unnamed parameter; `type` is `pg_catalog.format_type(oid, NULL)` text.

- [PgRest.Function.Return](PgRest.Function.Return.md): What a `PgRest.Function` returns.
- [PgRest.Grammar.Common](PgRest.Grammar.Common.md): Building blocks shared by the PostgREST grammars: quoted values, identifiers,
field names with JSON paths, tree paths, the cast-name rule, and error helpers.
- [PgRest.Grammar.Filter](PgRest.Grammar.Filter.md): Parser for PostgREST horizontal filters (`col=op.value`) and logic trees
(`or=(a.eq.1,and(...))`).
- [PgRest.Grammar.Order](PgRest.Grammar.Order.md): Parser for the PostgREST `order=` parameter:
`a.desc.nullslast,data->>x,clients(name).asc`.
- [PgRest.Grammar.Select](PgRest.Grammar.Select.md): Parser for the PostgREST `select=` parameter: columns with aliases, `::` casts and
JSON paths, aggregates, and embedded resources (`alias:rel!hint!inner(...)`, spreads
`...rel(...)`, empty embeds `rel()`).
- [PgRest.JWT.HS256](PgRest.JWT.HS256.md): HS256 bearer-token verification (`PgRest.JWT.Verifier`), with PostgREST's errors and claim
rules: `exp`, `nbf` and `iat` are checked with `:leeway` seconds of clock skew, `aud` against
`:audience` when one is set.
- [PgRest.JWT.Verifier](PgRest.JWT.Verifier.md): Verifies the bearer token of an RLS-mode request (`PgRest.Plug`'s `rls: [jwt: {module, opts}]`).
- [PgRest.MediaType](PgRest.MediaType.md): One media type of an `Accept` header, as PostgREST understands it.
- [PgRest.Negotiate](PgRest.Negotiate.md): Picks the response media type of a request from its `Accept` types and what the endpoint
can produce, as PostgREST's content negotiation does.
- [PgRest.Plan](PgRest.Plan.md): The resolved plan of a read: a tree of `PgRest.Plan.Read` nodes joined by
`PgRest.Plan.Embed`. Built by `PgRest.Planner`, compiled by `PgRest.SQL.Read`.

- [PgRest.Plan.Call](PgRest.Plan.Call.md): The function call an RPC read plan reads from (`PgRest.Plan.Read` `source: {:call, call}`),
compiled by `PgRest.SQL.Call`.
- [PgRest.Plan.Embed](PgRest.Plan.Embed.md): An embedded resource: the relationship from the parent, the JSON output name and the
plan of the target. `join_conditions` are the equalities that tie the target to its parent,
resolved by the planner as `{left_alias, left_field, right_alias, right_field}` over the
exposed (Ecto field) column names. `agg_alias` (`"pgrst_e<n>"`, numbered per statement so
it never exceeds 63 bytes) names the lateral that holds the embed's rows, and
`junction_alias` and `junction_source_query` the junction of a many-to-many embed.
- [PgRest.Plan.Read](PgRest.Plan.Read.md): One node of a read plan (the root, or the target of an embed).
- [PgRest.Planner](PgRest.Planner.md): Plans a read: validates the request against the registered resources and resolves it
into a `PgRest.Plan.Read` tree, before any SQL runs.
- [PgRest.Planner.Columns](PgRest.Planner.Columns.md): Per-resource column data for the planner and request-column validation.
- [PgRest.Planner.Params](PgRest.Planner.Params.md): Splits the query string of a read into per-embed-path groups.
- [PgRest.Planner.Result](PgRest.Planner.Result.md): Helpers for planner steps that run over a list and stop at the first error.

- [PgRest.Planner.Tree](PgRest.Planner.Tree.md): The plan tree: embed resolution through the schema graph, authorization of every
resource it touches, and the build of `PgRest.Plan.Read` nodes with their embeds.
- [PgRest.Plug](PgRest.Plug.md): Phoenix Plug that serves registered PgRest resources, PostgREST style.
- [PgRest.Prefer](PgRest.Prefer.md): The parsed `Prefer` request header.
- [PgRest.RPC.Args](PgRest.RPC.Args.md): Splits an RPC request into function arguments and row filters, as PostgREST's
`pRequestFilter`/`isRpcRead` do, and builds the arguments of the call.
- [PgRest.RPC.Resolver](PgRest.RPC.Resolver.md): Finds the function a `/rpc/<name>` request calls, a port of PostgREST's `Plan.hs` `findProc`
over the registry snapshot's functions.
- [PgRest.Registry](PgRest.Registry.md): GenServer that discovers PgRest resources and database functions at startup and publishes
them as an immutable `PgRest.Registry.Snapshot`.
- [PgRest.Registry.Snapshot](PgRest.Registry.Snapshot.md): The immutable schema cache a `PgRest.Registry` publishes: its resources keyed by
`{schema, table}`, the exposed schemas (the first is the default) and the relationship
graph.
- [PgRest.Request](PgRest.Request.md): A parsed HTTP request: ordered params, `Prefer`, `Range` and the JSON body.
- [PgRest.Request.Accept](PgRest.Request.Accept.md): Parses an `Accept` header into `PgRest.MediaType`s, PostgREST's `Accept` handling.
- [PgRest.Request.Prefer](PgRest.Request.Prefer.md): Parses `Prefer` headers into a `PgRest.Prefer` and renders `Preference-Applied`.
- [PgRest.Request.QueryString](PgRest.Request.QueryString.md): Parses a raw query string into an ordered list of `{key, value}` pairs.
- [PgRest.Request.Range](PgRest.Request.Range.md): Combines the `Range` header with the `limit`/`offset` query parameters into a
single `%{offset, limit}`, porting PostgREST's `getRanges`.
- [PgRest.Resource](PgRest.Resource.md): Behavior for defining PgRest API resources from Ecto schemas.
- [PgRest.Responder](PgRest.Responder.md): Turns results and errors into HTTP responses, following PostgREST.
- [PgRest.ResponseGucs](PgRest.ResponseGucs.md): The `response.headers` and `response.status` GUCs a function, a trigger or a
`pre_request` function sets, as PostgREST's `Response.hs` handles them.
- [PgRest.SQL.Aggregate](PgRest.SQL.Aggregate.md): The aggregate half of the read compiler: aggregate select items, the to-one spread
hoisting and the implicit `GROUP BY`, mirroring PostgREST's `pgFmtApplyAggregate`,
`hoistSpreadAggFunctions` and `groupF`.
- [PgRest.SQL.Builder](PgRest.SQL.Builder.md): Accumulates bind parameters and emits SQL fragments as iodata.
- [PgRest.SQL.Call](PgRest.SQL.Call.md): Compiles the function call of an RPC (`PgRest.Plan.Call`) to the `FROM` item the root of its
read plan reads, following PostgREST's `callPlanToQuery`.
- [PgRest.SQL.Explain](PgRest.SQL.Explain.md): Wraps a compiled statement in `EXPLAIN`, PostgREST's `explainF`: the plan of the statement a
request would run, for the `application/vnd.pgrst.plan` media type.
- [PgRest.SQL.Format](PgRest.SQL.Format.md): The SQL expression of a response `body` column, by media type: PostgREST's `asJsonF`,
`asJsonSingleF`, `addNullsToSnip`, `asCsvF` and `asGeoJsonF`.
- [PgRest.SQL.Placeholders](PgRest.SQL.Placeholders.md): Shifts the `$n` placeholders of a SQL text by an offset.
- [PgRest.SQL.Read](PgRest.SQL.Read.md): Compiles a `PgRest.Plan.Read` tree to one SQL statement, mirroring PostgREST's
`QueryBuilder.readPlanToQuery`.
- [PgRest.SQL.Read.Embed](PgRest.SQL.Read.Embed.md): The embed half of the read compiler: lateral joins, the select items they add, spreads
and `embed=is.null` filters. Called from `PgRest.SQL.Read`, which compiles the child
nodes.
- [PgRest.SQL.ScopedSource](PgRest.SQL.ScopedSource.md): Splices a resource's Ecto-scoped base query into PgRest's hand-built SQL.
- [PgRest.SQL.Where](PgRest.SQL.Where.md): Compiles filter and logic-tree AST nodes (`PgRest.AST.Condition`, `PgRest.AST.Logic`)
to a SQL boolean expression.
- [PgRest.SQL.Write](PgRest.SQL.Write.md): Compiles writes to one SQL statement, mirroring PostgREST's `mutatePlanToQuery`.
- [PgRest.SchemaGraph](PgRest.SchemaGraph.md): The relationship graph over registered resources, with PostgREST's embedding
resolution rules.
- [PgRest.SchemaGraph.Fuzzy](PgRest.SchemaGraph.Fuzzy.md): Fuzzy name matching for the "Perhaps you meant ..." hints, modelled on the
`fuzzyset` library PostgREST uses: gram-count cosine similarity (gram size 3,
then 2), rescored with a Levenshtein ratio.

- [PgRest.SchemaGraph.Relationship](PgRest.SchemaGraph.Relationship.md): One directed relationship between two registered resources, shaped like
PostgREST's schema-cache relationships.
- [PgRest.StatementCache](PgRest.StatementCache.md): Promotes hot SQL texts to named prepared statements.
- [PgRest.Telemetry](PgRest.Telemetry.md): Telemetry events emitted by PgRest.
- [PgRest.Write](PgRest.Write.md): The pipeline shared by every write: insert, upsert, update and delete.
- [PgRest.Write.Insert](PgRest.Write.Insert.md): Serves `POST /<table>`: single and bulk inserts and upserts, on the pipeline in
`PgRest.Write`.
- [PgRest.Write.Modify](PgRest.Write.Modify.md): Serves `PATCH /<table>?<filters>` and `DELETE /<table>?<filters>`, on the pipeline in
`PgRest.Write`.
- [PgRest.Write.Payload](PgRest.Write.Payload.md): Validates and prepares the body of a write for `PgRest.SQL.Write`.
- [PgRest.Write.Put](PgRest.Write.Put.md): Serves `PUT /<table>?<pk>=eq.<value>`: a single-row upsert on the pipeline in
`PgRest.Write.Insert`.

- Exceptions
  - [PgRest.Error](PgRest.Error.md): A PostgREST-shaped error: HTTP status plus the `code`, `message`, `details` and
`hint` body fields. `headers` are response headers the error carries: `PgRest.Responder`
sends them without adding an authentication challenge. A headerless PgRest 401
defaults to `www-authenticate: Bearer`; `custom_headers?: true` preserves an empty
custom RAISE header map without that default.

