User Agents

Web browsers and everyday web tech, explained

PostgreSQL Extension Development: A Step-by-Step Guide

· 5 min read · Extensions

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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-all or postgresql-devel).
  • A C compiler (GCC or Clang) and make build tools.
  • A running PostgreSQL instance for testing.
  • Basic knowledge of C programming and the PostgreSQL internal architecture.

Step-by-Step

  1. Set Up Your Project Structure: Create a directory for your extension. A standard layout includes a src/ folder for C files and a sql/ folder for the control scripts. For example, name your project my_extension.
  2. Write the C Logic: Create a C file (e.g., my_ext.c). You must include postgres.h and other necessary headers like fmgr.h. Define your function logic here. Ensure you use the PG_FUNCTION_INFO_V1 macro for every function you intend to expose to SQL, as this informs the PostgreSQL function manager about the function's version.
  3. Define the Function Entry Point: Use the Datum type for return values and arguments, as PostgreSQL uses a generic data type for its internal representation. Convert these using macros like PG_GETARG_INT32 to get the actual value and PG_RETURN_INT32 to return it.
  4. Create the Control File: Create a file named my_extension.control in the root directory. This file tells PostgreSQL the version of the extension and its dependencies. A basic control file contains: default_version = '1.0' and module_pathname = '$libdir/my_extension'.
  5. Write the SQL Installation Script: Create a file named my_extension--1.0.sql in the sql/ folder. This script should contain the CREATE FUNCTION statements 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;.
  6. 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)
        
  7. Compile the Extension: Run make in your terminal. This will compile your C code into a shared object file (.so) and place it in the appropriate build directory.
  8. Install the Extension: Run sudo make install. This moves the .so file to the PostgreSQL library directory and the .control and .sql files to the extension directory.
  9. Enable the Extension in Database: Connect to your PostgreSQL instance using psql and execute the command: CREATE EXTENSION my_extension;.
  10. Verify Functionality: Test your new functionality by calling the function you created: SELECT my_func(10);.

Common Mistakes

  • Memory Leaks: Using standard malloc instead of PostgreSQL's palloc. palloc allocates 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.h after 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 palloc over malloc to avoid manual memory management and prevent leaks during transaction rollbacks.
  • Strict Functions: Mark your functions as STRICT in 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() or elog() for logging and error handling instead of printf(), 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.