PostgreSQL Extension Development: A Step-by-Step Guide
In this article
Writing a PostgreSQL extension allows you to add custom data types, index types, functions, and background workers to the database engine, extending its core functionality beyond what is possible with standard SQL or PL/pgSQL. By writing an extension in C, you can optimize performance-critical operations and integrate external libraries directly into the database kernel.
What You'll Need
- A Linux-based development environment (Ubuntu, Debian, or Fedora are common).
- The PostgreSQL source code or the server development headers (e.g.,
postgresql-server-dev-allorpostgresql-devel). - A C compiler (GCC or Clang) and
makebuild tools. - A running PostgreSQL instance for testing.
- Basic knowledge of C programming and the PostgreSQL internal architecture.
Step-by-Step
- Set Up Your Project Structure: Create a directory for your extension. A standard layout includes a
src/folder for C files and asql/folder for the control scripts. For example, name your projectmy_extension. - Write the C Logic: Create a C file (e.g.,
my_ext.c). You must includepostgres.hand other necessary headers likefmgr.h. Define your function logic here. Ensure you use thePG_FUNCTION_INFO_V1macro for every function you intend to expose to SQL, as this informs the PostgreSQL function manager about the function's version. - Define the Function Entry Point: Use the
Datumtype for return values and arguments, as PostgreSQL uses a generic data type for its internal representation. Convert these using macros likePG_GETARG_INT32to get the actual value andPG_RETURN_INT32to return it. - Create the Control File: Create a file named
my_extension.controlin the root directory. This file tells PostgreSQL the version of the extension and its dependencies. A basic control file contains:default_version = '1.0'andmodule_pathname = '$libdir/my_extension'. - Write the SQL Installation Script: Create a file named
my_extension--1.0.sqlin thesql/folder. This script should contain theCREATE FUNCTIONstatements that map the SQL function name to the C symbol defined in your code. Example:CREATE FUNCTION my_func(integer) RETURNS integer AS 'MODULE_PATHNAME', 'my_c_function_name' LANGUAGE C STRICT;. - Configure the Makefile: Use the PostgreSQL build infrastructure called PGXS (PostgreSQL Extension Tool). Your Makefile should look like this:
EXTENSION = my_extension MODULES = my_ext PG_CONFIG = pg_config PGXS := $(shell $(PG_CONFIG) --pgxs) include $(PGXS) - Compile the Extension: Run
makein your terminal. This will compile your C code into a shared object file (.so) and place it in the appropriate build directory. - Install the Extension: Run
sudo make install. This moves the.sofile to the PostgreSQL library directory and the.controland.sqlfiles to the extension directory. - Enable the Extension in Database: Connect to your PostgreSQL instance using
psqland execute the command:CREATE EXTENSION my_extension;. - Verify Functionality: Test your new functionality by calling the function you created:
SELECT my_func(10);.
Common Mistakes
- Memory Leaks: Using standard
mallocinstead of PostgreSQL'spalloc.pallocallocates memory in a memory context that is automatically cleaned up at the end of a transaction or function call. - Missing PG_FUNCTION_INFO_V1: Forgetting this macro causes the server to crash or fail to load the function because the function manager cannot find the required metadata.
- Incorrect Header Order: Including
postgres.hafter other PostgreSQL headers. It must always be the first include in the file. - Version Mismatch: Compiling the extension against one version of PostgreSQL headers but attempting to install it on a server running a different version.
Tips
- Use palloc: Always prefer
pallocovermallocto avoid manual memory management and prevent leaks during transaction rollbacks. - Strict Functions: Mark your functions as
STRICTin the SQL definition if they cannot handle NULL inputs; this prevents the C code from even being called if any argument is NULL. - Logging: Use
ereport()orelog()for logging and error handling instead ofprintf(), as these integrate with the PostgreSQL server logs. - Incremental Development: Build and test small functions individually before implementing complex data types or index methods.
Troubleshooting
If the CREATE EXTENSION command fails, first check the PostgreSQL server logs (usually found in /var/log/postgresql/). The logs will specify if there is a missing shared library or a permissions issue with the .so file.
If the server crashes (Segfault) upon calling your function, use gdb to attach to the backend process. Check for null pointer dereferences or improper casting of Datum values. Ensure that you are not attempting to access memory that has already been freed by a memory context.
If make fails, verify that pg_config is in your system PATH. If it is not, you may need to specify the full path to pg_config in your Makefile.
Frequently Asked Questions
Can I write extensions in languages other than C?
While the core extension framework is C, you can use PL/Python, PL/Perl, or PL/v8 to add functionality. However, these require the respective language extensions to be installed first and generally offer lower performance than C.
What is the difference between a function and an extension?
A function is a single piece of logic. An extension is a package that can include multiple functions, new data types, operators, and configuration files, making it portable and easy to install across different databases.
Do I need to restart the server after installing an extension?
For most extensions that only add functions, no restart is required. However, if your extension adds a background worker or modifies shared memory, a server restart is necessary.
How do I update an extension to a new version?
You must provide an update script named my_extension--1.0--1.1.sql and then run the command ALTER EXTENSION my_extension UPDATE TO '1.1';.
Where are the extension files stored on disk?
The .control and .sql files are stored in the SHAREDIR/extension directory, while the compiled .so binaries are stored in the PKGLIBDIR. You can find these paths by running pg_config --sharedir and pg_config --pkglibdir.