Skip to content
Edit this page

PostgreSQL database

Titancore provides an async PostgreSQL integration with an fluent fluent query facade. SQLAlchemy owns model mapping, query compilation, identity tracking, and transactions. Psycopg 3 owns driver I/O, pgvector-python provides vector types and codecs, and Alembic owns schema migrations.

PostgreSQL with the pgvector extension is the only supported database. The Python dependencies are included in the standard Titancore installation. Install PostgreSQL and pgvector on the database server before using vector columns.

Define models

Models use SQLAlchemy's public mapping API. The framework supplies one shared declarative base and exports pgvector's VECTOR type:

from __future__ import annotations

from sqlalchemy import ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship

from titancore.database import Model, VECTOR


class Author(Model):
    __tablename__ = "authors"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    articles: Mapped[list[Article]] = relationship(
        back_populates="author",
    )


class Article(Model):
    __tablename__ = "articles"

    id: Mapped[int] = mapped_column(primary_key=True)
    author_id: Mapped[int] = mapped_column(ForeignKey("authors.id"))
    title: Mapped[str]
    embedding: Mapped[list[float]] = mapped_column(VECTOR(1536))
    author: Mapped[Author] = relationship(back_populates="articles")

Query and write

Create a Database with a PostgreSQL URL. Plain postgresql:// URLs are normalized to SQLAlchemy's async Psycopg 3 dialect. A session is one unit of work: it commits when the block succeeds and rolls back when an exception escapes.

from titancore.database import Database

database = Database("postgresql://user:password@localhost/app")

async with database.session() as session:
    author = await session.create(Author, name="Ada")
    await session.create(
        Article,
        author_id=author.id,
        title="Vector search",
        embedding=[0.1] * 1536,
    )

    nearest = await (
        session.query(Article)
        .where("title", "ilike", "%vector%")
        .with_relations("author")
        .nearest_to("embedding", [0.1] * 1536, metric="cosine")
        .limit(10)
        .get()
    )

where accepts (column, value) or (column, operator, value). Supported operators are =, !=, <, <=, >, >=, in, not_in, like, ilike, is, and is_not. Column names must match mapped columns; values are bound by SQLAlchemy. with_relations accepts mapped relationship paths such as author or posts.author. nearest_to supports cosine, l2, l1, and inner_product distance metrics on pgvector VECTOR columns.

Sessions also provide model, where, create, save, find, delete, and flush. Queries provide get, first, count, exists, update, and delete. A query starts from an explicit session rather than hidden process-global model state. session.query(Model) remains available when the lower-level terminology is clearer.

Compose with FastAPI and the application container

Pass DatabaseServiceProvider with the application's other providers. It owns one application-scoped engine and yields one committing session per request:

from titancore import Application
from titancore.database import DatabaseServiceProvider, DatabaseSession
from titancore.foundation.http import inject
from titancore.foundation.http import Kernel

database_url = "postgresql+psycopg://localhost/app"
application = Application()
application.register(DatabaseServiceProvider(database_url))
kernel = Kernel(application)


@kernel.asgi.get("/articles")
@inject
async def list_articles(
    session: DatabaseSession,
) -> list[dict[str, int | str]]:
    articles = await session.query(Article).order_by("id").get()
    return [
        {"id": article.id, "title": article.title}
        for article in articles
    ]

The provider closes the engine when the application shuts down. Applications that do not configure the provider do not open database connections.

Run migrations

Use Alembic's async migration environment. Import application model modules before creating the migration config, and set target_metadata in migrations/env.py from config.attributes["target_metadata"].

from alembic import command

from titancore.database import Database

database = Database(database_url)
config = database.migration_config(script_location="migrations")
command.revision(config, message="create articles", autogenerate=True)
command.upgrade(config, "head")

Alembic autogeneration produces candidate revisions. Review generated files before applying them. A revision that first uses vector columns should enable the PostgreSQL extension with CREATE EXTENSION IF NOT EXISTS vector. The migration config contains the connection credentials; never log it.

For the implementation boundary, see Architecture.

Register DatabaseServiceProvider() to read the required database.url and optional database.echo from application configuration. Explicit constructor URLs remain supported.

Fluent migration declarations

Use Schema inside standard Alembic revision functions:

from titancore.database.schema import Blueprint
from titancore.facades import Schema


def columns(table: Blueprint) -> None:
    table.id()
    table.string("name").unique()
    table.jsonb("metadata")
    table.vector("embedding", 1536).nullable()
    table.timestamp("created_at").use_current()


def upgrade() -> None:
    Schema.create("documents", columns)


def downgrade() -> None:
    Schema.drop_if_exists("documents")

Blueprint supports strings, text, integers, booleans, UUIDs, dates, timezone-aware timestamps, JSONB and pgvector, plus native keys, constraints and indexes. Column modifiers include nullable, default, primary, unique, index, constrained, cascade_on_delete and change. Schema.table applies additions, alterations and removals through Alembic. Unsupported native dialect behavior remains a native error; this is not another SQL grammar.

The application's Alembic env.py only calls titancore.database.migrations.run_environment(). Migrator(database, path) exposes awaited migrate, rollback(steps) and status operations over native revision history. Migration status follows the configured PostgreSQL schema.

Factories and seeders

Extend titancore.database.factories.Factory[YourModel], set model, and implement definition() -> dict[str, object]. state(attributes) and count(number) return independent factory configurations. make() constructs ORM objects; await factory.create(database) commits them through the existing session. A factory without count returns one model; an explicit count returns a list. Relationships, Faker integration and factory callbacks are not yet implemented.

Extend titancore.database.seeder.Seeder and implement async run(). await self.call(OtherSeeder) resolves registered seeder classes through the existing container. Seed data, idempotency and transaction policy remain application-owned. Configure database.seeder with the registered root class for the Console db:seed command. This API does not serialize or execute untrusted seed definitions.

Factories and schema inspection

Factories expose a native Faker instance through factory.faker. States may be mappings or callbacks receiving the accumulated attributes. after_making() runs before persistence; after_creating() runs after commit. Native ORM relationships support for_(parent, relationship) and has(related_factory, relationship). SQLAlchemy owns relationship cascades. Model.factory() resolves database.factories.<model_name>_factory and validates the conventional <ModelName>Factory against the selected model.

Schema supports has_table, has_column, has_columns, get_tables, get_column_listing, rename, rename_column and drop. Column checks ignore case. For example, Schema.has_columns("users", ["id", "email"]) checks for both columns with one inspection. A missing table has an empty column listing. Seeder.call_once() avoids repeated successful calls within that seeder instance.

A Migration class may group up() and down() methods; expose their bound methods as the revision's upgrade and downgrade callbacks. Alembic retains revision declarations and execution. Invocation metadata is recorded through its public version callback inside the native PostgreSQL transaction. Migrator.rollback_batch() and migrate:rollback without a positive step reverse the last invocation's revisions in a linear history. Explicit --step=N retains native revision-step rollback. Branched histories require explicit native targets. No separate migration engine is introduced.