开发一个简单的postgresql extension

 

主要是学习如何编写一个简单的pg extension,参考https://severalnines.com/blog/creating-new-modules-using-postgresql-create-extension

目的

创建一个类似oracel 的nvl 函数

项目创建

为了简化使用,使用docker && docker-compose 运行

  • 项目结构

    项目包含了一个zombodb的扩展,同时集成了 graphql-engine

├── Dockerfile
├── README.md
├── docker-compose.yaml
├── extension
│ ├── Makefile
│ ├── nvlfunc--1.0.sql
│ └── nvlfunc.control
└── zombodb_centos7_pg10-10-1.0.3_1.x86_64.rpm
  • 代码说明
    dockerfile: 主要是添加了扩展文件目录的拷贝,因为使用了一个三方的pg 镜像,需要调整目录
FROM centos/postgresql-10-centos7
LABEL mail="1141591465@qq.com"
LABEL author="dalong"
COPY zombodb_centos7_pg10-10-1.0.3_1.x86_64.rpm /app/zombodb_centos7_pg10-10-1.0.3_1.x86_64.rpm
USER root
RUN rpm -Uvh /app/zombodb_centos7_pg10-10-1.0.3_1.x86_64.rpm
RUN cp -rf /usr/pgsql-10/share/extension/* /opt/rh/rh-postgresql10/root/usr/share/pgsql/extension
RUN cp /usr/pgsql-10/lib/zombodb.so /opt/rh/rh-postgresql10/root/lib64/pgsql/
COPY extension/nvlfunc--1.0.sql /opt/rh/rh-postgresql10/root/usr/share/pgsql/extension/
COPY extension/nvlfunc.control /opt/rh/rh-postgresql10/root/usr/share/pgsql/extension/
USER postgres

扩展的核心,对于扩展的开发比较重要的是nvlfunc.control 以及需要暴露sql
nvlfunc.control 文件

# nvlfunc extension
comment = 'Oracle compatible nvl function'
default_version = '1.0'
module_pathname = '$libdir/nvlfunc'
relocatable = false

nvlfunc--1.0.sql: 定义了nvl 函数的定义,注意命名格式

/* nvlfunc--1.0.sql */

-- complain if script is sourced in psql, rather than via ALTER EXTENSION
\echo Use "CREATE EXTENSION nvlfunc" to load this file. \quit

CREATE OR REPLACE FUNCTION public.NVL(SMALLINT,SMALLINT)
RETURNS SMALLINT AS $$
SELECT COALESCE($1,$2);
$$ LANGUAGE SQL IMMUTABLE;

docker-compose 文件

version: '3'
services:
  postgresql_db:
    build: ./
    image: dalongrong/my-ex-zombodb-postgresql-10-centos7
    ports:
    - "5432:5432"
    environment: 
    - "POSTGRESQL_ADMIN_PASSWORD=dalong"
  graphql-engine:
    image: hasura/graphql-engine:v1.0.0-alpha41
    ports:
    - "8080:8080"
    environment:
    - "POSTGRES_PASSWORD:dalong"
    command: >
      /bin/sh -c "
      graphql-engine --database-url postgres://postgres:dalong@postgresql_db:5432/postgres serve --enable-console;
      "

使用

  • 构建镜像
docker-compose build
  • 使用
    使用psql 或者pg 连接客户端
CREATE EXTENSION nvlfunc;

SELECT NVL(NULL::SMALLINT, 121::SMALLINT);
 nvl
-----
 121
(1 row)

说明

这是一个很简单的pg 扩展,实际上pg 扩展可以支持好多种语言的开发,同时做的比较好的方式是我们应该将扩展做成一个deb 或者rpm 包,方便安装使用

参考资料

https://severalnines.com/blog/creating-new-modules-using-postgresql-create-extension
https://github.com/rongfengliang/postgres-extension-demo
http://big-elephants.com/2015-10/writing-postgres-extensions-part-i/