Skip to main content

nc-db

The nc-db package provides an easy way to use the document/object oriented capabilites of Postgres while maintaining good performance with large object by using B-tree indexes instead of GINs.

Serialization and deserialization is handled for you with pydantic.

Prerequisites

  • Python 3.14+
  • Pydantic 2.x (nc-db currently requires Pydantic 2.11.7 or newer)
  • PostgreSQL 15+ available locally, or run via the provided K8s manifests
  • pgvector installed on the PostgreSQL server and enabled in each database using the vector type

How To Use

  1. Install the package

    • poetry install nc-db
      
  2. Import the necessary classes

    • from nc_db.decorators import schema_version
      from nc_db.identifiable import Identifiable
      from nc_db.db_settings import DbSettings        
      # Import index types as needed (IntDbIndex is just one example)
      from nc_db.metadata.db_column import IntDbIndex
      
  3. Define your Postgres connection settings in a .env file (see example.env) or in the code by passing options to the DbSettings class.

  4. Create an instance of the Db class in your service somewhere near startup

    • my_db = Db(my_settings)
      
  5. Specify the schema version for the class you want to save in the database

    •   @schema_version(1)
        class Foo(Identifiable):
      
    • NOTE: If you make changes to your class (e.g attributes, attribute types, etc.) you should update the schema version number. This includes changes to classes that are referenced as attributes on your class. nc-db will raise an exception at run-time if anything changes and you forget to update the schema version number. You can suppress this with @schema_varsion(1,True) but it's not recommended as it may lead to hard-to-find bugs.
    • NOTE: This is only needed on the top-level class. If your class references other classes as attributes, they don't need a schema version but you'll need to update the schema version on your top-level class if anything changes on other classses it references.
  6. Define any custom indexes on attributes you wish to query (don't worry about the id attribute -- it's automatically added when you inherit from Identifiable)

    • NOTE: You MUST define an index on any attribute you wish to query or a run-time exception will be thrown.
    •   class Foo(Identifiable):
            my_var: IntDbIndex
      
    • OR use annotations for more customized indexes:
      class Foo(Identifiable):
          name: Annotated[str, DbColumn('VARCHAR NOT NULL', True, False)]
      
  7. Perform CRUD as frequently and quickly as you like (basic use cases)

    • # Save a new instance of an object to the database
      await db.insert(my_class_instance)
      # Get one or more instances from the databse by id
      await db.get(MyClass,[1])
      # Search for all objects where an attribute equals a value
      # NOTE: The my_attribute must be annotated as an index on 'MyClass'
      await db.search(MyClass,'my_attribute',23)
      # Search for all objects that meet arbitrary criteria
      # NOTE: my_attribute must be annotated as an index on 'MyClass'
      await db.search(MyClass,t"my_attribute < 23 AND my_attribute > 2")
      
  8. Perform advanced custom querying

    • # Generate columns in your SQL (e.g. pull out statistics, counts, calculate or concatenate values, etc.)
      # and map the query results to an object.
      # NOTE: Columns will be mapped based upon the class attributes. All class attibutes must map to a column
      # from the select statement or an exception will be raised.
      await db.select(MyQueryResult,t"SELECT COUNT(COL1) as count, (COL2 + COL3) as total FROM my_class WHERE COL1 LIKE 'TEST_%';")
      

pgvector setup

Install pgvector on the PostgreSQL server, using a package or container image that matches the server's PostgreSQL major version. Installing the Python pgvector package does not install the server extension. A missing vector.control file means the server installation is missing pgvector; SQL alone cannot fix that.

Connect to each application database as a role permitted to create the extension (typically a database administrator), then run:

CREATE EXTENSION IF NOT EXISTS vector WITH SCHEMA public;

Enable the extension before opening nc-db's connection pool. If the pool is already open, recreate it afterward so its connections register vector adapters. Connection pools created by nc-db automatic include public in the search path; the command above assumes a new extension installation in that schema. If the extension already exists in another schema, the database administrator must make its types accessible on the connection's search path (i.e. use the schema defined in your settings)

The pgvector integration-test fixtures enable the extension in each isolated test database automatically. The test server must still have pgvector installed, and the configured test administrator must have permission to enable it.

pgvector columns (nc-db >=0.6.0)

The PostgreSQL server must have pgvector installed, and each application database must have the extension enabled by database provisioning (see pgvector setup). nc-db does not install or enable extensions. The vector dimension is chosen in the column declaration; PostgreSQL checks value lengths. Declare model fields as nc_db.Vector, which accepts lists and upstream pgvector vectors. NumPy arrays are accepted when the application installs NumPy; NumPy is not required by nc-db at runtime. Reads return Vector values; use to_list() to access their elements. SQL predicates, partial updates, and compare-and-set values should pass explicit Vector instances. Bare Python lists in SQL templates retain ordinary PostgreSQL-array meaning. If pgvector is enabled after a pool has opened, recreate the pool so its connections register the vector adapters. nc-db registers pgvector adapters on pools it creates. Caller-created pools must set their own search path and register adapters on each connection with pgvector.psycopg.register_vector_async, then commit that setup.

from typing import Annotated

from nc_db import Vector
from nc_db.decorators import schema_version
from nc_db.identifiable import Identifiable
from nc_db.metadata.db_column import DbColumn

@schema_version(1)
class SampleEmbedding(Identifiable):
    hash: Annotated[bytes, DbColumn("BYTEA NOT NULL", index=True)]
    embedding: Annotated[Vector, DbColumn("vector(768) NOT NULL")]

query_vector = Vector([0.125] * 768)
rows = await db.search(SampleEmbedding, t"embedding <=> {query_vector} < 0.2")

If the application already installs NumPy, model_validate also accepts ndarray input:

import numpy as np

array_item = SampleEmbedding.model_validate({
    "hash": b"a" * 32,
    "embedding": np.asarray([0.125] * 768, dtype=np.float32),
})

await db.insert_ignore_conflict(item) returns None when a uniqueness conflict skips the insert; skipped items retain NEW_ID. db.insert(item) raises on a conflict.

Migrations and Backwards Compatibility

Schema signature update

The first nc-db release with signature format v2 updates matching legacy registrations the first time each class is used. Deploy it with persisted model definitions unchanged, allow each class to register, then deploy API annotation changes. Stop older nc-db workers before using the upgraded release against the same database. nc-db 0.8.1 and earlier releases use legacy signatures and cannot validate the v2 format.

Legacy signatures could omit definitions for fields named title, description, or example. This is unlikely to affect most applications, but if one of those fields changed at the same time as the library upgrade, unexpected behavior may occur. An annotation can also change the emitted shape of a union. That corner case requires a schema-version bump and a no-op migration such as lambda row: row passed to Db.migrate().

Migrating your application classes to a new version

NOTE:

  • This is required anytime you change the type or name of any attribute, or add or delete any attribute on a class with a schema_version
  • This includes nested classes (e.g. a class attribute that points to an instance of a class that has been modified) Db.migrate() reads a source table by its version and converts stored dictionaries to the current model. Historical Python classes are not needed. The source table must already exist; migration does not create it or require its registered schema signature. The destination class must have a newer @schema_version and pass the normal destination signature check.

The dictionary contains JSON body values and every physical table column, including id and promoted or generated columns. Physical columns override duplicate keys from the body. JSON values retain their stored JSON representation; promoted values use Psycopg's decoded Python values. The converter must preserve each source ID and return one dictionary per source. nc-db validates every result with the current Pydantic class, writes it, verifies Pydantic equality on read-back, and deletes source rows by default. Applications should test reusable transformation steps and prevent conflicting writes and deployments while migration runs.

from copy import deepcopy
from typing import Any

def upgrade_v1_to_v2(documents: list[dict[str, Any]]) -> list[dict[str, Any]]:
    updated = deepcopy(documents)
    for document in updated:
        document["new_field"] = "default"
    return updated

def upgrade_v2_to_v3(documents: list[dict[str, Any]]) -> list[dict[str, Any]]:
    updated = deepcopy(documents)
    for document in updated:
        document["current_name"] = document.pop("old_name")
    return updated

def upgrade_v1_to_v3(documents: list[dict[str, Any]]) -> list[dict[str, Any]]:
    return upgrade_v2_to_v3(upgrade_v1_to_v2(documents))

# MyClass is the current @schema_version(3) model; no v1/v2 model is needed.
migrated_ids = await db.migrate(1, MyClass, upgrade_v1_to_v3)

# Migrate at most the next 1000 source rows, ordered by ID.
batch_ids = await db.migrate(1, MyClass, upgrade_v1_to_v3, count=1000)

# Combine a bounded batch and application status update atomically.
async with db.transaction() as tx:
    batch_ids = await db.migrate(1, MyClass, upgrade_v1_to_v3, tx=tx, count=1000)
    await db.update(status, tx=tx)

# Skip work when another cooperating process holds the same user lock key.
async with db.try_xact_lock(100) as tx:
    if tx is not None:
        await db.migrate(1, MyClass, upgrade_v1_to_v3, tx=tx, count=1000)

count must be a positive integer when supplied; each call selects at most that many source rows in ascending ID order. Independent calls commit separately, so repeated bounded calls advance when default source deletion is enabled. With delete_after_migrate=False, a repeat selects the same lowest source IDs and ordinary destination uniqueness errors apply. A caller-supplied tx makes the migration part of that transaction; returned IDs are not durable until its outer scope commits. A lost connection while waiting for commit acknowledgement can leave the commit outcome uncertain. If a migration using tx raises, let the error leave the outer transaction scope or explicitly abort that scope. Migration does not create a savepoint; catching an error inside the scope does not roll back the migration's work independently.

try_xact_lock starts a transaction and yields its handle if the requested signed 32-bit user key is available, otherwise it yields None. Pass that handle to all guarded operations. Locking is cooperative among callers using the same key, and lasts until that transaction commits or rolls back. Keys are database-wide. Applications do not need to manage nc-db's internal advisory lock namespaces. In a read-only snapshot, lock acquisition may establish the snapshot before the lock is obtained; acquiring the lock does not refresh the snapshot.

Upgrading a version-1 database

Before starting nc-db version 2 against an existing version-1 database, stop all nc-db processes and run the complete scripts/migrate-nc-db-from-1-to-2.sql file in pgAdmin using a role that can create sequences and assign them to the existing table owner. Set its target_schema declaration to the installed schema. The script assumes only one version of each class table exists and no processes access the database during the upgrade. It converts the identity columns to shared per-class sequences and advances the database version to 2 in the same transaction. Version-2 nc-db rejects the database until that transaction has committed successfully. Fresh databases need no manual upgrade.

Option 2

  1. Write your own code to update the DB tables or migrate.
    • NOTE: For this to work your table name must match the table name generated by nc-db.

Guidelines

The Db class provides easy document/object-oriented CRUD capabilities for Pydantic classes.

  • Connects to a Postgres DB.
  • Supports concurrent connections across multiple processes / services
  • Uses b-trees for indexes
  • To improve performance with large objects:
    1. each object type has a dedicated table in the database.
    2. indexes are always maintained in dedicated columns (B-trees, no GIN indexes)
    3. The Db class handles all of this for you but you MUST apply the 'index' attribute to fields you want to search on.
  • The Db instance should share a lifecycle with your service or application. Recommended practice is to treat it like a singleton for each database your service connects to.

How it Works

graph TB

    subgraph API            
        db["Db class<hr>API for performing CRUD"]
        db_index["DbIndex<hr>Annotation that defines indexes on user classes"]
        identifiable["Identifiable<hr>Base class all user classes must derive from"]
    end
    subgraph Handlers
        command_handler["CommandHandler<hr>SQL for inserts, updates, etc."]
        query_handler["QueryHandler<hr>SQL for get, search, etc."]
        common["common.py<hr>small reusable code for handlers"]
    end
    subgraph Metadata
        class_metadata["ClassMetadata<hr>Structural information about the user's class"]
        db_column["DbColumn<hr>Maps attributes to user-defined indexes"]
        nc_config["nc_config.py<hr>Very small global config constants"]
        column_mappers["ColumnMapper<hr>Maps data from the DB into a column"]
    end
    user["User App"]
    user_db_class["User Db Classes"]
    db--->|Execute DB CRUD|Handlers
    db--->|Track information about classes|Metadata
    user--->|Initiate CRUD actions|db
    user_db_class--->|Annotate attributes that should be indexed for searches|db_index
    user--->user_db_class
    user_db_class--->|Inherits from|identifiable

GitHub Repo Overview

Contents

nc_db/            # Python source: Db, handlers, queries, metadata classes, etc.
tests/           # Pytest suite and fixtures (isolated schemas)
k8s/              # K8s StatefulSet, init SQL, and ops scripts
pyproject.toml    # Poetry + pytest configuration
.github/          # Issue and PR templates
README.md         # This file (schema diagram below)

Perform Type Checking

poetry run pyright

Run Tests

poetry run pytest

Publish

rm dist/*
python -m build
python -m twine upload dist/*

Metadata

Release files for nc-db 0.8.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for nc-db 0.8.2
File Size Uploaded Provenance Actions
nc_db-0.8.2.tar.gz 37.1 kB Without provenance Details for nc_db-0.8.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for nc-db 0.8.2
File Interpreter ABI Platform Actions
nc_db-0.8.2-py3-none-any.whl Python 3 none any Details for nc_db-0.8.2-py3-none-any.whl

Total release size: 78.0 kB

Release files / nc_db-0.8.2.tar.gz

Download URL nc_db-0.8.2.tar.gz
Size 37.1 kB
Tags Source
SHA-256 checksum
How to use checksums
ca501d0d32aca3be4bbbb5f723499ee23cf9ef0ca4ff8089c1f7861b883564ed
BLAKE2b-256 checksum
How to use checksums
c8c5953cd084c375db77874fac141e4605d5eff1acca43c56e10ad45603456ff
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.0

Release files / nc_db-0.8.2-py3-none-any.whl

Download URL nc_db-0.8.2-py3-none-any.whl
Size 41.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e6bbec1f443cfae0cb3a15cac7ae7c6b63c17ff549a584b98228bad289ec0e84
BLAKE2b-256 checksum
How to use checksums
9237cab164f0ce06621fb4c14432c401e170f7e006e6b77721c3d80e94ba0dfa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.0

Security for nc-db 0.8.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page