開發一個簡單的postgresql extension

主要是學習如何編寫一個簡單的pg extension,參考https://severalnines.com/blog/creating-new-modules-using-postgresql-create-extensiongit

目的

建立一個相似oracel 的nvl 函數github

項目建立

爲了簡化使用,使用docker && docker-compose 運行sql

  • 項目結構

    項目包含了一個zombodb的擴展,同時集成了 graphql-enginedocker

├── 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 文件centos

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

nvlfunc--1.0.sql: 定義了nvl 函數的定義,注意命名格式app

/* 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 包,方便安裝使用post

參考資料

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/學習

相關文章
相關標籤/搜索