gopgext 讓開發者用 Go 程式碼打造 PostgreSQL 擴充功能
PostgreSQL Extensions in Go
想替 PostgreSQL 加入新功能,通常得處理資料庫和 C 程式碼之間的接線。
- gopgext 使用 TinyGo,讓開發者用 Go 撰寫函式,再自動產生連線用的 C 程式碼、安裝指令檔和控制檔。
- 除了 SQL 函式,也能製作觸發器、索引功能和外部資料包裝器。文章示範如何把 Go 函式安裝成 PostgreSQL 擴充功能。不過這個專案仍在實驗階段,產生的程式碼或 Go 執行環境若出錯,可能讓資料庫當掉或損壞資料,因此不適合用在正式環境。
AI 伴隨問答
針對這篇報導有疑問?可直接點選快捷問題或向 AI 追問背景脈絡與技術細節:
gopgext builds PostgreSQL extensions from plain Go code, using TinyGo. Mark a function with //gopgext:function and it becomes a SQL function: gopgext writes the C glue, the install script and the control file.

Experimentalgopgext is experimental. Don’t use it in production: a bug in the generated code or the Go runtime runs inside the server, where it can crash it or corrupt data, and the API and generated SQL may change without notice.
Just Go
A project is plain Go files. The standard library 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, return errors with SQLSTATE codes, log, read settings and stay responsive to query cancellation.
Beyond functions
Write triggers, aggregates, GiST, GIN, SP-GiST and BRIN operator classes, index access methods, foreign data wrappers and query hooks.
Proven on contrib
Ports of PostgreSQL’s contrib modules (pgcrypto, hstore, pg_stat_statements, cube, …) pass upstream’s regression tests.
Safe coexistence
Several Go extensions load 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 greeting for name.
//
//gopgext:function immutable parallel=safe
func Hello(name string) string {
return "Hello, " + name + "!"
}
// Shout upper-cases s. An empty string 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 once per backend, when PostgreSQL loads the library
gopgext init hello # creates hello/go.mod and hello/main.go
gopgext install 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 step by step.
A sibling project#
gopgext uses the same approach as gokm, which builds Linux kernel modules from Go: a custom TinyGo target and runtime layer for the host, a C runtime compiled by the host’s own build system (PGXS here, kbuild there), and generated glue.