post-graph: PostgreSQL-Backed Graph Database Library
PostgreSQL is already a graph database. A property graph is two kinds of table — vertices with a JSONB payload, and edges with a from, a to and a type — and PostgreSQL already has the rest: recursive CTEs to walk it, triggers to audit it, schemas to isolate tenants, pgvector for embeddings. post-graph is the Python API over that.
import asyncio
from post_graph import AsyncPostGraph
async def main():
client = AsyncPostGraph(dsn="postgresql://localhost:5432/postgres")
await client.connect()
await client.create_vertex_table("people", realm="acme")
await client.create_edge_table("knows", from_vertex_table="people",
to_vertex_table="people", realm="acme")
ada = await client.add_vertex("people", realm="acme", payload={"name": "Ada"})
bob = await client.add_vertex("people", realm="acme", payload={"name": "Bob"})
cy = await client.add_vertex("people", realm="acme", payload={"name": "Cy"})
await client.add_edge("knows", realm="acme", from_id=ada.id, to_id=bob.id, relation_type="knows")
await client.add_edge("knows", realm="acme", from_id=bob.id, to_id=cy.id, relation_type="knows")
# Everyone Ada can reach, walked inside PostgreSQL by a recursive CTE.
for step in await client.traverse("acme", "people", ada.id, edge_tables=["knows"], max_depth=3):
print(step["depth"], step["path"])
await client.close()
asyncio.run(main())
Because the graph is ordinary tables, an edge and the application row it describes commit in the same transaction, one backup covers both, and row-level security applies to the graph like everything else.
What you get: multi-tenant realms (shared tables or a schema per tenant), sub-grouping with space, trigger-written audit logs and append-only history, pgvector search on vertices and edges, filtered and temporal traversal, a measured subset of openCypher, and asyncpg and SQLAlchemy clients with the same public API.
What it is not: a graph engine. It makes no claim to out-run one on deep traversals over very large graphs, and the Cypher support is a subset — 179 of the openCypher TCK's 1,615 scenarios pass (details). If graph querying is your product, use a graph database.
| Neo4j | Apache AGE | post-graph | |
|---|---|---|---|
| Runs inside your PostgreSQL | ❌ | ✅ | ✅ |
| Needs no extension of its own | n/a | ❌ | ✅ (pgvector only for embeddings) |
| Graph and application rows in one transaction | ❌ | ✅ | ✅ |
| Tables you may index, constrain and add triggers to | n/a | discouraged | ✅ |
| openCypher | ✅ | ✅ | subset |
| Audit log and history built in | enterprise | ❌ | ✅ |
The longer comparison, with sources, is in the write-up.
🧪 Runnable Examples
Ten scripts in examples/, each one capability. They need
PostgreSQL and nothing else — no LLM, no API keys:
export POSTGRES_URI=postgresql://localhost:5432/postgres
cd examples && python 01_quickstart.py
| shows | |
|---|---|
01_quickstart.py |
Vertices, edges, traversal, shortest path |
02_vector_search.py |
pgvector search across main and history tables |
03_realms_and_spaces.py |
Tenant isolation and sub-grouping |
04_schema_per_realm.py |
A PostgreSQL schema per tenant |
05_range_queries.py |
Range filters, ordering, counting, bulk delete on JSONB |
06_history_and_audit.py |
Append-only history and the trigger-written audit log |
07_opencypher.py |
openCypher queries |
08_transactions.py |
Graph and application tables in one transaction |
09_uuid_keys.py |
UUID keys alongside generated ids |
10_full_tour.py |
All of it, end to end |
Every one was executed against a live database before being committed.
🌟 Key Features
- Table-Per-Vertex & Table-Per-Edge Architecture: Maps graph elements directly to relational tables, taking advantage of PostgreSQL's foreign keys, indexes, and constraints.
- Hierarchical Multi-Tenancy & Space Sub-grouping:
- Macro-Isolation (
realm): Primary tenant partitioning at database or schema level. - Micro-Isolation (
space): Optional application-level sub-grouping (space VARCHAR(255) DEFAULT 'default') within tables to segregate environments (e.g.production,staging,sandbox, or workspace spaces). - Dual Tenant Topologies:
- Single-Schema Multi-Tenancy: Logical isolation using
realm&spacecolumn partitions. - Schema-Per-Realm: Physical isolation creating dedicated PostgreSQL schema namespaces per tenant (
CREATE SCHEMA IF NOT EXISTS "realm_name").
- Single-Schema Multi-Tenancy: Logical isolation using
- Macro-Isolation (
- pgvector Similarity Search (
vector_search):- Native HNSW vector indexing (
vector(dim)) for vertex embeddings. - Cosine distance (
<=>), Euclidean L2 (<->), and Inner Product (<#>). - Multi-scope searching across main tables, associated data history tables, or both combined (
search_scope="both").
- Native HNSW vector indexing (
- Autogenerated
BIGSERIALPrimary Keys & Computedfqid:- Vertex FQID:
{realm}/{table_name}/{id} - Edge FQID:
{realm}/{table_name}/{id}— the edge table's own name, the same shape as a vertex's. (Before 1.14.0 it was the endpoint pair,{from_table}-{to_table}.fqidis a stored generated column, so an edge table created by an earlier release keeps the old form.) - Automatically populated at PostgreSQL level via
GENERATED ALWAYS AS ... STORED NOT NULL.
- Vertex FQID:
- Append-Only History Tables (
{table_name}_data):- Automatically created alongside vertex and edge tables.
- Stores timestamped JSONB payload updates (
data_id,realm,space,id,payload,timestamp,embedding). - Supports vector embeddings on data records for historical semantic matching.
- Cascades deletion when main vertex/edge is deleted (
ON DELETE CASCADE).
- Shadow Audit Logging (
{table_name}_audit):- Operates via PostgreSQL triggers to capture all
INSERT,UPDATE, andDELETEevents. - Logs old/new row state and the initiating
user_idpassed via session parameters (app.current_user_id).
- Operates via PostgreSQL triggers to capture all
- Advanced Graph Traversals & Cycle Detection:
- Recursive CTE queries for neighbor exploration, path discovery, and cycle-free shortest path calculation.
- Optional
check_cycle=TrueraisingCyclicReferenceErrorduring edge creation. - Direct object-oriented traversal APIs (
vertex.to(),vertex.from_(),step.vertex(),step.add_edge_to()).
- Promoted Payload Columns:
- Hot JSONB keys become generated, indexed columns maintained by PostgreSQL, so the planner can use an index where it previously scanned.
valid_fromandvalid_toare promoted by default aspt_valid_from/pt_valid_to, holding the date normalised toYYYY-MM-DD; any other key can be promoted viapromoted_keysasp_{key}.- The write path is unchanged — callers keep writing plain JSON — and a table without the columns falls back to
payload->>, returning the same rows.
- openCypher Queries (
CypherSession):- A documented Cypher subset over the same tables: a label is a vertex table, a relationship type is a
relation_typevalue, a property is a payload key. - Reads compile to a single SQL statement; writes run through the client's own methods, in one transaction, so audit tables and triggers behave and a failed query leaves nothing behind.
- Conformance is measured against the openCypher TCK rather than asserted. See docs/cypher.md.
- A documented Cypher subset over the same tables: a label is a vertex table, a relationship type is a
- Multiple Async Client Drivers:
- High-speed
asyncpgclient (AsyncPostGraph). SQLAlchemyv2.0 async client (SQLAlchemyPostGraph).
- High-speed
📦 Installation
Needs Python 3.11+ and PostgreSQL 16 or 18 with pgvector. CI runs 3.11
on 16, and 3.13 on both 16 and 18: this library's behaviour lives in the
database, so each PostgreSQL version is exercised rather than assumed.
PostgreSQL 18 gets its own job because it changed what
GENERATED ALWAYS AS (expr) means when no storage keyword is given — an error
before 18, and VIRTUAL from 18 on, which cannot be indexed. Every generated
column here says STORED, and a test asserts it against the catalogue.
Install post-graph from PyPI:
# Basic installation (includes asyncpg)
pip install post-graph
# Installation with SQLAlchemy support
pip install "post-graph[sqlalchemy]"
# Installation with all optional dependencies
pip install "post-graph[all]"
Using uv:
uv add post-graph
# or with SQLAlchemy support:
uv add "post-graph[sqlalchemy]"
PostgreSQL Setup
To enable pgvector similarity search, ensure the pgvector extension is enabled in PostgreSQL:
CREATE EXTENSION IF NOT EXISTS vector;
🏗️ Database Architecture & Multi-Tenancy Hierarchy
erDiagram
REALM ||--o{ SPACE : contains
SPACE ||--o{ VERTICES : contains
SPACE ||--o{ EDGES : contains
agent_registry {
text realm PK
bigserial id PK
varchar_255 space "Indexed optional sub-grouping (e.g. production, sandbox)"
text fqid "Generated: realm/table/id"
uuid uuid "Unique UUID identifier"
jsonb payload "JSON metadata"
vector embedding "HNSW Cosine Vector"
timestamptz created_at
timestamptz updated_at
}
agent_registry_data {
bigserial data_id PK
text realm FK
bigint id FK
varchar_255 space
jsonb payload
vector embedding
timestamptz timestamp
}
spawns {
text realm PK, FK
bigserial id PK
varchar_255 space
bigint from_id FK
bigint to_id FK
text relation_type
jsonb payload
timestamptz created_at
}
agent_registry ||--o{ agent_registry_data : "appends history"
agent_registry ||--o{ spawns : "from_id / to_id"
🚀 Quick Start Guide
import asyncio
from post_graph import AsyncPostGraph
async def main():
# 1. Initialize client
client = AsyncPostGraph(dsn="postgresql://user:password@localhost:5432/mydb")
await client.connect()
realm = "proj_alpha"
# 2. Declare Vertex & Edge tables
await client.create_vertex_table("agents", realm=realm, vector_dim=1536)
await client.create_edge_table("spawns", from_vertex_table="agents", to_vertex_table="agents", realm=realm)
# 3. Upsert Vertices with Space Sub-grouping
v_parent = await client.upsert_vertex(
table_name="agents",
realm=realm,
vertex_id=1,
space="production",
payload={"name": "The Prime Orchestrator", "caste": "genesis"},
embedding=[0.01] * 1536
)
v_progeny = await client.upsert_vertex(
table_name="agents",
realm=realm,
vertex_id=2,
space="production",
payload={"name": "Specialized Worker", "caste": "progeny"},
embedding=[0.02] * 1536
)
# 4. Create Directed Edge
edge = await client.add_edge(
table_name="spawns",
realm=realm,
from_id=v_parent.id,
to_id=v_progeny.id,
space="production",
relation_type="spawned_progeny",
payload={"reason": "Task Delegation"}
)
# 5. Query Vertices by Realm & Space
prod_agents = await client.get_vertices("agents", realm=realm, space="production")
print(f"Production agents: {[a.payload['name'] for a in prod_agents]}")
# 6. Object-Oriented Neighbor Traversal
neighbors = await v_parent.outgoing("spawns")
for step in neighbors:
print(f"Parent -> {step.vertex().payload['name']} (Edge: {step.edge.relation_type})")
await client.close()
if __name__ == "__main__":
asyncio.run(main())
⏱️ Range Queries, Ordering and Bulk Deletion
Polling a growing table must not mean fetching it. where pushes range
predicates into SQL over the JSONB payload (parameter-bound, key-validated),
order_by/limit shape the result server-side, and count_vertices /
delete_vertices complete the poll–work–purge loop without transferring rows.
# An event scheduler's tick: the few due, undone events — not the whole table.
due = await pg.find_vertices("events", realm=world,
where=[("done_at", "is_null", None), ("due_at", "<=", now_str)],
order_by="due_at", limit=200)
# A work queue's pending slice.
pending = await pg.find_vertices("decision_queue", realm="agents",
where=[("done_at", "is_null", None)], limit=500)
# Periodic purge of completed history, returning rows deleted.
purged = await pg.delete_vertices("events", realm=world,
where=[("done_at", "not_null", None), ("done_at", "<", cutoff_str)])
# Queue depth without row transfer; index the hot predicate once at startup.
depth = await pg.count_vertices("decision_queue", realm="agents",
where=[("done_at", "is_null", None)])
await pg.create_payload_index("events", realm=world, key="due_at")
Ops: = != < <= > >= is_null not_null in. Values always bind as
parameters. int/float compare numerically ((payload->>'k')::numeric);
str compares as text, so zero-padded sortable strings (fixed-width
timestamps) keep their text ordering. is_null matches absent keys and JSON
null alike — a scheduler's "not done yet" in one predicate. order_by follows
the numeric cast when a numeric predicate references the same key.
delete_vertices refuses an empty where: a full wipe must be the explicit
delete_realm. create_payload_index(..., numeric=True) indexes the cast
expression; idempotent, deterministically named.
🔌 Connection Pooling for Fleets
Each client manages an asyncpg pool. pool_min_size defaults to 1 (lazy):
a fleet of N workers holds N idle connections and grows to pool_max_size
(default 10) only under load. connect() retries "too many clients" and
"cannot connect now" with exponential backoff and jitter (retries=5 by
default), so a deploy herd staggers in instead of crashing.
Sizing rule: workers × pool_max_size must stay below the server's
max_connections, with headroom for everything else that talks to the
database. Past that point no client-side setting helps — put PgBouncer in
between.
Supplying your own pool
AsyncPostGraph(connection_or_pool=…) takes either a connection or a pool, and
tells them apart by capability rather than by type: anything with an
acquire() that is not an asyncpg Connection is driven as a pool. So a thin
wrapper of your own works, and that is the point —
class RoleAssumingPool:
"""Each acquisition is a transaction wearing one tenant's role."""
def __init__(self, pool, role):
self._pool, self._role = pool, role
@asynccontextmanager
async def acquire(self):
async with self._pool.acquire() as conn:
async with conn.transaction():
await conn.execute(f'SET LOCAL ROLE "{self._role}"')
yield conn
client = AsyncPostGraph(connection_or_pool=RoleAssumingPool(pool, "tenant_7"))
A wrapper is the only safe shape behind PgBouncer in transaction mode,
where a session-level SET ROLE would leave a server connection wearing one
tenant's role for the next client that borrows it. Being recognised does not
require subclassing asyncpg.Pool — and so does not require importing asyncpg
in code whose whole reason for using this library is to keep the driver in one
place.
advisory_xact_lock still refuses a pool of any kind, wrapper included: a
transaction-scoped lock taken on a borrowed connection is released by the
acquisition that took it, so it is already gone when the caller writes. Build
the client over a connection for that.
📚 Comprehensive API Reference
Client Initialization & Management
AsyncPostGraph(dsn, schema_per_realm=False)
Initializes the high-performance asyncpg graph client.
client = AsyncPostGraph(
dsn="postgresql://postgres:postgres@localhost:5432/postgres",
schema_per_realm=False # Set True for physical PostgreSQL schema isolation
)
await client.connect()
SQLAlchemyPostGraph(dsn_or_engine, schema_per_realm=False)
Initializes the SQLAlchemy v2.0 async graph client.
Schema Definition APIs
create_vertex_table(table_name, realm=None, vector_dim=None, temporal_keys=None, promoted_keys=None)
Creates a vertex table, associated audit table ({table_name}_audit), and append-only data history table ({table_name}_data).
await client.create_vertex_table(
table_name="agents",
realm="proj_alpha",
vector_dim=1536, # Enables pgvector HNSW index
promoted_keys=["status"], # Indexed column for a hot payload key
)
temporal_keys overrides which pair of payload keys is promoted as dates
(default ('valid_from', 'valid_to')); promoted_keys promotes further keys
verbatim. See Promoted Payload Columns below.
create_edge_table(table_name=None, from_vertex_table=..., to_vertex_table=..., cascade_delete_from=False, cascade_delete_to=False, realm=None, vector_dim=None, temporal_keys=None, promoted_keys=None)
Creates a directed edge table linking two vertex tables.
Pass vector_dim to give edges their own pgvector embedding column and HNSW
index, enabling vector_search_edges. Optional — most workloads reach edges by
traversing from a vertex rather than by similarity.
await client.create_edge_table(
"relations",
from_vertex_table="entities",
to_vertex_table="entities",
realm=realm,
vector_dim=1536 # Optional: enables semantic search over relationships
)
Vertex Operations
Optimistic concurrency: expected_updated_at
upsert_vertex and update_vertex take expected_updated_at=, a
compare-and-swap token. When it does not match the stored row they raise
ConcurrentModificationError and the write is not applied.
v = await client.get_vertex("RoleGrant", "identity", grant_id)
await client.update_vertex("RoleGrant", "identity", grant_id,
payload={"roles": [...]},
expected_updated_at=v.updated_at)
update_vertex distinguishes the two ways it can find nothing: a row that does
not exist returns None as always, while a row whose updated_at moved raises.
A missing row is not a lost race. upsert_vertex requires vertex_id with a
token — a sequence-assigned id is a row that does not exist yet, so there is no
prior updated_at to have moved from.
updated_at is maintained with clock_timestamp(), not now(). now() is the
transaction's start time, so two writes to one row inside a transaction would
leave updated_at unchanged between them and a token taken from the first would
still match after the second. An existing realm picks this up when a table is
next declared.
Typed errors
UniqueConstraintError carries constraint_name, so a caller can tell "this
username is taken" from "this id is taken" without reading __cause__ or
importing the driver's exception type. It subclasses TableExistsError, so code
written against earlier releases keeps working. Raised consistently by
add_vertex, upsert_vertex, update_vertex, add_edge and upsert_edge —
insert_vertex cannot raise it, since its untargeted ON CONFLICT DO NOTHING
absorbs any unique violation and reports False.
Also ConcurrentModificationError, NestedTransactionError and
CommitFailedError, all exported from post_graph.
add_vertex / upsert_vertex
Upserts a vertex object into a specific {realm} and optional {space}.
add_vertex inserts and refuses a duplicate: a vertex_id already in use
raises TableExistsError, naming the id, the table and the realm. (Before
1.11.0 the duplicate escaped as a raw asyncpg.UniqueViolationError — the
handler was there, the INSERT was outside it.) upsert_vertex merges
instead.
vertex = await client.upsert_vertex(
table_name="agents",
realm="proj_alpha",
vertex_id=101, # Optional numeric ID or FQID
space="production", # Optional space sub-grouping (default: 'default')
payload={"name": "Polymath Node"},
embedding=[0.05] * 1536, # Optional vector embedding
user_id="user_admin" # Optional for shadow audit attribution
)
update_vertex(table_name, realm, vertex_id, payload, space=None, replace=False)
Changes an existing vertex with a bare UPDATE, and never an INSERT. Returns the
updated vertex, or None when no row matches (realm, vertex_id) — it does not
create the row.
spent = await client.update_vertex(
table_name="invitations",
realm="trial_platform",
vertex_id=4211517,
payload={"redeemed_at": "2026-10-10T09:00:00Z"}, # merged, as upsert_vertex merges
)
if spent is None:
... # no such invitation
Use it where the grant is the containment. upsert_vertex emits INSERT … ON CONFLICT DO UPDATE, and PostgreSQL checks the INSERT privilege on that statement
unconditionally — not only when the insert path is taken, because the check is on the
statement, not on the branch the data happens to take. So a role granted
SELECT, UPDATE gets InsufficientPrivilegeError from upsert_vertex on a row it is
entitled to change. A caller that may spend a single-use token but must not be able to
mint one is granted UPDATE and withheld INSERT deliberately; update_vertex is the
write that fits that grant.
Two differences from upsert_vertex worth knowing:
-
spacedefaults toNone, meaning leave the space alone.upsert_vertexdefaults it to"default"and always writes it, because it may be creating the row. An update that relocated a row to"default"because the caller did not mention a space would be a surprising way to lose a tenant's data. Passspace="…"to move the row deliberately. -
On an audited table the shadow trigger runs
INSERT INTO <table>_auditas the invoking role, so aSELECT, UPDATErole still fails — withpermission denied for table <table>_audit, naming a table absent from the grant. Two write-only grants fix it without widening the role's reach into the audited table:GRANT INSERT ON <table>_audit TO <role>; GRANT USAGE ON SEQUENCE <table>_audit_audit_id_seq TO <role>;
The role can then append an audit record but still cannot read the audit table, nor insert into the audited one. The alternative,
create_vertex_table(..., audited=False), trades the audit trail away — for a security-relevant write, usually the wrong trade.
purge_record_audit(table_name, realm, record_ids)
Deletes the shadow _audit rows for specific records; returns how many went.
await client.purge_record_audit("Document", "learner_7", [doc_id])
An audited table keeps a copy of every version of every row, so deleting a row
from the live table leaves its contents behind — and for a row holding
something a person asked to have deleted, that is the whole of the problem
rather than a detail of it. drop_realm removes it, but a realm is everything
that person has, not the one record they deleted.
Matches old_row and new_row, because the two hold different halves of
the history: an INSERT audit row has old_row NULL and the contents under
new_row, a DELETE has it the other way about, and an UPDATE has both.
Matching only old_row would leave the original INSERT copy in place — the
one that has been there longest.
Returns 0 without touching the database for an empty id list, and 0 when there
is no audit table (declared audited=False, or dropped). Neither is an error:
the caller asked for the audit rows to be gone and they are. Accepts one id or
many; realm/table/42 is read as 42.
realm_exists(realm) · list_realms(prefix=…) · table_exists(table, realm) · drop_realm(realm, cascade=True)
The catalogue, so a caller need not reach for information_schema itself.
list_realms(prefix=…) matches the prefix literally — _ and % in it are
escaped, so prefix="learner_" does not also return learners_archive. That is
not cosmetic where the result decides which schemas get dropped.
drop_realm returns True if the schema was there and False if it was
already gone, and refuses when schema_per_realm=False: without it a realm is a
column value spread across shared tables and there is nothing to drop — use
delete_realm for that.
tables_containing_text(needle, include_realms=…, exclude_realm_prefixes=…)
{"schema.table", …} for every table holding needle anywhere in a row.
A residue check, for asserting that something asked to be deleted is actually
gone. It casts the whole row to text, so it finds the needle in a payload, in a
shadow _data row and in an _audit copy alike — the places a deletion tends
to miss.
Deliberately not fast: one LIMIT 1 probe per table, sequential scans, no
indexes. It is for tests and erasure receipts, not a request path.
exclude_realm_prefixes skips whole families of schemas unless
include_realms names them, which keeps such an assertion quick on a cluster
carrying hundreds of per-tenant schemas. needle is matched literally.
ensure_database(dsn, *, database, maintenance_database="postgres")
Creates the database if absent and returns a DSN pointing at it. A static method, because connecting normally requires the database to exist.
dsn = await AsyncPostGraph.ensure_database(admin_dsn, database="app")
client = AsyncPostGraph(dsn=dsn, schema_per_realm=True)
CREATE DATABASE cannot run inside a transaction and takes no bound parameter,
so the name is validated as a bare identifier before any connection is
opened. Idempotent under a deploy herd: replicas starting together race, and
the loser's error is success. Both shapes that race takes are handled — 42P04,
and a unique violation on pg_database's own index, which is what several
concurrent callers actually produce.
transaction(*, user_id, idle_in_transaction_timeout_ms=None)
One transaction spanning several calls; yields a client bound to it.
async with client.transaction(user_id="usr_alice") as tx:
grant = await tx.add_vertex("RoleGrant", realm="identity", payload=…)
await tx.add_edge("granted_by", realm="identity", from_id=…, to_id=…)
Every write here is already atomic on its own. This is for the cases where two of them must be atomic together, which no care at the call site can arrange from outside.
user_id is required and is remembered: a call inside the block that passes
no user_id is attributed to it rather than to nobody. Without that, the second
write in a block blanked app.current_user_id and its audit row recorded an
empty actor — the audit trail quietly losing exactly the writes important enough
to group. An inner call may still pass its own user_id without affecting the
ones after it.
idle_in_transaction_timeout_ms is applied with SET LOCAL, so it reverts on
commit and cannot leak onto a pooled backend another request borrows next.
A commit that itself fails raises CommitFailedError rather than an
ordinary error: everything in the block ran, so any external effect it had has
happened, and the caller needs to reconcile rather than retry. Nesting raises
NestedTransactionError — a nested block would be a SAVEPOINT whose exit
commits nothing. The yielded client is poisoned on exit, so a reference stashed
outside fails loudly instead of writing outside any transaction on a connection
now serving somebody else.
reassign_owned_to(role)
Gives every object the connected role owns in the current database to role,
by emitting REASSIGN OWNED BY CURRENT_USER TO "<role>".
await writer_client.reassign_owned_to("app_owner")
For the deployment where a subordinate role created objects that should belong
to somebody else: a batch indexer connecting as a writer role with a longer
statement_timeout, which happens to be the first session to reach a realm and
so creates its tables. Everything it makes — the tables, their _data and
_audit companions, every BIGSERIAL sequence and every index — is then owned
by the writer, and the owning role can no longer ALTER them, nor can pg_dump
take ACCESS SHARE on them. One statement repairs the lot as a catalogue
update, in milliseconds, with nothing copied and nothing re-indexed.
The writer keeps working afterwards, provided it is IN ROLE the owner: it
inherits the rights on the tables and sequences it has just given away.
The reach is the whole database, not one realm. That is what makes it a
one-statement repair, and it is also why a role owning objects beyond the realm
in hand hands those over too. Where that is not wanted, ALTER TABLE … OWNER TO
per object is the narrower tool and this library does not wrap it.
The source role is fixed to CURRENT_USER and is not a parameter. PostgreSQL
would accept REASSIGN OWNED BY <other> TO <role> from a session holding
privileges of both, so a source argument would make this a method for pulling
objects away from another role. Fixed as it is, it can only give away what the
connected role already owns.
Idempotent and cheap — with no matching pg_shdepend rows PostgreSQL takes no
relation lock — so it is safe to call unconditionally at start-up. Transactional,
unlike VACUUM, so it needs no special connection and is safe behind a
transaction-mode pooler. Raises ValueError for an identifier that is not a
bare name: REASSIGN OWNED takes no bound parameter, so validating before
quoting is the only defence there is.
execute_outside_transaction(statement)
Runs one statement with no transaction around it, and returns its command tag.
await client.execute_outside_transaction("VACUUM")
await client.execute_outside_transaction(
'CREATE INDEX CONCURRENTLY "idx_things_realm" ON "things" (realm, id)')
For the statements PostgreSQL refuses inside a transaction block: VACUUM,
CREATE INDEX CONCURRENTLY, DROP INDEX CONCURRENTLY, REINDEX CONCURRENTLY,
CREATE DATABASE, DROP DATABASE, ALTER SYSTEM, CREATE/DROP TABLESPACE.
Every other write here runs inside a transaction on purpose, so these had no
path a caller could rely on — execute happens not to open one, but that is
an implementation detail of execute, and a caller whose own architecture
forbids opening a connection needs the guarantee rather than the coincidence.
A separate method rather than a flag, because a flag is something a request-path
caller can pass. Named for the property rather than for maintenance, because
CREATE DATABASE is in the class and is not maintenance.
One statement per call is PostgreSQL's rule, not this library's. A
multi-statement simple query runs as a single implicit transaction, so
VACUUM; VACUUM; fails with the very error this method exists to escape, and in
a mixed pair a failure in the second statement rolls the first one back. The
client refuses a batched string itself, so the diagnosis does not arrive as a
driver complaint about a transaction you never opened.
It refuses rather than work around four situations:
| situation | why |
|---|---|
| the acquired connection is already in a transaction | a pool wrapper whose acquire() opens one — to hold a tenant's SET LOCAL ROLE — cannot serve this; the refusal names the wrapper instead of leaving the driver to report a transaction you never opened |
| connection-bound client, caller holds a transaction | it will not open a second connection to get around that: a client that quietly held one would make "every DDL call is inside a transaction" unenforceable for every caller, which is usually the guard that made someone want this method |
| no connection yet | same reason — it does not open one from the DSN |
the statement is INSERT/UPDATE/DELETE/MERGE/COPY/TRUNCATE/WITH |
these have a transactional path. Outside a transaction nothing has set app.current_user_id, so an audited table would record the write against nobody — a provenance hole invisible until someone reads the audit table. A first-word check: it catches the mistake, not the determined |
insert_vertex(table_name, realm, vertex_id, payload, *, space)
Inserts one row under a supplied id and returns True if it was written,
False if that id already held one. The append an INSERT-only role can run.
written = await client.insert_vertex(
table_name="usage_events",
realm="trial_platform",
vertex_id=event_id, # derived from the event: the idempotency key
payload={"case_id": "c-1", "class": "transcription", "seconds": 42},
space="metering", # keyword-only, no default
)
if not written:
... # a redelivered message; already recorded
It emits exactly one statement — INSERT … ON CONFLICT DO NOTHING — and reads
the answer out of the command tag. The caller needs INSERT on the table and
USAGE on the schema, and nothing else; not even the sequence, since a
supplied id never evaluates the column default. Each of the three things it
does without is a privilege the other writes need:
| needs | because | |
|---|---|---|
RETURNING |
SELECT on every column named |
PostgreSQL privilege-checks them column by column, even when the caller discards the result |
ON CONFLICT (realm, id) |
SELECT |
naming the arbiter reads the index; the untargeted form does not |
setval(…, MAX(id)) |
SELECT |
add_vertex resynchronises the sequence after a supplied id |
So this is the write for an append-only ledger whose containment is its grant:
the writer holds INSERT and nothing else, so no path it reaches can amend or
remove what it recorded, and its idempotency is the primary key. False means
"already recorded", not an error.
Two things to know:
spaceis keyword-only with no default, unlike every other write. A silently defaulted space on a ledger partitioned by tenant is rows written where nobody will look for them.- The untargeted conflict clause absorbs any unique violation on the row,
not only one on the primary key. A table with a second unique constraint
reports
Falsefor a collision on that one too — right when that constraint is your idempotency key, surprising otherwise.
On an audited table the shadow trigger's own INSERT runs as the invoking
role, so it needs the same two grants update_vertex documents above
(INSERT ON <table>_audit, USAGE ON SEQUENCE <table>_audit_audit_id_seq).
create_payload_index(table, realm, key, numeric=False, *, unique=False, scope_by_space=True, index_name=None)
Indexes (payload->>'key'); returns the index name.
key may be several keys for a composite index. unique=True makes it a
constraint rather than an optimisation, and a violation arrives as
UniqueConstraintError carrying this index name. scope_by_space decides what
the uniqueness is per:
True(default) leads with(realm, space, …), so each space has its own namespace — two tenants can each hold an"oliver"while a duplicate inside one tenant is refused.Falseleads with(realm, …), for a key unique across every space.
A non-unique index over a single key keeps exactly the name and shape earlier releases built, so an existing caller does not create a second index alongside the one it already has.
index_name must fit in 63 bytes. PostgreSQL truncates longer identifiers
silently, which would let two distinct indexes become one and drop a uniqueness
constraint nobody was told about — so this refuses instead. A derived name too
long to fit is shortened with a hash rather than truncated, so two key tuples
cannot collide.
get_vertex(table_name, realm, vertex_id)
Fetches a single vertex by its numeric ID, UUID, or FQID.
get_vertices(table_name, realm, space=None, limit=None)
Fetches all vertices belonging to a {realm}, with optional filtering by {space}.
# Fetch only production space vertices
prod_vertices = await client.get_vertices("agents", realm="proj_alpha", space="production")
# Fetch all vertices in realm regardless of space
all_vertices = await client.get_vertices("agents", realm="proj_alpha")
delete_vertex(table_name, realm, vertex_id, user_id=None)
Deletes a vertex and automatically cascades deletion to referencing edges and history records.
Edge Operations
add_edge
Creates a directed edge between from_id and to_id.
edge = await client.add_edge(
table_name="spawns",
realm="proj_alpha",
from_id=101,
to_id=102,
space="production",
relation_type="spawned_progeny",
payload={"timestamp": "2026-07-27"},
check_cycle=True # Raises CyclicReferenceError if edge creates a cycle
)
get_edges(table_name, realm, space=None, limit=None)
Fetches edges in a realm, optionally filtered by {space}.
pgvector Semantic Search (vector_search)
Performs high-speed cosine, L2, or inner product vector search using HNSW indexes.
results = await client.vector_search(
table_name="agents",
realm="proj_alpha",
query_vector=[0.05] * 1536,
top_k=5,
distance_metric="cosine", # 'cosine', 'l2', or 'inner_product'
search_scope="both" # 'main', 'data', or 'both'
)
for vertex, distance in results:
print(f"Agent: {vertex.payload['name']} | Distance: {distance:.4f}")
Edge Semantic Search (vector_search_edges)
Edges can carry embeddings too, when the edge table was created with a
vector_dim. Supply the vector on add_edge / upsert_edge, then search:
await client.add_edge(
"relations", realm=realm,
from_id=zeus.id, to_id=hera.id,
relation_type="married_to",
payload={"description": "spouse"},
embedding=[0.05] * 1536 # Optional: stored when the table has a vector column
)
results = await client.vector_search_edges(
table_name="relations",
realm=realm,
query_vector=[0.05] * 1536,
top_k=5,
distance_metric="cosine",
space="production", # Optional space filter
relation_type="married_to" # Optional relation type filter
)
for edge, distance in results:
print(f"{edge.relation_type} | Distance: {distance:.4f}")
If the edge table has no vector column, a supplied embedding is ignored with a
warning and vector_search_edges returns [].
Append-Only Data History ({table_name}_data)
Appends timestamped data records to vertices or edges for full auditability and semantic versioning.
# Append historical data record
record = await client.add_vertex_data(
table_name="agents",
realm="proj_alpha",
vertex_id=101,
payload={"checkpoint": 18, "status": "active"},
embedding=[0.02] * 1536
)
# Retrieve history records
history = await client.get_vertex_data("agents", realm="proj_alpha", vertex_id=101, limit=10)
Advanced Graph Traversals & Shortest Path (CTEs)
traverse
Executes recursive CTE traversals across edge tables.
paths = await client.traverse(
realm="proj_alpha",
start_table="agents",
start_id=101,
edge_tables=["spawns", "collaborates"],
max_depth=4
)
for p in paths:
print(f"Depth: {p['depth']} | Path: {' -> '.join(p['path'])}")
shortest_path
Finds the shortest cycle-free path between two vertices.
sp = await client.shortest_path(
realm="proj_alpha",
start_table="agents",
start_id=101,
target_table="agents",
target_id=105,
edge_tables=["spawns", "collaborates"],
max_depth=5
)
if sp:
print(f"Shortest path found at depth {sp['depth']}: {sp['path']}")
Promoted Payload Columns
Properties live in payload JSONB, which is flexible but opaque to the planner:
payload->>'valid_from' <= '2024-01-01' cannot use an index, so the as-of filter
— which runs on every step of every traversal — degraded to a sequential scan.
A promoted column fixes that without touching the write path. PostgreSQL
maintains it from payload on insert and update, so you keep writing plain JSON:
await client.create_edge_table(
"relations",
from_vertex_table="entities", to_vertex_table="entities",
realm=realm,
promoted_keys=["t_expired"], # p_t_expired, indexed
)
# Unchanged: nothing about writing has to know a column exists.
await client.add_edge("relations", realm, a.id, b.id, "WORKS_AT",
payload={"valid_from": "2024-06"})
| Column | Holds | From |
|---|---|---|
pt_valid_from, pt_valid_to |
ISO date normalised to YYYY-MM-DD |
promoted by default |
p_{key} |
payload->>'{key}' verbatim |
each entry in promoted_keys |
Measured on 65k rows, the temporal filter moves from a 588-buffer sequential scan to a 27-buffer bitmap index scan — about 31ms to 2.5ms warm — and the margin grows with the table.
Three things worth knowing:
- The names are prefixed.
valid_fromstays inpayload; the column beside it ispt_valid_from. Prefixes keep a promoted column from ever colliding with a real column. - They are database-side only.
VertexandEdgecarry nopt_fields. The column is derived and read-only, and whether it exists depends on when the table was created, so exposing it on the model would offer a field you can read but never assign, present on some objects and not others. - Existing tables do not gain them retroactively. The DDL runs at table
creation. A realm created before this feature keeps working and returns the
same rows via
payload->>, just without the index.
Temporal columns hold normalised text rather than DATE because casting text to
date is only STABLE and PostgreSQL rejects non-immutable expressions in a
generated column. ISO-8601 sorts lexically, so text and date comparison agree —
including partial dates, where '2024' normalises to '2024-01-01' rather than
sorting as a short string.
openCypher Queries
from post_graph import AsyncPostGraph, CypherSession
session = CypherSession(client, realm="my_realm")
rows = await session.run(
"MATCH (p:Person)-[:KNOWS]->(f:Person) "
"WHERE p.name = $name AND f.age > 30 "
"RETURN f.name AS friend ORDER BY friend",
{"name": "Alice"},
)
A label is a vertex table, a relationship type is a value in relation_type, and
a property is a payload key — read through a promoted column when one exists.
Reads compile to one SQL statement. Writes do not: CREATE, MERGE, SET and
DELETE go through the client's own methods so audit tables, triggers and realm
rules behave as for any other caller, and the whole query runs in one
transaction, so a CREATE that fails part-way leaves nothing behind.
session.explain(query) shows what will happen — the SQL for a read, the
sequence of client operations for a write — without running it.
The subset is bounded and every boundary raises rather than being approximated;
WITH, UNION, OPTIONAL MATCH, path variables and RETURN * are refused.
Conformance is measured against the openCypher TCK rather than asserted. See
docs/cypher.md for what is supported and the current numbers,
and examples/07_opencypher.py for a runnable tour.
Multi-Tenant Realm & Space Deletion
# Delete an entire realm across all tables
deleted_count = await client.delete_realm(realm="tenant_to_remove")
🤝 Contributing
Bug reports, failing test cases and pull requests are all welcome. CONTRIBUTING.md covers the parts that are specific to this project rather than generic advice: what the test suite needs, what it deliberately does not need, and the invariants worth understanding before changing them.
Issues tagged good first issue are real gaps rather than
make-work — each one names the file to look at, what "done" means, and what
you will learn from it.
Tests need PostgreSQL with pgvector and nothing else — no LLM, no API keys.
The same is true of every example.
📄 License
This project is licensed under the Apache License 2.0.
Developed by Chandan Rajah (chandan.rajah@gmail.com).
Metadata
Release files for post-graph 1.14.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| post_graph-1.14.2.tar.gz | 271.6 kB | Without provenance | Details for post_graph-1.14.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| post_graph-1.14.2-py3-none-any.whl | Python 3 | none | any | Details for post_graph-1.14.2-py3-none-any.whl |
Total release size: 405.5 kB
Release files / post_graph-1.14.2.tar.gz
| Download URL | post_graph-1.14.2.tar.gz |
|---|---|
| Size | 271.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c3ad48c11277044151dd5d6666e591001337afb9e9434f151c8179678f14e2de
|
|
BLAKE2b-256 checksum How to use checksums |
7a5d8c1b41f40b318056de89200312b482ce4cf3d36af94c9919946e5ede9746
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / post_graph-1.14.2-py3-none-any.whl
| Download URL | post_graph-1.14.2-py3-none-any.whl |
|---|---|
| Size | 133.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2ba24c7fb62733b78bff00306320868adf641107672143a66a320f2a86caec46
|
|
BLAKE2b-256 checksum How to use checksums |
d6aebbb03d158550e5b385d4e3f87f0fe4d53ac2752bea2f20271f4bb243986b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Security for post-graph 1.14.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.