转自:https://www.opsdash.com/blog/postgresql-triggers-golang.html 可以学习如何使用golang 编写pg extension

Triggers in PostgreSQL are a simple yet powerful mechanism to react to changes happening in tables.

Read on to find out how to write PostgreSQL triggers in Go.

POSTGRESQL FUNCTIONS AND TRIGGERS

PostgreSQL lets you create user-defined functions using the CREATE FUNCTION SQL statement. Functions are essentially how PostgreSQL can manage user-defined pieces of logic.

Functions can be written in various languages – the most common one is probably PL/pgSQL, which is what you use when you write “stored procedures”. You can also write them in other languages, like Python and Perl.

They can also be written in C. For this, the C code has to be compiled into a dynamically loadable shared library (*.so). PostgreSQL can be told that a function lives as a certain symbol name in a certain *.so file. This is somewhat similar to how modules in Apache or Nginx work.

Functions can be used as triggers, which is what we’re interested in.

TRIGGERS

Triggers are a form of event handlers – they are pieces of logic that can be executed when certain events happen to specified objects. Typically, the objects involved are tables, but they can also be views or foreign tables.

The events, not surprisingly, are:

  • insert (rows)
  • update (rows)
  • delete (rows)
  • truncate (table)

PostgreSQL triggers are versatile:

  • They can be invoked once per row or once per statement. For example, if a statement updates 5 rows, the trigger can be invoked once for the statement or 5 times, one for each row.
  • They can be invoked before or after the actual change happens.
  • The “before” triggers have a change to modify the values or cancel the change.
  • Triggers can be used to impose any arbitrary constraint on a table.

The most popular use of triggers is probably creating audit logs (or more specifically, change logs). You can read more about triggers here and here.

DYNAMICALLY LOADABLE MODULES IN GO

Starting with version 1.5, Go has the ability to create C-style shared libraries. Using this, you can export an arbitrary Go function that can be invoked by other language runtimes – like dlopen/dlysm in C, ctypes in Python or JNI in Java.

You can build a C-style shared library in Go like this:

go build -o myso.so -buildmode=c-shared myso.go

Here myso.go is a Go main package, which looks like this:

packagemainimport"C"//export MyNamefuncMyName(xint)int{return42+x}funcmain(){// empty}

Note the “decorator” comment just above the exported function. The import "C" statement is also required for the export to happen.

WRITING POSTGRESQL FUNCTIONS IN GO

With this feature, we can build a *.so file contains an exported method that can be invoked as a PostgreSQL function.

There are some conventions that must be adhered to when writing this function – they are detailed here.

Let’s start off by defining the “module”, and listing an exported function called mytrigger.

// file module.gopackagemain/*
#include "postgres.h"
#include "fmgr.h" #cgo LDFLAGS: -Wl,--unresolved-symbols=ignore-all #ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif PG_FUNCTION_INFO_V1(mytrigger);
*/import"C"funcmain(){}

Note the LDFLAGS declaration. This lets us build the so file without the linker complaining about unresolved symbols. For PostgreSQL, there are no libraries to link against, and the symbols that are needed by our shared library can be verified only when the so file is loaded by PostgreSQL.

Next, let’s flesh out the trigger function itself in another file mytrigger.go:

// file mytrigger.gopackagemain/*
#include "postgres.h"
#include "commands/trigger.h" //... */import"C"import("fmt""unsafe")//export mytriggerfuncmytrigger(fcInfo*C.FunctionCallInfoData)C.Datum{trigdata:=(*C.TriggerData)(unsafe.Pointer(fcInfo.context))//...}

The signature of the exported Go function, mytrigger, is mandated by the PostgreSQL function manager convention. In case of triggers, this function is passed the row itself, which it can possibly modify (in case of “before” triggers), and return back.

For now, we’ll create a simple function that will be triggered after INSERTs and UPDATEs. It will not modify the data, and will return it back unchanged. Let’s also assume that the first column in the row will of type “text”, which we’ll read and print.

Now would be a good time to look at how the trigger would look like in C. Here is the example from the PostgreSQL docs.

Within the function, we want to first get the correct row data, since the function can be invoked via an INSERT or an UPDATE:

varrettuple*C.HeapTupleDataifC.trigger_fired_by_update(trigdata.tg_event)!=0{rettuple=(*C.HeapTupleData)(trigdata.tg_newtuple)}else{rettuple=(*C.HeapTupleData)(trigdata.tg_trigtuple)}

And then we’ll extract the first column data (indices start from 1), assuming it is a “text” data type (with no embedded NULs):

url:=C.GoString(C.getarg_text(trigdata,rettuple,1))

We’ll just print it out for now, rather than actually processing it:

C.elog_info(C.CString(fmt.Sprintf("got url=%s",url)))fmt.Println(url)

And finally return the original, unmodified data:

returnC.pointer_get_datum(rettuple)

The full file can be seen here. See below for the github repo link and build instructions.

RUNNING THE TRIGGER

To see the trigger in action, first let’s create a table:

$ sudo -u postgres psql -d test
psql (9.6.2)
Type "help" for help. test=# CREATE TABLE urls ( url TEXT );
CREATE TABLE
test=#

And then our function (you’ll need the USAGE privilege on language C for this):

test=# CREATE FUNCTION mytrigger()
test-# RETURNS TRIGGER AS '/home/alice/ptgo/ptgo.so'
test-# LANGUAGE C;
CREATE FUNCTION
test=#

Next let’s create a trigger on INSERT and UPDATE on table urls, that invokes our function:

test=# CREATE TRIGGER trig_1
test-# AFTER INSERT OR UPDATE
test-# ON urls
test-# FOR EACH ROW
test-# EXECUTE PROCEDURE mytrigger();
CREATE TRIGGER
test=#

Now let’s insert a couple of rows. The “got url=” lines are printed by our function:

test=# INSERT INTO urls VALUES ('http://example.com/');
INFO: got url=http://example.com/
INSERT 0 1
test=#
test=# INSERT INTO urls VALUES ('http://mydomain.com/');
INFO: got url=http://mydomain.com/
INSERT 0 1
test=#

And when the rows are updated, the function receives the post-change values because it is an AFTER trigger:

test=# UPDATE urls SET url='http://www.test.com/';
INFO: got url=http://www.test.com/
INFO: got url=http://www.test.com/
UPDATE 2
test=#

And that’s it! We have our very own PostgreSQL trigger written in Go!

THE CODE

The entire code is available on GitHub here: github.com/rapidloop/ptgo. Feel free to fork it and modify it to implement your own triggers. It has been tested only on Linux. To get started, do:

git clone https://github.com/rapidloop/ptgo
cd ptgo
make

You might need to install the development package for Postgres first. For Debian-based systems, this can be done with:

sudo apt-get install postgresql-server-dev-9.6
NEW HERE?

OpsDash is a server monitoring, service monitoring, and database monitoring solution for monitoring MySQL, PostgreSQL, MongoDB, memcache, Redis, Apache, Nginx, Elasticsearch and more. It provides intelligent, customizable dashboards and spam-free alerting via email, HipChat, Slack, PagerDuty and Webhooks. Send in your custom metrics with StatsD and Graphite interfaces built into each agent.

 
 
 
 

WRITING POSTGRESQL TRIGGERS IN GO的更多相关文章

  1. PostgreSQL相关的软件,库,工具和资源集合

    PostgreSQL相关的软件,库,工具和资源集合. 备份 wal-e - Simple Continuous Archiving for Postgres to S3, Azure, or Swif ...

  2. pg 资料大全1

    https://github.com/ty4z2008/Qix/blob/master/pg.md?from=timeline&isappinstalled=0 PostgreSQL(数据库) ...

  3. A Deep Dive into PL/v8

    Back in August, Compose.io announced the addition of JavaScript as an internal language for all new ...

  4. postgreSQL PL/SQL编程学习笔记(五)——触发器(Triggers)

    Trigger Procedures PL/pgSQL can be used to define trigger procedures on data changes or database eve ...

  5. PostgreSQL Reading Ad Writing Files、Execution System Instructions Vul

    catalog . postgresql简介 . 文件读取/写入 . 命令执行 . 影响范围 . 恶意代码分析 . 缓解方案 1. postgresql简介 PostgreSQL 是一个自由的对象-关 ...

  6. PostgreSQL源码安装文档

    This document describes the installation of PostgreSQL using the source    code distribution. (If yo ...

  7. PostgreSQL 之 CREATE FUNCTION

    官方文档 语法: CREATE [ OR REPLACE ] FUNCTION name ( [ [ argmode ] [ argname ] argtype [ { DEFAULT | = } d ...

  8. postgresql spi开发笔记

    #include "postgres.h" #include "fmgr.h" #include <string.h> #ifdef PG_MODU ...

  9. 广州PostgreSQL用户会技术交流会小记 2015-9-19

    广州PostgreSQL用户会技术交流会小记 2015-9-19 今天去了广州PostgreSQL用户会组织的技术交流会 分别有两个session 第一个讲师介绍了他公司使用PostgreSQL-X2 ...

随机推荐

  1. CentOS磁盘用完的解决办法,以及Tomcat的server.xml里无引用,但是项目仍启动的问题

    这是我2018年的第一篇博客...人真是懒了啊...最近在写微信小程序,觉得小程序做的也... 好了不吐槽了,言归正传 前言: 由于我之前不是买了个三年的香港服务器么 , 之前广州2的服务器我就没有续 ...

  2. Android 虹软2.0人脸识别,注册失败问题 分析synchronized的作用

    人脸识别需要init初始化(FaceServer中),离开时需要unInit销毁:当一个含有人脸识别的界面A跳向另一个含有人脸识别的界面B时,由于初始化和销毁都是对FaceServer类加锁(sync ...

  3. ubuntu 18.04安装clojure工程的cli工具lein

    官网的安装过程https://leiningen.org/#install 是文字描述,并不够lazy. 我仿照code,chrome nodejs的方式,给出下面的命令行安装过程 wget http ...

  4. 调用系统命令 os.system()和os.popen()

    Python中os.system和os.popen区别 Python调用Shell,有两种方法:os.system(cmd)或os.popen(cmd)脚本执行过程中的输出内容.实际使用时视需求情况而 ...

  5. JAVA文件操作类和文件夹的操作代码示例

    JAVA文件操作类和文件夹的操作代码实例,包括读取文本文件内容, 新建目录,多级目录创建,新建文件,有编码方式的文件创建, 删除文件,删除文件夹,删除指定文件夹下所有文件, 复制单个文件,复制整个文件 ...

  6. jQuery中异步问题:数据传递

    最近写一个新页面,涉及到异步问题,为了获得异步过程中的数据,以下分享两种方法: 两种方法一句话总结: 方法一,Http请求后调用.then实现response的数据同步,然后根据resp接着处理: 方 ...

  7. 如何设置在html中保留超链接格式但不实现跳转

    ---恢复内容开始--- 老师布置了一个任务,要求用户登录或者不登录都会有一个主页(home.jsp),如果登录的话就会跳转至登录界面(login.jsp),在登录界面中有个验证码,还要求有个和很多登 ...

  8. [luogu P3648] [APIO2014]序列分割

    [luogu P3648] [APIO2014]序列分割 题目描述 小H最近迷上了一个分隔序列的游戏.在这个游戏里,小H需要将一个长度为n的非负整数序列分割成k+1个非空的子序列.为了得到k+1个子序 ...

  9. mysql 主从配置,主-》windows,从-》centos6.5

    1.虚拟机配置的主从关系.win7 ip地址192.168.52.102,虚拟机ip 192.168.184.128.docs进入主服务器(master)mysql目录下,添加用户,然后执行mysql ...

  10. canvas绘图基础

    <canvas>元素是HTML5中的绘图元素,通过定义一个画布区域,然后使用javascript动态地在这个区域里面绘制图形,对于2D和3D图形都可以绘制,我们将其分成2D上下文和WebG ...