PostgreSQL extensions in Go: from C basics to cgo

11 steps · about 4 h 25 min · Intermediate

  1. PostgreSQL: Documentation: 19: 36.10. C-Language Functions (doc, PostgreSQL docs, 30 min)

    Start with how Postgres loads compiled functions from a shared library, because every Go extension has to fit this model.

  2. PostgreSQL: Documentation: 18: 36.18. Extension Building Infrastructure (doc, PostgreSQL docs, 20 min)

    PGXS is the official build system that extensions plug into, including control files, SQL scripts and make install.

  3. PostgreSQL: Simple C extension Development for a Novice User (and Performance Advantages) (tutorial, Percona, 25 min)

    A small addme example that you can build and run, so you see the whole extension workflow before adding Go.

  4. PG 101 - Building Postgres Extensions (tutorial, Christy Jacob, 25 min)

    Explains the required macros (PG_MODULE_MAGIC and function registration) that a Go wrapper must also provide.

  5. A Guide to Create User-Defined Extension Modules to Postgres (tutorial, Highgo Software, 25 min)

    Compares a plpgsql extension with a C extension, which shows why a compiled library is the route Go has to take.

  6. src/cmd/cgo/doc.go (doc, Go project (cgo docs), 25 min)

    The primary source for cgo, which is how Go and C code call each other.

  7. Building Python modules with Go 1.5 (article, Filippo Valsorda, 20 min)

    Shows //export and -buildmode=c-shared in a clear worked example that is the same trick used for Postgres.

  8. go-cshared-examples: Calling Go Functions from Other Languages using C Shared Libraries (repo, Vladimir Vivien (GitHub), 25 min)

    Runnable examples of Go built as a .so and called from C, which is the mechanism under any Go Postgres extension.

  9. golang-psql-functions: Postgres Functions written in Golang (repo, unixlab (GitHub), 15 min)

    A tiny repo with one .go and one .c file that makes the Go-to-Postgres glue easy to read.

  10. pgxs package - github.com/jchappelow/go-pgxs (reference, pkg.go.dev, 30 min)

    A reusable package for Datum conversion and function registration, so you can see how type mapping is handled.

  11. plgo package - github.com/microo8/plgo (reference, pkg.go.dev, 25 min)

    A higher-level tool that generates the wrapper code, control files and Makefile, showing how the manual steps can be automated.