blob: f4493adb74c10fe461842c0f7cfa5a63233c10be (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
https://www.reddit.com/r/golang/comments/1ol2tqv/write_postgresql_functions_in_go_golang_example/
Write PostgreSQL functions in Go Golang example
It took me a while to figure this out. Go compiles the C files automatically.
add_two.c
#include "postgres.h"
#include "fmgr.h"
PG_MODULE_MAGIC;
extern int32 Adder(int32);
PG_FUNCTION_INFO_V1(add_two);
Datum
add_two(PG_FUNCTION_ARGS)
{
int32 arg = PG_GETARG_INT32(0);
PG_RETURN_INT32(Adder(arg));
}
adder.go
package main
/*
#cgo CFLAGS: -DWIN32 -ID:/pg18headers -ID:/pg18headers/port/win32
#cgo LDFLAGS: -LD:/pg18lib
#include "postgres.h"
#include "fmgr.h"
// Forward declare the C function so cgo compiles add_two.c too.
extern void init_add_two();
*/
import "C"
//export Adder
func Adder(a C.int32) C.int32 {
return a + 3
}
func main() {}
Compile it
PS D:\C\myextension> go build -o add_two.dll -buildmode=c-shared
In PostgreSQL: open the query window (adjust path to your generated dynamically loaded library and header file (.dll, .h).
CREATE FUNCTION add_two(int4) RETURNS int4
AS 'D:/C/myextension/add_two.dll', 'add_two'
LANGUAGE C STRICT;
And finally test it:
SELECT add_two(10)
Result:
add_two (integer)
1 13
|