Example extensions
Every example is a self-contained Zig package that depends on pgzx by path, so you can copy one as the starting point for your own extension.
The following sample extensions (ordered from simple to complex) show how to use pgzx:
| Extension | Description |
|---|---|
| char_count_zig | Adds a function that counts how many times a particular character shows up in a string. Shows how to register a function and how to interpret the parameters. |
| pghostname_zig | Adds a function that returns the database server’s host name. |
| sqlfns | The ways to export a Zig function to SQL: a raw C export, PG_FUNCTION_V1, and PG_EXPORT for a whole struct or file. |
| guc | Registers custom GUCs (bool, int, string, enum) in _PG_init, including a check hook that clamps a value, and reads them back into SQL. |
| bgworker | Registers a static background worker (pgzx.bgworker.register) that the postmaster launches on the next server start. |
| pg_audit_zig | Inspired by the pgaudit C extension, this one registers callbacks to multiple hooks and uses more advanced error handling and memory allocation patterns. |
| srf | Port of pgrx-examples/srf. Set-returning functions with pgzx.srf.SetOf (RETURNS SETOF) and pgzx.srf.Table (RETURNS TABLE), driven by a plain Zig iterator. |
| arrays | Port of pgrx-examples/arrays. Postgres arrays as Zig slices ([]const i32, []const ?i32, text[]), plus parameter defaults, VARIADIC and pgzx.IntList. |
| spi_sql | Uses SPI to run SQL statements; the exported functions double as the regression-test fixture. |
| spi | Port of pgrx-examples/spi. Queries with arguments, a prepared plan kept for the session, cursors fetched in batches, subtransactions that skip failing rows, and SECURITY DEFINER. |
| rational | A rational base type with btree and hash operator classes. Shows the type system end to end: pg_type, operators, pg_opclass, casts and how they make indexes and GROUP BY work. |
| file_io | Backend-safe file I/O through the virtual file descriptor layer (pgzx.fd), plus asynchronous VFD reads on PostgreSQL 18 (pgzx.aio). |
| compress_zig | A Timescale-style columnar compression layer: SPI reads a heap table, encodes it into type-aware batches (plain, rle, delta, delta2, gorilla, dictionary, bit-packed bool) in a sidecar relation, and decodes them back. |