Skip to content

About

Reusable template for developing, integrating, and testing SQLite C extensions.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

projects
urls

SQLite C Extension Template

This template integrates Alphabet, a minimal demo extension written in C, into the SQLite core and tests both its SQL interface and its C API from Python. CTD, a C module with no SQLite dependency, illustrates the broader aim: testing a component through its own C API while it remains part of a larger library.

Overview

The Windows build harness compiles both components into the SQLite amalgamation (sqlite3.c). They expose different interfaces:

  • Alphabet provides the scalar SQL function alpha_string(), the read-only virtual tables letters and digits, and a C API for UTF-8 traversal and alphabet selection. In the SQL-enabled build, Alphabet’s built-in auto-extension registers the function and both tables on each new connection without loading a separate extension DLL. Python’s sqlite3 exercises SQL registration, argument handling, results and errors. A compiled CFFI API-mode wrapper calls the helpers exported by the test build.
  • CTD is a standalone C module from CFFI_Pytest_C_Testing. It implements only a C API: it calls no SQLite routines and has no SQL functions or SQLite initializer. Its examples demonstrate how to test pointers, buffers, structures, callbacks, ownership and failure behavior from Python with CFFI and pytest.

The template is intended for small or medium SQLite extensions with C logic worth testing independently of SQL. It supplies the Alphabet and CTD build hooks and one C API test preset. The primary source for the Windows build harness is SQLite-ICU-MinGW’s Current/MSVC README. The SQLite MSVC build field note explains how the harness integrates loadable extensions into the amalgamation and registers them automatically on each new connection.

Important

AI-Assisted Development Disclosure

This project has been developed with extensive generative-AI assistance. Assistance covered project exploration, design discussion, specification development, implementation, testing, technical review, and documentation. See AI_DISCLOSURE.md for further details. Responsibility for the published software remains with the maintainer.

Build the worked example on Windows

Run the commands from the repository root in Windows CMD. Install the Visual C++ Build Tools with a Windows SDK and use a checkout path without spaces for the project hooks.

Use one base directory per build. Keep each architecture, build configuration or dependency installation in a separate checkout or copy of the template. The harness stages dependencies under out\sqlite and packages headers and libraries outside out\build. The CFFI builder also writes the wrapper and copies binaries under alphabet\src\alphabet. Replacing only out\build does not isolate two configurations.

Prepare the Python environment

If you already have a dedicated test environment with architecture-matched Python, CFFI, setuptools and pytest, use it with the matching MSVC toolchain and skip the bundled setup. The bundled Conda-Bootstrap scripts set up an x64 Python environment.

Caution

The bundled scripts also change the Windows user profile. The environment launcher removes existing %LOCALAPPDATA%\pip\cache and %LOCALAPPDATA%\uv\cache directories and replaces them with junctions to its selected caches. On first bootstrap, Anaconda.bat also removes %APPDATA%\mamba if it exists. To leave those locations untouched, use your own environment and skip both commands below.

To use the bundled environment, start a clean cmd.exe /d /e:on /v:on with CONDA_PREFIX unset and with python.exe and conda.bat absent from PATH. Create the environment on first use, then activate it in the current prompt:

call pyenv\Anaconda.bat
call pyenv\conda_far.bat /batch

The bootstrap creates pyenv\Anaconda and reuses it when its python.exe exists. The launcher calls its sibling pyenv\msbuild.bat before Conda activation and sets DISTUTILS_USE_SDK=1 after successful MSVC verification. Set SQLite build switches after activation.

Choose a test build

Choose one of the two configurations below for this checkout. Both export the Alphabet and CTD C APIs and register Alphabet’s SQL function and virtual tables.

Building local changes. The project hooks fetch missing C sources and headers from this repository’s main branch, then reuse the files in out\cache\SQLiteExtensionTemplate\src. For local edits or a checkout at a different revision, seed the cache from that checkout before compiling. When rebuilding edited sources within the same configuration, start with a fresh out\build so NMAKE regenerates the amalgamation. Commands for local source edits

Full suite: SQL and C API tests

Call the main harness directly with the full-suite settings. SQLITE_EXTRA=1 includes the auto-extension dispatcher and enables ZLIB. This recipe does not require ICU.

set "USE_ICU=0"
set "SQLITE_EXTRA=1"
set "USE_EXTRAS=1"
set "SQLITE_ENABLE_ALPHABET=1"
set "USE_TEST=1"
cmd /d /c sqlite_msbuild.bat

USE_EXTRAS=1 runs both project hooks, but only Alphabet has a SQL feature to enable:

  • The Alphabet hook skips the component when SQLITE_ENABLE_ALPHABET=0. Otherwise it adds -DSQLITE_ENABLE_ALPHABET, the compile definition that guards the dispatcher’s call to sqlite3AlphabetInit(db).
  • There is no SQLITE_ENABLE_CTD switch. The CTD hook adds ctd.c whenever project hooks run. CTD has no SQLite initializer for the dispatcher to call.

USE_TEST=1 enables the C test exports of the included components.

Template preset

Run the single preset in a child CMD to keep its settings local. It enables the project hooks and C test exports with ICU, ZLIB and the stock stage disabled.

cmd /d /c sqlite_msbuild_extra.bat

Verify dispatcher integration

Start out\bin\sqlite3.exe ":memory:" from the repository root and enter these queries.

SELECT sqlite_compileoption_used('EXTRA_AUTOEXT') AS dispatcher;
SELECT alpha_string('en', 0, 3);

Both documented builds should return 1 for dispatcher. A 0 means the running SQLite was compiled without the dispatcher option. The second query checks Alphabet’s registration on this connection and should return ABC.

Test with Python

On Windows, Conda Python’s standard-library sqlite3 module normally loads Library\bin\sqlite3.dll from the environment. A fresh Python process can use the template’s DLL without rebuilding Python, provided the MSVC target matches the interpreter’s architecture and the SQLite build preserves the binary interface expected by Python’s _sqlite3 module. The upstream MSVC guide to custom SQLite in Conda Python covers runtime compatibility and dependencies.

On Linux, the corresponding runtime is lib/libsqlite3.so.0 under the Conda prefix. The upstream GCC workflow uses a Bash wrapper to install and verify SQLite in its own out/conda environment by default. Its shipped presets do not build Alphabet or CTD; this template supplies Windows build hooks.

Select the SQLite DLL used by pytest

If your interpreter already uses the desired template build, skip to the SQL checks. The fixtures import sqlite3 before the CFFI wrapper, so placing a DLL beside the wrapper cannot replace the one Python has already loaded. Run the DLL path helper with the interpreter you will use for pytest:

python tool\sqlite3_dll_path.py

Use the path the helper reports. If it finds no separately loaded sqlite3.dll, this method does not apply. Use the commands below only if the path is %CONDA_PREFIX%\Library\bin\sqlite3.dll in your dedicated test environment. Close processes using it and rename the original to an unused backup name so the copy does not overwrite a file that may be hard-linked to Conda’s package cache:

ren "%CONDA_PREFIX%\Library\bin\sqlite3.dll" sqlite3.dll.before-alphabet && copy "out\bin\sqlite3.dll" "%CONDA_PREFIX%\Library\bin\sqlite3.dll"

For either template build, copy only sqlite3.dll. Both disable ICU. The preset disables ZLIB, and the full-suite configuration links it statically by default, so Python does not need the collected zlib1.dll. For a different configuration, place any missing runtime DLLs beside sqlite3.dll. If you enable ICU and use the Conda environment that supplied it, the matching ICU DLLs are already there.

Run SQL tests with the active Python

Start python in the target environment and check the dispatcher and Alphabet separately. A successful check in out\bin\sqlite3.exe or a matching sqlite3.sqlite_version does not tell you which build Python loaded.

import sqlite3
from contextlib import closing

with closing(sqlite3.connect(":memory:")) as db:
    print(db.execute("SELECT sqlite_compileoption_used('EXTRA_AUTOEXT')").fetchone()[0])
    row = db.execute("""
        SELECT alpha_string(?, 0, 3),
               (SELECT count(*) FROM letters(?)),
               (SELECT count(*) FROM digits(?))
    """, ("en", "ru", 16)).fetchone()
    print(row)

Both documented builds should print 1 and ('ABC', 66, 16). The 1 confirms the dispatcher option, not Alphabet registration. The tuple shows that the scalar and both tables work on this connection without load_extension(): letters('ru') returns 33 uppercase and 33 lowercase letters, and digits(16) returns 16 digits.

From the repository root, run the existing SQL tests with the same interpreter. They need pytest but not the CFFI wrapper; their fixtures open and close the in-memory connections.

python -m pytest alphabet/tests/test_registration.py alphabet/tests/test_alpha_string_sql.py alphabet/tests/test_virtual_tables.py

These tests cover scalar arities 1, 2 and 3, argument handling and virtual-table behavior, including hidden arguments, Unicode rows and independent scans. CTD has no SQL interface; test it and Alphabet’s exported C helpers through CFFI below.

Compile the CFFI wrapper and run pytest

Use the same Python and an active MSVC environment. The SQLite harness collects sqlite3*.h under out\include. The wrapper compiler also needs the original alphabet.h, ctd.h and their _api.h catalogues. Copy the project's headers from the same revision used for the DLL before invoking the builder.

copy /y "src\*.h" "out\include\"
python alphabet\src\alphabet\build_wrapper.py

The builder discovers each src\*_api.h with its matching .c and .h. In CFFI’s out-of-line API mode, the builder reads the catalogue for ffi.cdef() and the C compiler checks the generated wrapper against the staged component headers. The builder compiles a single _cffi_wrapper with <NAME>_TEST and <NAME>_USE_LIB and links it against the import libraries in out\lib\import; the C implementation stays in sqlite3.dll. It writes the wrapper under alphabet\src\alphabet and copies the contents of out\bin beside it. The pytest fixtures import that prebuilt module and expose its ffi and lib objects. Wrapper builder · Fixtures

To run the C API tests for both modules, use the following subset.

python -m pytest ^
  alphabet\tests\test_alphabet_helpers.py ^
  alphabet\tests\test_alphabet_wrapper_api.py ^
  alphabet\tests\test_cffi_usage_patterns.py ^
  alphabet\tests\test_globals_status_and_scalars.py ^
  alphabet\tests\test_pointers_arrays_and_bytes.py ^
  alphabet\tests\test_strings_structures_and_ownership.py

With either documented test build, run the entire suite.

python -m pytest alphabet\tests

Run pytest from a staged directory

Running pytest without arguments from the repository root uses pyproject.toml. Running it from alphabet\ uses pytest.ini there. Both configurations locate the Alphabet package relative to the configuration file. Tests import their sibling helpers (cffi_types.py and support.py) through the tests package, so collection also works with --import-mode=importlib.

For a staged SQL run, copy alphabet\pytest.ini and the complete alphabet\tests\ directory. Use the Python environment with the Alphabet SQLite build and select the SQL test modules.

For the full suite, also copy alphabet\src\alphabet\, including __init__.py, the wrapper built for that Python, and its runtime binaries. The C API fixture checks that Python found the package in this staged directory before importing alphabet._cffi_wrapper.

To run the full staged suite from another directory, pass both the configuration and the tests directory.

python -m pytest -c B:\stage\alphabet\pytest.ini B:\stage\alphabet\tests

What each test proves

Test surface Examples in this repository
Alphabet SQL registration and behavior Arity and flags, argument validation, Unicode slicing, NULL propagation, expression indexes, execution with an untrusted schema, and virtual-table scans with optional arguments. Registration · SQL contract · SQL contexts · Virtual tables
Alphabet C API Function signatures, byte widths, code-point counts, byte offsets, and lifetime of borrowed alphabet strings. Helper tests · Wrapper API tests
CTD C API Mutable globals, failure contracts, pointer and buffer capacities, callbacks, structured data and C-owned allocations. Pointers and buffers · Ownership · CFFI usage

A passing C helper test does not show that SQLite registered the SQL function. If the helpers pass but Python reports no such function: alpha_string, check which configuration you built and which DLL Python loaded. Conversely, an expected SQL result does not prove that the DLL exports the C symbols or that a helper honors its buffer and lifetime contracts. Those are direct C API checks.

Testing CTD inside a larger library

In the standalone CTD build, the CFFI wrapper links against ctd.dll, which contains only CTD. Here the wrapper links against the test build of sqlite3.dll, which contains CTD alongside Alphabet and SQLite itself. No separate CTD DLL is needed.

The original callback test and its counterpart in this template illustrate what stays the same: both pass a Python callback and user data to lib.ctd_apply_callback() and check that it returns CTD_OK and writes 32 to the output. The test exercises the component through its own C API regardless of which DLL contains it.

The Alphabet SQL interface

alpha_string(language [, start [, length]])

'en' and 'English' select the 52-character Latin alphabet. 'ru' and 'Russian' select the 66-character Russian alphabet including Ё and ё. Names are case-insensitive, and each alphabet lists uppercase letters before lowercase letters. start is a zero-based Unicode code-point index. Negative indices count from the end, and a start at the end returns an empty string. length is a nonnegative integer capped at the number of remaining code points. A NULL in any supplied argument returns NULL. Invalid types, unknown languages and out-of-range indices raise SQL errors.

SELECT alpha_string('English', 0, 3);  -- ABC
SELECT alpha_string('Russian', 2, 4);  -- ВГДЕ
SELECT alpha_string('ru', -2);         -- юя

Read-only virtual tables

Each table returns one text symbol per row and accepts one optional argument. Both names are available as soon as the SQL-enabled extension initializes a connection.

SELECT * FROM letters;         -- English alphabet
SELECT * FROM letters('ru');   -- Russian alphabet

SELECT * FROM digits;          -- Decimal digits
SELECT * FROM digits(16);      -- Hexadecimal digits
Table Column returned by SELECT * Hidden argument column Values
letters letter (TEXT) language (TEXT), default 'en' The same English and Russian alphabets as alpha_string(), including its case-insensitive language aliases.
digits digit (TEXT) radix (INTEGER), default 10 Integer 10 gives 0–9. Integer 16 adds uppercase A–F.

Each scan numbers its rows from 1. Use ORDER BY rowid to request alphabet or digit order explicitly. An omitted argument selects the default. An explicit SQL NULL produces zero rows. Unsupported values, argument types and excess arguments raise SQL errors.

The tables are eponymous-only. The module sets xCreate to NULL, so SQL can use each registered name directly. SQLite maps a positional argument to an equality constraint on the hidden column. For example, FROM digits(16) is equivalent to FROM digits WHERE radix = 16. You can also select a hidden column by name. It returns the supplied argument or the default.

SELECT rowid, digit, radix FROM digits(16) WHERE rowid = 11;  -- 11, A, 16

Built-in and loadable extension registration

The SQLite-facing code lives in one internal registration routine. The three fixed scalar arities let SQLite reject an unsupported argument count before calling alphabetStringFunc(). The routine then registers each table name with the shared sqlite3_module and returns the first registration error to the caller. Source

/*
** Register the extension's SQL function and virtual tables.
**
** Three fixed arities let SQLite reject alpha_string() calls with zero
** arguments or more than three arguments.
*/
static int alphabetInit(sqlite3 *db) {
    static const int flags = SQLITE_UTF8 | SQLITE_DETERMINISTIC | SQLITE_INNOCUOUS;
    int rc = SQLITE_OK;

    if (rc == SQLITE_OK) {
        rc = sqlite3_create_function(
            db, "alpha_string", 1, flags, 0,
            alphabetStringFunc, 0, 0
        );
    }

    if (rc == SQLITE_OK) {
        rc = sqlite3_create_function(
            db, "alpha_string", 2, flags, 0,
            alphabetStringFunc, 0, 0
        );
    }

    if (rc == SQLITE_OK) {
        rc = sqlite3_create_function(
            db, "alpha_string", 3, flags, 0,
            alphabetStringFunc, 0, 0
        );
    }

#ifndef SQLITE_OMIT_VIRTUALTABLE
    if (rc == SQLITE_OK) {
        rc = sqlite3_create_module(db, "letters", &alphabetTableModule, 0);
    }
    if (rc == SQLITE_OK) {
        rc = sqlite3_create_module(db, "digits", &alphabetTableModule, 0);
    }
#endif

    return rc;
}

The two entry points in the same source file share that routine. In both documented builds, the dispatcher calls sqlite3AlphabetInit(db) when SQLite opens a database connection. A standalone loadable build exports sqlite3_alphabet_init, which first initializes the SQLite API dispatch table from pApi. The Windows harness builds the integrated form.

#ifdef SQLITE_CORE

int sqlite3AlphabetInit(sqlite3 *db) {
    return alphabetInit(db);
}

#else

# if defined(_WIN32)
__declspec(dllexport)
# endif
int sqlite3_alphabet_init(
    sqlite3 *db,
    char **pzErrMsg,
    const sqlite3_api_routines *pApi
) {
    SQLITE_EXTENSION_INIT2(pApi);
    (void)pzErrMsg;  /* Unused parameter */
    return alphabetInit(db);
}

#endif /* SQLITE_CORE */

The test-visible C contract

The implementation, linkage rules and declaration catalogue have separate jobs. For Alphabet, alphabet.c implements the SQL adapter and four helper routines, alphabet.h selects linkage and includes the catalogue, and alphabet_api.h declares the helpers and documents their preconditions. CTD uses the same file arrangement. Alphabet header · Alphabet API catalogue · CTD header

In a production build ALPHABET_TEST_API gives the helpers internal linkage. In the test DLL, ALPHABET_TEST with ALPHABET_BUILD_LIB exports them. The wrapper consumes the same declarations with ALPHABET_TEST and ALPHABET_USE_LIB. CTD uses the corresponding CTD_* macros. This makes selected routines testable directly while the SQL interface stays the same.

The API catalogue records details the C types alone cannot express. For example, ab_utf8_length() expects valid, NUL-terminated UTF-8. ab_utf8_byte_offset() takes a code-point index in the documented range and returns a byte offset. ab_alphabet_select() returns borrowed static storage for a supported language or a null pointer for an unknown name. Direct tests exercise those contracts, and the SQL tests exercise validation before SQLite passes values to the helpers.

One direct test passes the pointer returned by one C function straight to another. The expected length is measured in code points even when the Russian string occupies two bytes per letter. Alphabet wrapper tests

@pytest.mark.parametrize(
    ("language", "expected_length"),
    [
        pytest.param(b"en", 52, id="selected-latin"),
        pytest.param(b"ru", 66, id="selected-cyrillic"),
    ],
)
def test_utf8_length_accepts_borrowed_alphabet_storage(
    ffi: Any, lib: Any, language: bytes, expected_length: int
) -> None:
    alphabet = lib.ab_alphabet_select(language)
    assert alphabet != ffi.NULL
    assert lib.ab_utf8_length(alphabet) == expected_length

Keep borrowed storage alive while C uses it. For each CTD allocation, use the release function documented for that return value:

Value What the caller must do
Storage passed with ffi.new() or ffi.from_buffer() Keep the owning Python/CFFI object alive while C uses it. Do not pass it to a C deallocator.
Borrowed string from ab_alphabet_select() Do not free it. Use ffi.string() to make an independent Python copy when needed.
Counter from ctd_counter_create() or sequence from ctd_alloc_sequence_i32() Release each successful allocation once with ctd_free().
Handle from ctd_accumulator_create() Use ctd_accumulator_destroy(). It releases the nested storage as well as the handle; ctd_free() alone does not.

The CTD API catalogue documents these contracts. The fixtures demonstrate resetting mutable globals and pairing allocations with release; the accumulator lifecycle test shows the type-specific destructor in a finally block.

Adapting the template

  1. Define the C contract. For each component the wrapper should expose, provide src\<name>.c, src\<name>.h and src\<name>_api.h. The wrapper builder scans every *_api.h and checks that the matching linkage header contains <NAME>_TEST and defines <NAME>_TEST_API. Keep compiler-only includes and linkage logic in <name>.h. The catalogue supplies the declarations for ffi.cdef(); document pointer direction, valid ranges, length units, ownership, lifetime and failure behavior there.
  2. Stage your own sources. Add a sqlite_ext_<name>.bat hook beside sqlite_msbuild.bat; USE_EXTRAS=1 runs the project hooks. When copying the Alphabet hook, change URL_PREFIX, the filenames and the cache path to use your own repository and intended revision. Stage the sources and headers in tsrc, run the patcher and bundler on the staged C file, and append it to EXTRA_SRC. When USE_TEST=1, add -D<NAME>_TEST and -D<NAME>_BUILD_LIB to OPT_XTRA.
  3. Register SQL features separately from compiling them. For a SQL extension, provide an initializer the patcher recognizes, such as sqlite3AlphabetInit. Enable the matching dispatcher guard (for Alphabet, SQLITE_ENABLE_ALPHABET) in the hook. The harness includes the dispatcher for project hooks with either setting of SQLITE_EXTRA. Adding a C file to EXTRA_SRC alone does not register a SQL function. A plain C module like CTD needs neither a SQLite initializer nor a dispatcher guard.
  4. Verify the result. Rebuild SQLite, check the DLL exports and, for a SQL extension, check registration on a new connection. Stage the matching headers, compile the wrapper, then test the C contract and the SQL behavior through their respective interfaces.

Repository guide

Path Contents
sqlite_msbuild.bat and sqlite_msbuild.md Native build entry point, template preset, feature switches, cache and rebuild instructions.
msbuild.bat and pyenv/ MSVC discovery and verification, plus the Python bootstrap and activation scripts.
src/ and tool/ Project C sources and declaration catalogues, Tcl preparation scripts and development utilities.
alphabet/src/alphabet/ CFFI builder, CTD demonstration, wrapper introspection and SQLite metadata utilities.
alphabet/tests/ and pyproject.toml pytest suite and Python project configuration.
out\ (generated) cache holds downloaded inputs, sqlite the extracted tree, and build the NMAKE working files. Packaged outputs go to bin, include, lib\import and lib\static.

Further examples

Extension What it demonstrates
ICUex Registers the ICU-backed UTF_CI and UTF_CI_AI collations and exposes Unicode case folding and normalization through str_casefold() and str_normalize().
InfoSchema Exposes SQLite metadata through read-only virtual tables. For example, SELECT * FROM funcs lists the SQL functions registered on the current connection.
PackedBlob pblob_pack() encodes a one-dimensional JSON array of numbers as a binary16 or binary32 BLOB; pblob_unpack() decodes it to JSON text.
RegexpMatches Reuses SQLite’s ext/misc/regexp.c in the amalgamation. regexp_matches() and regexpi_matches() return non-overlapping matches as a JSON array.

Summary

  • Keep SQL registration and argument handling in the SQLite adapter. The same registration routine can serve both built-in and loadable entry points.
  • Use a project hook to stage the C implementation and a shared *_api.h catalogue to declare the routines worth testing directly. Test-build macros expose those routines from sqlite3.dll without making them public in the normal build.
  • Test the same DLL through both interfaces: Python’s sqlite3 for Alphabet’s SQL registration and behavior, and the compiled CFFI wrapper for Alphabet’s helpers and CTD’s C API. CTD can be tested inside SQLite without adding a SQL adapter.

About

Reusable template for developing, integrating, and testing SQLite C extensions.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages