Repository navigation
Releases
v0.4.0
What's Changed
- test(harness): read PGHOST, PGPORT and PGDATABASE in ConformanceServer.base_opts by @milmazz in #169
- test: make DbSettingsTest's role cleanup best-effort by @milmazz in #170
- test(harness): give recv_until an overall deadline, and share the WAL helpers by @milmazz in #171
- fix(wal): authorize table subscriptions without waiting on relation locks by @milmazz in #168
- chore: #155 cleanup batch, PostgreSQL 18 in CI, and the Dockerfile on Elixir 1.20 by @milmazz in #172
- test: use the shared WAL helper in the #168 authorization tests by @milmazz in #173
- Sync the conformance pin to v16.6.0-suite.1 (PostgREST v16.6, 860 cases) by @milmazz in #174
- chore: release v0.4.0 by @milmazz in #188
Full Changelog: v0.3.0...v0.4.0
v0.3.0
The headline is the WAL change feed: GET /events?table=<name> streams
typed row changes straight from PostgreSQL's write-ahead log, with cursor
resume, alongside the existing NOTIFY channels (see the
Realtime tutorial and the
Realtime events guide). The conformance
target also moves from PostgREST v16.0 to v16.4.
Upgrading from 0.2. Two changes can break a setup that worked:
- Aggregate functions in
selectare now off by default, as in PostgREST
v16. Setdb_aggregates_enabled: true(or
PGRST_DB_AGGREGATES_ENABLED=true) to keep using them. Bier.CLI.run/2and twoBier.Embedfunctions changed shape. This only
matters if you call those modules directly.
One behavior change is worth knowing about as well: an SSE subscription now
ends when the JWT that opened it expires, instead of living on indefinitely.
Details for all three are under Changed below.
Added
db_aggregates_enabled(PostgRESTdb-aggregates-enabled,
PGRST_DB_AGGREGATES_ENABLED, defaultfalse): gates aggregate functions in
a request'sselect. When off, any aggregate — including one inside a spread
embed — is rejected with 400PGRST123, matching PostgREST v16. When on,
aggregates on a one-to-many or many-to-many spread are rejected with 400
PGRST127. Settable from the environment, the config file and — as
upstream'sdbSettingsNamesallows — the in-database config source.- Aggregates inside spread embeds now hoist the enclosing
GROUP BY, so
select=total:amount.sum(),...category(owner)groups by the spread's columns
instead of erroring or returning ungrouped rows. - WAL change feed on the events endpoint: with
events_publicationnaming an
operator-created publication,GET /events?table=<name>streams typed
INSERT/UPDATE/DELETE/TRUNCATE events with row images over SSE — no NOTIFY
payload cap, no triggers. Frames carry an LSN cursor (id:) and reconnects
resume viaLast-Event-IDwithin a bounded in-memory window; anything the
server can no longer replay is announced with an explicitbier:reset
frame, never silently skipped. Subscriptions require SELECT on the table
(column images are filtered per role) and a role the authenticator may
actually assume; tables with RLS refuse subscription in this release. Boot
fails fast (with remediation hints) unlesswal_level=logical, the
publication exists, and the role has REPLICATION. A response carrying a
table subscription also sendsConnection: closeover HTTP/1.1 (the WAL
stream can end at any time, unlike a NOTIFY-only response; the header is
malformed in HTTP/2 and is omitted there). An unknown table, a view,
materialized view or foreign table, and an unpublished, RLS-enabled,
unexposed, or unprivileged table all refuse with the same 404
(BIER003), so the endpoint cannot be used as an existence or privilege
oracle. (The refusals are byte-identical but not time-identical:
configuration-only refusals skip the database round trip the catalog
checks cost, a gap that reveals only configuration.) A
transaction overevents_max_tx_events, or over a fixed 64 MiB of decoded
column values, is dropped with atransaction_too_largereset. - WAL change feed: partitioned tables can be subscribed through a
publication createdWITH (publish_via_partition_root = true)(#140).
GET /events?table=orderson a partitionedordersstreams changes from
every partition, at any depth, named afterorders. PostgreSQL reports
them that way itself, resolved as of each change, soATTACHand
DETACH PARTITIONtake effect at their exact position in the stream.
The partitioned table's own grants, column grants and RLS flag decide the
subscription. Under that setting its leaf partitions are refused with
404 BIER003, because PostgreSQL never names them. Without the setting
it is the other way round: partitioned tables are refused and leaves stay
subscribable as ordinary tables. In general, a table is published to the feed
exactly whenpg_publication_tableslists it.
A cross-partitionUPDATEarrives asDELETEthenINSERT. PostgreSQL
does not publish aTRUNCATEof a single partition in this mode. That gap
cannot be announced per event, so it is documented and logged as a
warning when the feed starts. A second warning at feed start names every
partition whoseREPLICA IDENTITYdiffers from its partitioned table's.
oldandold_kindare labelled and shaped from the partitioned table's
identity, so such a mismatch silently produces wrongolddata: for
example, aDEFAULTpartition under aFULLparent reports
never-logged columns asnull. Both warnings only read the catalogs,
take no relation locks, and are skipped with a logged reason if they
fail, so they can neither block nor fail boot. GET /ready/walon the admin server reports on the WAL change feed alone:
200while it runs,503once it has been given up on,404when the
instance has noevents_publication;Bier.Health.wal_feed/1is the same
answer in code./readyis unchanged and still means "the API can serve",
so a stopped feed does not take a working instance out of rotation, while
operators can alert on, or routetable=subscriptions by, the feed itself
(#166).events_publicationis validated at boot: it must be a non-empty
identifier of at most 63 bytes with no quotes, backslashes, or null bytes.bier:is a reservedevent:prefix:events_channelsentries claiming
it are refused at boot, and atable=subscription naming such a table is
refused like any other unavailable table. Without the reservation a
channel or table could emit a frame a client reads as a control message.db_schemasis validated at boot: the list must be non-empty and no entry
may be blank. An empty list previously aborted the schema-cache load with an
opaqueFunctionClauseErrorbehind a PGRST002 log, and a blank entry booted
a working instance whose default schema silently resolved nothing. Both are
Bier-only rules — PostgREST's comma-separateddb-schemascannot express an
empty list — so they run at boot only and--dump-configstill prints
whatever it parsed (#143).jwt_role_claim_keyaccepts the pre-v16 leading-dot JSPath syntax again
(.roles.user_role,."https://x"[0],.roles[?(@ ^== "app_")]), as
PostgREST v16.2 ([PostgREST#5171][pgrst-5171]) does: a value the RFC 9535
parser rejects falls back to the old grammar — keys, quoted keys, indexes and
one trailing==/!=/^==/==^/*==string filter — and the role is the
first match. Such a value logs a deprecationWARNINGat boot (also written
to stderr by--dump-config) and dumps with every key quoted
(."roles"."user_role"). A value neither grammar accepts stays fatal.jwt-cache-max-entriescan be set from the in-database config source
(ALTER ROLE … SET pgrst.jwt_cache_max_entries), matching PostgREST v16.4
([PostgREST#5269][pgrst-5269]), whosedbSettingsNamespreviously listed a
key no parser reads in its place.- PGRST200 ("Could not find a relationship…") errors now carry PostgREST's fuzzy
hint, which was previously alwaysnull. It is a suggestion computed off the
schema cache rather than an echo of the request's own!hint: a near-miss child
drawn from the origin's own relationships when the origin participates in any,
and a near-miss parent drawn from the relationships map's keys when it does not
(Error.hsL320-331). Both sit at fuzzyset's default 0.33 minimum score —
markedly more permissive than the 0.75 gate PGRST205's table hint uses — with
the exact-hit short-circuit and< 1.0guard reproduced, so an embed naming a
relation that really is related still yields no hint (cases 1527/1529/1530).
Changed
- Breaking: aggregate functions in
selectare now disabled by default.
They were previously always available; PostgREST v16 defaults
db-aggregates-enabledto off and answers 400PGRST123, and Bier now
matches. Setdb_aggregates_enabled: true(or
PGRST_DB_AGGREGATES_ENABLED=true) to restore the old behavior. - Breaking (API):
Bier.CLI.run/2performs the--readyhealth check
itself and returns a result map like every other command, instead of handing
the caller a{:ready, url}directive to probe. InBier.Embed,group_by
takes a fourth argument andbuild_row_selectreturns a 4-tuple carrying the
aggregate metadata. - SSE subscriptions are now bounded by their JWT's
exp(with the same 30s
skew allowance the request path uses) instead of living on indefinitely
after the token that authorized them expired. The[:bier, :events, :subscribe, :stop]span reports this as:reason:token_expired. BIER002's message and hint now mentiontable=alongsidechannel=.- Subscriptions are re-authorized centrally after a schema reload — one
query per distinct role over the union of that role's subscribed tables,
rather than one per subscriber — so a reload applies immediately without
queueing a checkout per subscriber against the connection pool. - The WAL ring buffer stores each table's column metadata once instead of on
every buffered entry. A DDL that changes a table's columns now invalidates
that table's buffered history, so a client resuming across the change gets
an announcedbier:resetrather than rows labelled with the wrong
columns. Last-Event-IDis validated more strictly: LSN halves must fit in 32
bits, signs are rejected, and oversized input is refused before parsing.
An unparseable cursor still just starts the stream at the live head.- A stream the server ends on its own now says why first, with a terminal
event: bier:closedframe (noid:) whosereasonis `...
v0.2.0
Added
db_prepared_statements(PostgRESTdb-prepared-statements,
PGRST_DB_PREPARED_STATEMENTS, defaulttrue): the hot-path statements —
the auth preamble, reads, mutations, and RPC — are cached as named prepared
statements on each pool connection, skipping the parse step when a query
shape repeats. Set it tofalsebehind a transaction-mode pooler such as
PgBouncer (#127).
Changed
- Typed filter values and RPC scalar arguments are now bound as parameters
(($n::text)::<type>) instead of being inlined as escaped literals
('<v>'::<type>). The server-side coercion — and every error it can
raise — is identical (PostgreSQL I/O-conversion casts), the conformance
suite is byte-for-byte unchanged, and it matches the SQL PostgREST
executes ("id" = $1). This is what makes the statement cache effective:
requests differing only in their values now share one SQL text (#127).
Fixed
- PGRST205/PGRST202 not-found errors (and their "Perhaps you meant" hints)
now qualify the missing table/function with the request's active schema,
matching real PostgREST (Error.hsbuildsqi <> "." <> namefrom the
resolved profile). Previously area-mirror schemas were reported as
test.<name>— an assumption the conformance suite's oracle disproved.
Conformancespec/bumped tov16.0.0-suite.3, which pins the corrected
behavior (cases 1360/1368/1373).
Full changelog: v0.1.0...v0.2.0
Hex: https://hex.pm/packages/bier/0.2.0
v0.1.0
First release. Bier serves a RESTful API generated at boot from PostgreSQL
introspection, reproducing the request/response behavior of
PostgREST v16.0.
The API surface
- Reads with the full PostgREST query grammar:
select(columns, aliases,
casts, JSON paths, computed columns, aggregates), horizontal filters and
the operator set, logical trees (and/or, negation, nesting),
quantifiers, ordering,limit/offsetandRangepagination, and
resource embedding (many-to-one, one-to-many, many-to-many,!inner,
spread, aliases, disambiguation). - Mutations —
POSTinsert,PATCHupdate,PUTsingle-row upsert,
DELETE— withPrefer: return=,resolution=,missing=default,
handling=strictandmax-affected=. /rpc/<function>calls overGET/HEAD/POST, rendering every routine
return kind (scalar, composite,SETOF,TABLE(...),void).- Every request compiled into a single parameterized SQL statement whose
response bodies are byte-identical to PostgREST's, row separators and
embedded-JSON internals included. - Content negotiation across
application/json,text/csv,
application/geo+json(relations, mutations, RPC and embedded reads,
wherever PostGIS is installed), thevnd.pgrst.object/arrayvariants
withnulls=stripped, andvnd.pgrst.plan. Prefer: timezone=<tz>for per-requesttimestamptzrendering, including
numeric UTC offsets.- A generated OpenAPI document at the root, with per-role privilege
filtering, an opt-in OpenAPI 3.0.3 emitter (openapi_version: "3.0", a
Bier extension), anddb_root_specto replace it wholesale.
Authentication
- JWT verification through JOSE: HS256/384/512, plus RS/ES/PS/EdDSA from a
JWK or JWK Set, with the algorithm family decided by the key's shape rather
than the token'salgheader. - Role switching and request-scoped GUCs (
request.jwt.claims, headers,
cookies,app.settings.*), applied as a single batched
SELECT set_config(…)statement per request — one database round trip
for the whole preamble, the same shape PostgREST executes. jwt_role_claim_keyas an RFC 9535 JSON Path into the claims,
jwt_secret_is_base64,jwt_aud, and a per-instance verification cache.db_pre_request, run inside the request transaction before the main query.
Operations
- Multiple named instances per BEAM node, each with its own configuration,
connection pool, runtime-built router, and Bandit server. - Schema-cache reload over
LISTEN/NOTIFYandBier.reload_schema_cache/1;
a failed reload leaves the previous snapshot serving. - Standalone operation with no host application: PostgREST-compatible
PGRST_*environment variables, a config-file parser, the in-database
(ALTER ROLE … SET pgrst.*) configuration source, abierescript with
--dump-config/--example, amix releasetarget, and a Dockerfile. - Observability:
:telemetryevents for requests, schema-cache loads, pool
status, JWT cache and SSE; an Apache-combined access log gated by
log_level, with optionallog_query;Server-Timing; a trace-header
passthrough; and/live+/readyon an optional admin listener. - Query cancellation at the PostgreSQL backend when the HTTP client
disconnects (cancel_on_disconnect, on by default) — something PostgREST
cannot do.
Beyond PostgREST
- Realtime events: a config-gated SSE endpoint bridging Postgres
LISTEN/NOTIFYto browsers (events_channels,events_path,
events_heartbeat_interval). PostgREST has no equivalent. Vary: Originon CORS responses that echo the request'sOrigin, which
upstream omits.- RFC 4180 CSV quoting, where upstream emits malformed CSV for values
containing quotes or newlines. Server: bier/<version>and an OpenAPIinfo.versionreporting Bier's
own version. The PostgREST dialect is advertised through the document's
externalDocsinstead.
The README's "Deliberate divergences from PostgREST" section is the
authoritative list; everything else is intended to match upstream byte for
byte.