用 Go 编写的 PostgreSQL 扩展
PostgreSQL Extensions in Go

原始链接: https://jespino.github.io/gopgext/

gopgext 是一个用于用纯 Go 编写 PostgreSQL 扩展的实验性框架。它映射 Go 和 SQL 类型,支持 SPI 查询、类型化错误、日志、设置、取消,以及触发器、聚合、索引操作符类、访问方法、外部数据封装器和钩子等高级 PostgreSQL 特性。它已成功移植多个 contrib 模块,并允许多个 Go 扩展安全共存,PostgreSQL 错误不会穿过 Go 调用栈展开,结果也会复制到 PostgreSQL 内存中。一个小型示例定义了 `Hello` 和 `Shout` 函数,使用 `gopgext init`/`install` 构建扩展,并从 psql 调用它。它采用类似于 gokm 的 TinyGo 方式,包含宿主特定的运行时胶水代码。它尚不适用于生产环境。

Hacker News 新 | 过去 | 评论 | 提问 | 展示 | 工作 | 提交 登录 Go 中的 PostgreSQL 扩展 ( jespino.github.io ) 4 分 由 valyala 22 分钟前 | 隐藏 | 过去 | 收藏 | 讨论 帮助 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索:
相关文章

原文

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.

联系我们 contact @ memedata.com