Last active
June 16, 2021 18:24
-
-
Save ranjanprj/952254072c69acb092bc01260e7b73dd to your computer and use it in GitHub Desktop.
Creating a very simple PostgreSQL Extension in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sudo apt-get update | |
sudo apt install postgresql-server-dev-12 | |
C File | |
========= | |
#include "postgres.h" | |
#include <string.h> | |
#include "fmgr.h" | |
#ifdef PG_MODULE_MAGIC | |
PG_MODULE_MAGIC; | |
#endif | |
/* by value */ | |
PG_FUNCTION_INFO_V1(add_one); | |
Datum | |
add_one(PG_FUNCTION_ARGS) | |
{ | |
int32 arg = PG_GETARG_INT32(0); | |
PG_RETURN_INT32(arg + 1); | |
} | |
Makefile | |
========== | |
MODULES = funcs | |
PG_CONFIG = pg_config | |
PGXS = $(shell $(PG_CONFIG) --pgxs) | |
INCLUDEDIR = $(shell $(PG_CONFIG) --includedir-server) | |
include $(PGXS) | |
funcs.so: funcs.o | |
cc -shared -o funcs.so funcs.o | |
funcs.o: funcs.c | |
cc -o funcs.o -c funcs.c $(CFLAGS) -I$(INCLUDEDIR) | |
Build | |
============== | |
sudo make && sudo make install | |
SQL | |
================ | |
drop function if exists add_one(integer); | |
CREATE or replace FUNCTION add_one(integer) RETURNS integer | |
AS '/home/ranjan/funcs.so', 'add_one' | |
LANGUAGE C STRICT; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment