Creating a PostgreSQL extension involves several steps, including writing the C code for the extension, defining the SQL interface to the extension, and compiling the code into a shared library that PostgreSQL can load. Below is a simplified example of how to create a "Hello, World!" PostgreSQL extension in C.
- Write the C code for the extension:
// hello_world.c
#include "postgres.h"
#include "fmgr.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
PG_FUNCTION_INFO_V1(hello_world);
Datum
hello_world(PG_FUNCTION_ARGS)
{
PG_RETURN_TEXT_P(cstring_to_text("Hello, World!"));
}
- Define the SQL interface to the extension:
-- hello_world.sql
CREATE OR REPLACE FUNCTION hello_world()
RETURNS text AS 'MODULE_PATHNAME'
LANGUAGE C STRICT;
- Create a Makefile to compile the extension:
# Makefile
MODULES = hello_world
EXTENSION = hello_world
DATA = hello_world--1.0.sql
PG_CONFIG = pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)
- The SQL file to define the extension version:
-- hello_world--1.0.sql
CREATE OR REPLACE FUNCTION hello_world()
RETURNS text AS 'MODULE_PATHNAME', 'hello_world'
LANGUAGE C STRICT;
- Compile the extension:
make
make install
- Connect to your PostgreSQL database and create the extension:
-- In the psql command line interface or through a SQL script
CREATE EXTENSION hello_world;
- Use the new function in SQL:
SELECT hello_world();
This should return:
hello_world
-------------
Hello, World!
(1 row)
Please note that the actual process may require additional steps depending on the PostgreSQL version and how it's set up on your system. You also need to have appropriate permissions to create new extensions in the database. Furthermore, the shared library file (hello_world.so) should be placed in the PostgreSQL library directory, and the SQL control file (hello_world.control) should be in the extension directory for PostgreSQL to recognize the extension. The control file typically contains metadata about the extension, such as its default version and other dependencies.