DEV Community

Prachi
Prachi

Posted on

Introduction to Creating Extensions in PostgreSQL with C : Part-2

  1. Setting up the Development Environment is the first step.
    Ensure that PostgreSQL and the required development libraries and headers are installed. You may install them using the package manager on the majority of systems.
    Also, add a PostgreSQL binary path to your environment, to ensure that pg_config is there in the path.

  2. Now we will create an extension 'addtwonumbers' that will add two numbers.

$ mkdir addtwonumbers

  1. Now for building the extension we will create a Makefile.

  2. We also need a control file addtwonumbers.control with the following content:

comment = 'Simple number add function'
default_version = '0.0.1'
relocatable = true
module_pathname = '$libdir/addme'
Enter fullscreen mode Exit fullscreen mode
  1. And then prepare the function and run the following command to make the file
#include "postgres.h"
#include "fmgr.h"

PG_MODULE_MAGIC;

PG_FUNCTION_INFO_V1(addme);

Datum
addtwonumbers(PG_FUNCTION_ARGS)
{
int32 arg1 = PG_GETARG_INT32(0);
int32 arg2 = PG_GETARG_INT32(1);

PG_RETURN_INT32(arg1 + arg2);
}

`$ make`
Enter fullscreen mode Exit fullscreen mode
  1. And now we can install the extension: $ sudo make install

Reference: https://www.percona.com/blog/postgresql-simple-c-extension-development-for-a-novice-user/

Top comments (0)