pg_when

PostgreSQL 自然语言时间解析扩展

概览

扩展包名版本分类许可证语言
pg_when0.1.9TIMEMITRust
ID扩展名BinLibLoadCreateTrustReloc模式
1120pg_when-

manually upgraded PGRX from 0.15.0 to 0.17.0 by Vonng

版本

类型仓库版本PG 大版本包名依赖
EXTPIGSTY0.1.91817161514pg_when-
RPMPIGSTY0.1.91817161514pg_when_$v-
DEBPIGSTY0.1.91817161514postgresql-$v-pg-when-
OS / PGPG18PG17PG16PG15PG14
el8.x86_64
el8.aarch64
el9.x86_64
el9.aarch64
el10.x86_64
el10.aarch64
d12.x86_64
d12.aarch64
d13.x86_64
d13.aarch64
u22.x86_64
u22.aarch64
PIGSTY 0.1.9
PIGSTY 0.1.9
PIGSTY 0.1.9
PIGSTY 0.1.9
PIGSTY 0.1.9
u24.x86_64
u24.aarch64
PIGSTY 0.1.9
PIGSTY 0.1.9
PIGSTY 0.1.9
PIGSTY 0.1.9
PIGSTY 0.1.9
u26.x86_64PIGSTY MISSPIGSTY MISSPIGSTY MISSPIGSTY MISSPIGSTY MISS
u26.aarch64PIGSTY MISSPIGSTY MISSPIGSTY MISSPIGSTY MISSPIGSTY MISS

构建

您可以使用 pig build 命令构建 pg_when 扩展的 RPM / DEB 包:

pig build pkg pg_when         # 构建 RPM / DEB 包

安装

您可以直接安装 pg_when 扩展包的预置二进制包,首先确保 PGDGPIGSTY 仓库已经添加并启用:

pig repo add pgsql -u          # 添加仓库并更新缓存

使用 pig 或者是 apt/yum/dnf 安装扩展:

pig install pg_when;          # 当前活跃 PG 版本安装
pig ext install -y pg_when -v 18  # PG 18
pig ext install -y pg_when -v 17  # PG 17
pig ext install -y pg_when -v 16  # PG 16
pig ext install -y pg_when -v 15  # PG 15
pig ext install -y pg_when -v 14  # PG 14
dnf install -y pg_when_18       # PG 18
dnf install -y pg_when_17       # PG 17
dnf install -y pg_when_16       # PG 16
dnf install -y pg_when_15       # PG 15
dnf install -y pg_when_14       # PG 14
apt install -y postgresql-18-pg-when   # PG 18
apt install -y postgresql-17-pg-when   # PG 17
apt install -y postgresql-16-pg-when   # PG 16
apt install -y postgresql-15-pg-when   # PG 15
apt install -y postgresql-14-pg-when   # PG 14

创建扩展

CREATE EXTENSION pg_when;

用法

来源: official README, official repo

pg-when 解析受限的自然语言时间表达式,并返回 PostgreSQL timestamp with time zone,或返回不同精度的 Unix epoch 值。

CREATE EXTENSION pg_when;

SELECT when_is('next friday at 8:00 pm in America/New_York');
SELECT seconds_at('next friday at 8:00 pm in America/New_York');
SELECT millis_at('next friday at 8:00 pm in America/New_York');
SELECT micros_at('next friday at 8:00 pm in America/New_York');
SELECT nanos_at('next friday at 8:00 pm in America/New_York');

支持的查询形态

解析器最多接受三部分:

SELECT when_is('<date> at <time> in <timezone>');
SELECT when_is('<date>');
SELECT when_is('<time> in <timezone>');
SELECT when_is('<date> at <time>');

如果没有提供时区,上游说明默认使用 UTC。

常见输入

  • 相对日期:today, tomorrow, last month, this friday, 5 days ago, in 2 years
  • 精确日期:YYYY-MM-DD, DD/MM/YYYY, January 10, 2004, 10 Jan 2004
  • 相对时间:noon, midnight, morning, evening, next hour
  • 精确时间:8:30 pm, 15:45
  • 时区:America/New_York, Europe/London, UTC-08:00, UTC+05:30

示例

SELECT when_is('5 days ago at this hour in Asia/Tokyo');
SELECT when_is('in 2 months at midnight in UTC-8');
SELECT when_is('December 31, 2026 at evening');

注意事项

  • 该扩展面向上面记录的语法,而不是任意英文表达。
  • 上游提供了 PostgreSQL 13 到 18 的现成 Docker 镜像,但这个 stub 应聚焦 SQL 用法,而不是容器部署。