PostgreSQL can run far more than SQL, but extending the server has traditionally meant working with C, PostgreSQL’s internal APIs and risks that application developers rarely encounter. The experimental gopgext project offers another route: building PostgreSQL extensions in Go, compiling the code through TinyGo and generating the C glue and metadata PostgreSQL expects. It is an intriguing bridge between Go database development and PostgreSQL internals—but explicitly not a production-ready shortcut.
At its simplest, gopgext can expose an annotated Go function as a callable SQL function. Its ambitions extend much further, covering PostgreSQL triggers, aggregates, operator classes, foreign data wrappers, index access methods and query hooks. This guide explains the model, development workflow and safety constraints, based on the project’s status and documentation as of November 2026.
What is gopgext?
gopgext is an experimental toolkit for PostgreSQL extension development in Go. Developers write ordinary Go functions and mark PostgreSQL entry points with annotations such as //gopgext:function. The toolchain analyzes those declarations and produces the surrounding artifacts needed to load them into PostgreSQL.
Those generated artifacts include C interoperability code, SQL installation scripts and a PostgreSQL extension control file. TinyGo compiles the Go portion into native code that can be linked into a loadable shared library. You avoid writing the C adapter manually, but C has not disappeared: gopgext generates and compiles that boundary for you.
The result runs inside the PostgreSQL server process. It is not a Go service communicating over a database connection, and it does not receive the process isolation of an external application. That distinction explains both its power and its danger.
How the architecture works
SQL query
|
v
PostgreSQL function manager
|
v
Generated C glue <-- generated SQL and control metadata
|
v
TinyGo-compiled Go function
|
+-- PostgreSQL values and memory
+-- SPI queries
+-- errors, interrupts and extension callbacksPostgreSQL calls a native entry point using its function-manager conventions. The generated layer converts PostgreSQL datums and null flags into supported Go values, invokes the Go function, and converts its result back. More advanced extension points add callback tables, lifecycle rules and PostgreSQL-specific state.
This code executes within a PostgreSQL backend. A panic, invalid pointer, ABI mismatch or runtime defect can terminate that backend. Memory corruption can have consequences beyond a failed function call.
Build requirements and installation workflow
Expect a native toolchain rather than the simple go build workflow used for an API server. Exact commands and supported versions can change while gopgext is experimental, so pin a repository revision and follow the instructions shipped with that revision.
- Go: required for gopgext’s tooling and source workflow.
- TinyGo: compiles the supported Go subset for the native extension.
- PostgreSQL development files: headers, PGXS build support and
pg_configmust match the target PostgreSQL installation. - A C toolchain: required to compile the generated adapter and link the shared library.
- Build utilities: typically Make and the platform tools used by PostgreSQL extensions.
A sensible setup begins by cloning or installing gopgext from its official repository, checking the documented compatibility matrix, and confirming the local tools:
go version
tinygo version
pg_config --version
pg_config --includedir-serverNext, create the Go source and extension configuration, run the generator for the pinned gopgext revision, compile the output, and install the resulting control, SQL and library files into the directories reported by pg_config. Installation generally requires permission to write into PostgreSQL’s extension and library directories. A database administrator can then enable the package with CREATE EXTENSION.
Use a disposable PostgreSQL instance or container for this process. Installing an experimental native module into a valuable development database is an unnecessary risk.
Creating a simple Go PostgreSQL extension
A minimal source file can contain a typed Go function preceded by the directive recognized by the generator:
package extension
//gopgext:function
func AddInt32(left int32, right int32) int32 {
return left + right
}During generation, gopgext discovers the annotation and creates a PostgreSQL-callable wrapper plus the corresponding SQL declaration. The exact generated SQL name and schema depend on the project’s configuration and naming rules. After building, installing and enabling the extension, the function can be called from SQL under that generated or configured name:
CREATE EXTENSION example_math;
SELECT add_int32(20, 22);The important boundary is the function signature. PostgreSQL passes values using its own type and memory systems; the generated wrapper must know how every argument and return value should be represented. Unsupported signatures cannot safely become PostgreSQL custom functions merely because they compile as Go.
Mapping Go types to PostgreSQL types
Use fixed-width Go types where the corresponding SQL width matters. For example, int32 naturally expresses an integer-sized value more clearly than architecture-dependent int. Boolean, floating-point, text and byte-oriented values also require mappings defined by the gopgext version being used.
Nullability deserves special attention. SQL NULL is not equivalent to a zero, empty string or false value. Use only the nullable representation documented by gopgext, and test null arguments and null results independently. Complex PostgreSQL values, arrays, composite types and user-defined types may need project-specific wrappers rather than arbitrary Go structs.
Executing SQL through PostgreSQL SPI
The PostgreSQL Server Programming Interface, or SPI, lets extension code execute SQL within the current backend. Through gopgext’s SPI support, a Go function can inspect tables, perform a parameterized query or participate in the transaction that invoked it.
The conceptual sequence is:
- Enter or connect to SPI through the API supplied by the pinned gopgext version.
- Execute parameterized SQL instead of assembling untrusted text.
- Read and convert returned rows while their PostgreSQL memory remains valid.
- Release SPI resources on every success or error path.
SPI is useful for validation functions, audit logic and metadata-driven behavior, but it is not a free database connection. The code runs inside an existing statement and transaction. Recursive SQL, locks, trigger re-entry and transaction aborts remain PostgreSQL concerns. Developers must also respect the memory-context lifetime of values returned by the server.
SQLSTATE errors and query cancellation
A database-facing error needs more structure than a Go error string. PostgreSQL uses five-character SQLSTATE codes to distinguish invalid input, constraint failures, cancellation and internal errors. gopgext provides mechanisms for translating extension failures into PostgreSQL errors; use the documented error abstraction to attach the appropriate SQLSTATE and safe client message. Do not treat an unchecked panic as normal error handling.
Long-running native code must also cooperate with PostgreSQL interrupts. If a client cancels a query or a statement timeout expires, computation that never checks the server’s cancellation state may continue occupying the backend. Break large loops into bounded units and call the gopgext interrupt or cancellation facility at documented safe points. Cancellation testing should cover explicit cancel requests, statement timeouts and shutdown behavior.
Beyond functions: advanced extension points
gopgext is broader than a Go-to-SQL function generator. Its documented scope reaches several of PostgreSQL’s native plugin interfaces:
- Triggers: react to row or statement events, inspect trigger context and return the appropriate tuple behavior.
- Aggregates: implement transition, combination and finalization logic while carefully managing state lifetimes.
- Operator classes: supply support behavior for GIN, GiST, SP-GiST and BRIN indexes. Correctness is essential because inconsistent comparison or search logic can produce wrong query results.
- Index access methods: define lower-level index behavior, including scans and maintenance callbacks.
- Foreign data wrappers: connect PostgreSQL planning and execution callbacks to an external data source.
- Query hooks: observe or modify selected stages of parsing, planning, execution or utility processing, depending on the hook exposed.
These are not merely larger versions of scalar functions. They involve callback lifecycles, planner contracts, memory contexts, concurrency assumptions and version-sensitive PostgreSQL structures. An operator class that appears to work on a small test table can still return incomplete results under unusual values, concurrent updates or different plans. Start with scalar functions before attempting an index or planner integration.
Go vs C PostgreSQL extensions, PL/pgSQL and application code
Compared with PostgreSQL C extensions, gopgext removes much of the handwritten conversion and registration boilerplate and offers familiar Go syntax. C still has the most direct access to PostgreSQL internals, the longest history and fewer runtime layers. Both approaches can crash the server when incorrect.
Compared with PostgreSQL procedural languages, PL/pgSQL is generally the safer choice for transactional logic composed primarily of SQL. It is installed, managed and understood as database code, but it cannot implement low-level facilities such as a new index access method.
Compared with application-level code, an extension avoids network round trips and can participate directly in server hooks. A separate Go service is easier to deploy independently and isolates its failures from PostgreSQL. Business workflows, remote API calls and long tasks usually belong outside a database backend.
Performance, compatibility and production risk
It is tempting to assume that TinyGo makes every function fast. Actual performance depends on wrapper conversions, allocation behavior, SPI use, callback frequency and the generated runtime. A tiny function invoked for every row may expose overhead that is invisible in a coarse benchmark. Conversely, moving a carefully chosen computation into the server may eliminate data transfer.
Benchmark the full SQL call path against C, PL/pgSQL, built-in SQL expressions and application-side processing. Measure latency, throughput, backend memory growth and behavior under concurrent sessions. Include null-heavy data, large values, errors and cancellation—not only the happy path.
Compatibility must be tested across each intended combination of PostgreSQL, TinyGo, operating system, architecture and gopgext revision. PostgreSQL’s internal interfaces can change between major releases, while TinyGo does not provide exactly the same runtime behavior or package support as standard Go.
Most importantly, gopgext’s maintainers label the project experimental and warn against production use. Defects in generated code or the Go runtime can crash PostgreSQL or corrupt data. Before any future production consideration, the project would need substantially more hardening, repeatable compatibility testing, fuzzing at type boundaries, crash recovery tests, upgrade and rollback exercises, concurrency testing, and independent code review. Backups do not turn unsafe native code into safe code.
Realistic uses today
Appropriate current uses include learning PostgreSQL internals, prototyping a custom function, evaluating Go-based trigger logic, experimenting with a foreign data wrapper, or comparing index strategies in an isolated lab. gopgext can also help teams explore whether a concept warrants a mature C implementation. It should not currently protect critical data, enforce the only copy of a business invariant or run untested in a production cluster.
Frequently asked questions
Does gopgext eliminate C from extension development?
It eliminates the need to hand-write much of the C boundary. The tool still generates C glue, which must be compiled and linked against PostgreSQL. Developers therefore avoid C source work without escaping the native extension model or its safety implications.
Can standard Go packages be used in a gopgext extension?
Not automatically. The code is compiled with TinyGo, whose runtime and package compatibility differ from standard Go. Packages may also assume operating-system behavior that is inappropriate inside a PostgreSQL backend. Verify every dependency with the pinned TinyGo and gopgext versions.
Is gopgext suitable for production PostgreSQL?
No. The project is explicitly experimental, and its maintainers warn that generated-code or runtime bugs can crash the server or corrupt data. Use an isolated environment and treat the project as research and prototyping technology.
When should PL/pgSQL be preferred?
Prefer PL/pgSQL when the task is primarily SQL orchestration, validation or transactional data manipulation and does not require native PostgreSQL hooks. It is simpler to deploy and avoids introducing an experimental native runtime into the server process.