You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This guide covers the pydantic-native schema interface for the TerminusDB
Python client: declare your domain model once as pydantic models, and let
TerminusDB hold the schema. Documents validate against the same models on the
way in and out — no second declaration, no drift.
The pydantic interface is the primary way to manage schemas from Python. The
older DocumentTemplate/WOQLSchema API remains supported; see Migrating from DocumentTemplate.
Why pydantic + TerminusDB
A TerminusDB schema is a graph of class documents. A pydantic model is a
typed Python class. They describe the same thing — this package makes them
interchangeable:
Declare models once. The schema in the database is generated from them, or
the models are generated from the schema — your choice, per project.
Documents coming out of the database validate into your models. A document
that fails validation means schema drift, and it fails loudly.
Code-first — author models in Python, schema.commit(client) pushes
the schema. Best for greenfield.
Schema-first — evolve the schema in TerminusDB, tdbpy sync regenerates schema.py. The generated file is a check-in artefact: schema changes and
model diffs land in the same PR.
Dynamic — PydanticSchema.from_db(client) builds models from the
database at runtime. Drift is impossible by construction; the trade-off is
no static types. For tools, notebooks and agents.
tdbpy check is the guard rail: it diffs your local models against the
schema graph and exits non-zero when they disagree.
Installation
pip install "terminusdb[pydantic]"
Requires pydantic >= 2 and Python >= 3.9. The core client keeps working
without the extra; importing terminusdb_client.schema.pydantic without
pydantic installed raises a single ImportError telling you to install the
extra.
Declaring models
Subclass TerminusModel and annotate fields exactly as you would in any
pydantic model:
fromtypingimportList, Optionalfromterminusdb_client.schema.pydanticimportTerminusModelfromterminusdb_client.schemaimportLexicalKeyclassPerson(TerminusModel):
"""A person tracked by the system. Attributes ---------- name : str Full display name. """_key=LexicalKey("name")
name: strage: Optional[int] =Nonetags: List[str] = []
This class emits the TerminusDB schema document:
{"@type": "Class", "@id": "Person",
"@documentation": {"@comment": "A person tracked by the system.",
"@properties": {"name": "Full display name."}},
"@key": {"@type": "Lexical", "@fields": ["name"]},
"name": "xsd:string",
"age": {"@type": "Optional", "@class": "xsd:integer"},
"tags": {"@type": "List", "@class": "xsd:string"}}
Everything DocumentTemplate can declare, a TerminusModel can declare:
Class attributes
Attribute
Effect on the schema
_key
@key — document id scheme. All key classes: HashKey, LexicalKey, ValueHashKey, RandomKey (default), UuidV7Key
_subdocument = []
@subdocument — embedded document, no independent id
_shared = True
"@shared": [] — reference-counted document, cascade-deleted on last unreference (see Shared documents)
_unfoldable = True
"@unfoldable": [] — always expanded on read (see links)
_abstract = []
@abstract — no instances
_foreign = True
{"@type": "Foreign"} — opaque reference to another data product (see Foreign references)
_base = "prefix/"
@base — id minting prefix for this class
_metadata = {...}
@metadata — arbitrary class metadata (render_as, order_by, embedding config, …)
_schema = my_schema
registers the class into a Schema at definition time
Underscore-prefixed names are pydantic-private by convention, never
fields. UuidV7Key accepts any supplied IRI as @id (no @base enforcement) —
useful when loading data that already carries external identifiers.
Field types
The annotation alone determines the schema entry — validators, defaults and
constraints (Field(gt=), pattern=) are client-side concerns and never
appear in the schema document. Optional is the only way to say a field may
be absent.
Write Optional[X] = None when the field should be truly optional at
construction time — Optional[X] alone is still a required field in
pydantic. Optional[Set[X]] and Optional[List[X]] are invalid
(TypeError): a collection already permits zero elements.
| List[X] / list[X] | {"@type": "List", "@class": X} |
| Set[X] / set[X] | {"@type": "Set", "@class": X} |
| Set[X] with Field(min_length=, max_length=) | adds @min_cardinality/@max_cardinality (equal values collapse to @cardinality) |
| Annotated[list[X], Array] | {"@type": "Array", "@class": X} — ordered, gaps allowed; @dimensions from list nesting (list[list[float]] → 2) |
| None (inside TerminusUnion) | sys:Unit — a tagged-union member carrying no value |
| another TerminusModel | object property — the class name; embedded when the target is a subdocument |
| Enum subclass | the enum's @id; the enum itself emits {"@type": "Enum", "@value": [...]} |
| forward reference "Person" | the class name (self- and mutual references) |
| Literal, Union[A, B] (non-Optional), tuple, frozenset, Callable | TypeError — not representable; see TerminusUnion below |
Enums
Enums register with TerminusEnum (a str, Enum subclass); member values
are the stored values:
Colour emits {"@type": "Enum", "@id": "Colour", "@value": ["red", "blue", "Information Technology"]} and registers into the same _schema. Values
serialise as member.value.
Subdocuments
A subdocument is embedded inside its parent — it mints no id of its own:
address emits {"@type": "Optional", "@class": "Address"} and the stored
document embeds the Address object inline. Engine rule: a subdocument's
key must be RandomKey, UuidV7Key or ValueHashKey.
Shared documents — _shared
A shared document is a regular document — own id, any key type, linkable
from many parents — whose lifecycle is reference-counted: when its last
inbound reference is removed (parent deleted, field updated, triple
removed), the engine cascade-deletes it at commit, recursively, including
circular islands of shared documents that reference only each other.
classFootnote(TerminusModel):
_shared=Truelabel: strcontent: strclassArticle(TerminusModel):
notes: Set[Footnote] # several articles may share one Footnote
Constraints: _shared is mutually exclusive with _subdocument (a class
definition carrying both raises ValueError at declaration time), is
inherited, and unlike a subdocument it does not auto-unfold — add _unfoldable on the class or Unfold on the property for that. A shared
document with zero references may be created standalone; the cascade only
fires when a reference is removed.
Foreign references — _foreign
Foreign types are opaque references to documents living in another data
product: no fields, no referential integrity — just an identifier.
classPerson(TerminusModel):
_foreign=TrueclassEvent(TerminusModel):
person: Optional[Person] =None# stores the IRI only
Person emits {"@type": "Foreign", "@id": "Person"} (no properties).
Assign a plain string id/IRI on write; on read it materialises as a stub
carrying _backend_id — fields never unfold because nothing local exists
to unfold.
Tagged unions — TerminusUnion
A tagged union says "the document carries the fields of exactly one member".
Declare members as fields on a TerminusUnion subclass:
emits {"@type": "TaggedUnion", "@id": "Contact", "@oneOf": {"email": ..., "phone": ...}}. Non-Optional Union[A, B] annotations are not the same
thing — use TerminusUnion.
A member with no value is sys:Unit, written as a None-annotated field —
the canonical binary-tree example:
(TerminusDB also supports the general @oneOf list on ordinary Class
documents — multiple disjoint property groups. TerminusUnion covers the TaggedUnion sugar only; the general form is a documented limitation, see
the reference chapter.)
Person emits "@inherits": "Party" — fields resolve through __mro__
exactly as pydantic resolves them.
Documentation
The class docstring is parsed with numpydoc (ClassDoc) and becomes @documentation; Field(description=...) adds or overrides a property
entry. Per-language (@language) documentation is handled by the engine —
author the default text in code.
Documents and links: the unfold contract
Links to other documents are the one place where TerminusDB storage and
pydantic models differ in shape. TerminusDB may return a link as an id
string ("Person/bob"), as a {"@type", "@id"} reference, or as a full
nested document — depending on schema markers and the request flag. The
client maps each mechanism to exactly one pydantic construct:
TerminusDB mechanism
Pydantic equivalent
@subdocument class
Nested TerminusModel — always a full embedded object
"@unfoldable": [] on the class
_unfoldable = True on the model — always expanded
"@unfold": true on a property
Annotated[Sub, Unfold] marker — this property always expands
folded link ("Class/id" string or {"@type","@id"})
stub — an id-carrying model with no populated fields
fromtypingimportAnnotatedfromterminusdb_client.schema.pydanticimportTerminusModel, UnfoldclassAudit(TerminusModel):
_subdocument= []
_unfoldable=True# class marker: this type always expandsclassTicket(TerminusModel):
title: straudit: Annotated[Optional[Audit], Unfold] =None# property markerassignee: Optional[Person] =None# ordinary link — may be a stub
Unfold is a metadata marker for Annotated; it emits "@unfold": true
on the property — {"@class": "Audit", "@unfold": true} for a required
field, {"@type": "Optional", "@class": "Audit", "@unfold": true} inside
complex specs (Optional, Set, List, Array). _unfoldable emits "@unfoldable": [] on the class document. Unfoldability is transitive
through inheritance, matching the engine.
Unfolding is bounded: the engine detects cycles (a document that unfolds
into itself comes back as an IRI at the repeated leaf) and caps expansion
at a configurable default of 500,000 documents.
Stubs
A folded link loads as a stub: a model instance carrying only its _backend_id, with no fields populated. Accessing a field on a stub raises AttributeError; serialising a stub writes its id back — a document with
unresolved links round-trips losslessly.
ticket=schema.parse_document(client.get_document("Ticket/1"))
ticket.assignee._backend_id# "Person/bob"ticket.assignee.name# AttributeError — it's a stubbob=schema.parse_document(client.get_document(ticket.assignee._backend_id))
Stubs are the same compromise DocumentTemplate always made — the
alternative (fetching every linked document eagerly) is not offered. When
you want real objects, fetch with unfold=True and every link arrives as a
full model instead:
ticket=schema.parse_document(client.get_document("Ticket/1", unfold=True))
ticket.assignee.name# works — unfolded document
Setting cls._schema = schema at class-definition time registers
automatically — the same idiom as DocumentTemplate. Schema also accepts metadata={...}: arbitrary JSON written verbatim into the context object's @metadata — this is where data-product options such as terminusdb.options (store_indices, store_clustering) live.
Schema-first: tdbpy sync
Inside a tdbpy project (tdbpy startproject creates config.json + .TDB):
tdbpy sync --format pydantic # writes schema.py with TerminusModel classes
tdbpy sync # writes schema.py with DocumentTemplate classes (default)
sync --format pydantic also records "model_backend": "pydantic" in config.json; subsequent sync runs keep the pydantic emitter, and commit/check know which module shape to expect. The generated file is
meant to be committed to version control — review schema and code together.
Drift gate: tdbpy check
tdbpy check # exit 0: models match the schema graph
tdbpy check --ignore-docs # ignore @documentation differences
On drift it prints which classes are missing on each side and a unified
diff of differing classes, then exits 1. Wire it into CI and "the schema
changed without regenerating models" becomes impossible to merge. Schema.diff(client, ignore_docs=False) exposes the same comparison
(returning a list of diff lines) for tests and tooling.
Typed documents
parse_document is the single entry point — it finds the model by @type
and validates:
schema=PydanticSchema().from_db(client) # or a Schema with models added via add_obj/_schematicket=schema.parse_document(client.get_document("Ticket/1"))
ticket.title# str, validatedticket._backend_id# "Ticket/1"
Writing uses the ordinary document API — models serialise through _obj_to_dict, which the client already understands:
new_ticket=Ticket(title="Login broken", audit=Audit(by="alice"))
client.insert_document(new_ticket) # mints + stamps idnew_ticket._backend_id# "Ticket/<minted>"client.update_document(new_ticket) # writes changed fieldsclient.replace_document(new_ticket) # full replaceclient.delete_document(new_ticket) # or an id string
After a successful insert, client stamps the minted id onto the object
(_backend_id), exactly as it does for DocumentTemplate instances.
Multi-object writes use the same @capture/@ref graph the engine
expects: linking a not-yet-inserted object emits a @ref, and insert_document writes the whole reachable graph in one call:
bob=Person(name="bob")
ticket=Ticket(title="x", assignee=bob)
client.insert_document(ticket) # writes bob + ticket in one request
to_document() returns (doc, references) — the dict your model becomes
on the wire. from_document(doc) / schema.parse_document(doc) is the
inverse, for when you fetch raw dicts yourself (e.g. via WOQL).
Evolving the schema
Two loops, one source of truth.
Database-first (recommended for production). Evolve the schema in
TerminusDB — via the migration API or a schema push — then regenerate:
tdbpy sync --format pydantic # models follow the database
git diff schema.py # review what changed
tdbpy check # 0 — local matches server
The regenerated file is the reviewable artefact of the migration.
Model-first (local development). Edit the model, check the diff, push:
When a model-first push would lose data (dropped fields, narrowed types)
the engine's migration machinery decides what happens — see the schema
migration reference. --ignore-docs on check separates cosmetic doc
edits from structural drift.
from_db rebuilds the full class graph — inheritance, enums, tagged
unions, subdocuments, keys, forward and self references — as real pydantic
models. Use it for tools, notebooks and agents that must match whatever the
database currently says; use codegen (sync) for application code, where
static types and reviewable diffs matter.
Migrating from DocumentTemplate
The declaration syntaxes coexist in one Schema — migrate a class at a
time, and the emitted schema document (hence the database) does not change:
DocumentTemplate
TerminusModel
class P(DocumentTemplate):
class P(TerminusModel):
name: str
name: str — unchanged
_key = LexicalKey("name")
unchanged
_subdocument, _abstract, _base
unchanged
EnumTemplate + transform_enum_dict
TerminusEnum (str, Enum) with explicit values
TaggedUnion
TerminusUnion (fields are the union members)
typeguard on __setattr__
pydantic validators
obj._id
obj._backend_id for loaded ids; _id still computes custom ids
— (new constructs)
_shared, _foreign, _metadata, Unfold, Array, Field cardinality — pydantic-only additions
DocumentTemplate stays supported — existing code keeps working. New code
should use TerminusModel: it is the documented interface going forward,
and the only one that gains the codegen/check tooling.
Recipes
FastAPI. The same model is the API contract and the database schema:
@app.post("/tickets")asyncdefcreate_ticket(ticket: Ticket): # pydantic validates the requestclient.insert_document(ticket) # and the documentreturn {"id": ticket._backend_id}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
This is a working proposal for a Pydantic setup with TerminusDB for authoring and working with schema.
See pull request here:
terminusdb/terminusdb-client-python#482
Pydantic models for TerminusDB — user guide
This guide covers the pydantic-native schema interface for the TerminusDB
Python client: declare your domain model once as pydantic models, and let
TerminusDB hold the schema. Documents validate against the same models on the
way in and out — no second declaration, no drift.
The pydantic interface is the primary way to manage schemas from Python. The
older
DocumentTemplate/WOQLSchemaAPI remains supported; seeMigrating from DocumentTemplate.
Why pydantic + TerminusDB
A TerminusDB schema is a graph of class documents. A pydantic model is a
typed Python class. They describe the same thing — this package makes them
interchangeable:
the models are generated from the schema — your choice, per project.
that fails validation means schema drift, and it fails loudly.
model_dump/model_validate, JSON Schema export, mypy-friendly typing.Three supported workflows:
schema.commit(client)pushesthe schema. Best for greenfield.
tdbpy syncregeneratesschema.py. The generated file is a check-in artefact: schema changes andmodel diffs land in the same PR.
PydanticSchema.from_db(client)builds models from thedatabase at runtime. Drift is impossible by construction; the trade-off is
no static types. For tools, notebooks and agents.
tdbpy checkis the guard rail: it diffs your local models against theschema graph and exits non-zero when they disagree.
Installation
pip install "terminusdb[pydantic]"Requires pydantic >= 2 and Python >= 3.9. The core client keeps working
without the extra; importing
terminusdb_client.schema.pydanticwithoutpydantic installed raises a single
ImportErrortelling you to install theextra.
Declaring models
Subclass
TerminusModeland annotate fields exactly as you would in anypydantic model:
This class emits the TerminusDB schema document:
{"@type": "Class", "@id": "Person", "@documentation": {"@comment": "A person tracked by the system.", "@properties": {"name": "Full display name."}}, "@key": {"@type": "Lexical", "@fields": ["name"]}, "name": "xsd:string", "age": {"@type": "Optional", "@class": "xsd:integer"}, "tags": {"@type": "List", "@class": "xsd:string"}}Everything
DocumentTemplatecan declare, aTerminusModelcan declare:Class attributes
_key@key— document id scheme. All key classes:HashKey,LexicalKey,ValueHashKey,RandomKey(default),UuidV7Key_subdocument = []@subdocument— embedded document, no independent id_shared = True"@shared": []— reference-counted document, cascade-deleted on last unreference (see Shared documents)_unfoldable = True"@unfoldable": []— always expanded on read (see links)_abstract = []@abstract— no instances_foreign = True{"@type": "Foreign"}— opaque reference to another data product (see Foreign references)_base = "prefix/"@base— id minting prefix for this class_metadata = {...}@metadata— arbitrary class metadata (render_as,order_by, embedding config, …)_schema = my_schemaSchemaat definition timeUnderscore-prefixed names are pydantic-private by convention, never
fields.
UuidV7Keyaccepts any supplied IRI as@id(no@baseenforcement) —useful when loading data that already carries external identifiers.
Field types
The annotation alone determines the schema entry — validators, defaults and
constraints (
Field(gt=),pattern=) are client-side concerns and neverappear in the schema document.
Optionalis the only way to say a field maybe absent.
str/int/float/boolxsd:string/xsd:integer/xsd:double/xsd:booleandatetime,date,time,timedeltaxsd:dateTime,xsd:date,xsd:time,xsd:durationdecimal.Decimalxsd:decimaldictsys:JSON(arbitrary JSON blob)woql_typeNewTypes (gYear,anyURI,token,long,dayTimeDuration, …)xsd:counterpartsOptional[X]/X | None{"@type": "Optional", "@class": X}Write
Optional[X] = Nonewhen the field should be truly optional atconstruction time —
Optional[X]alone is still a required field inpydantic.
Optional[Set[X]]andOptional[List[X]]are invalid(
TypeError): a collection already permits zero elements.|
List[X]/list[X]|{"@type": "List", "@class": X}||
Set[X]/set[X]|{"@type": "Set", "@class": X}||
Set[X]withField(min_length=, max_length=)| adds@min_cardinality/@max_cardinality(equal values collapse to@cardinality) ||
Annotated[list[X], Array]|{"@type": "Array", "@class": X}— ordered, gaps allowed;@dimensionsfrom list nesting (list[list[float]]→2) ||
None(insideTerminusUnion) |sys:Unit— a tagged-union member carrying no value || another
TerminusModel| object property — the class name; embedded when the target is a subdocument ||
Enumsubclass | the enum's@id; the enum itself emits{"@type": "Enum", "@value": [...]}|| forward reference
"Person"| the class name (self- and mutual references) ||
Literal,Union[A, B](non-Optional),tuple,frozenset,Callable|TypeError— not representable; seeTerminusUnionbelow |Enums
Enums register with
TerminusEnum(astr, Enumsubclass); member valuesare the stored values:
Colouremits{"@type": "Enum", "@id": "Colour", "@value": ["red", "blue", "Information Technology"]}and registers into the same_schema. Valuesserialise as
member.value.Subdocuments
A subdocument is embedded inside its parent — it mints no id of its own:
addressemits{"@type": "Optional", "@class": "Address"}and the storeddocument embeds the
Addressobject inline. Engine rule: a subdocument'skey must be
RandomKey,UuidV7KeyorValueHashKey.Shared documents —
_sharedA shared document is a regular document — own id, any key type, linkable
from many parents — whose lifecycle is reference-counted: when its last
inbound reference is removed (parent deleted, field updated, triple
removed), the engine cascade-deletes it at commit, recursively, including
circular islands of shared documents that reference only each other.
Constraints:
_sharedis mutually exclusive with_subdocument(a classdefinition carrying both raises
ValueErrorat declaration time), isinherited, and unlike a subdocument it does not auto-unfold — add
_unfoldableon the class orUnfoldon the property for that. A shareddocument with zero references may be created standalone; the cascade only
fires when a reference is removed.
Foreign references —
_foreignForeigntypes are opaque references to documents living in another dataproduct: no fields, no referential integrity — just an identifier.
Personemits{"@type": "Foreign", "@id": "Person"}(no properties).Assign a plain string id/IRI on write; on read it materialises as a stub
carrying
_backend_id— fields never unfold because nothing local existsto unfold.
Tagged unions —
TerminusUnionA tagged union says "the document carries the fields of exactly one member".
Declare members as fields on a
TerminusUnionsubclass:emits
{"@type": "TaggedUnion", "@id": "Contact", "@oneOf": {"email": ..., "phone": ...}}. Non-OptionalUnion[A, B]annotations are not the samething — use
TerminusUnion.A member with no value is
sys:Unit, written as aNone-annotated field —the canonical binary-tree example:
(TerminusDB also supports the general
@oneOflist on ordinaryClassdocuments — multiple disjoint property groups.
TerminusUnioncovers theTaggedUnionsugar only; the general form is a documented limitation, seethe reference chapter.)
Inheritance and abstract classes
Personemits"@inherits": "Party"— fields resolve through__mro__exactly as pydantic resolves them.
Documentation
The class docstring is parsed with
numpydoc(ClassDoc) and becomes@documentation;Field(description=...)adds or overrides a propertyentry. Per-language (
@language) documentation is handled by the engine —author the default text in code.
Documents and links: the unfold contract
Links to other documents are the one place where TerminusDB storage and
pydantic models differ in shape. TerminusDB may return a link as an id
string (
"Person/bob"), as a{"@type", "@id"}reference, or as a fullnested document — depending on schema markers and the request flag. The
client maps each mechanism to exactly one pydantic construct:
@subdocumentclassTerminusModel— always a full embedded object"@unfoldable": []on the class_unfoldable = Trueon the model — always expanded"@unfold": trueon a propertyAnnotated[Sub, Unfold]marker — this property always expandsunfoldflag on a document requestclient.get_document(id, unfold=True)— expands reachable links server-side"Class/id"string or{"@type","@id"})Unfoldis a metadata marker forAnnotated; it emits"@unfold": trueon the property —
{"@class": "Audit", "@unfold": true}for a requiredfield,
{"@type": "Optional", "@class": "Audit", "@unfold": true}insidecomplex specs (
Optional,Set,List,Array)._unfoldableemits"@unfoldable": []on the class document. Unfoldability is transitivethrough inheritance, matching the engine.
Unfolding is bounded: the engine detects cycles (a document that unfolds
into itself comes back as an IRI at the repeated leaf) and caps expansion
at a configurable default of 500,000 documents.
Stubs
A folded link loads as a stub: a model instance carrying only its
_backend_id, with no fields populated. Accessing a field on a stub raisesAttributeError; serialising a stub writes its id back — a document withunresolved links round-trips losslessly.
Stubs are the same compromise
DocumentTemplatealways made — thealternative (fetching every linked document eagerly) is not offered. When
you want real objects, fetch with
unfold=Trueand every link arrives as afull model instead:
The schema lifecycle
Model-first: commit
Register models into a
Schemaand push:Setting
cls._schema = schemaat class-definition time registersautomatically — the same idiom as
DocumentTemplate.Schemaalso acceptsmetadata={...}: arbitrary JSON written verbatim into the context object's@metadata— this is where data-product options such asterminusdb.options(store_indices,store_clustering) live.Schema-first:
tdbpy syncInside a
tdbpyproject (tdbpy startprojectcreatesconfig.json+.TDB):sync --format pydanticalso records"model_backend": "pydantic"inconfig.json; subsequentsyncruns keep the pydantic emitter, andcommit/checkknow which module shape to expect. The generated file ismeant to be committed to version control — review schema and code together.
Drift gate:
tdbpy checkOn drift it prints which classes are missing on each side and a unified
diff of differing classes, then exits 1. Wire it into CI and "the schema
changed without regenerating models" becomes impossible to merge.
Schema.diff(client, ignore_docs=False)exposes the same comparison(returning a list of diff lines) for tests and tooling.
Typed documents
parse_documentis the single entry point — it finds the model by@typeand validates:
Writing uses the ordinary document API — models serialise through
_obj_to_dict, which the client already understands:After a successful insert,
clientstamps the minted id onto the object(
_backend_id), exactly as it does forDocumentTemplateinstances.Multi-object writes use the same
@capture/@refgraph the engineexpects: linking a not-yet-inserted object emits a
@ref, andinsert_documentwrites the whole reachable graph in one call:to_document()returns(doc, references)— the dict your model becomeson the wire.
from_document(doc)/schema.parse_document(doc)is theinverse, for when you fetch raw dicts yourself (e.g. via WOQL).
Evolving the schema
Two loops, one source of truth.
Database-first (recommended for production). Evolve the schema in
TerminusDB — via the migration API or a schema push — then regenerate:
The regenerated file is the reviewable artefact of the migration.
Model-first (local development). Edit the model, check the diff, push:
When a model-first push would lose data (dropped fields, narrowed types)
the engine's migration machinery decides what happens — see the schema
migration reference.
--ignore-docsoncheckseparates cosmetic docedits from structural drift.
Dynamic loading
from_dbrebuilds the full class graph — inheritance, enums, taggedunions, subdocuments, keys, forward and self references — as real pydantic
models. Use it for tools, notebooks and agents that must match whatever the
database currently says; use codegen (
sync) for application code, wherestatic types and reviewable diffs matter.
Migrating from DocumentTemplate
The declaration syntaxes coexist in one
Schema— migrate a class at atime, and the emitted schema document (hence the database) does not change:
DocumentTemplateTerminusModelclass P(DocumentTemplate):class P(TerminusModel):name: strname: str— unchanged_key = LexicalKey("name")_subdocument,_abstract,_baseEnumTemplate+transform_enum_dictTerminusEnum(str, Enum) with explicit valuesTaggedUnionTerminusUnion(fields are the union members)typeguardon__setattr__obj._idobj._backend_idfor loaded ids;_idstill computes custom ids_shared,_foreign,_metadata,Unfold,Array,Fieldcardinality — pydantic-only additionsDocumentTemplatestays supported — existing code keeps working. New codeshould use
TerminusModel: it is the documented interface going forward,and the only one that gains the codegen/check tooling.
Recipes
FastAPI. The same model is the API contract and the database schema:
Notebooks. Pull the live schema, explore:
CI drift gate.
Reference
Error catalogue
TypeError: use TerminusUnion for non-Optional unions—Union[A, B]or
Literalis not a schema type; declareTerminusUnion/Enum.AttributeErroron a model field — the value is a stub, not apopulated object; fetch with
unfold=Trueor resolve_backend_id.ValidationErrorfromparse_document— the stored document does notsatisfy the model. That is drift: sync the models or fix the data.
ImportError: install terminusdb[pydantic]— missing the extra.ValueErrorfromclienton insert — "Subdocument cannot be addeddirectly" (subdocuments only exist embedded) or a non-model object.
ValueErrorat class definition —_sharedand_subdocumenton oneclass (mutually exclusive), or
_foreignwith declared fields.Limitations
Not yet mapped to pydantic constructs —
from_dbraises a precise errorrather than round-tripping these incorrectly:
@oneOflist onClassdocuments (only theTaggedUnionsugar is covered by
TerminusUnion)Tabletype family (engine surface without reference-guide docs)@languagemultilingual@documentation(author the default language;per-language docs are engine-managed)
layer:Layer,layer:identifier) —_base/schema_refcover the common cases@valuesonEnum@documentation)sys:JSONDocument— unstructured JSON storage is an insert-flag feature(
client.insert_document(raw_dict)/ CLI-j), not a schema constructFAQ
are client-side. Only
Optional[]changes the schema.DocumentTemplateandTerminusModel? Yes — oneSchema, both kinds of class, one commit.syncwrite? Alwaysschema.py;model_backendinconfig.jsondecides whether it containsTerminusModelorDocumentTemplateclasses.Literalfields? Not schema types; use anEnum.pydanticrequired for the rest of the client? No — it is anoptional extra; everything else works as before.
All reactions