Newshot

Go 语言中的 PostgreSQL 扩展

Translation(model translation, not the source's own text)

Go 中的 PostgreSQL 扩展

gopgext 使用 TinyGo,从纯 Go 代码构建 PostgreSQL 扩展。用 //gopgext:function 标记一个函数,它就会变成 SQL 函数:gopgext 会编写 C 胶水代码、安装脚本和控制文件。

穿着 PostgreSQL 大象服装的 Go gopher
穿着 PostgreSQL 大象服装的 Go gopher

就是 Go

一个项目就是纯 Go 文件。标准库可用:fmt、regexp、encoding/json、crypto/*、maps、泛型、迭代器、defer/recover。

类型映射到 SQL

字符串、数字、数组、NULL、集合、行、时间戳、UUID 和 JSON 都映射到 SQL 类型。在 Go 中定义自己的数据类型和复合类型。

查询与错误

通过 SPI 运行 SQL,以 SQLSTATE 代码返回错误,记录日志、读取设置,并对查询取消保持响应。

函数之外

编写触发器、聚合、GiST、GIN、SP-GiST 和 BRIN 操作符类、索引访问方法、外部数据包装器和查询钩子。

在 contrib 上得到验证

PostgreSQL 的 contrib 模块(pgcrypto、hstore、pg_stat_statements、cube 等)的移植版本通过了上游的回归测试。

安全共存

多个 Go 扩展可以在一个后端中加载。PostgreSQL 错误绝不会穿过 Go 栈帧展开,结果会被复制到 PostgreSQL 内存中。

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!
      

教程会一步步带你完成。

一个兄弟项目

gopgext 使用与 gokm 相同的方法,后者从 Go 构建 Linux 内核模块:一个针对宿主的自定义 TinyGo target 和运行时层,一个由宿主自己的构建系统编译的 C 运行时(这里用 PGXS,那里用 kbuild),以及生成的胶水代码。

The translation is machine-generated and individual terms may be off. Nothing is rewritten or cut; the original is authoritative.

Published by Hacker News
This site only summarises and aggregates; copyright stays with the original author. Headlines and summaries follow the source — where they differ, the original wins.
Read the original ↗