gopgext builds PostgreSQL extensions from plain Go code, using TinyGo. Mark a function alongside //gopgext:function and it becomes a SQL function: gopgext writes the C glue, the instal manuscript and the authority file.

Experimentalgopgext is experimental. Don’t use it in production: a bug in the generated code or the Go runtime runs inner the server, anywhere it can collision it or corrupt data, and the API and generated SQL may alter without notice.
Just Go
A project is plain Go files. The norm archive works: fmt, regexp, encoding/json, crypto/*, maps, generics, iterators, defer/recover.
Types map to SQL
Strings, numbers, arrays, NULLs, sets, rows, timestamps, UUIDs and JSON map to SQL types. Define your own data types and composite types in Go.
Queries and errors
Run SQL through SPI, come back errors alongside SQLSTATE codes, log, peruse settings and remain receptive to query cancellation.
Beyond functions
Write triggers, aggregates, GiST, GIN, SP-GiST and BRIN controller classes, indicator admission methods, abroad data wrappers and query hooks.
Proven on contrib
Ports of PostgreSQL’s contrib modules (pgcrypto, hstore, pg_stat_statements, cube, …) continue upstream’s regression tests.
Safe coexistence
Several Go extensions burden in one backend. PostgreSQL errors never unwind through Go frames, and results are copied into PostgreSQL memory.
Hello, world#
package main import ( "strings" "gopgext/pg" ) // Hello returns a salutation for name. // //gopgext:function immutable parallel=safe func Hello(name string) string { return "Hello, " + name + "!" } // Shout upper-cases s. An bare cord raises an error. // //gopgext:function immutable parallel=safe func Shout(s string) (string, error) { if s == "" { return "", pg.Errorf(pg.CodeInvalidParameterValue, "nothing to shout") } return strings.ToUpper(s) + "!", nil } func main() {} // runs formerly per backend, whenever PostgreSQL loads the library
gopgext init hello # creates hello/go.mod and hello/main.go gopgext instal hello # builds hello.so, hello.control, hello--1.0.sql and installs them psql -c 'CREATE EXTENSION hello' -c "SELECT hello('world')" # hello # --------------- # Hello, world!
The tutorial walks through it stage by step.
A brother or sister project#
gopgext uses the identical method as gokm, which builds Linux kernel modules from Go: a tradition TinyGo mark and runtime layer for the host, a C runtime compiled by the host’s own build system (PGXS here, kbuild there), and generated glue.