Skip to content

v0.20.0

Latest

Choose a tag to compare

@eeeebbbbrrrr eeeebbbbrrrr released this 12 Nov 18:37
3e6d5de

Welcome to pgrx v0.20.0. This is a big one, and it's the first production release of the 0.20 series.

pgrx now generates Rust versions of Postgres' C macros and static inline functions during every build, and the hand-written ports are gone. We also fixed a long list of safe APIs that could cause undefined behavior, picked up the CVE-2026-6460 fix from Postgres' November minor releases, dropped Postgres 13 and 14, moved to Postgres 19rc2, and now require Rust 1.99.1. cargo-pgrx can assemble upgrade scripts from SQL fragments and build RPM and DEB packages, and pgrx gained tsvector and tsquery types.

Many of these changes will break existing code, some of them in behavior rather than at compile time. Please read the v0.20.0 Migration Guide before upgrading.

Install with:

$ rustup update stable
$ cargo install cargo-pgrx --version 0.20.0 --locked

Then update your extension's dependencies with cargo pgrx upgrade, and run a plain cargo pgrx init, with no arguments. That downloads and builds the patched Postgres releases: 15.20, 16.16, 17.12, 18.7 and 19rc2.

Builds now need a clang whose major version matches libclang, and should have llvm-ar from the same LLVM release. On Debian-likes that's apt install clang llvm libclang-dev. See Build requirements.

Coming from a beta?

Since beta.1, a generated C macro whose result is a truth value returns a Rust bool, so drop .is_true() from calls like IsA!. PgSqlErrorCode is now #[non_exhaustive]. Composite datums are version-checked when built against the patched Postgres releases. And cargo pgrx init --pg19=download now gets 19rc2. Each is described below.

Thanks to everyone who tried the betas and told us what broke.


Generated C Macros and Static Inline Functions

This is the headline item, and it arrived on develop through #2405.

pgrx has always carried hand-written Rust ports of the Postgres macros and static inline functions it needed. They covered a small part of the headers, and they drifted from the C as Postgres changed from version to version.

The new pgrx-c-macros crate runs during every pgrx-pg-sys build and translates Postgres' function-like C macros into documented Rust macro_rules!. The translations keep C's arithmetic, integer promotions, casts and evaluation order, so they compute what the C computes for the headers you build against. You call them by their Postgres names:

// Before (v0.19)
let len = pgrx::varsize_any(ptr);
check_for_interrupts!();

// After (v0.20)
let len = unsafe { pgrx::VARSIZE_ANY!(ptr).get() as usize };
pgrx::check_for_interrupts();

A macro that can't be translated faithfully is skipped, and OUT_DIR/pgNN_macro_report.json says why.

Static inline functions get the same treatment. When the translator supports every statement in a function's body, the body becomes Rust, and pg_sys::NAME(...) runs that translation with the binding's ordinary signature. Otherwise pg_sys::NAME is still the guarded C binding. On PG16 and later, that means hot conversions such as Int32GetDatum no longer pay for a sigsetjmp and a thread check on every call.

The hand-written ports are removed, including pgrx::varsize_any, check_for_interrupts!, pg_sys::heap_tuple_get_struct and the pgrx::srf_* helpers. The C macro guide lists each one with its replacement. A generated macro that reads storage or backend state needs an unsafe block, even where the helper it replaces was safe.

Using the Results from Rust

A macro whose C result is a comparison, a logical operator or a _Bool returns a Rust bool, so a predicate reads if pg_sys::IsA!(node, pg_sys::Query). Other macros return a wrapper. .get_usize() and .get_as::<T>() replace most .get() as ... casts, and pg_sys::Oid::from(...) and friends convert macro results. NodeTag::try_from(nodeTag!(node).get()) gives you a NodeTag without a transmute.

pg_sys::maxalign and the rest of pg_sys::align work in const contexts. pg_sys::expression_tree_walker and the other walkers and mutators no longer need a cfg split between PG15 and PG16+. pg_sys::InvalidOid and the transaction ID constants are still Oid and TransactionId, so code written for 0.19 that uses them compiles unchanged.

Node Macros

  • Generate C macros that paste a prefix onto a type operand, such as IsA, castNode and makeNode by @eeeebbbbrrrr in #2465
  • Generate makeNode! on PostgreSQL 15 and 16 by translating GNU statement expressions by @eeeebbbbrrrr in #2468
  • Let IsA!, castNode! and makeNode! take OpExpr, DistinctExpr and NullIfExpr by @eeeebbbbrrrr in #2490

IsA!, castNode!, makeNode! and the lfirst_node! family of list macros are generated on every supported Postgres version. The type operand is the Rust type, and all of them need unsafe:

if unsafe { pg_sys::IsA!(node, pg_sys::Query) } {
    let query = unsafe { pg_sys::castNode!(pg_sys::Query, node).get() };
}

OpExpr, DistinctExpr and NullIfExpr are one Rust type with three node tags. The last segment of the path you write picks the tag, as in C, so pg_sys::IsA!(node, pg_sys::DistinctExpr) tests for T_DistinctExpr. See Node macros.

Assert-enabled and Release Postgres

  • Generate the same C macros for assert-enabled and release PostgreSQL by @eeeebbbbrrrr in #2461
  • Translate inline functions that differ between assert-enabled and release PostgreSQL, such as TupleDescCompactAttr by @eeeebbbbrrrr in #2487
  • Make a C macro do what its own build flavor's definition does by @eeeebbbbrrrr in #2492

cargo pgrx init builds Postgres with --enable-cassert, and packaged Postgres is built without it. pg_sys now offers the same items against both, so an extension that compiles against one compiles against the other. What you'll notice:

  • Bindings that only an assert-enabled Postgres declares are gone from every build, such as MemoryContextCheck, castNodeImpl and the USE_ASSERT_CHECKING constant.
  • Assertion functions such as AssertTransactionIdInAllowableRange are macros in both builds.
  • pg_sys::Assert! is a statement, and a macro needs unsafe wherever either build's definition does.
  • Assertions only run against a server built with them. A failed one prints Postgres' TRAP: line with the Rust file and line, and aborts.
  • Where Postgres defines a macro differently for the two builds, as it does castNode and pg_unreachable, the generated macro does what the server's own definition does.

TupleDescCompactAttr, which fastgetattr and index_getattr call on PG18 and 19, is now translated to Rust instead of called natively. See Assert-enabled and release PostgreSQL.

Clang Versions and Other Fixes

  • Generate C macros correctly with clang 19 and later by @eeeebbbbrrrr in #2422
  • Generate CHECK_FOR_INTERRUPTS and other builtin macros under Clang 18 by @eeeebbbbrrrr in #2459
  • Generate the same C macros on Linux as on macOS where system headers repeat NULL, and under libclang 15 by @eeeebbbbrrrr in #2470
  • Generate the C macros under every Clang from 14 to 23 in CI and compare them by @eeeebbbbrrrr in #2473
  • Translate inline functions that read a local only a callee wrote, such as ExecQual by @eeeebbbbrrrr in #2485
  • Run the thread check once per generated C macro expansion by @eeeebbbbrrrr in #2478
  • Wrap a generated sizeof operand in unsafe only when it needs it by @eeeebbbbrrrr in #2479
  • Keep the native call for inline bodies that need a pointer cast by @eeeebbbbrrrr in #2447
  • Replace petgraph in pgrx-c-macros with an in-tree graph by @eeeebbbbrrrr in #2411

On Linux, CI now generates the C macros with every Clang major from 14 through 23, on x86_64 and aarch64, and requires them all to generate the same macros. That covers LLVM 18, which Ubuntu 24.04 installs by default and which beta.0 failed to build with, and clang 21 with glibc 2.43, as on Ubuntu 26.04.

#2478 makes a macro that reads several Postgres globals, like BufferGetPage!, run pgrx's active-thread check once instead of once per read. One side effect: a temporary created inside an operand of such a macro is now dropped when the macro finishes, not at the end of your statement.


Soundness Fixes

Several pgrx APIs let safe code read freed, misaligned or mistyped Postgres memory. Fixing them changed signatures and behavior. The migration guide has a section for each, but the highlights are:

  • Copies instead of borrows. PgVarlena<T> now holds its value in Rust. A PgBox<T> read from an array element or tuple attribute is a copy in CurrentMemoryContext. PgTupleDesc returns FormData_pg_attribute by value and no longer dereferences to PgBox<TupleDescData>. PgRelation::name() and namespace() return String, and PgRelation no longer dereferences to RelationData.
  • New unsafe fns. AnyArray::into, heap_getattr, heap_getattr_datum_ex, composite_row_type_make_tuple, DatumWithTypeInfo::into_value, and the <type>_recv function generated for #[pg_binary_protocol] types depend on their input being right, so they are now unsafe. The new AnyArray::value::<T>() and AnyElement::value::<T>() check the type and return a Result.
  • Borrowed PostgresType values. A #[derive(PostgresType)] type with a lifetime now borrows from the Datum it was read from. Vec<Part<'_>> arguments no longer compile; use Array<'_, Part<'_>>.
  • fn_call checks argument types against the called function's parameters and returns FnCallError::IncompatibleArgumentType instead of crashing the backend. FnCallError is now #[non_exhaustive].
  • rust_regtypein finds an extension's own types through pg_depend instead of search_path, so an extension's own type named Point no longer resolves to pg_catalog.point.
  • PgVarlena::new requires T: Default. Use the unsafe PgVarlena::new_zeroed where all-zero bytes are a valid T.
  • Text array elements are checked. Reading text array elements as &str or String now checks their encoding as FromDatum for &str does, and panics instead of producing an invalid str.
  • Treat a not-null NULL pointer as uninitialized in Internal by @eeeebbbbrrrr in #2414
  • Document liveness and aliasing requirements for Internal's unsafe methods by @eeeebbbbrrrr in #2416
  • Allocate memory-context callbacks before leaking Rust values by @eeeebbbbrrrr in #2496

PgMemoryContexts::leak_and_drop_on_delete could leak its value if allocating the reset callback failed. It now allocates the callback first.

CVE-2026-6460

Postgres 15.20, 16.16, 17.12, 18.7 and 19rc2 record a version in each composite datum. Postgres checks that version before reading an attribute, so it raises an ERROR instead of misreading a row formed under an incompatible definition of its type. pgrx reads composite attributes with its own code, which skipped that check until now. PgHeapTuple and the htup functions now perform it.

To get the fix, build your extension against a patched Postgres. The check is compiled in only when the Postgres headers you build against include the fix. An extension built against the fixed headers will not load on an earlier minor release.

The same fix shipped for the 0.19 series in v0.19.4.


Error Handling

  • Rethrow caught Postgres ERRORs intact, and flush only after handling one by @eeeebbbbrrrr in #2458

Rethrowing a CaughtError::PostgresError after something else had flushed Postgres' error stack, for example when a PgTryBuilder catch handler returned the error for its caller to rethrow, failed with errstart was not called or raised a different error. pgrx now keeps a copy of every field of a caught ERROR and raises that copy when Postgres no longer has the original, so handlers such as PL/pgSQL's GET STACKED DIAGNOSTICS see the same error either way.

PgTryBuilder::execute also no longer flushes the error stack after a Rust panic or an ErrorReport, which could discard an ERROR that C code calling into Rust was still handling. If you swallow a Postgres ERROR with std::panic::catch_unwind, it stays on Postgres' error stack. Catch it with PgTryBuilder instead, or call pg_sys::FlushErrorState() afterwards. See Caught PostgreSQL errors.

  • Add missing SQLSTATEs to PgSqlErrorCode and make it #[non_exhaustive] by @eeeebbbbrrrr in #2499

PgSqlErrorCode only knew Postgres 12's error codes. It now has the seven added since, including ERRCODE_DATUM_VERSION_MISMATCH from the CVE fix, on every supported version. Before, a caught error with one of those codes reported ERRCODE_INTERNAL_ERROR. The enum is now #[non_exhaustive], so a match on it needs a wildcard arm.


Postgres Versions

pgrx now supports Postgres 15 through 18, plus 19rc2. Remove the pg13 and pg14 features from your Cargo.toml and change default if it names one of them. New extensions default to pg15. If you have a 19 beta or 19rc1 that cargo pgrx init downloaded, run cargo pgrx init --pg19=download to replace it with rc2.

  • Fix building for PostgreSQL 19 on Windows (MSVC) by @mstaros in #2388
  • Type the PG19 BUFFER_LOCK_* re-exports as BufferLockMode::Type by @eeeebbbbrrrr in #2410
  • Check PG19's LockBuffer and index lock constants in every build by @eeeebbbbrrrr in #2412

The PG19 BUFFER_LOCK_* constants have the type LockBuffer takes, which is u32 on Linux and macOS and i32 on MSVC. Code that builds for several versions should pass them as pg_sys::BUFFER_LOCK_SHARE as _.

Rust 1.99.1

Not 1.99.0, which can miscompile an extern "C" function that returns bool on x86_64 (rust-lang/rust#163911). pgrx hands Postgres plenty of those, such as GUC check hooks.


cargo-pgrx

SQL Migration Fragments

  • Add cargo pgrx migrate for SQL migration fragments by @eeeebbbbrrrr in #2407
  • Make SQL migration fragments opt-in, fix release assembly, and document them by @eeeebbbbrrrr in #2406
  • Warn that temporary fragment versions differ from the crate version by @eeeebbbbrrrr in #2431
  • Strengthen migration fragment checks across sql/ and release branches. by @stuhood in #2495
  • Expose the installed extension version at compile time by @stuhood in #2493

An extension can now keep its upgrade SQL as one small file per change in sql/unreleased/ instead of one hand-edited script per release. That helps when several pull requests change the schema at once, or when fixes get backported. Opt in from Cargo.toml:

[package.metadata.pgrx]
unreleased-sql-dir = "sql/unreleased"

cargo pgrx install, run, test, regress and bench then assemble the fragments into a temporary upgrade script so ALTER EXTENSION ... UPDATE works during development. cargo pgrx migrate assemble writes the real versioned script at release time. cargo pgrx migrate check lints fragments for dependency cycles and undeclared dependencies, and with --base <REF> and --upstream <REF> it also rejects edits to released upgrade scripts and fragments that differ from upstream. Extensions that don't opt in see no change.

Because the temporary version differs from your crate's version, pgrx::extversion!() gives the version cargo-pgrx actually installed, and pgrx::pkgversion!() gives the crate's.

This started as @stuhood's work in #2380. The new Upgrading Extensions chapter of the book and the migration_fragments example show how to use it.

RPM and DEB Packages

On Linux, cargo pgrx package now builds .rpm and .deb files itself. Add an empty [package.metadata.rpm] or [package.metadata.deb] section to Cargo.toml and you get a package laid out like the PGDG ones, filled in from your crate's name, version, description, license and authors. Any key you set in the section overrides the default. --no-distrib-packages skips them when you only want the staged files.

If you already have a [package.metadata.deb] section for cargo deb, it uses different keys and can now make cargo pgrx package fail. See Existing cargo deb metadata.

cargo pgrx regress

A regression test can now say which Postgres versions it runs on with a comment line such as -- pgrx-regress-skip pg15 pg16 or -- pgrx-regress-only pg17 pg18. On other versions it's reported as skipped and needs no expected output.

cargo pgrx regress also takes several test names now, and exits with status 1 when a name matches no test. Only a file named exactly setup.sql is the setup file, so a test like post_setup.sql now runs as an ordinary test.

Other cargo-pgrx Changes

  • Fix cargo pgrx upgrade reading the wrong Cargo index cache directory by @isdaniel in #2398

cargo pgrx upgrade without --to failed on Cargo 1.85 and newer. It works again.

  • feat: accept any pgrx patch release within cargo-pgrx's minor series by @Vinnu124 in #2419
  • Let a prerelease cargo-pgrx accept matching pgrx prereleases by @eeeebbbbrrrr in #2443

cargo-pgrx 0.20.x accepts any pgrx 0.20.x, so you no longer need to upgrade the CLI for every pgrx patch release.

  • Retry cargo-pgrx's fetch of PostgreSQL's release list by @eeeebbbbrrrr in #2477
  • Restore a latest minor version that postgresql.org listed without its trailing zero by @eeeebbbbrrrr in #2500

cargo pgrx init now tries each of its downloads up to four times. Since the November releases, postgresql.org lists Postgres 15's latest minor as 15.2 instead of 15.20, and cargo pgrx init downloaded 15.2 from 2023. It now checks for the longer version and gets 15.20.


New Features

  • Add TsVector and TsQuery types and operators by @ibotty in #2475

pgrx now has types for Postgres' tsvector and tsquery. &TsVector and &TsQuery are zero-copy function arguments, and TsVectorBuf and TsQueryBuf are Rust-owned copies. They come with the matching, concatenation, boolean and phrase operators, lexeme and query item iterators, TsConfig, the to_tsvector and to_tsquery style constructors, and ts_rank and ts_rank_cd ranking.

  • Add LWLocks for dynamic shared memory and parallel foreign scans by @eeeebbbbrrrr in #2409

pgrx::lwlock::dsm::DsmLwLockTranche and pgrx::lwlock::scan::ParallelScanLwLock provide LWLocks that live in dynamic shared memory, which a parallel foreign scan needs and PgLwLock can't provide. The new parallel_scan_lwlock example implements a parallel FDW with them. This is @fkomauli's work from #2395.

  • Add the no_thread_check_in_release feature and pgrx::assert_active_thread() by @eeeebbbbrrrr in #2486

pgrx checks that the caller is the backend thread on every guarded call into Postgres. An extension that never touches Postgres from another thread can turn on the no_thread_check_in_release feature to drop that check from builds without debug_assertions, so cargo pgrx test still catches mistakes. It's off by default because it gives up a soundness check: in such a build, calling a safe pgrx function like check_for_interrupts() from another thread is undefined behavior that nothing reports. Cargo unifies features, so one crate that sets it removes the check from the whole build. pgrx::assert_active_thread() always checks, for extension code that wants to keep it.

Bugfixes

Any aggregate that implemented Aggregate::deserial failed CREATE AGGREGATE, so no pgrx aggregate with an internal state could run in parallel. deserial now takes the serialized bytes and returns Self::State.

Testing

#[pg_test] functions can now open their own connections back to Postgres with pgrx_tests::client(), which makes multi-session tests possible. It needs the new client feature of pgrx-tests. See pgrx_tests::client.

An extension that depends on another pgrx extension can now keep its #[pg_schema] mod tests. The test harness creates the tests schema itself, and both extensions share it. If you have test builds of dependency extensions already installed, rebuild and reinstall them.

Windows

cargo pgrx regress now works on Windows, where it used to print passed=0 failed=0. pgrx-pg-sys builds with LLVM 22. Test binaries no longer hang forever when Windows reuses a process id. And the test framework and cargo pgrx bench ask Windows for the account name instead of trusting USERNAME, which fixes connecting from an SSH session.


Dependencies

  • Replace petgraph with lightweight in-tree directed graph by @cbandy in #2403
  • Cut third-party dependencies from extension builds and cargo-pgrx by @eeeebbbbrrrr in #2452

Extension builds, extension test builds and cargo install cargo-pgrx all compile noticeably fewer crates. petgraph and its Zlib-licensed foldhash dependency are gone, an extension's test build no longer pulls in postgres and tokio, and installing cargo-pgrx on Linux no longer needs OpenSSL's development headers. That came with some changes you may need to act on:

  • The generated schema can list statements in a different order. If an extension_sql! block names an object from elsewhere in your extension, make sure it lists that object in requires, or CREATE EXTENSION can fail. See Order of the generated schema.
  • cargo-pgrx no longer has rustls and native-tls features. Remove them from any cargo install cargo-pgrx --features ... command. It always uses rustls with the platform's certificate store, and still honors the proxy environment variables.
  • cargo pgrx init unpacks Postgres with the tar on your PATH on Linux and macOS, and downloads the .tar.gz archive instead of .tar.bz2.
  • pgrx::nullable::BitSliceNulls is replaced by NullBitmap and RawArray::nulls_bitslice is gone, along with the bitvec dependency. See Array null bitmaps.
  • PgXactCallbackEvent no longer implements enum_map::Enum.
  • pgrx-pg-config's API changed for code that uses it directly. See pgrx-pg-config.

This also fixes raw string arguments to #[pg_extern] attributes, which the old parsing mangled.

Documentation

Project Administrativa

New Contributors

Thanks also to @stuhood and @fkomauli, whose work became the SQL fragment and DSM LWLock features, to @ibotty for the text search types, and to @daamien, @isdaniel and @cbandy. Your work is appreciated!

Full Changelog: v0.19.3...v0.20.0