Skip to content

Instantly share code, notes, and snippets.

@ranjanprj
Last active November 9, 2019 18:10
Show Gist options
  • Save ranjanprj/c18f0927ace72cf70b028e02e9f8f6e5 to your computer and use it in GitHub Desktop.
Save ranjanprj/c18f0927ace72cf70b028e02e9f8f6e5 to your computer and use it in GitHub Desktop.
PostgreSQL Extension in C with Rustlang

Just a small gist to show how you can easily create a Rust shared lib, wrap it with C and call it from PostgreSQL SQL Command.

  1. Prereq : Tested on Ubuntu 18, GCC, postgresql-server-11, postgresql-dev-11, rustlang
  2. Create new project Cargo embed and cd embed
  3. Rename the file src/main.rs to lib.rs
  4. Add following code
#[no_mangle]
pub extern fn double_input(input: i32) -> i32 {
    input * 2
}

  1. Create a c file called funcs.c add following code in embed folder
#include "postgres.h"
#include <string.h>
#include "fmgr.h"
#include "utils/geo_decls.h"

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

/* by value */
extern int32_t double_input(int32_t input);
PG_FUNCTION_INFO_V1(double_num);

Datum
double_num(PG_FUNCTION_ARGS)
{
    int32   arg = PG_GETARG_INT32(0);

    PG_RETURN_INT32(double_input(arg));
}
  1. Create a file called Makefile in same folder Please change the file path to point to your home directory

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 /home/ranjanprj/embed/target/release/libembed.so

funcs.o: funcs.c
        cc -o funcs.o -c funcs.c $(CFLAGS) -I$(INCLUDEDIR)

  1. sudo make && sudo make install
  2. In postgresql create the extension Please change the file path to point to your home directory
drop function if exists double_num(integer);

CREATE or replace FUNCTION double_num(integer) RETURNS integer
     AS '/home/ranjanprj/embed/funcs.so', 'double_num'
     LANGUAGE C STRICT;   
    
  1. Execute
select double_num(4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment