Conversations
gopgext lets ordinary Go code build PostgreSQL extensions
The gopgext project showcased on Hacker News can use TinyGo to compile ordinary Go code into PostgreSQL extensions. Developers mark functions through comments, and the tool generates C glue code, installation scripts, and control files; the project supports the standard library, SQL type mapping, SPI queries, error codes, triggers, aggregates, index access methods, and foreign-data wrappers, among other capabilities.
The core usage of gopgext is to add a //gopgext:function comment to a Go function so that it becomes a SQL function. The project itself consists of ordinary Go files and can use fmt, regexp, encoding/json, the crypto family of packages, as well as language features such as maps, generics, iterators, defer, and recover. The tool is responsible for generating the C glue layer, installation scripts, and control files.
In terms of the type system, strings, numbers, arrays, NULL, sets, rows, timestamps, UUIDs, and JSON can be mapped to SQL types, and developers can also define custom data types and composite types in Go. For database interaction, code can run SQL through SPI, return errors with SQLSTATE codes, log records, read settings, and respond to query cancellation.
Its capabilities go beyond scalar functions. The material shows that gopgext also supports writing triggers, aggregates, GiST, GIN, SP-GiST, and BRIN operator classes, index access methods, foreign-data wrappers, and query hooks. The project says it has ported modules from PostgreSQL contrib including pgcrypto, hstore, pg_stat_statements, and cube, and has passed upstream regression tests.
For runtime coexistence, multiple Go extensions can be loaded into the same backend; PostgreSQL errors do not unwind through the Go stack, and results are copied into PostgreSQL memory. The examples show two immutable, parallel-safe functions, Hello and Shout, which after initialization, building, and installation can be invoked through CREATE EXTENSION and SELECT. Its sister project gokm uses a similar idea, building Linux kernel modules with a custom TinyGo target, a host runtime layer, and generated glue code.