Skip to main content

OGM and schema migrations for FalkorDB.

Project description

Runic logo

Runic

Graph schema migrations and ORM for FalkorDB.

Version Python License: MIT

FeaturesInstallationMigrationsORMDocumentation


Runic is a Python toolkit for FalkorDB that covers two layers:

  • runic.migrate — Alembic-style schema migrations with revision tracking, a CLI, and rollback snapshots.
  • runic.orm — A lightweight graph ORM: declare Node and Edge models, manage sessions, traverse relationships, and sync indexes — all using FalkorDB-native Cypher under the hood.

Features

Migration CLI

  • Alembic-Style Workflow — Familiar CLI verbs: init, revision, upgrade, downgrade, current, baseline.
  • Graph-Native — Migration state stored inside dedicated graph nodes (:_FalkorMigrateVersion).
  • Idempotent Cypher — Explicit, guarded migration steps; safe to replay on an empty graph.
  • Offline & Dry Run — Review generated Cypher scripts before running them in production.
  • Rollback Snapshots — Uses GRAPH.COPY for high-risk, non-reversible migrations.

Graph ORM

  • Declarative ModelsNode and Edge subclasses with typed Field descriptors; no metaclass magic.
  • Session & Repository — Unit-of-work session with change tracking; typed Repository for queries and pagination.
  • RelationshipsRelation field for INCOMING / OUTGOING edges; lazy and eager loading; edge property models.
  • Schema ManagementIndexManager and SchemaManager to create, validate, and sync RANGE, FULLTEXT, and UNIQUE indexes.
  • Native FalkorDB Types — First-class Vector (vecf32), GeoLocation (point), interned strings, and auto-converters for datetime and Enum.
  • Async SupportAsyncSession, AsyncRepository, and AsyncConnectionManager for async-first applications.

Installation

uv pip install runic

Or add it to an existing project:

uv add runic

[!NOTE] Runic requires Python 3.14+ and is optimized for the latest FalkorDB clients.


Migrations

Initialize your project and generate a new revision:

runic init
runic revision -m "create user index"

Open the generated file in runic/versions/ and define your upgrade and downgrade:

revision = "1975ea83b712"
down_revision = None


def upgrade(op) -> None:
    op.create_range_index("User", "email")


def downgrade(op) -> None:
    op.drop_range_index("User", "email")

Apply or roll back:

runic upgrade            # apply all pending revisions
runic downgrade          # roll back one step
runic downgrade 1975e    # roll back to a specific revision (prefix is enough)

Baselining an existing graph

Bring an unmanaged FalkorDB graph under runic control without re-running anything:

runic baseline -m "baseline"   # introspect, generate root revision, stamp it
runic current                  # verify it is now tracked

The generated revision recreates all indexes from scratch — safe to replay on a fresh graph (CI, cloning, new tenants):

runic upgrade head   # rebuilds full schema on an empty graph

Programmatic SDK

from pathlib import Path
from runic import Runic, init
from runic.migrate.adapters import create_adapter

init(Path("runic/"))

adapter = create_adapter(
    "falkordb", url="falkor://localhost:6379", graph_name="my_graph"
)
runic = Runic(adapter, script_location=Path("runic/"))
runic.migrate.upgrade("head")

print("current:", runic.migrate.current())

runic.orm

Defining models

from runic.orm import Field, Node, Edge, Relation


class User(Node, labels=["User"]):
    id: str
    email: str = Field(unique=True)
    name: str


class Post(Node, labels=["Post"]):
    id: str
    title: str = Field(index_type="FULLTEXT")
    published: bool = False


class AuthoredEdge(Edge, type="AUTHORED"):
    created_at: str  # ISO-8601


class Author(Node, labels=["Author"]):
    id: str
    name: str
    posts: list[Post] = Relation(
        relationship="AUTHORED",
        direction="OUTGOING",
        target="Post",
        edge_model=AuthoredEdge,
    )

Session-based CRUD

from runic.orm import Session, Repository

with Session(graph) as session:
    session.add_all([
        User(id="alice", email="alice@example.com", name="Alice"),
        User(id="bob", email="bob@example.com", name="Bob"),
    ])
    session.commit()

with Session(graph) as session:
    repo = Repository(session, User)
    alice = session.get(User, "alice")
    alice.name = "Alice Smith"  # change tracking — no explicit dirty flag
    session.commit()

with Session(graph) as session:
    user = session.get(User, "bob")
    session.delete(user)
    session.commit()

Relationships

# Lazy load (default) — triggers a query on first access
with Session(graph) as session:
    author = session.get(Author, "alice")
    posts = author.posts  # query executed here

# Eager load — single round-trip
with Session(graph) as session:
    author = session.get(Author, "alice", fetch=["posts"])
    posts = author.posts  # already loaded, no extra query

Pagination and custom queries

from runic.orm import Pageable, Repository

with Session(graph) as session:
    repo = Repository(session, User)
    page = repo.find_all_paginated(Pageable(page=0, size=20, sort_by="name"))
    print(f"{len(list(page))} of {page.total_elements} total")

Extend Repository to add typed Cypher helpers:

class UserRepository(Repository[User]):
    def find_by_email(self, email: str) -> User | None:
        return self.cypher_one(
            "MATCH (u:User {email: $email}) RETURN u",
            {"email": email},
            returns=User,
        )

Schema management

Declare indexes inline on Field, then let SchemaManager keep the live graph in sync:

from runic.orm import Field, IndexManager, Node, SchemaManager


class Place(Node, labels=["Place"]):
    id: str
    name: str = Field(index_type="FULLTEXT")
    slug: str = Field(unique=True)
    lat: float = Field(index=True)
    lon: float = Field(index=True)


schema = SchemaManager(graph)
schema.sync_schema([Place], drop_extra=False)  # create missing; leave extras alone

result = schema.validate_schema([Place])
print("valid:", result.is_valid)

Native FalkorDB types

Vector, GeoLocation, datetime, and Enum fields get their converters assigned automatically — no converter= argument needed:

from datetime import UTC, datetime
from enum import StrEnum
from runic.orm import Field, GeoLocation, Node, Vector


class Status(StrEnum):
    DRAFT = "draft"
    PUBLISHED = "published"


class Article(Node, labels=["Article"]):
    id: str = Field(primary_key=True)
    category: str = Field(interned=True)  # intern() deduplication
    status: Status  # EnumConverter auto-assigned
    published_at: datetime | None = None  # DatetimeConverter auto-assigned
    embedding: Vector | None = None  # VectorConverter → vecf32()
    origin: GeoLocation | None = None  # GeoLocationConverter → point()

Documentation

Full conceptual overview, async usage, advanced CLI flags, and API reference at the complete Runic Documentation.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

runic_py-0.2.2.tar.gz (78.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

runic_py-0.2.2-py3-none-any.whl (103.0 kB view details)

Uploaded Python 3

File details

Details for the file runic_py-0.2.2.tar.gz.

File metadata

  • Download URL: runic_py-0.2.2.tar.gz
  • Upload date:
  • Size: 78.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.18 {"installer":{"name":"uv","version":"0.11.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for runic_py-0.2.2.tar.gz
Algorithm Hash digest
SHA256 a325c7ed44c55a8617632e4eec6c91f8435ab9f4ee9862dcf1b7c299eec739b6
MD5 72353b7581fbbbea7e7148e33084b060
BLAKE2b-256 56abbd10d56fc26950d67375ce87070c43afe3481765f278695faf2c2f372a76

See more details on using hashes here.

File details

Details for the file runic_py-0.2.2-py3-none-any.whl.

File metadata

  • Download URL: runic_py-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 103.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.18 {"installer":{"name":"uv","version":"0.11.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for runic_py-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 c0c3477214db462d7b1b7ac3f8595a68fa162472884adeec699d065016c49c09
MD5 bdcc0ff11ecb1048775e3955c84ab6ca
BLAKE2b-256 86bb61ee237ea24f52cca6b587e6d4850faeef64a2a337b877950938b63c2199

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page