uni_pydantic
uni-pydantic: Pydantic-based OGM for Uni Graph Database.
This package provides a type-safe Object-Graph Mapping layer on top of the Uni graph database, using Pydantic v2 for model definitions.
Example:
from uni_db import Uni from uni_pydantic import UniNode, UniSession, Field, Relationship, Vector
class Person(UniNode): ... name: str ... age: int | None = None ... email: str = Field(unique=True) ... embedding: Vector[1536] ... friends: list["Person"] = Relationship("FRIEND_OF", direction="both")
db = Uni("./my_graph") session = UniSession(db) session.register(Person) session.sync_schema()
alice = Person(name="Alice", age=30, email="alice@example.com") session.add(alice) session.commit()
Query with type safety
adults = session.query(Person).filter(Person.age >= 18).all()
1# SPDX-License-Identifier: Apache-2.0 2# Copyright 2024-2026 Dragonscale Team 3 4""" 5uni-pydantic: Pydantic-based OGM for Uni Graph Database. 6 7This package provides a type-safe Object-Graph Mapping layer on top of 8the Uni graph database, using Pydantic v2 for model definitions. 9 10Example: 11 >>> from uni_db import Uni 12 >>> from uni_pydantic import UniNode, UniSession, Field, Relationship, Vector 13 >>> 14 >>> class Person(UniNode): 15 ... name: str 16 ... age: int | None = None 17 ... email: str = Field(unique=True) 18 ... embedding: Vector[1536] 19 ... friends: list["Person"] = Relationship("FRIEND_OF", direction="both") 20 >>> 21 >>> db = Uni("./my_graph") 22 >>> session = UniSession(db) 23 >>> session.register(Person) 24 >>> session.sync_schema() 25 >>> 26 >>> alice = Person(name="Alice", age=30, email="alice@example.com") 27 >>> session.add(alice) 28 >>> session.commit() 29 >>> 30 >>> # Query with type safety 31 >>> adults = session.query(Person).filter(Person.age >= 18).all() 32""" 33 34from pathlib import Path 35 36# Base classes 37# Async support 38from .async_query import AsyncQueryBuilder 39from .async_session import AsyncUniSession, AsyncUniTransaction 40from .base import SearchScores, UniEdge, UniNode 41 42# Database wrappers 43from .database import AsyncUniDatabase, UniDatabase 44 45# Exceptions 46from .exceptions import ( 47 BulkLoadError, 48 CypherInjectionError, 49 LazyLoadError, 50 NotPersisted, 51 NotRegisteredError, 52 NotTrackedError, 53 QueryError, 54 RelationshipError, 55 SchemaError, 56 SessionError, 57 TransactionError, 58 TypeMappingError, 59 UniPydanticError, 60 ValidationError, 61) 62 63# Field configuration 64from .fields import ( 65 Direction, 66 Field, 67 FieldConfig, 68 IndexType, 69 Relationship, 70 RelationshipConfig, 71 RelationshipDescriptor, 72 VectorMetric, 73 get_field_config, 74) 75 76# Lifecycle hooks 77from .hooks import ( 78 after_create, 79 after_delete, 80 after_load, 81 after_update, 82 before_create, 83 before_delete, 84 before_load, 85 before_update, 86) 87 88# Query builder 89from .query import ( 90 FilterExpr, 91 FilterOp, 92 HybridSearchConfig, 93 ModelProxy, 94 OrderByClause, 95 PropertyProxy, 96 QueryBuilder, 97 SparseSearchConfig, 98 TraversalStep, 99 VectorSearchConfig, 100) 101 102# Schema generation 103from .schema import ( 104 DatabaseSchema, 105 EdgeTypeSchema, 106 LabelSchema, 107 PropertySchema, 108 SchemaGenerator, 109 generate_schema, 110) 111 112# Session management 113from .session import UniSession, UniTransaction 114 115# Type utilities 116from .types import ( 117 DATETIME_TYPES, 118 Btic, 119 SparseVector, 120 Vector, 121 db_to_python_value, 122 get_sparse_vector_dimensions, 123 get_vector_dimensions, 124 is_list_type, 125 is_optional, 126 python_to_db_value, 127 python_type_to_uni, 128 uni_to_python_type, 129 unwrap_annotated, 130) 131 132 133def _package_version() -> str: 134 """Read the version from installed package metadata. 135 136 Derived rather than hand-written: a literal here is a second source of truth 137 beside ``pyproject.toml`` and drifts silently, because only ``pyproject.toml`` 138 is checked at release time. It had drifted to ``2.5.0`` against a ``3.3.0`` 139 package, which would have shipped a wrong ``__version__`` to every consumer. 140 141 Falls back to reading ``pyproject.toml`` for a source checkout that has not 142 been installed, and finally to ``"0.0.0"`` so an import never fails over a 143 version string. 144 """ 145 from importlib.metadata import PackageNotFoundError, version 146 147 try: 148 return version("uni-pydantic") 149 except PackageNotFoundError: 150 pass 151 152 try: 153 import tomllib 154 155 pyproject = Path(__file__).resolve().parents[2] / "pyproject.toml" 156 with pyproject.open("rb") as fh: 157 return str(tomllib.load(fh)["project"]["version"]) 158 except Exception: # noqa: BLE001 - a version string must never break import 159 return "0.0.0" 160 161 162__version__ = _package_version() 163 164 165__all__ = [ 166 # Version 167 "__version__", 168 # Base classes 169 "UniNode", 170 "UniEdge", 171 "SearchScores", 172 # Session 173 "UniSession", 174 "UniTransaction", 175 # Async Session 176 "AsyncUniSession", 177 "AsyncUniTransaction", 178 # Fields 179 "Field", 180 "FieldConfig", 181 "Relationship", 182 "RelationshipConfig", 183 "RelationshipDescriptor", 184 "get_field_config", 185 "IndexType", 186 "Direction", 187 "VectorMetric", 188 # Types 189 "Btic", 190 "Vector", 191 "SparseVector", 192 "python_type_to_uni", 193 "uni_to_python_type", 194 "get_vector_dimensions", 195 "get_sparse_vector_dimensions", 196 "is_optional", 197 "is_list_type", 198 "unwrap_annotated", 199 "python_to_db_value", 200 "db_to_python_value", 201 "DATETIME_TYPES", 202 # Query 203 "QueryBuilder", 204 "AsyncQueryBuilder", 205 "FilterExpr", 206 "FilterOp", 207 "PropertyProxy", 208 "ModelProxy", 209 "OrderByClause", 210 "TraversalStep", 211 "VectorSearchConfig", 212 "SparseSearchConfig", 213 "HybridSearchConfig", 214 # Schema 215 "SchemaGenerator", 216 "DatabaseSchema", 217 "LabelSchema", 218 "EdgeTypeSchema", 219 "PropertySchema", 220 "generate_schema", 221 # Database 222 "UniDatabase", 223 "AsyncUniDatabase", 224 # Hooks 225 "before_create", 226 "after_create", 227 "before_update", 228 "after_update", 229 "before_delete", 230 "after_delete", 231 "before_load", 232 "after_load", 233 # Exceptions 234 "UniPydanticError", 235 "SchemaError", 236 "TypeMappingError", 237 "ValidationError", 238 "SessionError", 239 "NotRegisteredError", 240 "NotPersisted", 241 "NotTrackedError", 242 "TransactionError", 243 "QueryError", 244 "RelationshipError", 245 "LazyLoadError", 246 "BulkLoadError", 247 "CypherInjectionError", 248]
415class UniNode(BaseModel, metaclass=UniModelMeta): 416 """ 417 Base class for graph node models. 418 419 Subclass this to define your node types. Each UniNode subclass 420 represents a vertex label in the graph database. 421 422 Attributes: 423 __label__: The vertex label name. Defaults to the class name. 424 __relationships__: Dictionary of relationship configurations. 425 426 Private Attributes: 427 _vid: The vertex ID assigned by the database. 428 _uid: The unique identifier (content-addressed hash). 429 _session: Reference to the owning session. 430 _dirty: Set of modified field names. 431 432 Example: 433 >>> class Person(UniNode): 434 ... __label__ = "Person" 435 ... 436 ... name: str 437 ... age: int | None = None 438 ... email: str = Field(unique=True) 439 ... 440 ... friends: list["Person"] = Relationship("FRIEND_OF", direction="both") 441 """ 442 443 model_config = ConfigDict( 444 # Allow extra fields for future extensibility 445 extra="forbid", 446 # Validate on assignment for dirty tracking 447 validate_assignment=True, 448 # Allow arbitrary types (for Vector, etc.) 449 arbitrary_types_allowed=True, 450 # Use enum values 451 use_enum_values=True, 452 ) 453 454 # Class-level configuration 455 __label__: ClassVar[str] = "" 456 __relationships__: ClassVar[dict[str, RelationshipConfig]] = {} 457 458 # Private attributes for session tracking 459 _vid: int | None = PrivateAttr(default=None) 460 _uid: str | None = PrivateAttr(default=None) 461 _session: UniSession | AsyncUniSession | None = PrivateAttr(default=None) 462 _dirty: set[str] = PrivateAttr(default_factory=set) 463 _is_new: bool = PrivateAttr(default=True) 464 _scores: SearchScores | None = PrivateAttr(default=None) 465 466 def __init_subclass__(cls, **kwargs: Any) -> None: 467 super().__init_subclass__(**kwargs) 468 # Set default label to class name if not specified 469 if not cls.__label__: 470 cls.__label__ = cls.__name__ 471 472 def model_post_init(self, __context: Any) -> None: 473 """Clear dirty tracking after construction.""" 474 super().model_post_init(__context) 475 self._dirty = set() 476 477 @property 478 def vid(self) -> int | None: 479 """The vertex ID assigned by the database.""" 480 return self._vid 481 482 @property 483 def uid(self) -> str | None: 484 """The unique identifier (content-addressed hash).""" 485 return self._uid 486 487 @property 488 def is_persisted(self) -> bool: 489 """Whether this node has been saved to the database.""" 490 return self._vid is not None 491 492 @property 493 def is_dirty(self) -> bool: 494 """Whether this node has unsaved changes.""" 495 return bool(self._dirty) 496 497 @property 498 def search_scores(self) -> SearchScores | None: 499 """Relevance scores, if this instance came from a search builder. 500 501 ``None`` for instances from ordinary queries. See :class:`SearchScores`. 502 """ 503 return self._scores 504 505 def __setattr__(self, name: str, value: Any) -> None: 506 # Track dirty fields (but not private attributes) 507 if not name.startswith("_") and hasattr(self, "_dirty"): 508 self._dirty.add(name) 509 super().__setattr__(name, value) 510 511 def _mark_clean(self) -> None: 512 """Mark all fields as clean (called after commit).""" 513 self._dirty.clear() 514 self._is_new = False 515 516 def _attach_session( 517 self, session: UniSession | AsyncUniSession, vid: int, uid: str | None = None 518 ) -> None: 519 """Attach this node to a session with its database IDs.""" 520 self._session = session 521 self._vid = vid 522 self._uid = uid 523 self._is_new = False 524 525 @classmethod 526 def get_property_fields(cls) -> dict[str, FieldInfo]: 527 """Get all property fields (excluding relationships).""" 528 return { 529 name: info 530 for name, info in cls.model_fields.items() 531 if name not in cls.__relationships__ 532 } 533 534 @classmethod 535 def get_relationship_fields(cls) -> dict[str, RelationshipConfig]: 536 """Get all relationship field configurations.""" 537 return cls.__relationships__ 538 539 def to_properties(self) -> dict[str, Any]: 540 """Convert to a property dictionary for database storage. 541 542 Uses python_to_db_value() for type conversion. Includes None 543 explicitly so null-outs work. 544 """ 545 return _model_to_properties(self, self.get_property_fields()) 546 547 @classmethod 548 def from_properties( 549 cls: type[_NodeSelfT], 550 props: dict[str, Any], 551 *, 552 vid: int | None = None, 553 uid: str | None = None, 554 session: UniSession | AsyncUniSession | None = None, 555 ) -> _NodeSelfT: 556 """Create an instance from a property dictionary. 557 558 Accepts _id (string->int vid) and _label from uni-db node dicts. 559 Does not mutate the input dict. 560 """ 561 data = dict(props) 562 563 raw_id = data.pop("_id", None) 564 if raw_id is not None and vid is None: 565 vid = int(raw_id) if not isinstance(raw_id, int) else raw_id 566 data.pop("_label", None) 567 568 converted = _convert_db_values(data, cls) 569 570 instance = cls.model_validate(converted) 571 if vid is not None: 572 instance._vid = vid 573 if uid is not None: 574 instance._uid = uid 575 if session is not None: 576 instance._session = session 577 instance._is_new = vid is None 578 instance._dirty = set() 579 return instance 580 581 def __repr__(self) -> str: 582 vid_str = f"vid={self._vid}" if self._vid is not None else "unsaved" 583 return f"{self.__class__.__name__}({vid_str}, {super().__repr__()})"
Base class for graph node models.
Subclass this to define your node types. Each UniNode subclass represents a vertex label in the graph database.
Attributes: __label__: The vertex label name. Defaults to the class name. __relationships__: Dictionary of relationship configurations.
Private Attributes: _vid: The vertex ID assigned by the database. _uid: The unique identifier (content-addressed hash). _session: Reference to the owning session. _dirty: Set of modified field names.
Example:
class Person(UniNode): ... __label__ = "Person" ... ... name: str ... age: int | None = None ... email: str = Field(unique=True) ... ... friends: list["Person"] = Relationship("FRIEND_OF", direction="both")
477 @property 478 def vid(self) -> int | None: 479 """The vertex ID assigned by the database.""" 480 return self._vid
The vertex ID assigned by the database.
482 @property 483 def uid(self) -> str | None: 484 """The unique identifier (content-addressed hash).""" 485 return self._uid
The unique identifier (content-addressed hash).
487 @property 488 def is_persisted(self) -> bool: 489 """Whether this node has been saved to the database.""" 490 return self._vid is not None
Whether this node has been saved to the database.
492 @property 493 def is_dirty(self) -> bool: 494 """Whether this node has unsaved changes.""" 495 return bool(self._dirty)
Whether this node has unsaved changes.
497 @property 498 def search_scores(self) -> SearchScores | None: 499 """Relevance scores, if this instance came from a search builder. 500 501 ``None`` for instances from ordinary queries. See :class:`SearchScores`. 502 """ 503 return self._scores
Relevance scores, if this instance came from a search builder.
None for instances from ordinary queries. See SearchScores.
525 @classmethod 526 def get_property_fields(cls) -> dict[str, FieldInfo]: 527 """Get all property fields (excluding relationships).""" 528 return { 529 name: info 530 for name, info in cls.model_fields.items() 531 if name not in cls.__relationships__ 532 }
Get all property fields (excluding relationships).
534 @classmethod 535 def get_relationship_fields(cls) -> dict[str, RelationshipConfig]: 536 """Get all relationship field configurations.""" 537 return cls.__relationships__
Get all relationship field configurations.
539 def to_properties(self) -> dict[str, Any]: 540 """Convert to a property dictionary for database storage. 541 542 Uses python_to_db_value() for type conversion. Includes None 543 explicitly so null-outs work. 544 """ 545 return _model_to_properties(self, self.get_property_fields())
Convert to a property dictionary for database storage.
Uses python_to_db_value() for type conversion. Includes None explicitly so null-outs work.
547 @classmethod 548 def from_properties( 549 cls: type[_NodeSelfT], 550 props: dict[str, Any], 551 *, 552 vid: int | None = None, 553 uid: str | None = None, 554 session: UniSession | AsyncUniSession | None = None, 555 ) -> _NodeSelfT: 556 """Create an instance from a property dictionary. 557 558 Accepts _id (string->int vid) and _label from uni-db node dicts. 559 Does not mutate the input dict. 560 """ 561 data = dict(props) 562 563 raw_id = data.pop("_id", None) 564 if raw_id is not None and vid is None: 565 vid = int(raw_id) if not isinstance(raw_id, int) else raw_id 566 data.pop("_label", None) 567 568 converted = _convert_db_values(data, cls) 569 570 instance = cls.model_validate(converted) 571 if vid is not None: 572 instance._vid = vid 573 if uid is not None: 574 instance._uid = uid 575 if session is not None: 576 instance._session = session 577 instance._is_new = vid is None 578 instance._dirty = set() 579 return instance
Create an instance from a property dictionary.
Accepts _id (string->int vid) and _label from uni-db node dicts. Does not mutate the input dict.
586class UniEdge(BaseModel, metaclass=UniModelMeta): 587 """ 588 Base class for graph edge models with properties. 589 590 Subclass this to define edge types with typed properties. 591 Edges represent relationships between nodes. 592 593 Attributes: 594 __edge_type__: The edge type name. 595 __from__: The source node type(s). 596 __to__: The target node type(s). 597 598 Private Attributes: 599 _eid: The edge ID assigned by the database. 600 _src_vid: The source vertex ID. 601 _dst_vid: The destination vertex ID. 602 _session: Reference to the owning session. 603 604 Example: 605 >>> class FriendshipEdge(UniEdge): 606 ... __edge_type__ = "FRIEND_OF" 607 ... __from__ = Person 608 ... __to__ = Person 609 ... 610 ... since: date 611 ... strength: float = 1.0 612 """ 613 614 model_config = ConfigDict( 615 extra="forbid", 616 validate_assignment=True, 617 arbitrary_types_allowed=True, 618 use_enum_values=True, 619 ) 620 621 # Class-level configuration 622 __edge_type__: ClassVar[str] = "" 623 __from__: ClassVar[type[UniNode] | tuple[type[UniNode], ...] | None] = None 624 __to__: ClassVar[type[UniNode] | tuple[type[UniNode], ...] | None] = None 625 __relationships__: ClassVar[dict[str, RelationshipConfig]] = {} 626 627 # Private attributes 628 _eid: int | None = PrivateAttr(default=None) 629 _src_vid: int | None = PrivateAttr(default=None) 630 _dst_vid: int | None = PrivateAttr(default=None) 631 _session: UniSession | AsyncUniSession | None = PrivateAttr(default=None) 632 _is_new: bool = PrivateAttr(default=True) 633 634 def __init_subclass__(cls, **kwargs: Any) -> None: 635 super().__init_subclass__(**kwargs) 636 # Set default edge type to class name if not specified 637 if not cls.__edge_type__: 638 cls.__edge_type__ = cls.__name__ 639 640 @property 641 def eid(self) -> int | None: 642 """The edge ID assigned by the database.""" 643 return self._eid 644 645 @property 646 def src_vid(self) -> int | None: 647 """The source vertex ID.""" 648 return self._src_vid 649 650 @property 651 def dst_vid(self) -> int | None: 652 """The destination vertex ID.""" 653 return self._dst_vid 654 655 @property 656 def is_persisted(self) -> bool: 657 """Whether this edge has been saved to the database.""" 658 return self._eid is not None 659 660 def _attach( 661 self, 662 session: UniSession | AsyncUniSession, 663 eid: int, 664 src_vid: int, 665 dst_vid: int, 666 ) -> None: 667 """Attach this edge to a session with its database IDs.""" 668 self._session = session 669 self._eid = eid 670 self._src_vid = src_vid 671 self._dst_vid = dst_vid 672 self._is_new = False 673 674 @classmethod 675 def get_from_labels(cls) -> list[str]: 676 """Get the source label names.""" 677 if cls.__from__ is None: 678 return [] 679 if isinstance(cls.__from__, tuple): 680 return [n.__label__ for n in cls.__from__] 681 return [cls.__from__.__label__] 682 683 @classmethod 684 def get_to_labels(cls) -> list[str]: 685 """Get the target label names.""" 686 if cls.__to__ is None: 687 return [] 688 if isinstance(cls.__to__, tuple): 689 return [n.__label__ for n in cls.__to__] 690 return [cls.__to__.__label__] 691 692 @classmethod 693 def get_property_fields(cls) -> dict[str, FieldInfo]: 694 """Get all property fields.""" 695 return dict(cls.model_fields) 696 697 def to_properties(self) -> dict[str, Any]: 698 """Convert to a property dictionary for database storage.""" 699 return _model_to_properties(self, self.get_property_fields()) 700 701 @classmethod 702 def from_properties( 703 cls: type[_EdgeSelfT], 704 props: dict[str, Any], 705 *, 706 eid: int | None = None, 707 src_vid: int | None = None, 708 dst_vid: int | None = None, 709 session: UniSession | AsyncUniSession | None = None, 710 ) -> _EdgeSelfT: 711 """Create an instance from a property dictionary. 712 713 Accepts _id, _type, _src, _dst from uni-db edge dicts. 714 Does not mutate the input dict. 715 """ 716 data = dict(props) 717 718 raw_id = data.pop("_id", None) 719 if raw_id is not None and eid is None: 720 eid = int(raw_id) if not isinstance(raw_id, int) else raw_id 721 data.pop("_type", None) 722 raw_src = data.pop("_src", None) 723 if raw_src is not None and src_vid is None: 724 src_vid = int(raw_src) if not isinstance(raw_src, int) else raw_src 725 raw_dst = data.pop("_dst", None) 726 if raw_dst is not None and dst_vid is None: 727 dst_vid = int(raw_dst) if not isinstance(raw_dst, int) else raw_dst 728 729 converted = _convert_db_values(data, cls) 730 731 instance = cls.model_validate(converted) 732 if eid is not None: 733 instance._eid = eid 734 if src_vid is not None: 735 instance._src_vid = src_vid 736 if dst_vid is not None: 737 instance._dst_vid = dst_vid 738 if session is not None: 739 instance._session = session 740 instance._is_new = eid is None 741 return instance 742 743 @classmethod 744 def from_edge_result( 745 cls, 746 data: dict[str, Any], 747 *, 748 session: UniSession | AsyncUniSession | None = None, 749 ) -> UniEdge: 750 """Create an instance from a uni-db edge result dict. 751 752 Convenience method that handles _id, _type, _src, _dst keys. 753 """ 754 return cls.from_properties(data, session=session) 755 756 def __repr__(self) -> str: 757 eid_str = f"eid={self._eid}" if self._eid is not None else "unsaved" 758 return f"{self.__class__.__name__}({eid_str}, {super().__repr__()})"
Base class for graph edge models with properties.
Subclass this to define edge types with typed properties. Edges represent relationships between nodes.
Attributes: __edge_type__: The edge type name. __from__: The source node type(s). __to__: The target node type(s).
Private Attributes: _eid: The edge ID assigned by the database. _src_vid: The source vertex ID. _dst_vid: The destination vertex ID. _session: Reference to the owning session.
Example:
class FriendshipEdge(UniEdge): ... __edge_type__ = "FRIEND_OF" ... __from__ = Person ... __to__ = Person ... ... since: date ... strength: float = 1.0
640 @property 641 def eid(self) -> int | None: 642 """The edge ID assigned by the database.""" 643 return self._eid
The edge ID assigned by the database.
645 @property 646 def src_vid(self) -> int | None: 647 """The source vertex ID.""" 648 return self._src_vid
The source vertex ID.
650 @property 651 def dst_vid(self) -> int | None: 652 """The destination vertex ID.""" 653 return self._dst_vid
The destination vertex ID.
655 @property 656 def is_persisted(self) -> bool: 657 """Whether this edge has been saved to the database.""" 658 return self._eid is not None
Whether this edge has been saved to the database.
674 @classmethod 675 def get_from_labels(cls) -> list[str]: 676 """Get the source label names.""" 677 if cls.__from__ is None: 678 return [] 679 if isinstance(cls.__from__, tuple): 680 return [n.__label__ for n in cls.__from__] 681 return [cls.__from__.__label__]
Get the source label names.
683 @classmethod 684 def get_to_labels(cls) -> list[str]: 685 """Get the target label names.""" 686 if cls.__to__ is None: 687 return [] 688 if isinstance(cls.__to__, tuple): 689 return [n.__label__ for n in cls.__to__] 690 return [cls.__to__.__label__]
Get the target label names.
692 @classmethod 693 def get_property_fields(cls) -> dict[str, FieldInfo]: 694 """Get all property fields.""" 695 return dict(cls.model_fields)
Get all property fields.
697 def to_properties(self) -> dict[str, Any]: 698 """Convert to a property dictionary for database storage.""" 699 return _model_to_properties(self, self.get_property_fields())
Convert to a property dictionary for database storage.
701 @classmethod 702 def from_properties( 703 cls: type[_EdgeSelfT], 704 props: dict[str, Any], 705 *, 706 eid: int | None = None, 707 src_vid: int | None = None, 708 dst_vid: int | None = None, 709 session: UniSession | AsyncUniSession | None = None, 710 ) -> _EdgeSelfT: 711 """Create an instance from a property dictionary. 712 713 Accepts _id, _type, _src, _dst from uni-db edge dicts. 714 Does not mutate the input dict. 715 """ 716 data = dict(props) 717 718 raw_id = data.pop("_id", None) 719 if raw_id is not None and eid is None: 720 eid = int(raw_id) if not isinstance(raw_id, int) else raw_id 721 data.pop("_type", None) 722 raw_src = data.pop("_src", None) 723 if raw_src is not None and src_vid is None: 724 src_vid = int(raw_src) if not isinstance(raw_src, int) else raw_src 725 raw_dst = data.pop("_dst", None) 726 if raw_dst is not None and dst_vid is None: 727 dst_vid = int(raw_dst) if not isinstance(raw_dst, int) else raw_dst 728 729 converted = _convert_db_values(data, cls) 730 731 instance = cls.model_validate(converted) 732 if eid is not None: 733 instance._eid = eid 734 if src_vid is not None: 735 instance._src_vid = src_vid 736 if dst_vid is not None: 737 instance._dst_vid = dst_vid 738 if session is not None: 739 instance._session = session 740 instance._is_new = eid is None 741 return instance
Create an instance from a property dictionary.
Accepts _id, _type, _src, _dst from uni-db edge dicts. Does not mutate the input dict.
743 @classmethod 744 def from_edge_result( 745 cls, 746 data: dict[str, Any], 747 *, 748 session: UniSession | AsyncUniSession | None = None, 749 ) -> UniEdge: 750 """Create an instance from a uni-db edge result dict. 751 752 Convenience method that handles _id, _type, _src, _dst keys. 753 """ 754 return cls.from_properties(data, session=session)
Create an instance from a uni-db edge result dict.
Convenience method that handles _id, _type, _src, _dst keys.
386@dataclass(frozen=True) 387class SearchScores: 388 """Relevance scores attached to a hydrated search result. 389 390 Populated on instances returned by the search builders 391 (``vector_search`` / ``sparse_search`` / ``hybrid_search``) and reachable 392 via :attr:`UniNode.search_scores`. Kept in a sidecar (rather than as a model 393 field) so it never collides with a user field named ``score`` and survives 394 hydration under ``extra="forbid"``. 395 396 ``score`` is the primary score used for ordering (the fused score for 397 hybrid; the per-source score for single-source search). The per-arm fields 398 are populated only when that retrieval source contributed, ``None`` otherwise. 399 """ 400 401 score: float 402 vector: float | None = None 403 fts: float | None = None 404 sparse: float | None = None 405 rerank: float | None = None 406 distance: float | None = None
Relevance scores attached to a hydrated search result.
Populated on instances returned by the search builders
(vector_search / sparse_search / hybrid_search) and reachable
via UniNode.search_scores. Kept in a sidecar (rather than as a model
field) so it never collides with a user field named score and survives
hydration under extra="forbid".
score is the primary score used for ordering (the fused score for
hybrid; the per-source score for single-source search). The per-arm fields
are populated only when that retrieval source contributed, None otherwise.
204class UniSession: 205 """ 206 Session for interacting with the graph database using Pydantic models. 207 208 The session manages model registration, schema synchronization, 209 and provides CRUD operations and query building. 210 211 Example: 212 >>> from uni_db import Uni 213 >>> from uni_pydantic import UniSession 214 >>> 215 >>> db = Uni("./my_graph") 216 >>> session = UniSession(db) 217 >>> session.register(Person, Company) 218 >>> session.sync_schema() 219 >>> 220 >>> alice = Person(name="Alice", age=30) 221 >>> session.add(alice) 222 >>> session.commit() 223 """ 224 225 def __init__(self, db: uni_db.Uni) -> None: 226 self._db = db 227 self._db_session = db.session() 228 self._schema_gen = SchemaGenerator() 229 self._identity_map: WeakValueDictionary[tuple[str, int], UniNode] = ( 230 WeakValueDictionary() 231 ) 232 self._pending_new: list[UniNode] = [] 233 self._pending_delete: list[UniNode] = [] 234 235 def __enter__(self) -> UniSession: 236 return self 237 238 def __exit__( 239 self, 240 exc_type: type[BaseException] | None, 241 exc_val: BaseException | None, 242 exc_tb: TracebackType | None, 243 ) -> None: 244 self.close() 245 246 def close(self) -> None: 247 """Close the session and clear all pending state.""" 248 self._pending_new.clear() 249 self._pending_delete.clear() 250 251 @property 252 def db(self) -> uni_db.Uni: 253 """Access the underlying uni_db.Uni for low-level operations.""" 254 return self._db 255 256 def locy( 257 self, program: str, params: dict[str, Any] | None = None 258 ) -> uni_db.LocyResult: 259 """ 260 Evaluate a Locy program and return derived facts, stats, and warnings. 261 262 Delegates to the underlying ``uni_db.Session.locy()``. 263 """ 264 return self._db_session.locy(program, params) 265 266 def register(self, *models: type[UniNode] | type[UniEdge]) -> None: 267 """ 268 Register model classes with the session. 269 270 Registered models can be used for schema generation and queries. 271 272 Args: 273 *models: UniNode or UniEdge subclasses to register. 274 """ 275 self._schema_gen.register(*models) 276 277 def sync_schema(self) -> None: 278 """ 279 Synchronize database schema with registered models. 280 281 Creates labels, edge types, properties, and indexes as needed. 282 This is additive-only; it won't remove existing schema elements. 283 """ 284 self._schema_gen.apply_to_database(self._db) 285 286 def query(self, model: type[NodeT]) -> QueryBuilder[NodeT]: 287 """ 288 Create a query builder for the given model. 289 290 Args: 291 model: The UniNode subclass to query. 292 293 Returns: 294 A QueryBuilder for constructing queries. 295 """ 296 return QueryBuilder(self, model) 297 298 def add(self, entity: UniNode) -> None: 299 """ 300 Add a new entity to be persisted. 301 302 The entity will be inserted on the next commit(). 303 """ 304 if entity.is_persisted: 305 raise SessionError(f"Entity {entity!r} is already persisted") 306 entity._session = self 307 self._pending_new.append(entity) 308 309 def add_all(self, entities: Sequence[UniNode]) -> None: 310 """Add multiple entities to be persisted.""" 311 for entity in entities: 312 self.add(entity) 313 314 def delete(self, entity: UniNode) -> None: 315 """Mark an entity for deletion.""" 316 if not entity.is_persisted: 317 raise NotPersisted(entity) 318 self._pending_delete.append(entity) 319 320 def get( 321 self, 322 model: type[NodeT], 323 vid: int | None = None, 324 uid: str | None = None, 325 **kwargs: Any, 326 ) -> NodeT | None: 327 """ 328 Get an entity by ID or unique properties. 329 330 Args: 331 model: The model type to retrieve. 332 vid: Vertex ID to look up. 333 uid: Unique ID to look up. 334 **kwargs: Property equality filters. 335 336 Returns: 337 The model instance or None if not found. 338 """ 339 # Check identity map first 340 if vid is not None: 341 cached = self._identity_map.get((model.__label__, vid)) 342 if cached is not None: 343 return cached # type: ignore[return-value] 344 345 # Build query 346 label = model.__label__ 347 params: dict[str, Any] = {} 348 349 if vid is not None: 350 cypher = f"MATCH (n:{label}) WHERE id(n) = $vid RETURN {_NODE_RETURN}" 351 params["vid"] = vid 352 elif uid is not None: 353 cypher = f"MATCH (n:{label}) WHERE n._uid = $uid RETURN {_NODE_RETURN}" 354 params["uid"] = uid 355 elif kwargs: 356 # Validate property names 357 for k in kwargs: 358 _validate_property(k, model) 359 conditions = [f"n.{k} = ${k}" for k in kwargs] 360 cypher = f"MATCH (n:{label}) WHERE {' AND '.join(conditions)} RETURN {_NODE_RETURN} LIMIT 1" 361 params.update(kwargs) 362 else: 363 raise ValueError("Must provide vid, uid, or property filters") 364 365 results = self._db_session.query(cypher, params) 366 if not results: 367 return None 368 369 node_data = _row_to_node_dict(results[0].to_dict()) 370 if node_data is None: 371 return None 372 return self._result_to_model(node_data, model) 373 374 def refresh(self, entity: UniNode) -> None: 375 """Refresh an entity's properties from the database.""" 376 if not entity.is_persisted: 377 raise NotPersisted(entity) 378 379 label = entity.__class__.__label__ 380 cypher = f"MATCH (n:{label}) WHERE id(n) = $vid RETURN {_NODE_RETURN}" 381 results = self._db_session.query(cypher, {"vid": entity._vid}) 382 383 if not results: 384 raise SessionError(f"Entity with vid={entity._vid} no longer exists") 385 386 # Update properties 387 props = _row_to_node_dict(results[0].to_dict()) 388 if props is None: 389 raise SessionError(f"Entity with vid={entity._vid} no longer exists") 390 hints = _resolve_type_hints(type(entity)) 391 392 for field_name in entity.get_property_fields(): 393 if field_name in props: 394 value = props[field_name] 395 if field_name in hints: 396 value = db_to_python_value(value, hints[field_name]) 397 setattr(entity, field_name, value) 398 399 entity._mark_clean() 400 401 def commit(self) -> None: 402 """ 403 Commit all pending changes to the database. 404 405 This persists new entities, updates dirty entities, 406 and deletes marked entities. 407 """ 408 # Insert new entities 409 for entity in self._pending_new: 410 self._create_node(entity) 411 412 # Update dirty entities in identity map 413 for (label, vid), entity in list(self._identity_map.items()): 414 if entity.is_dirty and entity.is_persisted: 415 self._update_node(entity) 416 417 # Delete marked entities 418 for entity in self._pending_delete: 419 self._delete_node(entity) 420 421 # Flush to storage 422 self._db.flush() 423 424 # Clear pending lists 425 self._pending_new.clear() 426 self._pending_delete.clear() 427 428 def rollback(self) -> None: 429 """Discard all pending changes.""" 430 # Clear pending new — detach entities 431 for entity in self._pending_new: 432 entity._session = None 433 self._pending_new.clear() 434 435 # Clear pending deletes 436 self._pending_delete.clear() 437 438 # Invalidate dirty identity map entries 439 for entity in list(self._identity_map.values()): 440 if entity.is_dirty: 441 self.refresh(entity) 442 443 @contextmanager 444 def transaction(self) -> Iterator[UniTransaction]: 445 """Create a transaction context.""" 446 tx = UniTransaction(self) 447 with tx: 448 yield tx 449 450 def begin(self) -> UniTransaction: 451 """Begin a new transaction.""" 452 tx = UniTransaction(self) 453 tx._tx = self._db_session.tx() 454 return tx 455 456 def cypher( 457 self, 458 query: str, 459 params: dict[str, Any] | None = None, 460 result_type: type[NodeT] | None = None, 461 ) -> list[NodeT] | list[dict[str, Any]]: 462 """ 463 Execute a raw Cypher query. 464 465 Args: 466 query: Cypher query string. 467 params: Query parameters. 468 result_type: Optional model type for result mapping. 469 470 Returns: 471 List of results (model instances if result_type provided). 472 """ 473 results = self._db_session.query(query, params) 474 475 if result_type is None: 476 return [r.to_dict() for r in results] 477 478 # Map results to model instances 479 mapped: list[NodeT] = [] 480 node_models = self._schema_gen._node_models 481 for raw_row in results: 482 row = raw_row.to_dict() 483 # The first column holding a node of `result_type` (or a registered 484 # subclass) is the row's entity. 485 for value in row.values(): 486 target = _cypher_node_target(value, result_type, node_models) 487 if target is None: 488 continue 489 instance = self._result_to_model(*target) 490 if instance is not None: 491 mapped.append(instance) 492 break 493 else: 494 # No node column: an unlabelled map in the first column is a 495 # projection of `result_type`'s properties. 496 first_value = next(iter(row.values()), None) 497 if isinstance(first_value, dict) and "_label" not in first_value: 498 instance = self._result_to_model(first_value, result_type) 499 if instance is not None: 500 mapped.append(instance) 501 502 return mapped 503 504 @staticmethod 505 def _validate_edge_endpoints( 506 source: UniNode, target: UniNode 507 ) -> tuple[int, int, str, str]: 508 """Validate that both endpoints are persisted and return (src_vid, dst_vid, src_label, dst_label).""" 509 # `is_persisted` is `_vid is not None`; test the ids themselves so the 510 # returned vids are known to be ints. 511 src_vid = source._vid 512 if src_vid is None: 513 raise NotPersisted(source) 514 dst_vid = target._vid 515 if dst_vid is None: 516 raise NotPersisted(target) 517 return ( 518 src_vid, 519 dst_vid, 520 source.__class__.__label__, 521 target.__class__.__label__, 522 ) 523 524 @staticmethod 525 def _normalize_edge_properties( 526 properties: dict[str, Any] | UniEdge | None, 527 ) -> dict[str, Any]: 528 """Normalize edge properties from dict, UniEdge, or None.""" 529 if isinstance(properties, UniEdge): 530 return properties.to_properties() 531 if properties: 532 return properties 533 return {} 534 535 def create_edge( 536 self, 537 source: UniNode, 538 edge_type: str, 539 target: UniNode, 540 properties: dict[str, Any] | UniEdge | None = None, 541 ) -> None: 542 """Create an edge between two nodes.""" 543 src_vid, dst_vid, src_label, dst_label = self._validate_edge_endpoints( 544 source, target 545 ) 546 props = self._normalize_edge_properties(properties) 547 548 # Build CREATE edge query with labels (required by Cypher implementation) 549 props_str = ", ".join(f"{k}: ${k}" for k in props) 550 if props_str: 551 cypher = f"MATCH (a:{src_label}), (b:{dst_label}) WHERE a._vid = $src AND b._vid = $dst CREATE (a)-[r:{edge_type} {{{props_str}}}]->(b)" 552 else: 553 cypher = f"MATCH (a:{src_label}), (b:{dst_label}) WHERE a._vid = $src AND b._vid = $dst CREATE (a)-[r:{edge_type}]->(b)" 554 555 params = {"src": src_vid, "dst": dst_vid, **props} 556 with self._db_session.tx() as tx: 557 tx.execute(cypher, params) 558 tx.commit() 559 560 def delete_edge( 561 self, 562 source: UniNode, 563 edge_type: str, 564 target: UniNode, 565 ) -> int: 566 """Delete edges between two nodes. Returns the number of deleted edges.""" 567 src_vid, dst_vid, src_label, dst_label = self._validate_edge_endpoints( 568 source, target 569 ) 570 cypher = ( 571 f"MATCH (a:{src_label})-[r:{edge_type}]->(b:{dst_label}) " 572 f"WHERE a._vid = $src AND b._vid = $dst " 573 f"DELETE r RETURN count(r) as count" 574 ) 575 with self._db_session.tx() as tx: 576 results = tx.query(cypher, {"src": src_vid, "dst": dst_vid}) 577 tx.commit() 578 return cast(int, results[0]["count"]) if results else 0 579 580 def update_edge( 581 self, 582 source: UniNode, 583 edge_type: str, 584 target: UniNode, 585 properties: dict[str, Any], 586 ) -> int: 587 """Update properties on edges between two nodes. Returns the number of updated edges.""" 588 src_vid, dst_vid, src_label, dst_label = self._validate_edge_endpoints( 589 source, target 590 ) 591 set_parts = [f"r.{k} = ${k}" for k in properties] 592 params: dict[str, Any] = {"src": src_vid, "dst": dst_vid, **properties} 593 cypher = ( 594 f"MATCH (a:{src_label})-[r:{edge_type}]->(b:{dst_label}) " 595 f"WHERE a._vid = $src AND b._vid = $dst " 596 f"SET {', '.join(set_parts)} " 597 f"RETURN count(r) as count" 598 ) 599 with self._db_session.tx() as tx: 600 results = tx.query(cypher, params) 601 tx.commit() 602 return cast(int, results[0]["count"]) if results else 0 603 604 def get_edge( 605 self, 606 source: UniNode, 607 edge_type: str, 608 target: UniNode, 609 edge_model: type[EdgeT] | None = None, 610 ) -> list[dict[str, Any]] | list[EdgeT]: 611 """Get edges between two nodes. Returns dicts or edge model instances.""" 612 src_vid, dst_vid, src_label, dst_label = self._validate_edge_endpoints( 613 source, target 614 ) 615 cypher = ( 616 f"MATCH (a:{src_label})-[r:{edge_type}]->(b:{dst_label}) " 617 f"WHERE a._vid = $src AND b._vid = $dst " 618 f"RETURN properties(r) AS _props, id(r) AS _eid" 619 ) 620 results = self._db_session.query(cypher, {"src": src_vid, "dst": dst_vid}) 621 rows = [r.to_dict() for r in results] 622 623 if edge_model is None: 624 edge_dicts: list[dict[str, Any]] = [] 625 for row in rows: 626 props = row.get("_props", {}) 627 if isinstance(props, dict): 628 edge_dict = dict(props) 629 edge_dict["_eid"] = row.get("_eid") 630 edge_dicts.append(edge_dict) 631 return edge_dicts 632 633 edges = [] 634 for row in rows: 635 r_data = row.get("_props", {}) 636 if isinstance(r_data, dict): 637 edge = edge_model.from_properties( 638 r_data, 639 src_vid=src_vid, 640 dst_vid=dst_vid, 641 session=self, 642 ) 643 edges.append(edge) 644 return edges 645 646 def bulk_add(self, entities: Sequence[UniNode]) -> list[int]: 647 """ 648 Bulk-add entities using bulk_writer for performance. 649 650 Every label goes into one bulk load with one commit, so the whole call 651 is applied or not applied as a unit. Returns VIDs and attaches sessions. 652 653 Args: 654 entities: Sequence of UniNode instances to bulk-insert. 655 656 Returns: 657 List of assigned vertex IDs, in label-group order. 658 659 Raises: 660 BulkLoadError: The load failed before its commit point; nothing was 661 applied and retrying is safe. 662 uni_db.UniBulkCommitIncompleteError: The load is committed and the 663 next open completes it. Do not retry. 664 uni_db.UniBulkCommitOutcomeUnknownError: Whether the load committed 665 is unknown; check ``bulk_load_applied(e.load_id)`` after 666 reopening before retrying. 667 """ 668 if not entities: 669 return [] 670 671 # Group by label 672 by_label: dict[str, list[UniNode]] = {} 673 for entity in entities: 674 label = entity.__class__.__label__ 675 if label not in by_label: 676 by_label[label] = [] 677 by_label[label].append(entity) 678 679 import uni_db 680 681 assigned: list[tuple[str, list[UniNode], list[int]]] = [] 682 try: 683 tx = self._db_session.tx() 684 with tx.bulk_writer().build() as bw: 685 for label, group in by_label.items(): 686 for entity in group: 687 run_hooks(entity, _BEFORE_CREATE) 688 prop_dicts = [e.to_properties() for e in group] 689 assigned.append( 690 (label, group, bw.insert_vertices(label, prop_dicts)) 691 ) 692 bw.commit() 693 tx.commit() 694 except ( 695 uni_db.UniBulkCommitIncompleteError, 696 uni_db.UniBulkCommitOutcomeUnknownError, 697 ): 698 # Committed, or possibly committed: a BulkLoadError would invite a 699 # retry that loads the entities twice. 700 raise 701 except Exception as e: 702 raise BulkLoadError(f"Bulk insert failed: {e}") from e 703 704 all_vids: list[int] = [] 705 for label, group, vids in assigned: 706 for entity, vid in zip(group, vids): 707 entity._attach_session(self, vid) 708 self._identity_map[(label, vid)] = entity 709 run_hooks(entity, _AFTER_CREATE) 710 entity._mark_clean() 711 all_vids.extend(vids) 712 return all_vids 713 714 def explain(self, cypher: str) -> uni_db.ExplainOutput: 715 """Get the query execution plan without running it.""" 716 # `explain`/`profile` live on the builder `query_with()` returns, not on 717 # Session itself -- calling them on the session raised AttributeError. 718 return self._db_session.query_with(cypher).explain() 719 720 def profile(self, cypher: str) -> tuple[uni_db.QueryResult, uni_db.ProfileOutput]: 721 """Run the query with profiling and return results + stats.""" 722 return self._db_session.query_with(cypher).profile() 723 724 def save_schema(self, path: str) -> None: 725 """Save the database schema to a file.""" 726 self._db.save_schema(path) 727 728 def load_schema(self, path: str) -> None: 729 """Load a database schema from a file.""" 730 self._db.load_schema(path) 731 732 # ------------------------------------------------------------------------- 733 # Internal Methods 734 # ------------------------------------------------------------------------- 735 736 def _create_node(self, entity: UniNode) -> None: 737 """Create a node in the database.""" 738 # Run before_create hooks 739 run_hooks(entity, _BEFORE_CREATE) 740 741 label = entity.__class__.__label__ 742 props = entity.to_properties() 743 744 # Build CREATE query 745 props_str = ", ".join(f"{k}: ${k}" for k in props) 746 cypher = f"CREATE (n:{label} {{{props_str}}}) RETURN id(n) as vid" 747 748 with self._db_session.tx() as tx: 749 results = tx.query(cypher, props) 750 tx.commit() 751 if results: 752 vid = results[0]["vid"] 753 entity._attach_session(self, vid) 754 755 # Add to identity map 756 self._identity_map[(label, vid)] = entity 757 758 # Run after_create hooks 759 run_hooks(entity, _AFTER_CREATE) 760 entity._mark_clean() 761 762 def _create_node_in_tx(self, entity: UniNode, tx: uni_db.Transaction) -> None: 763 """Create a node within a transaction.""" 764 run_hooks(entity, _BEFORE_CREATE) 765 766 label = entity.__class__.__label__ 767 props = entity.to_properties() 768 769 props_str = ", ".join(f"{k}: ${k}" for k in props) 770 cypher = f"CREATE (n:{label} {{{props_str}}}) RETURN id(n) as vid" 771 772 results = tx.query(cypher, props) 773 if results: 774 vid = results[0]["vid"] 775 entity._attach_session(self, vid) 776 self._identity_map[(label, vid)] = entity 777 778 run_hooks(entity, _AFTER_CREATE) 779 780 def _create_edge_in_tx( 781 self, 782 source: UniNode, 783 edge_type: str, 784 target: UniNode, 785 properties: UniEdge | None, 786 tx: uni_db.Transaction, 787 ) -> None: 788 """Create an edge within a transaction.""" 789 props = properties.to_properties() if properties else {} 790 src_label = source.__class__.__label__ 791 dst_label = target.__class__.__label__ 792 793 props_str = ", ".join(f"{k}: ${k}" for k in props) 794 if props_str: 795 cypher = f"MATCH (a:{src_label}), (b:{dst_label}) WHERE a._vid = $src AND b._vid = $dst CREATE (a)-[:{edge_type} {{{props_str}}}]->(b)" 796 else: 797 cypher = f"MATCH (a:{src_label}), (b:{dst_label}) WHERE a._vid = $src AND b._vid = $dst CREATE (a)-[:{edge_type}]->(b)" 798 799 params = {"src": source._vid, "dst": target._vid, **props} 800 tx.query(cypher, params) 801 802 def _update_node(self, entity: UniNode) -> None: 803 """Update a node in the database.""" 804 run_hooks(entity, _BEFORE_UPDATE) 805 806 label = entity.__class__.__label__ 807 808 # Convert dirty prop values via python_to_db_value 809 hints = _resolve_type_hints(type(entity)) 810 811 dirty_props = {} 812 for name in entity._dirty: 813 value = getattr(entity, name) 814 if name in hints: 815 value = python_to_db_value(value, hints[name]) 816 dirty_props[name] = value 817 818 if not dirty_props: 819 return 820 821 set_clause = ", ".join(f"n.{k} = ${k}" for k in dirty_props) 822 cypher = f"MATCH (n:{label}) WHERE id(n) = $vid SET {set_clause}" 823 params = {"vid": entity._vid, **dirty_props} 824 825 with self._db_session.tx() as tx: 826 tx.execute(cypher, params) 827 tx.commit() 828 829 run_hooks(entity, _AFTER_UPDATE) 830 entity._mark_clean() 831 832 def _delete_node(self, entity: UniNode) -> None: 833 """Delete a node from the database.""" 834 run_hooks(entity, _BEFORE_DELETE) 835 836 label = entity.__class__.__label__ 837 vid = entity._vid 838 839 # DETACH DELETE to also remove connected edges 840 cypher = f"MATCH (n:{label}) WHERE id(n) = $vid DETACH DELETE n" 841 with self._db_session.tx() as tx: 842 tx.execute(cypher, {"vid": vid}) 843 tx.commit() 844 845 # Remove from identity map 846 if vid is not None and (label, vid) in self._identity_map: 847 del self._identity_map[(label, vid)] 848 849 # Clear entity IDs 850 entity._vid = None 851 entity._uid = None 852 entity._session = None 853 854 run_hooks(entity, _AFTER_DELETE) 855 856 def _result_to_model( 857 self, 858 data: dict[str, Any], 859 model: type[NodeT], 860 ) -> NodeT | None: 861 """Convert a query result row to a model instance. 862 863 Does not mutate the input dict. 864 """ 865 if not data: 866 return None 867 868 # Work on a copy 869 data = dict(data) 870 871 # Run before_load hooks 872 data = run_class_hooks(model, _BEFORE_LOAD, data) or data 873 874 # Extract _id → vid (uni-db returns _id as string or int) 875 vid = data.pop("_id", None) 876 if vid is None: 877 vid = data.pop("_vid", None) 878 if vid is None: 879 vid = data.pop("vid", None) 880 if vid is not None and not isinstance(vid, int): 881 vid = int(vid) 882 883 # Remove _label (informational) 884 data.pop("_label", None) 885 886 try: 887 instance = model.from_properties(data, vid=vid, session=self) 888 except ValidationError as exc: 889 _warn_unhydratable(model, vid, exc) 890 return None 891 892 # Add to identity map if we have a vid 893 if vid is not None: 894 existing = self._identity_map.get((model.__label__, vid)) 895 if existing is not None: 896 return cast(NodeT, existing) 897 self._identity_map[(model.__label__, vid)] = instance 898 899 # Run after_load hooks 900 run_hooks(instance, _AFTER_LOAD) 901 902 return instance 903 904 def _load_relationship( 905 self, 906 entity: UniNode, 907 descriptor: RelationshipDescriptor[Any], 908 ) -> list[UniNode] | UniNode | None: 909 """Load a relationship for an entity.""" 910 if not entity.is_persisted: 911 raise NotPersisted(entity) 912 913 config = descriptor.config 914 label = entity.__class__.__label__ 915 pattern = _edge_pattern(config.edge_type, config.direction) 916 917 cypher = ( 918 f"MATCH (a:{label}){pattern}(b) WHERE id(a) = $vid " 919 f"RETURN properties(b) AS _props, id(b) AS _vid, labels(b) AS _labels" 920 ) 921 results = self._db_session.query(cypher, {"vid": entity._vid}) 922 923 nodes = [] 924 for raw_row in results: 925 row = raw_row.to_dict() 926 node_data = _row_to_node_dict(row) 927 if node_data is None: 928 continue 929 # Try to find the model for this node 930 node_label = node_data.get("_label") 931 if node_label and node_label in self._schema_gen._node_models: 932 model = self._schema_gen._node_models[node_label] 933 instance = self._result_to_model(node_data, model) 934 if instance is not None: 935 nodes.append(instance) 936 937 if not descriptor.is_list: 938 return nodes[0] if nodes else None 939 return nodes 940 941 def _eager_load_relationships( 942 self, 943 entities: list[NodeT], 944 relationships: list[str], 945 ) -> None: 946 """Eager load relationships for a list of entities.""" 947 if not entities: 948 return 949 950 model = type(entities[0]) 951 rel_configs = model.get_relationship_fields() 952 953 for rel_name in relationships: 954 if rel_name not in rel_configs: 955 continue 956 957 config = rel_configs[rel_name] 958 label = model.__label__ 959 vids = [e._vid for e in entities if e._vid is not None] 960 961 if not vids: 962 continue 963 964 pattern = _edge_pattern(config.edge_type, config.direction) 965 cypher = ( 966 f"MATCH (a:{label}){pattern}(b) WHERE id(a) IN $vids " 967 f"RETURN id(a) as src_vid, properties(b) AS _props, id(b) AS _vid, labels(b) AS _labels" 968 ) 969 results = self._db_session.query(cypher, {"vids": vids}) 970 971 # Hydrate, exactly as the lazy path does. 972 # 973 # These rows used to be cached as raw result dicts. 974 # `RelationshipDescriptor.__get__` returns the cache verbatim, so 975 # eager loading handed back `list[dict]` where lazy loading hands 976 # back `list[Model]` -- `user.posts[0].title` raised where the same 977 # access worked without `.eager_load()`. 978 descriptor = getattr(model, rel_name, None) 979 is_list = getattr(descriptor, "is_list", True) 980 981 by_source: dict[int, list[Any]] = {} 982 for raw_row in results: 983 row = raw_row.to_dict() 984 src_vid = row["src_vid"] 985 node_data = _row_to_node_dict(row) 986 if node_data is None: 987 continue 988 node_label = node_data.get("_label") 989 if not node_label or node_label not in self._schema_gen._node_models: 990 continue 991 target_model = self._schema_gen._node_models[node_label] 992 instance = self._result_to_model(node_data, target_model) 993 if instance is None: 994 continue 995 by_source.setdefault(src_vid, []).append(instance) 996 997 # Every entity gets a cache entry, including the ones with nothing 998 # attached. Leaving those unset sends the descriptor down the lazy 999 # path on first access -- which on an async session raises, telling 1000 # the caller to use the `eager_load()` they already used. 1001 cache_attr = f"_rel_cache_{rel_name}" 1002 for entity in entities: 1003 related = ( 1004 by_source.get(entity._vid, []) if entity._vid is not None else [] 1005 ) 1006 if is_list: 1007 setattr(entity, cache_attr, related) 1008 else: 1009 setattr(entity, cache_attr, related[0] if related else None)
Session for interacting with the graph database using Pydantic models.
The session manages model registration, schema synchronization, and provides CRUD operations and query building.
Example:
from uni_db import Uni from uni_pydantic import UniSession
db = Uni("./my_graph") session = UniSession(db) session.register(Person, Company) session.sync_schema()
alice = Person(name="Alice", age=30) session.add(alice) session.commit()
225 def __init__(self, db: uni_db.Uni) -> None: 226 self._db = db 227 self._db_session = db.session() 228 self._schema_gen = SchemaGenerator() 229 self._identity_map: WeakValueDictionary[tuple[str, int], UniNode] = ( 230 WeakValueDictionary() 231 ) 232 self._pending_new: list[UniNode] = [] 233 self._pending_delete: list[UniNode] = []
246 def close(self) -> None: 247 """Close the session and clear all pending state.""" 248 self._pending_new.clear() 249 self._pending_delete.clear()
Close the session and clear all pending state.
251 @property 252 def db(self) -> uni_db.Uni: 253 """Access the underlying uni_db.Uni for low-level operations.""" 254 return self._db
Access the underlying uni_db.Uni for low-level operations.
256 def locy( 257 self, program: str, params: dict[str, Any] | None = None 258 ) -> uni_db.LocyResult: 259 """ 260 Evaluate a Locy program and return derived facts, stats, and warnings. 261 262 Delegates to the underlying ``uni_db.Session.locy()``. 263 """ 264 return self._db_session.locy(program, params)
Evaluate a Locy program and return derived facts, stats, and warnings.
Delegates to the underlying uni_db.Session.locy().
266 def register(self, *models: type[UniNode] | type[UniEdge]) -> None: 267 """ 268 Register model classes with the session. 269 270 Registered models can be used for schema generation and queries. 271 272 Args: 273 *models: UniNode or UniEdge subclasses to register. 274 """ 275 self._schema_gen.register(*models)
Register model classes with the session.
Registered models can be used for schema generation and queries.
Args: *models: UniNode or UniEdge subclasses to register.
277 def sync_schema(self) -> None: 278 """ 279 Synchronize database schema with registered models. 280 281 Creates labels, edge types, properties, and indexes as needed. 282 This is additive-only; it won't remove existing schema elements. 283 """ 284 self._schema_gen.apply_to_database(self._db)
Synchronize database schema with registered models.
Creates labels, edge types, properties, and indexes as needed. This is additive-only; it won't remove existing schema elements.
286 def query(self, model: type[NodeT]) -> QueryBuilder[NodeT]: 287 """ 288 Create a query builder for the given model. 289 290 Args: 291 model: The UniNode subclass to query. 292 293 Returns: 294 A QueryBuilder for constructing queries. 295 """ 296 return QueryBuilder(self, model)
Create a query builder for the given model.
Args: model: The UniNode subclass to query.
Returns: A QueryBuilder for constructing queries.
298 def add(self, entity: UniNode) -> None: 299 """ 300 Add a new entity to be persisted. 301 302 The entity will be inserted on the next commit(). 303 """ 304 if entity.is_persisted: 305 raise SessionError(f"Entity {entity!r} is already persisted") 306 entity._session = self 307 self._pending_new.append(entity)
Add a new entity to be persisted.
The entity will be inserted on the next commit().
309 def add_all(self, entities: Sequence[UniNode]) -> None: 310 """Add multiple entities to be persisted.""" 311 for entity in entities: 312 self.add(entity)
Add multiple entities to be persisted.
314 def delete(self, entity: UniNode) -> None: 315 """Mark an entity for deletion.""" 316 if not entity.is_persisted: 317 raise NotPersisted(entity) 318 self._pending_delete.append(entity)
Mark an entity for deletion.
320 def get( 321 self, 322 model: type[NodeT], 323 vid: int | None = None, 324 uid: str | None = None, 325 **kwargs: Any, 326 ) -> NodeT | None: 327 """ 328 Get an entity by ID or unique properties. 329 330 Args: 331 model: The model type to retrieve. 332 vid: Vertex ID to look up. 333 uid: Unique ID to look up. 334 **kwargs: Property equality filters. 335 336 Returns: 337 The model instance or None if not found. 338 """ 339 # Check identity map first 340 if vid is not None: 341 cached = self._identity_map.get((model.__label__, vid)) 342 if cached is not None: 343 return cached # type: ignore[return-value] 344 345 # Build query 346 label = model.__label__ 347 params: dict[str, Any] = {} 348 349 if vid is not None: 350 cypher = f"MATCH (n:{label}) WHERE id(n) = $vid RETURN {_NODE_RETURN}" 351 params["vid"] = vid 352 elif uid is not None: 353 cypher = f"MATCH (n:{label}) WHERE n._uid = $uid RETURN {_NODE_RETURN}" 354 params["uid"] = uid 355 elif kwargs: 356 # Validate property names 357 for k in kwargs: 358 _validate_property(k, model) 359 conditions = [f"n.{k} = ${k}" for k in kwargs] 360 cypher = f"MATCH (n:{label}) WHERE {' AND '.join(conditions)} RETURN {_NODE_RETURN} LIMIT 1" 361 params.update(kwargs) 362 else: 363 raise ValueError("Must provide vid, uid, or property filters") 364 365 results = self._db_session.query(cypher, params) 366 if not results: 367 return None 368 369 node_data = _row_to_node_dict(results[0].to_dict()) 370 if node_data is None: 371 return None 372 return self._result_to_model(node_data, model)
Get an entity by ID or unique properties.
Args: model: The model type to retrieve. vid: Vertex ID to look up. uid: Unique ID to look up. **kwargs: Property equality filters.
Returns: The model instance or None if not found.
374 def refresh(self, entity: UniNode) -> None: 375 """Refresh an entity's properties from the database.""" 376 if not entity.is_persisted: 377 raise NotPersisted(entity) 378 379 label = entity.__class__.__label__ 380 cypher = f"MATCH (n:{label}) WHERE id(n) = $vid RETURN {_NODE_RETURN}" 381 results = self._db_session.query(cypher, {"vid": entity._vid}) 382 383 if not results: 384 raise SessionError(f"Entity with vid={entity._vid} no longer exists") 385 386 # Update properties 387 props = _row_to_node_dict(results[0].to_dict()) 388 if props is None: 389 raise SessionError(f"Entity with vid={entity._vid} no longer exists") 390 hints = _resolve_type_hints(type(entity)) 391 392 for field_name in entity.get_property_fields(): 393 if field_name in props: 394 value = props[field_name] 395 if field_name in hints: 396 value = db_to_python_value(value, hints[field_name]) 397 setattr(entity, field_name, value) 398 399 entity._mark_clean()
Refresh an entity's properties from the database.
401 def commit(self) -> None: 402 """ 403 Commit all pending changes to the database. 404 405 This persists new entities, updates dirty entities, 406 and deletes marked entities. 407 """ 408 # Insert new entities 409 for entity in self._pending_new: 410 self._create_node(entity) 411 412 # Update dirty entities in identity map 413 for (label, vid), entity in list(self._identity_map.items()): 414 if entity.is_dirty and entity.is_persisted: 415 self._update_node(entity) 416 417 # Delete marked entities 418 for entity in self._pending_delete: 419 self._delete_node(entity) 420 421 # Flush to storage 422 self._db.flush() 423 424 # Clear pending lists 425 self._pending_new.clear() 426 self._pending_delete.clear()
Commit all pending changes to the database.
This persists new entities, updates dirty entities, and deletes marked entities.
428 def rollback(self) -> None: 429 """Discard all pending changes.""" 430 # Clear pending new — detach entities 431 for entity in self._pending_new: 432 entity._session = None 433 self._pending_new.clear() 434 435 # Clear pending deletes 436 self._pending_delete.clear() 437 438 # Invalidate dirty identity map entries 439 for entity in list(self._identity_map.values()): 440 if entity.is_dirty: 441 self.refresh(entity)
Discard all pending changes.
443 @contextmanager 444 def transaction(self) -> Iterator[UniTransaction]: 445 """Create a transaction context.""" 446 tx = UniTransaction(self) 447 with tx: 448 yield tx
Create a transaction context.
450 def begin(self) -> UniTransaction: 451 """Begin a new transaction.""" 452 tx = UniTransaction(self) 453 tx._tx = self._db_session.tx() 454 return tx
Begin a new transaction.
456 def cypher( 457 self, 458 query: str, 459 params: dict[str, Any] | None = None, 460 result_type: type[NodeT] | None = None, 461 ) -> list[NodeT] | list[dict[str, Any]]: 462 """ 463 Execute a raw Cypher query. 464 465 Args: 466 query: Cypher query string. 467 params: Query parameters. 468 result_type: Optional model type for result mapping. 469 470 Returns: 471 List of results (model instances if result_type provided). 472 """ 473 results = self._db_session.query(query, params) 474 475 if result_type is None: 476 return [r.to_dict() for r in results] 477 478 # Map results to model instances 479 mapped: list[NodeT] = [] 480 node_models = self._schema_gen._node_models 481 for raw_row in results: 482 row = raw_row.to_dict() 483 # The first column holding a node of `result_type` (or a registered 484 # subclass) is the row's entity. 485 for value in row.values(): 486 target = _cypher_node_target(value, result_type, node_models) 487 if target is None: 488 continue 489 instance = self._result_to_model(*target) 490 if instance is not None: 491 mapped.append(instance) 492 break 493 else: 494 # No node column: an unlabelled map in the first column is a 495 # projection of `result_type`'s properties. 496 first_value = next(iter(row.values()), None) 497 if isinstance(first_value, dict) and "_label" not in first_value: 498 instance = self._result_to_model(first_value, result_type) 499 if instance is not None: 500 mapped.append(instance) 501 502 return mapped
Execute a raw Cypher query.
Args: query: Cypher query string. params: Query parameters. result_type: Optional model type for result mapping.
Returns: List of results (model instances if result_type provided).
535 def create_edge( 536 self, 537 source: UniNode, 538 edge_type: str, 539 target: UniNode, 540 properties: dict[str, Any] | UniEdge | None = None, 541 ) -> None: 542 """Create an edge between two nodes.""" 543 src_vid, dst_vid, src_label, dst_label = self._validate_edge_endpoints( 544 source, target 545 ) 546 props = self._normalize_edge_properties(properties) 547 548 # Build CREATE edge query with labels (required by Cypher implementation) 549 props_str = ", ".join(f"{k}: ${k}" for k in props) 550 if props_str: 551 cypher = f"MATCH (a:{src_label}), (b:{dst_label}) WHERE a._vid = $src AND b._vid = $dst CREATE (a)-[r:{edge_type} {{{props_str}}}]->(b)" 552 else: 553 cypher = f"MATCH (a:{src_label}), (b:{dst_label}) WHERE a._vid = $src AND b._vid = $dst CREATE (a)-[r:{edge_type}]->(b)" 554 555 params = {"src": src_vid, "dst": dst_vid, **props} 556 with self._db_session.tx() as tx: 557 tx.execute(cypher, params) 558 tx.commit()
Create an edge between two nodes.
560 def delete_edge( 561 self, 562 source: UniNode, 563 edge_type: str, 564 target: UniNode, 565 ) -> int: 566 """Delete edges between two nodes. Returns the number of deleted edges.""" 567 src_vid, dst_vid, src_label, dst_label = self._validate_edge_endpoints( 568 source, target 569 ) 570 cypher = ( 571 f"MATCH (a:{src_label})-[r:{edge_type}]->(b:{dst_label}) " 572 f"WHERE a._vid = $src AND b._vid = $dst " 573 f"DELETE r RETURN count(r) as count" 574 ) 575 with self._db_session.tx() as tx: 576 results = tx.query(cypher, {"src": src_vid, "dst": dst_vid}) 577 tx.commit() 578 return cast(int, results[0]["count"]) if results else 0
Delete edges between two nodes. Returns the number of deleted edges.
580 def update_edge( 581 self, 582 source: UniNode, 583 edge_type: str, 584 target: UniNode, 585 properties: dict[str, Any], 586 ) -> int: 587 """Update properties on edges between two nodes. Returns the number of updated edges.""" 588 src_vid, dst_vid, src_label, dst_label = self._validate_edge_endpoints( 589 source, target 590 ) 591 set_parts = [f"r.{k} = ${k}" for k in properties] 592 params: dict[str, Any] = {"src": src_vid, "dst": dst_vid, **properties} 593 cypher = ( 594 f"MATCH (a:{src_label})-[r:{edge_type}]->(b:{dst_label}) " 595 f"WHERE a._vid = $src AND b._vid = $dst " 596 f"SET {', '.join(set_parts)} " 597 f"RETURN count(r) as count" 598 ) 599 with self._db_session.tx() as tx: 600 results = tx.query(cypher, params) 601 tx.commit() 602 return cast(int, results[0]["count"]) if results else 0
Update properties on edges between two nodes. Returns the number of updated edges.
604 def get_edge( 605 self, 606 source: UniNode, 607 edge_type: str, 608 target: UniNode, 609 edge_model: type[EdgeT] | None = None, 610 ) -> list[dict[str, Any]] | list[EdgeT]: 611 """Get edges between two nodes. Returns dicts or edge model instances.""" 612 src_vid, dst_vid, src_label, dst_label = self._validate_edge_endpoints( 613 source, target 614 ) 615 cypher = ( 616 f"MATCH (a:{src_label})-[r:{edge_type}]->(b:{dst_label}) " 617 f"WHERE a._vid = $src AND b._vid = $dst " 618 f"RETURN properties(r) AS _props, id(r) AS _eid" 619 ) 620 results = self._db_session.query(cypher, {"src": src_vid, "dst": dst_vid}) 621 rows = [r.to_dict() for r in results] 622 623 if edge_model is None: 624 edge_dicts: list[dict[str, Any]] = [] 625 for row in rows: 626 props = row.get("_props", {}) 627 if isinstance(props, dict): 628 edge_dict = dict(props) 629 edge_dict["_eid"] = row.get("_eid") 630 edge_dicts.append(edge_dict) 631 return edge_dicts 632 633 edges = [] 634 for row in rows: 635 r_data = row.get("_props", {}) 636 if isinstance(r_data, dict): 637 edge = edge_model.from_properties( 638 r_data, 639 src_vid=src_vid, 640 dst_vid=dst_vid, 641 session=self, 642 ) 643 edges.append(edge) 644 return edges
Get edges between two nodes. Returns dicts or edge model instances.
646 def bulk_add(self, entities: Sequence[UniNode]) -> list[int]: 647 """ 648 Bulk-add entities using bulk_writer for performance. 649 650 Every label goes into one bulk load with one commit, so the whole call 651 is applied or not applied as a unit. Returns VIDs and attaches sessions. 652 653 Args: 654 entities: Sequence of UniNode instances to bulk-insert. 655 656 Returns: 657 List of assigned vertex IDs, in label-group order. 658 659 Raises: 660 BulkLoadError: The load failed before its commit point; nothing was 661 applied and retrying is safe. 662 uni_db.UniBulkCommitIncompleteError: The load is committed and the 663 next open completes it. Do not retry. 664 uni_db.UniBulkCommitOutcomeUnknownError: Whether the load committed 665 is unknown; check ``bulk_load_applied(e.load_id)`` after 666 reopening before retrying. 667 """ 668 if not entities: 669 return [] 670 671 # Group by label 672 by_label: dict[str, list[UniNode]] = {} 673 for entity in entities: 674 label = entity.__class__.__label__ 675 if label not in by_label: 676 by_label[label] = [] 677 by_label[label].append(entity) 678 679 import uni_db 680 681 assigned: list[tuple[str, list[UniNode], list[int]]] = [] 682 try: 683 tx = self._db_session.tx() 684 with tx.bulk_writer().build() as bw: 685 for label, group in by_label.items(): 686 for entity in group: 687 run_hooks(entity, _BEFORE_CREATE) 688 prop_dicts = [e.to_properties() for e in group] 689 assigned.append( 690 (label, group, bw.insert_vertices(label, prop_dicts)) 691 ) 692 bw.commit() 693 tx.commit() 694 except ( 695 uni_db.UniBulkCommitIncompleteError, 696 uni_db.UniBulkCommitOutcomeUnknownError, 697 ): 698 # Committed, or possibly committed: a BulkLoadError would invite a 699 # retry that loads the entities twice. 700 raise 701 except Exception as e: 702 raise BulkLoadError(f"Bulk insert failed: {e}") from e 703 704 all_vids: list[int] = [] 705 for label, group, vids in assigned: 706 for entity, vid in zip(group, vids): 707 entity._attach_session(self, vid) 708 self._identity_map[(label, vid)] = entity 709 run_hooks(entity, _AFTER_CREATE) 710 entity._mark_clean() 711 all_vids.extend(vids) 712 return all_vids
Bulk-add entities using bulk_writer for performance.
Every label goes into one bulk load with one commit, so the whole call is applied or not applied as a unit. Returns VIDs and attaches sessions.
Args: entities: Sequence of UniNode instances to bulk-insert.
Returns: List of assigned vertex IDs, in label-group order.
Raises:
BulkLoadError: The load failed before its commit point; nothing was
applied and retrying is safe.
uni_db.UniBulkCommitIncompleteError: The load is committed and the
next open completes it. Do not retry.
uni_db.UniBulkCommitOutcomeUnknownError: Whether the load committed
is unknown; check bulk_load_applied(e.load_id) after
reopening before retrying.
714 def explain(self, cypher: str) -> uni_db.ExplainOutput: 715 """Get the query execution plan without running it.""" 716 # `explain`/`profile` live on the builder `query_with()` returns, not on 717 # Session itself -- calling them on the session raised AttributeError. 718 return self._db_session.query_with(cypher).explain()
Get the query execution plan without running it.
720 def profile(self, cypher: str) -> tuple[uni_db.QueryResult, uni_db.ProfileOutput]: 721 """Run the query with profiling and return results + stats.""" 722 return self._db_session.query_with(cypher).profile()
Run the query with profiling and return results + stats.
105class UniTransaction: 106 """ 107 Transaction context for atomic operations. 108 109 Provides commit/rollback semantics for a group of operations. 110 111 Example: 112 >>> with session.transaction() as tx: 113 ... alice = Person(name="Alice") 114 ... tx.add(alice) 115 ... # Auto-commits on success, rolls back on exception 116 """ 117 118 def __init__(self, session: UniSession) -> None: 119 self._session = session 120 self._tx: uni_db.Transaction | None = None 121 self._pending_nodes: list[UniNode] = [] 122 self._pending_edges: list[tuple[UniNode, str, UniNode, UniEdge | None]] = [] 123 self._committed = False 124 self._rolled_back = False 125 126 def __enter__(self) -> UniTransaction: 127 self._tx = self._session._db_session.tx() 128 return self 129 130 def __exit__( 131 self, 132 exc_type: type[BaseException] | None, 133 exc_val: BaseException | None, 134 exc_tb: TracebackType | None, 135 ) -> None: 136 if exc_type is not None: 137 self.rollback() 138 return 139 if not self._committed and not self._rolled_back: 140 self.commit() 141 142 def add(self, entity: UniNode) -> None: 143 """Add a node to be created in this transaction.""" 144 self._pending_nodes.append(entity) 145 146 def create_edge( 147 self, 148 source: UniNode, 149 edge_type: str, 150 target: UniNode, 151 properties: UniEdge | None = None, 152 **kwargs: Any, 153 ) -> None: 154 """Create an edge between two nodes in this transaction.""" 155 if not source.is_persisted: 156 raise NotPersisted(source) 157 if not target.is_persisted: 158 raise NotPersisted(target) 159 self._pending_edges.append((source, edge_type, target, properties)) 160 161 def commit(self) -> None: 162 """Commit the transaction.""" 163 if self._committed: 164 raise TransactionError("Transaction already committed") 165 if self._rolled_back: 166 raise TransactionError("Transaction already rolled back") 167 168 if self._tx is None: 169 raise TransactionError("Transaction not started") 170 171 try: 172 # Create pending nodes 173 for node in self._pending_nodes: 174 self._session._create_node_in_tx(node, self._tx) 175 176 # Create pending edges 177 for source, edge_type, target, props in self._pending_edges: 178 self._session._create_edge_in_tx( 179 source, edge_type, target, props, self._tx 180 ) 181 182 self._tx.commit() 183 self._committed = True 184 185 # Mark nodes as clean 186 for node in self._pending_nodes: 187 node._mark_clean() 188 189 except Exception as e: 190 self.rollback() 191 raise TransactionError(f"Commit failed: {e}") from e 192 193 def rollback(self) -> None: 194 """Rollback the transaction.""" 195 if self._rolled_back: 196 return 197 if self._tx is not None: 198 self._tx.rollback() 199 self._rolled_back = True 200 self._pending_nodes.clear() 201 self._pending_edges.clear()
Transaction context for atomic operations.
Provides commit/rollback semantics for a group of operations.
Example:
with session.transaction() as tx: ... alice = Person(name="Alice") ... tx.add(alice) ... # Auto-commits on success, rolls back on exception
118 def __init__(self, session: UniSession) -> None: 119 self._session = session 120 self._tx: uni_db.Transaction | None = None 121 self._pending_nodes: list[UniNode] = [] 122 self._pending_edges: list[tuple[UniNode, str, UniNode, UniEdge | None]] = [] 123 self._committed = False 124 self._rolled_back = False
142 def add(self, entity: UniNode) -> None: 143 """Add a node to be created in this transaction.""" 144 self._pending_nodes.append(entity)
Add a node to be created in this transaction.
146 def create_edge( 147 self, 148 source: UniNode, 149 edge_type: str, 150 target: UniNode, 151 properties: UniEdge | None = None, 152 **kwargs: Any, 153 ) -> None: 154 """Create an edge between two nodes in this transaction.""" 155 if not source.is_persisted: 156 raise NotPersisted(source) 157 if not target.is_persisted: 158 raise NotPersisted(target) 159 self._pending_edges.append((source, edge_type, target, properties))
Create an edge between two nodes in this transaction.
161 def commit(self) -> None: 162 """Commit the transaction.""" 163 if self._committed: 164 raise TransactionError("Transaction already committed") 165 if self._rolled_back: 166 raise TransactionError("Transaction already rolled back") 167 168 if self._tx is None: 169 raise TransactionError("Transaction not started") 170 171 try: 172 # Create pending nodes 173 for node in self._pending_nodes: 174 self._session._create_node_in_tx(node, self._tx) 175 176 # Create pending edges 177 for source, edge_type, target, props in self._pending_edges: 178 self._session._create_edge_in_tx( 179 source, edge_type, target, props, self._tx 180 ) 181 182 self._tx.commit() 183 self._committed = True 184 185 # Mark nodes as clean 186 for node in self._pending_nodes: 187 node._mark_clean() 188 189 except Exception as e: 190 self.rollback() 191 raise TransactionError(f"Commit failed: {e}") from e
Commit the transaction.
193 def rollback(self) -> None: 194 """Rollback the transaction.""" 195 if self._rolled_back: 196 return 197 if self._tx is not None: 198 self._tx.rollback() 199 self._rolled_back = True 200 self._pending_nodes.clear() 201 self._pending_edges.clear()
Rollback the transaction.
140class AsyncUniSession: 141 """ 142 Async session for interacting with the graph database. 143 144 Mirrors UniSession with async methods. Uses AsyncUni. 145 146 Example: 147 >>> from uni_db import AsyncUni 148 >>> from uni_pydantic import AsyncUniSession 149 >>> 150 >>> db = await AsyncUni.open("./my_graph") 151 >>> async with AsyncUniSession(db) as session: 152 ... session.register(Person) 153 ... await session.sync_schema() 154 ... alice = Person(name="Alice", age=30) 155 ... session.add(alice) 156 ... await session.commit() 157 """ 158 159 def __init__(self, db: uni_db.AsyncUni) -> None: 160 self._db = db 161 self._db_session = db.session() 162 self._schema_gen = SchemaGenerator() 163 self._identity_map: WeakValueDictionary[tuple[str, int], UniNode] = ( 164 WeakValueDictionary() 165 ) 166 self._pending_new: list[UniNode] = [] 167 self._pending_delete: list[UniNode] = [] 168 169 async def __aenter__(self) -> AsyncUniSession: 170 return self 171 172 async def __aexit__( 173 self, 174 exc_type: type[BaseException] | None, 175 exc_val: BaseException | None, 176 exc_tb: TracebackType | None, 177 ) -> None: 178 self.close() 179 180 def close(self) -> None: 181 """Close the session and clear pending state.""" 182 self._pending_new.clear() 183 self._pending_delete.clear() 184 185 @property 186 def db(self) -> uni_db.AsyncUni: 187 """Access the underlying uni_db.AsyncUni for low-level operations.""" 188 return self._db 189 190 async def locy(self, program: str, params: dict[str, Any] | None = None) -> Any: 191 """ 192 Evaluate a Locy program and return derived facts, stats, and warnings. 193 194 Delegates to the underlying ``uni_db.AsyncSession.locy()``. 195 """ 196 return await self._db_session.locy(program, params) 197 198 def register(self, *models: type[UniNode] | type[UniEdge]) -> None: 199 """Register model classes with the session (sync).""" 200 self._schema_gen.register(*models) 201 202 async def sync_schema(self) -> None: 203 """Synchronize database schema with registered models.""" 204 await self._schema_gen.async_apply_to_database(self._db) 205 206 def query(self, model: type[NodeT]) -> AsyncQueryBuilder[NodeT]: 207 """Create an async query builder for the given model.""" 208 return AsyncQueryBuilder(self, model) 209 210 def add(self, entity: UniNode) -> None: 211 """Add a new entity to be persisted (sync — just collects).""" 212 if entity.is_persisted: 213 raise SessionError(f"Entity {entity!r} is already persisted") 214 entity._session = self 215 self._pending_new.append(entity) 216 217 def add_all(self, entities: Sequence[UniNode]) -> None: 218 """Add multiple entities (sync — just collects).""" 219 for entity in entities: 220 self.add(entity) 221 222 def delete(self, entity: UniNode) -> None: 223 """Mark an entity for deletion (sync — just collects).""" 224 if not entity.is_persisted: 225 raise NotPersisted(entity) 226 self._pending_delete.append(entity) 227 228 async def get( 229 self, 230 model: type[NodeT], 231 vid: int | None = None, 232 uid: str | None = None, 233 **kwargs: Any, 234 ) -> NodeT | None: 235 """Get an entity by ID or unique properties.""" 236 if vid is not None: 237 cached = self._identity_map.get((model.__label__, vid)) 238 if cached is not None: 239 return cached # type: ignore[return-value] 240 241 label = model.__label__ 242 params: dict[str, Any] = {} 243 244 if vid is not None: 245 cypher = f"MATCH (n:{label}) WHERE id(n) = $vid RETURN {_NODE_RETURN}" 246 params["vid"] = vid 247 elif uid is not None: 248 cypher = f"MATCH (n:{label}) WHERE n._uid = $uid RETURN {_NODE_RETURN}" 249 params["uid"] = uid 250 elif kwargs: 251 for k in kwargs: 252 _validate_property(k, model) 253 conditions = [f"n.{k} = ${k}" for k in kwargs] 254 cypher = f"MATCH (n:{label}) WHERE {' AND '.join(conditions)} RETURN {_NODE_RETURN} LIMIT 1" 255 params.update(kwargs) 256 else: 257 raise ValueError("Must provide vid, uid, or property filters") 258 259 results = await self._db_session.query(cypher, params) 260 if not results: 261 return None 262 263 node_data = _row_to_node_dict(results[0].to_dict()) 264 if node_data is None: 265 return None 266 return self._result_to_model(node_data, model) 267 268 async def refresh(self, entity: UniNode) -> None: 269 """Refresh an entity's properties from the database.""" 270 if not entity.is_persisted: 271 raise NotPersisted(entity) 272 273 label = entity.__class__.__label__ 274 cypher = f"MATCH (n:{label}) WHERE id(n) = $vid RETURN {_NODE_RETURN}" 275 results = await self._db_session.query(cypher, {"vid": entity._vid}) 276 277 if not results: 278 raise SessionError(f"Entity with vid={entity._vid} no longer exists") 279 280 props = _row_to_node_dict(results[0].to_dict()) 281 if props is None: 282 raise SessionError(f"Entity with vid={entity._vid} no longer exists") 283 hints = _resolve_type_hints(type(entity)) 284 285 for field_name in entity.get_property_fields(): 286 if field_name in props: 287 value = props[field_name] 288 if field_name in hints: 289 value = db_to_python_value(value, hints[field_name]) 290 setattr(entity, field_name, value) 291 292 entity._mark_clean() 293 294 async def commit(self) -> None: 295 """Commit all pending changes.""" 296 for entity in self._pending_new: 297 await self._create_node(entity) 298 299 for (label, vid), entity in list(self._identity_map.items()): 300 if entity.is_dirty and entity.is_persisted: 301 await self._update_node(entity) 302 303 for entity in self._pending_delete: 304 await self._delete_node(entity) 305 306 await self._db.flush() 307 self._pending_new.clear() 308 self._pending_delete.clear() 309 310 async def rollback(self) -> None: 311 """Discard all pending changes.""" 312 for entity in self._pending_new: 313 entity._session = None 314 self._pending_new.clear() 315 self._pending_delete.clear() 316 for entity in list(self._identity_map.values()): 317 if entity.is_dirty: 318 await self.refresh(entity) 319 320 async def transaction(self) -> AsyncUniTransaction: 321 """Create an async transaction. Use as `async with session.transaction() as tx:`.""" 322 return AsyncUniTransaction(self) 323 324 async def cypher( 325 self, 326 query: str, 327 params: dict[str, Any] | None = None, 328 result_type: type[NodeT] | None = None, 329 ) -> list[NodeT] | list[dict[str, Any]]: 330 """Execute a raw Cypher query.""" 331 results = await self._db_session.query(query, params) 332 333 if result_type is None: 334 return [r.to_dict() for r in results] 335 336 mapped: list[NodeT] = [] 337 node_models = self._schema_gen._node_models 338 for raw_row in results: 339 row = raw_row.to_dict() 340 # Same column selection as `UniSession.cypher`. 341 for value in row.values(): 342 target = _cypher_node_target(value, result_type, node_models) 343 if target is None: 344 continue 345 instance = self._result_to_model(*target) 346 if instance is not None: 347 mapped.append(instance) 348 break 349 else: 350 first_value = next(iter(row.values()), None) 351 if isinstance(first_value, dict) and "_label" not in first_value: 352 instance = self._result_to_model(first_value, result_type) 353 if instance is not None: 354 mapped.append(instance) 355 356 return mapped 357 358 async def create_edge( 359 self, 360 source: UniNode, 361 edge_type: str, 362 target: UniNode, 363 properties: dict[str, Any] | UniEdge | None = None, 364 ) -> None: 365 """Create an edge between two nodes.""" 366 src_vid, dst_vid, src_label, dst_label = UniSession._validate_edge_endpoints( 367 source, target 368 ) 369 props = UniSession._normalize_edge_properties(properties) 370 371 props_str = ", ".join(f"{k}: ${k}" for k in props) 372 if props_str: 373 cypher = f"MATCH (a:{src_label}), (b:{dst_label}) WHERE a._vid = $src AND b._vid = $dst CREATE (a)-[r:{edge_type} {{{props_str}}}]->(b)" 374 else: 375 cypher = f"MATCH (a:{src_label}), (b:{dst_label}) WHERE a._vid = $src AND b._vid = $dst CREATE (a)-[r:{edge_type}]->(b)" 376 377 async with await self._db_session.tx() as tx: 378 await tx.execute(cypher, {"src": src_vid, "dst": dst_vid, **props}) 379 await tx.commit() 380 381 async def delete_edge( 382 self, source: UniNode, edge_type: str, target: UniNode 383 ) -> int: 384 """Delete edges between two nodes. Returns the number of deleted edges.""" 385 src_vid, dst_vid, src_label, dst_label = UniSession._validate_edge_endpoints( 386 source, target 387 ) 388 cypher = ( 389 f"MATCH (a:{src_label})-[r:{edge_type}]->(b:{dst_label}) " 390 f"WHERE a._vid = $src AND b._vid = $dst " 391 f"DELETE r RETURN count(r) as count" 392 ) 393 async with await self._db_session.tx() as tx: 394 results = await tx.query(cypher, {"src": src_vid, "dst": dst_vid}) 395 await tx.commit() 396 return cast(int, results[0]["count"]) if results else 0 397 398 async def bulk_add(self, entities: Sequence[UniNode]) -> list[int]: 399 """Bulk-add entities using bulk_writer. 400 401 One bulk load and one commit for every label; see the sync 402 ``UniSession.bulk_add`` for the error contract. 403 """ 404 if not entities: 405 return [] 406 407 by_label: dict[str, list[UniNode]] = {} 408 for entity in entities: 409 label = entity.__class__.__label__ 410 if label not in by_label: 411 by_label[label] = [] 412 by_label[label].append(entity) 413 414 import uni_db 415 416 assigned: list[tuple[str, list[UniNode], list[int]]] = [] 417 try: 418 tx = await self._db_session.tx() 419 async with await tx.bulk_writer().build() as bw: 420 for label, group in by_label.items(): 421 for entity in group: 422 run_hooks(entity, _BEFORE_CREATE) 423 prop_dicts = [e.to_properties() for e in group] 424 vids = await bw.insert_vertices(label, prop_dicts) 425 assigned.append((label, group, vids)) 426 await bw.commit() 427 await tx.commit() 428 except ( 429 uni_db.UniBulkCommitIncompleteError, 430 uni_db.UniBulkCommitOutcomeUnknownError, 431 ): 432 # Committed, or possibly committed: never a retry-inviting 433 # BulkLoadError. 434 raise 435 except Exception as e: 436 raise BulkLoadError(f"Bulk insert failed: {e}") from e 437 438 all_vids: list[int] = [] 439 for label, group, vids in assigned: 440 for entity, vid in zip(group, vids): 441 entity._attach_session(self, vid) 442 self._identity_map[(label, vid)] = entity 443 run_hooks(entity, _AFTER_CREATE) 444 entity._mark_clean() 445 all_vids.extend(vids) 446 return all_vids 447 448 async def explain(self, cypher: str) -> Any: 449 """Get the query execution plan.""" 450 # See the sync twin in session.py: these live on the `query_with()` 451 # builder, not on AsyncSession. 452 return await self._db_session.query_with(cypher).explain() 453 454 async def profile(self, cypher: str) -> Any: 455 """Run the query with profiling and return results + stats.""" 456 return await self._db_session.query_with(cypher).profile() 457 458 async def save_schema(self, path: str) -> None: 459 """Save the database schema to a file.""" 460 await self._db.save_schema(path) 461 462 async def load_schema(self, path: str) -> None: 463 """Load a database schema from a file.""" 464 await self._db.load_schema(path) 465 466 # ---- Internal methods ---- 467 468 async def _create_node(self, entity: UniNode) -> None: 469 run_hooks(entity, _BEFORE_CREATE) 470 label = entity.__class__.__label__ 471 props = entity.to_properties() 472 props_str = ", ".join(f"{k}: ${k}" for k in props) 473 cypher = f"CREATE (n:{label} {{{props_str}}}) RETURN id(n) as vid" 474 async with await self._db_session.tx() as tx: 475 results = await tx.query(cypher, props) 476 await tx.commit() 477 if results: 478 vid = results[0]["vid"] 479 entity._attach_session(self, vid) 480 self._identity_map[(label, vid)] = entity 481 run_hooks(entity, _AFTER_CREATE) 482 entity._mark_clean() 483 484 async def _create_node_in_tx( 485 self, entity: UniNode, tx: uni_db.AsyncTransaction 486 ) -> None: 487 run_hooks(entity, _BEFORE_CREATE) 488 label = entity.__class__.__label__ 489 props = entity.to_properties() 490 props_str = ", ".join(f"{k}: ${k}" for k in props) 491 cypher = f"CREATE (n:{label} {{{props_str}}}) RETURN id(n) as vid" 492 results = await tx.query(cypher, props) 493 if results: 494 vid = results[0]["vid"] 495 entity._attach_session(self, vid) 496 self._identity_map[(label, vid)] = entity 497 run_hooks(entity, _AFTER_CREATE) 498 499 async def _create_edge_in_tx( 500 self, 501 source: UniNode, 502 edge_type: str, 503 target: UniNode, 504 properties: UniEdge | None, 505 tx: uni_db.AsyncTransaction, 506 ) -> None: 507 props = properties.to_properties() if properties else {} 508 src_label = source.__class__.__label__ 509 dst_label = target.__class__.__label__ 510 props_str = ", ".join(f"{k}: ${k}" for k in props) 511 if props_str: 512 cypher = f"MATCH (a:{src_label}), (b:{dst_label}) WHERE a._vid = $src AND b._vid = $dst CREATE (a)-[:{edge_type} {{{props_str}}}]->(b)" 513 else: 514 cypher = f"MATCH (a:{src_label}), (b:{dst_label}) WHERE a._vid = $src AND b._vid = $dst CREATE (a)-[:{edge_type}]->(b)" 515 params = {"src": source._vid, "dst": target._vid, **props} 516 await tx.query(cypher, params) 517 518 async def _update_node(self, entity: UniNode) -> None: 519 run_hooks(entity, _BEFORE_UPDATE) 520 label = entity.__class__.__label__ 521 hints = _resolve_type_hints(type(entity)) 522 dirty_props = {} 523 for name in entity._dirty: 524 value = getattr(entity, name) 525 if name in hints: 526 value = python_to_db_value(value, hints[name]) 527 dirty_props[name] = value 528 if not dirty_props: 529 return 530 set_clause = ", ".join(f"n.{k} = ${k}" for k in dirty_props) 531 cypher = f"MATCH (n:{label}) WHERE id(n) = $vid SET {set_clause}" 532 params = {"vid": entity._vid, **dirty_props} 533 async with await self._db_session.tx() as tx: 534 await tx.execute(cypher, params) 535 await tx.commit() 536 run_hooks(entity, _AFTER_UPDATE) 537 entity._mark_clean() 538 539 async def _delete_node(self, entity: UniNode) -> None: 540 run_hooks(entity, _BEFORE_DELETE) 541 label = entity.__class__.__label__ 542 vid = entity._vid 543 cypher = f"MATCH (n:{label}) WHERE id(n) = $vid DETACH DELETE n" 544 async with await self._db_session.tx() as tx: 545 await tx.execute(cypher, {"vid": vid}) 546 await tx.commit() 547 if vid is not None and (label, vid) in self._identity_map: 548 del self._identity_map[(label, vid)] 549 entity._vid = None 550 entity._uid = None 551 entity._session = None 552 run_hooks(entity, _AFTER_DELETE) 553 554 def _result_to_model( 555 self, 556 data: dict[str, Any], 557 model: type[NodeT], 558 ) -> NodeT | None: 559 """Convert a query result row to a model instance (sync — pure dict processing).""" 560 if not data: 561 return None 562 563 data = dict(data) 564 data = run_class_hooks(model, _BEFORE_LOAD, data) or data 565 566 vid = data.pop("_id", None) 567 if vid is None: 568 vid = data.pop("_vid", None) 569 if vid is None: 570 vid = data.pop("vid", None) 571 if vid is not None and not isinstance(vid, int): 572 vid = int(vid) 573 data.pop("_label", None) 574 575 try: 576 instance = model.from_properties(data, vid=vid, session=self) 577 except ValidationError as exc: 578 _warn_unhydratable(model, vid, exc) 579 return None 580 581 if vid is not None: 582 existing = self._identity_map.get((model.__label__, vid)) 583 if existing is not None: 584 return cast(NodeT, existing) 585 self._identity_map[(model.__label__, vid)] = instance 586 587 run_hooks(instance, _AFTER_LOAD) 588 return instance 589 590 def _load_relationship( 591 self, 592 entity: UniNode, 593 descriptor: RelationshipDescriptor[Any], 594 ) -> list[UniNode] | UniNode | None: 595 """Sync relationship loading — raises error for async session. 596 Use _async_load_relationship instead.""" 597 raise SessionError( 598 "Cannot synchronously load relationships in an async session. " 599 "Use eager_load() or access relationships via async queries." 600 ) 601 602 async def _async_eager_load_relationships( 603 self, 604 entities: list[NodeT], 605 relationships: list[str], 606 ) -> None: 607 """Eager load relationships for a list of entities (async).""" 608 if not entities: 609 return 610 611 model = type(entities[0]) 612 rel_configs = model.get_relationship_fields() 613 614 for rel_name in relationships: 615 if rel_name not in rel_configs: 616 continue 617 618 config = rel_configs[rel_name] 619 label = model.__label__ 620 vids = [e._vid for e in entities if e._vid is not None] 621 622 if not vids: 623 continue 624 625 pattern = _edge_pattern(config.edge_type, config.direction) 626 cypher = ( 627 f"MATCH (a:{label}){pattern}(b) WHERE id(a) IN $vids " 628 f"RETURN id(a) as src_vid, properties(b) AS _props, id(b) AS _vid, labels(b) AS _labels" 629 ) 630 results = await self._db_session.query(cypher, {"vids": vids}) 631 632 # Hydrate, mirroring the sync session. This matters more here: 633 # `_load_relationship` raises on an async session and tells the 634 # caller to use `eager_load()`, so this is the *only* relationship 635 # path async has -- and it was the broken one. 636 descriptor = getattr(model, rel_name, None) 637 is_list = getattr(descriptor, "is_list", True) 638 639 by_source: dict[int, list[Any]] = {} 640 for raw_row in results: 641 row = raw_row.to_dict() 642 src_vid = row["src_vid"] 643 node_data = _row_to_node_dict(row) 644 if node_data is None: 645 continue 646 node_label = node_data.get("_label") 647 if not node_label or node_label not in self._schema_gen._node_models: 648 continue 649 target_model = self._schema_gen._node_models[node_label] 650 instance = self._result_to_model(node_data, target_model) 651 if instance is None: 652 continue 653 by_source.setdefault(src_vid, []).append(instance) 654 655 cache_attr = f"_rel_cache_{rel_name}" 656 for entity in entities: 657 related = ( 658 by_source.get(entity._vid, []) if entity._vid is not None else [] 659 ) 660 if is_list: 661 setattr(entity, cache_attr, related) 662 else: 663 setattr(entity, cache_attr, related[0] if related else None)
Async session for interacting with the graph database.
Mirrors UniSession with async methods. Uses AsyncUni.
Example:
from uni_db import AsyncUni from uni_pydantic import AsyncUniSession
db = await AsyncUni.open("./my_graph") async with AsyncUniSession(db) as session: ... session.register(Person) ... await session.sync_schema() ... alice = Person(name="Alice", age=30) ... session.add(alice) ... await session.commit()
159 def __init__(self, db: uni_db.AsyncUni) -> None: 160 self._db = db 161 self._db_session = db.session() 162 self._schema_gen = SchemaGenerator() 163 self._identity_map: WeakValueDictionary[tuple[str, int], UniNode] = ( 164 WeakValueDictionary() 165 ) 166 self._pending_new: list[UniNode] = [] 167 self._pending_delete: list[UniNode] = []
180 def close(self) -> None: 181 """Close the session and clear pending state.""" 182 self._pending_new.clear() 183 self._pending_delete.clear()
Close the session and clear pending state.
185 @property 186 def db(self) -> uni_db.AsyncUni: 187 """Access the underlying uni_db.AsyncUni for low-level operations.""" 188 return self._db
Access the underlying uni_db.AsyncUni for low-level operations.
190 async def locy(self, program: str, params: dict[str, Any] | None = None) -> Any: 191 """ 192 Evaluate a Locy program and return derived facts, stats, and warnings. 193 194 Delegates to the underlying ``uni_db.AsyncSession.locy()``. 195 """ 196 return await self._db_session.locy(program, params)
Evaluate a Locy program and return derived facts, stats, and warnings.
Delegates to the underlying uni_db.AsyncSession.locy().
198 def register(self, *models: type[UniNode] | type[UniEdge]) -> None: 199 """Register model classes with the session (sync).""" 200 self._schema_gen.register(*models)
Register model classes with the session (sync).
202 async def sync_schema(self) -> None: 203 """Synchronize database schema with registered models.""" 204 await self._schema_gen.async_apply_to_database(self._db)
Synchronize database schema with registered models.
206 def query(self, model: type[NodeT]) -> AsyncQueryBuilder[NodeT]: 207 """Create an async query builder for the given model.""" 208 return AsyncQueryBuilder(self, model)
Create an async query builder for the given model.
210 def add(self, entity: UniNode) -> None: 211 """Add a new entity to be persisted (sync — just collects).""" 212 if entity.is_persisted: 213 raise SessionError(f"Entity {entity!r} is already persisted") 214 entity._session = self 215 self._pending_new.append(entity)
Add a new entity to be persisted (sync — just collects).
217 def add_all(self, entities: Sequence[UniNode]) -> None: 218 """Add multiple entities (sync — just collects).""" 219 for entity in entities: 220 self.add(entity)
Add multiple entities (sync — just collects).
222 def delete(self, entity: UniNode) -> None: 223 """Mark an entity for deletion (sync — just collects).""" 224 if not entity.is_persisted: 225 raise NotPersisted(entity) 226 self._pending_delete.append(entity)
Mark an entity for deletion (sync — just collects).
228 async def get( 229 self, 230 model: type[NodeT], 231 vid: int | None = None, 232 uid: str | None = None, 233 **kwargs: Any, 234 ) -> NodeT | None: 235 """Get an entity by ID or unique properties.""" 236 if vid is not None: 237 cached = self._identity_map.get((model.__label__, vid)) 238 if cached is not None: 239 return cached # type: ignore[return-value] 240 241 label = model.__label__ 242 params: dict[str, Any] = {} 243 244 if vid is not None: 245 cypher = f"MATCH (n:{label}) WHERE id(n) = $vid RETURN {_NODE_RETURN}" 246 params["vid"] = vid 247 elif uid is not None: 248 cypher = f"MATCH (n:{label}) WHERE n._uid = $uid RETURN {_NODE_RETURN}" 249 params["uid"] = uid 250 elif kwargs: 251 for k in kwargs: 252 _validate_property(k, model) 253 conditions = [f"n.{k} = ${k}" for k in kwargs] 254 cypher = f"MATCH (n:{label}) WHERE {' AND '.join(conditions)} RETURN {_NODE_RETURN} LIMIT 1" 255 params.update(kwargs) 256 else: 257 raise ValueError("Must provide vid, uid, or property filters") 258 259 results = await self._db_session.query(cypher, params) 260 if not results: 261 return None 262 263 node_data = _row_to_node_dict(results[0].to_dict()) 264 if node_data is None: 265 return None 266 return self._result_to_model(node_data, model)
Get an entity by ID or unique properties.
268 async def refresh(self, entity: UniNode) -> None: 269 """Refresh an entity's properties from the database.""" 270 if not entity.is_persisted: 271 raise NotPersisted(entity) 272 273 label = entity.__class__.__label__ 274 cypher = f"MATCH (n:{label}) WHERE id(n) = $vid RETURN {_NODE_RETURN}" 275 results = await self._db_session.query(cypher, {"vid": entity._vid}) 276 277 if not results: 278 raise SessionError(f"Entity with vid={entity._vid} no longer exists") 279 280 props = _row_to_node_dict(results[0].to_dict()) 281 if props is None: 282 raise SessionError(f"Entity with vid={entity._vid} no longer exists") 283 hints = _resolve_type_hints(type(entity)) 284 285 for field_name in entity.get_property_fields(): 286 if field_name in props: 287 value = props[field_name] 288 if field_name in hints: 289 value = db_to_python_value(value, hints[field_name]) 290 setattr(entity, field_name, value) 291 292 entity._mark_clean()
Refresh an entity's properties from the database.
294 async def commit(self) -> None: 295 """Commit all pending changes.""" 296 for entity in self._pending_new: 297 await self._create_node(entity) 298 299 for (label, vid), entity in list(self._identity_map.items()): 300 if entity.is_dirty and entity.is_persisted: 301 await self._update_node(entity) 302 303 for entity in self._pending_delete: 304 await self._delete_node(entity) 305 306 await self._db.flush() 307 self._pending_new.clear() 308 self._pending_delete.clear()
Commit all pending changes.
310 async def rollback(self) -> None: 311 """Discard all pending changes.""" 312 for entity in self._pending_new: 313 entity._session = None 314 self._pending_new.clear() 315 self._pending_delete.clear() 316 for entity in list(self._identity_map.values()): 317 if entity.is_dirty: 318 await self.refresh(entity)
Discard all pending changes.
320 async def transaction(self) -> AsyncUniTransaction: 321 """Create an async transaction. Use as `async with session.transaction() as tx:`.""" 322 return AsyncUniTransaction(self)
Create an async transaction. Use as async with session.transaction() as tx:.
324 async def cypher( 325 self, 326 query: str, 327 params: dict[str, Any] | None = None, 328 result_type: type[NodeT] | None = None, 329 ) -> list[NodeT] | list[dict[str, Any]]: 330 """Execute a raw Cypher query.""" 331 results = await self._db_session.query(query, params) 332 333 if result_type is None: 334 return [r.to_dict() for r in results] 335 336 mapped: list[NodeT] = [] 337 node_models = self._schema_gen._node_models 338 for raw_row in results: 339 row = raw_row.to_dict() 340 # Same column selection as `UniSession.cypher`. 341 for value in row.values(): 342 target = _cypher_node_target(value, result_type, node_models) 343 if target is None: 344 continue 345 instance = self._result_to_model(*target) 346 if instance is not None: 347 mapped.append(instance) 348 break 349 else: 350 first_value = next(iter(row.values()), None) 351 if isinstance(first_value, dict) and "_label" not in first_value: 352 instance = self._result_to_model(first_value, result_type) 353 if instance is not None: 354 mapped.append(instance) 355 356 return mapped
Execute a raw Cypher query.
358 async def create_edge( 359 self, 360 source: UniNode, 361 edge_type: str, 362 target: UniNode, 363 properties: dict[str, Any] | UniEdge | None = None, 364 ) -> None: 365 """Create an edge between two nodes.""" 366 src_vid, dst_vid, src_label, dst_label = UniSession._validate_edge_endpoints( 367 source, target 368 ) 369 props = UniSession._normalize_edge_properties(properties) 370 371 props_str = ", ".join(f"{k}: ${k}" for k in props) 372 if props_str: 373 cypher = f"MATCH (a:{src_label}), (b:{dst_label}) WHERE a._vid = $src AND b._vid = $dst CREATE (a)-[r:{edge_type} {{{props_str}}}]->(b)" 374 else: 375 cypher = f"MATCH (a:{src_label}), (b:{dst_label}) WHERE a._vid = $src AND b._vid = $dst CREATE (a)-[r:{edge_type}]->(b)" 376 377 async with await self._db_session.tx() as tx: 378 await tx.execute(cypher, {"src": src_vid, "dst": dst_vid, **props}) 379 await tx.commit()
Create an edge between two nodes.
381 async def delete_edge( 382 self, source: UniNode, edge_type: str, target: UniNode 383 ) -> int: 384 """Delete edges between two nodes. Returns the number of deleted edges.""" 385 src_vid, dst_vid, src_label, dst_label = UniSession._validate_edge_endpoints( 386 source, target 387 ) 388 cypher = ( 389 f"MATCH (a:{src_label})-[r:{edge_type}]->(b:{dst_label}) " 390 f"WHERE a._vid = $src AND b._vid = $dst " 391 f"DELETE r RETURN count(r) as count" 392 ) 393 async with await self._db_session.tx() as tx: 394 results = await tx.query(cypher, {"src": src_vid, "dst": dst_vid}) 395 await tx.commit() 396 return cast(int, results[0]["count"]) if results else 0
Delete edges between two nodes. Returns the number of deleted edges.
398 async def bulk_add(self, entities: Sequence[UniNode]) -> list[int]: 399 """Bulk-add entities using bulk_writer. 400 401 One bulk load and one commit for every label; see the sync 402 ``UniSession.bulk_add`` for the error contract. 403 """ 404 if not entities: 405 return [] 406 407 by_label: dict[str, list[UniNode]] = {} 408 for entity in entities: 409 label = entity.__class__.__label__ 410 if label not in by_label: 411 by_label[label] = [] 412 by_label[label].append(entity) 413 414 import uni_db 415 416 assigned: list[tuple[str, list[UniNode], list[int]]] = [] 417 try: 418 tx = await self._db_session.tx() 419 async with await tx.bulk_writer().build() as bw: 420 for label, group in by_label.items(): 421 for entity in group: 422 run_hooks(entity, _BEFORE_CREATE) 423 prop_dicts = [e.to_properties() for e in group] 424 vids = await bw.insert_vertices(label, prop_dicts) 425 assigned.append((label, group, vids)) 426 await bw.commit() 427 await tx.commit() 428 except ( 429 uni_db.UniBulkCommitIncompleteError, 430 uni_db.UniBulkCommitOutcomeUnknownError, 431 ): 432 # Committed, or possibly committed: never a retry-inviting 433 # BulkLoadError. 434 raise 435 except Exception as e: 436 raise BulkLoadError(f"Bulk insert failed: {e}") from e 437 438 all_vids: list[int] = [] 439 for label, group, vids in assigned: 440 for entity, vid in zip(group, vids): 441 entity._attach_session(self, vid) 442 self._identity_map[(label, vid)] = entity 443 run_hooks(entity, _AFTER_CREATE) 444 entity._mark_clean() 445 all_vids.extend(vids) 446 return all_vids
Bulk-add entities using bulk_writer.
One bulk load and one commit for every label; see the sync
UniSession.bulk_add for the error contract.
448 async def explain(self, cypher: str) -> Any: 449 """Get the query execution plan.""" 450 # See the sync twin in session.py: these live on the `query_with()` 451 # builder, not on AsyncSession. 452 return await self._db_session.query_with(cypher).explain()
Get the query execution plan.
454 async def profile(self, cypher: str) -> Any: 455 """Run the query with profiling and return results + stats.""" 456 return await self._db_session.query_with(cypher).profile()
Run the query with profiling and return results + stats.
60class AsyncUniTransaction: 61 """Async transaction context for atomic operations.""" 62 63 def __init__(self, session: AsyncUniSession) -> None: 64 self._session = session 65 self._tx: uni_db.AsyncTransaction | None = None 66 self._pending_nodes: list[UniNode] = [] 67 self._pending_edges: list[tuple[UniNode, str, UniNode, UniEdge | None]] = [] 68 self._committed = False 69 self._rolled_back = False 70 71 async def __aenter__(self) -> AsyncUniTransaction: 72 self._tx = await self._session._db_session.tx() 73 return self 74 75 async def __aexit__( 76 self, 77 exc_type: type[BaseException] | None, 78 exc_val: BaseException | None, 79 exc_tb: TracebackType | None, 80 ) -> None: 81 if exc_type is not None: 82 await self.rollback() 83 return 84 if not self._committed and not self._rolled_back: 85 await self.commit() 86 87 def add(self, entity: UniNode) -> None: 88 """Add a node to be created in this transaction (sync — just collects).""" 89 self._pending_nodes.append(entity) 90 91 def create_edge( 92 self, 93 source: UniNode, 94 edge_type: str, 95 target: UniNode, 96 properties: UniEdge | None = None, 97 ) -> None: 98 """Create an edge between two nodes in this transaction (sync — just collects).""" 99 if not source.is_persisted: 100 raise NotPersisted(source) 101 if not target.is_persisted: 102 raise NotPersisted(target) 103 self._pending_edges.append((source, edge_type, target, properties)) 104 105 async def commit(self) -> None: 106 """Commit the transaction.""" 107 if self._committed: 108 raise TransactionError("Transaction already committed") 109 if self._rolled_back: 110 raise TransactionError("Transaction already rolled back") 111 if self._tx is None: 112 raise TransactionError("Transaction not started") 113 114 try: 115 for node in self._pending_nodes: 116 await self._session._create_node_in_tx(node, self._tx) 117 for source, edge_type, target, props in self._pending_edges: 118 await self._session._create_edge_in_tx( 119 source, edge_type, target, props, self._tx 120 ) 121 await self._tx.commit() 122 self._committed = True 123 for node in self._pending_nodes: 124 node._mark_clean() 125 except Exception as e: 126 await self.rollback() 127 raise TransactionError(f"Commit failed: {e}") from e 128 129 async def rollback(self) -> None: 130 """Rollback the transaction.""" 131 if self._rolled_back: 132 return 133 if self._tx is not None: 134 await self._tx.rollback() 135 self._rolled_back = True 136 self._pending_nodes.clear() 137 self._pending_edges.clear()
Async transaction context for atomic operations.
63 def __init__(self, session: AsyncUniSession) -> None: 64 self._session = session 65 self._tx: uni_db.AsyncTransaction | None = None 66 self._pending_nodes: list[UniNode] = [] 67 self._pending_edges: list[tuple[UniNode, str, UniNode, UniEdge | None]] = [] 68 self._committed = False 69 self._rolled_back = False
87 def add(self, entity: UniNode) -> None: 88 """Add a node to be created in this transaction (sync — just collects).""" 89 self._pending_nodes.append(entity)
Add a node to be created in this transaction (sync — just collects).
91 def create_edge( 92 self, 93 source: UniNode, 94 edge_type: str, 95 target: UniNode, 96 properties: UniEdge | None = None, 97 ) -> None: 98 """Create an edge between two nodes in this transaction (sync — just collects).""" 99 if not source.is_persisted: 100 raise NotPersisted(source) 101 if not target.is_persisted: 102 raise NotPersisted(target) 103 self._pending_edges.append((source, edge_type, target, properties))
Create an edge between two nodes in this transaction (sync — just collects).
105 async def commit(self) -> None: 106 """Commit the transaction.""" 107 if self._committed: 108 raise TransactionError("Transaction already committed") 109 if self._rolled_back: 110 raise TransactionError("Transaction already rolled back") 111 if self._tx is None: 112 raise TransactionError("Transaction not started") 113 114 try: 115 for node in self._pending_nodes: 116 await self._session._create_node_in_tx(node, self._tx) 117 for source, edge_type, target, props in self._pending_edges: 118 await self._session._create_edge_in_tx( 119 source, edge_type, target, props, self._tx 120 ) 121 await self._tx.commit() 122 self._committed = True 123 for node in self._pending_nodes: 124 node._mark_clean() 125 except Exception as e: 126 await self.rollback() 127 raise TransactionError(f"Commit failed: {e}") from e
Commit the transaction.
129 async def rollback(self) -> None: 130 """Rollback the transaction.""" 131 if self._rolled_back: 132 return 133 if self._tx is not None: 134 await self._tx.rollback() 135 self._rolled_back = True 136 self._pending_nodes.clear() 137 self._pending_edges.clear()
Rollback the transaction.
69def Field( 70 default: Any = ..., 71 *, 72 default_factory: Callable[[], Any] | None = None, 73 alias: str | None = None, 74 title: str | None = None, 75 description: str | None = None, 76 examples: list[Any] | None = None, 77 exclude: bool = False, 78 json_schema_extra: dict[str, Any] | None = None, 79 # Uni-specific options 80 index: IndexType | None = None, 81 unique: bool = False, 82 tokenizer: str | None = None, 83 metric: VectorMetric | None = None, 84 generated: str | None = None, 85) -> Any: 86 """ 87 Create a field with uni-pydantic configuration. 88 89 This extends Pydantic's Field with graph database options. 90 91 Args: 92 default: Default value for the field. 93 default_factory: Factory function for default value. 94 alias: Field alias for serialization. 95 title: Human-readable title. 96 description: Field description. 97 examples: Example values. 98 exclude: Exclude from serialization. 99 json_schema_extra: Extra JSON schema properties. 100 index: Index type ("btree", "hash", "fulltext", "vector"). 101 unique: Whether to create a unique constraint. 102 tokenizer: Tokenizer for fulltext index (default: "standard"). 103 metric: Distance metric for vector index ("l2", "cosine", "dot"). 104 generated: Expression for generated/computed property. 105 106 Returns: 107 A Pydantic FieldInfo with uni-pydantic metadata attached. 108 109 Examples: 110 >>> class Person(UniNode): 111 ... name: str = Field(index="btree") 112 ... email: str = Field(unique=True) 113 ... bio: str = Field(index="fulltext", tokenizer="standard") 114 ... embedding: Vector[768] = Field(metric="cosine") 115 """ 116 # Default tokenizer for fulltext indexes 117 if index == "fulltext" and tokenizer is None: 118 tokenizer = "standard" 119 120 # Store uni config in json_schema_extra 121 uni_config = FieldConfig( 122 index=index, 123 unique=unique, 124 tokenizer=tokenizer, 125 metric=metric, 126 generated=generated, 127 default=default, 128 default_factory=default_factory, 129 alias=alias, 130 title=title, 131 description=description, 132 examples=examples, 133 exclude=exclude, 134 json_schema_extra=json_schema_extra, 135 ) 136 137 # Merge uni config into json_schema_extra 138 extra = json_schema_extra or {} 139 extra["uni_config"] = uni_config 140 141 # Create Pydantic FieldInfo 142 from pydantic.fields import FieldInfo as PydanticFieldInfo 143 144 if default_factory is not None: 145 return PydanticFieldInfo( 146 default_factory=default_factory, 147 alias=alias, 148 title=title, 149 description=description, 150 examples=examples, 151 exclude=exclude, 152 json_schema_extra=extra, 153 ) 154 elif default is not ...: 155 return PydanticFieldInfo( 156 default=default, 157 alias=alias, 158 title=title, 159 description=description, 160 examples=examples, 161 exclude=exclude, 162 json_schema_extra=extra, 163 ) 164 else: 165 return PydanticFieldInfo( 166 alias=alias, 167 title=title, 168 description=description, 169 examples=examples, 170 exclude=exclude, 171 json_schema_extra=extra, 172 )
Create a field with uni-pydantic configuration.
This extends Pydantic's Field with graph database options.
Args: default: Default value for the field. default_factory: Factory function for default value. alias: Field alias for serialization. title: Human-readable title. description: Field description. examples: Example values. exclude: Exclude from serialization. json_schema_extra: Extra JSON schema properties. index: Index type ("btree", "hash", "fulltext", "vector"). unique: Whether to create a unique constraint. tokenizer: Tokenizer for fulltext index (default: "standard"). metric: Distance metric for vector index ("l2", "cosine", "dot"). generated: Expression for generated/computed property.
Returns: A Pydantic FieldInfo with uni-pydantic metadata attached.
Examples:
class Person(UniNode): ... name: str = Field(index="btree") ... email: str = Field(unique=True) ... bio: str = Field(index="fulltext", tokenizer="standard") ... embedding: Vector[768] = Field(metric="cosine")
41@dataclass 42class FieldConfig: 43 """Configuration for a uni-pydantic field.""" 44 45 # Index configuration 46 index: IndexType | None = None 47 unique: bool = False 48 49 # Fulltext index options 50 tokenizer: str | None = None 51 52 # Vector index options 53 metric: VectorMetric | None = None 54 55 # Generated/computed property 56 generated: str | None = None 57 58 # Pydantic field options (passed through) 59 default: Any = dataclass_field(default_factory=lambda: ...) 60 default_factory: Callable[[], Any] | None = None 61 alias: str | None = None 62 title: str | None = None 63 description: str | None = None 64 examples: list[Any] | None = None 65 exclude: bool = False 66 json_schema_extra: dict[str, Any] | None = None
Configuration for a uni-pydantic field.
272def Relationship( 273 edge_type: str, 274 *, 275 direction: Direction = "outgoing", 276 edge_model: type[UniEdge] | None = None, 277 eager: bool = False, 278 cascade_delete: bool = False, 279) -> Any: 280 """ 281 Declare a relationship to another node type. 282 283 Relationships are lazy-loaded by default. Use eager=True or 284 query.eager_load() to load them with the parent query. 285 286 Args: 287 edge_type: The edge type name (e.g., "FRIEND_OF", "WORKS_AT"). 288 direction: Relationship direction: 289 - "outgoing": Follow edges from this node (default) 290 - "incoming": Follow edges to this node 291 - "both": Follow edges in both directions 292 edge_model: Optional UniEdge subclass for typed edge properties. 293 eager: Whether to eager-load this relationship by default. 294 cascade_delete: Whether to delete related edges when this node is deleted. 295 296 Returns: 297 A RelationshipDescriptor that will be processed during model creation. 298 299 Examples: 300 >>> class Person(UniNode): 301 ... # Outgoing relationship (default) 302 ... follows: list["Person"] = Relationship("FOLLOWS") 303 ... 304 ... # Incoming relationship 305 ... followers: list["Person"] = Relationship("FOLLOWS", direction="incoming") 306 ... 307 ... # Single optional relationship 308 ... manager: "Person | None" = Relationship("REPORTS_TO") 309 ... 310 ... # Relationship with edge properties 311 ... friendships: list[tuple["Person", FriendshipEdge]] = Relationship( 312 ... "FRIEND_OF", 313 ... edge_model=FriendshipEdge 314 ... ) 315 """ 316 config = RelationshipConfig( 317 edge_type=edge_type, 318 direction=direction, 319 edge_model=edge_model, 320 eager=eager, 321 cascade_delete=cascade_delete, 322 ) 323 # Return a marker that will be processed by the metaclass 324 return _RelationshipMarker(config)
Declare a relationship to another node type.
Relationships are lazy-loaded by default. Use eager=True or query.eager_load() to load them with the parent query.
Args: edge_type: The edge type name (e.g., "FRIEND_OF", "WORKS_AT"). direction: Relationship direction: - "outgoing": Follow edges from this node (default) - "incoming": Follow edges to this node - "both": Follow edges in both directions edge_model: Optional UniEdge subclass for typed edge properties. eager: Whether to eager-load this relationship by default. cascade_delete: Whether to delete related edges when this node is deleted.
Returns: A RelationshipDescriptor that will be processed during model creation.
Examples:
class Person(UniNode): ... # Outgoing relationship (default) ... follows: list["Person"] = Relationship("FOLLOWS") ... ... # Incoming relationship ... followers: list["Person"] = Relationship("FOLLOWS", direction="incoming") ... ... # Single optional relationship ... manager: "Person | None" = Relationship("REPORTS_TO") ... ... # Relationship with edge properties ... friendships: list[tuple["Person", FriendshipEdge]] = Relationship( ... "FRIEND_OF", ... edge_model=FriendshipEdge ... )
185@dataclass 186class RelationshipConfig: 187 """Configuration for a relationship field.""" 188 189 edge_type: str 190 direction: Direction = "outgoing" 191 edge_model: type[UniEdge] | None = None 192 eager: bool = False 193 cascade_delete: bool = False
Configuration for a relationship field.
196class RelationshipDescriptor(Generic[NodeT]): 197 """ 198 Descriptor for relationship fields that enables lazy loading. 199 200 When accessed on an instance, it returns the related nodes. 201 When accessed on the class, it returns the descriptor for query building. 202 """ 203 204 def __init__( 205 self, 206 config: RelationshipConfig, 207 field_name: str, 208 target_type: type[NodeT] | str | None = None, 209 is_list: bool = True, 210 ) -> None: 211 self.config = config 212 self.field_name = field_name 213 self.target_type = target_type 214 self.is_list = is_list 215 self._cache_attr = f"_rel_cache_{field_name}" 216 217 def __set_name__(self, owner: type, name: str) -> None: 218 self.field_name = name 219 self._cache_attr = f"_rel_cache_{name}" 220 221 @overload 222 def __get__( 223 self, obj: None, objtype: type[NodeT] 224 ) -> RelationshipDescriptor[NodeT]: ... 225 226 @overload 227 def __get__( 228 self, obj: NodeT, objtype: type[NodeT] | None = None 229 ) -> list[NodeT] | NodeT | None: ... 230 231 def __get__( 232 self, obj: NodeT | None, objtype: type[NodeT] | None = None 233 ) -> RelationshipDescriptor[NodeT] | list[NodeT] | NodeT | None: 234 if obj is None: 235 # Class-level access returns the descriptor 236 return self 237 238 # Instance-level access - check cache first 239 if hasattr(obj, self._cache_attr): 240 cached = getattr(obj, self._cache_attr) 241 return cast("list[NodeT] | NodeT | None", cached) 242 243 # Check if we have a session for lazy loading 244 session = getattr(obj, "_session", None) 245 if session is None: 246 from .exceptions import LazyLoadError 247 248 raise LazyLoadError( 249 self.field_name, 250 "No session attached. Use session.get() or enable eager loading.", 251 ) 252 253 # Lazy load the relationship 254 result = session._load_relationship(obj, self) 255 256 # Cache the result 257 setattr(obj, self._cache_attr, result) 258 return cast("list[NodeT] | NodeT | None", result) 259 260 def __set__(self, obj: NodeT, value: list[NodeT] | NodeT | None) -> None: 261 # Allow setting the cached value (e.g., during eager loading) 262 setattr(obj, self._cache_attr, value) 263 264 def __repr__(self) -> str: 265 return f"Relationship({self.config.edge_type!r}, direction={self.config.direction!r})"
Descriptor for relationship fields that enables lazy loading.
When accessed on an instance, it returns the related nodes. When accessed on the class, it returns the descriptor for query building.
204 def __init__( 205 self, 206 config: RelationshipConfig, 207 field_name: str, 208 target_type: type[NodeT] | str | None = None, 209 is_list: bool = True, 210 ) -> None: 211 self.config = config 212 self.field_name = field_name 213 self.target_type = target_type 214 self.is_list = is_list 215 self._cache_attr = f"_rel_cache_{field_name}"
175def get_field_config(field_info: FieldInfo) -> FieldConfig | None: 176 """Extract uni-pydantic config from a Pydantic FieldInfo.""" 177 extra = field_info.json_schema_extra 178 if isinstance(extra, dict): 179 config = extra.get("uni_config") 180 if isinstance(config, FieldConfig): 181 return config 182 return None
Extract uni-pydantic config from a Pydantic FieldInfo.
296class Btic: 297 """A BTIC temporal interval value for Uni graph database. 298 299 Construct from an ISO 8601-inspired string literal:: 300 301 Btic("1985") 302 Btic("1985-03/2024-06") 303 Btic("~1985") # approximate certainty 304 Btic("2020-03/") # ongoing (unbounded hi) 305 306 Use as a Pydantic model field type:: 307 308 class Event(UniNode): 309 when: Btic 310 """ 311 312 def __init__(self, value: str | object) -> None: 313 if _PyBtic is None: 314 raise ImportError("uni_db is required for Btic type") 315 if isinstance(value, str): 316 self._inner = _PyBtic(value) 317 elif _PyBtic is not None and isinstance(value, _PyBtic): 318 self._inner = value 319 elif isinstance(value, Btic): 320 self._inner = value._inner 321 else: 322 raise TypeError(f"Expected str or Btic, got {type(value)}") 323 324 @property 325 def lo(self) -> int: 326 """Lower bound in milliseconds since epoch.""" 327 return self._inner.lo 328 329 @property 330 def hi(self) -> int: 331 """Upper bound in milliseconds since epoch.""" 332 return self._inner.hi 333 334 @property 335 def meta(self) -> int: 336 """Raw 64-bit metadata word.""" 337 return self._inner.meta 338 339 @property 340 def lo_granularity(self) -> str: 341 """Lower bound granularity name.""" 342 return self._inner.lo_granularity 343 344 @property 345 def hi_granularity(self) -> str: 346 """Upper bound granularity name.""" 347 return self._inner.hi_granularity 348 349 @property 350 def lo_certainty(self) -> str: 351 """Lower bound certainty name.""" 352 return self._inner.lo_certainty 353 354 @property 355 def hi_certainty(self) -> str: 356 """Upper bound certainty name.""" 357 return self._inner.hi_certainty 358 359 @property 360 def duration_ms(self) -> int | None: 361 """Duration in milliseconds, or None if unbounded.""" 362 return self._inner.duration_ms 363 364 @property 365 def is_instant(self) -> bool: 366 """True if the interval is exactly 1 millisecond wide.""" 367 return self._inner.is_instant 368 369 @property 370 def is_unbounded(self) -> bool: 371 """True if either bound is infinite.""" 372 return self._inner.is_unbounded 373 374 @property 375 def is_finite(self) -> bool: 376 """True if both bounds are finite.""" 377 return self._inner.is_finite 378 379 def __repr__(self) -> str: 380 return f'Btic("{self._inner}")' 381 382 def __str__(self) -> str: 383 return str(self._inner) 384 385 def __eq__(self, other: object) -> bool: 386 if isinstance(other, Btic): 387 return self._inner == other._inner 388 return False 389 390 def __hash__(self) -> int: 391 return hash(self._inner) 392 393 @classmethod 394 def __get_pydantic_core_schema__( 395 cls, source_type: Any, handler: GetCoreSchemaHandler 396 ) -> CoreSchema: 397 """Make Btic compatible with Pydantic v2.""" 398 399 def validate_btic(v: Any) -> Btic: 400 if isinstance(v, Btic): 401 return v 402 if isinstance(v, str): 403 return Btic(v) 404 if _PyBtic is not None and isinstance(v, _PyBtic): 405 return Btic(v) 406 raise TypeError(f"Expected str or Btic, got {type(v)}") 407 408 return core_schema.no_info_plain_validator_function( 409 validate_btic, 410 serialization=core_schema.plain_serializer_function_ser_schema( 411 lambda v: str(v._inner) if isinstance(v, Btic) else str(v), 412 info_arg=False, 413 ), 414 )
A BTIC temporal interval value for Uni graph database.
Construct from an ISO 8601-inspired string literal::
Btic("1985")
Btic("1985-03/2024-06")
Btic("~1985") # approximate certainty
Btic("2020-03/") # ongoing (unbounded hi)
Use as a Pydantic model field type::
class Event(UniNode):
when: Btic
312 def __init__(self, value: str | object) -> None: 313 if _PyBtic is None: 314 raise ImportError("uni_db is required for Btic type") 315 if isinstance(value, str): 316 self._inner = _PyBtic(value) 317 elif _PyBtic is not None and isinstance(value, _PyBtic): 318 self._inner = value 319 elif isinstance(value, Btic): 320 self._inner = value._inner 321 else: 322 raise TypeError(f"Expected str or Btic, got {type(value)}")
324 @property 325 def lo(self) -> int: 326 """Lower bound in milliseconds since epoch.""" 327 return self._inner.lo
Lower bound in milliseconds since epoch.
329 @property 330 def hi(self) -> int: 331 """Upper bound in milliseconds since epoch.""" 332 return self._inner.hi
Upper bound in milliseconds since epoch.
334 @property 335 def meta(self) -> int: 336 """Raw 64-bit metadata word.""" 337 return self._inner.meta
Raw 64-bit metadata word.
339 @property 340 def lo_granularity(self) -> str: 341 """Lower bound granularity name.""" 342 return self._inner.lo_granularity
Lower bound granularity name.
344 @property 345 def hi_granularity(self) -> str: 346 """Upper bound granularity name.""" 347 return self._inner.hi_granularity
Upper bound granularity name.
349 @property 350 def lo_certainty(self) -> str: 351 """Lower bound certainty name.""" 352 return self._inner.lo_certainty
Lower bound certainty name.
354 @property 355 def hi_certainty(self) -> str: 356 """Upper bound certainty name.""" 357 return self._inner.hi_certainty
Upper bound certainty name.
359 @property 360 def duration_ms(self) -> int | None: 361 """Duration in milliseconds, or None if unbounded.""" 362 return self._inner.duration_ms
Duration in milliseconds, or None if unbounded.
364 @property 365 def is_instant(self) -> bool: 366 """True if the interval is exactly 1 millisecond wide.""" 367 return self._inner.is_instant
True if the interval is exactly 1 millisecond wide.
72class Vector(Generic[N], metaclass=VectorMeta): 73 """ 74 A vector type with fixed dimensions for embeddings. 75 76 Usage: 77 embedding: Vector[1536] # 1536-dimensional vector 78 79 At runtime, vectors are stored as list[float]. 80 """ 81 82 __dimensions__: int = 0 83 __origin__: type | None = None 84 85 def __init__(self, values: list[float]) -> None: 86 expected = self.__class__.__dimensions__ 87 if expected > 0 and len(values) != expected: 88 raise ValueError(f"Vector expects {expected} dimensions, got {len(values)}") 89 self._values = values 90 91 @property 92 def values(self) -> list[float]: 93 return self._values 94 95 def __repr__(self) -> str: 96 dims = self.__class__.__dimensions__ 97 return ( 98 f"Vector[{dims}]({self._values[:3]}...)" 99 if len(self._values) > 3 100 else f"Vector[{dims}]({self._values})" 101 ) 102 103 def __eq__(self, other: object) -> bool: 104 if isinstance(other, Vector): 105 return self._values == other._values 106 if isinstance(other, list): 107 return self._values == other 108 return False 109 110 def __len__(self) -> int: 111 return len(self._values) 112 113 def __iter__(self): # type: ignore[no-untyped-def] 114 return iter(self._values) 115 116 @classmethod 117 def __get_pydantic_core_schema__( 118 cls, source_type: Any, handler: GetCoreSchemaHandler 119 ) -> CoreSchema: 120 """Make Vector compatible with Pydantic v2.""" 121 dimensions = getattr(source_type, "__dimensions__", 0) 122 vec_cls = source_type if dimensions > 0 else cls 123 124 def validate_vector(v: Any) -> Vector: # type: ignore[type-arg] 125 if isinstance(v, Vector): 126 if dimensions > 0 and len(v) != dimensions: 127 raise ValueError( 128 f"Vector expects {dimensions} dimensions, got {len(v)}" 129 ) 130 return v 131 if isinstance(v, list): 132 if dimensions > 0 and len(v) != dimensions: 133 raise ValueError( 134 f"Vector expects {dimensions} dimensions, got {len(v)}" 135 ) 136 return vec_cls([float(x) for x in v]) 137 raise TypeError(f"Expected list or Vector, got {type(v)}") 138 139 return core_schema.no_info_plain_validator_function( 140 validate_vector, 141 serialization=core_schema.plain_serializer_function_ser_schema( 142 lambda v: v.values if isinstance(v, Vector) else list(v), 143 info_arg=False, 144 ), 145 )
A vector type with fixed dimensions for embeddings.
Usage: embedding: Vector[1536] # 1536-dimensional vector
At runtime, vectors are stored as list[float].
197class SparseVector(Generic[N], metaclass=SparseVectorMeta): 198 """ 199 A learned-sparse (SPLADE / BGE-M3) vector over a fixed-size vocabulary. 200 201 Usage: 202 terms: SparseVector[30522] # SPLADE head over a 30522-term BERT vocab 203 204 At runtime, holds parallel ``indices`` (term ids) and ``values`` (weights). 205 Accepts a ``dict[int, float]`` of term id -> weight, a ``uni_db.SparseVector``, 206 or an existing instance; ingestion serializes to the typed Rust binding when 207 available, otherwise to an ``{"indices": [...], "values": [...]}`` mapping. 208 """ 209 210 __sparse_dimensions__: int = 0 211 __origin__: type | None = None 212 213 def __init__(self, indices: list[int], values: list[float]) -> None: 214 if len(indices) != len(values): 215 raise ValueError( 216 f"SparseVector indices/values length mismatch: " 217 f"{len(indices)} vs {len(values)}" 218 ) 219 self._indices = [int(i) for i in indices] 220 self._values = [float(v) for v in values] 221 222 @property 223 def indices(self) -> list[int]: 224 return self._indices 225 226 @property 227 def values(self) -> list[float]: 228 return self._values 229 230 @classmethod 231 def from_dict(cls, mapping: dict[int, float]) -> SparseVector[Any]: 232 """Build from a ``{term_id: weight}`` mapping (sorted by term id).""" 233 items = sorted(mapping.items()) 234 return cls([k for k, _ in items], [v for _, v in items]) 235 236 def __repr__(self) -> str: 237 dims = self.__class__.__sparse_dimensions__ 238 return f"SparseVector[{dims}](indices={self._indices}, values={self._values})" 239 240 def __eq__(self, other: object) -> bool: 241 if isinstance(other, SparseVector): 242 return self._indices == other._indices and self._values == other._values 243 return False 244 245 def __len__(self) -> int: 246 return len(self._indices) 247 248 @classmethod 249 def __get_pydantic_core_schema__( 250 cls, source_type: Any, handler: GetCoreSchemaHandler 251 ) -> CoreSchema: 252 """Make SparseVector compatible with Pydantic v2.""" 253 dimensions = getattr(source_type, "__sparse_dimensions__", 0) 254 sv_cls = source_type if dimensions > 0 else cls 255 256 def validate_sparse(v: Any) -> SparseVector: # type: ignore[type-arg] 257 if isinstance(v, SparseVector): 258 return v 259 if _PySparseVector is not None and isinstance(v, _PySparseVector): 260 return sv_cls(list(v.indices), list(v.values)) 261 if isinstance(v, dict): 262 return sv_cls.from_dict(v) 263 if isinstance(v, (tuple, list)) and len(v) == 2: 264 return sv_cls(list(v[0]), list(v[1])) 265 raise TypeError( 266 f"Expected SparseVector, dict, or (indices, values), got {type(v)}" 267 ) 268 269 def serialize_sparse(v: SparseVector) -> Any: # type: ignore[type-arg] 270 if _PySparseVector is not None: 271 return _PySparseVector(v.indices, v.values) 272 return {"indices": v.indices, "values": v.values} 273 274 return core_schema.no_info_plain_validator_function( 275 validate_sparse, 276 serialization=core_schema.plain_serializer_function_ser_schema( 277 serialize_sparse, 278 info_arg=False, 279 ), 280 )
A learned-sparse (SPLADE / BGE-M3) vector over a fixed-size vocabulary.
Usage: terms: SparseVector[30522] # SPLADE head over a 30522-term BERT vocab
At runtime, holds parallel indices (term ids) and values (weights).
Accepts a dict[int, float] of term id -> weight, a uni_db.SparseVector,
or an existing instance; ingestion serializes to the typed Rust binding when
available, otherwise to an {"indices": [...], "values": [...]} mapping.
213 def __init__(self, indices: list[int], values: list[float]) -> None: 214 if len(indices) != len(values): 215 raise ValueError( 216 f"SparseVector indices/values length mismatch: " 217 f"{len(indices)} vs {len(values)}" 218 ) 219 self._indices = [int(i) for i in indices] 220 self._values = [float(v) for v in values]
230 @classmethod 231 def from_dict(cls, mapping: dict[int, float]) -> SparseVector[Any]: 232 """Build from a ``{term_id: weight}`` mapping (sorted by term id).""" 233 items = sorted(mapping.items()) 234 return cls([k for k, _ in items], [v for _, v in items])
Build from a {term_id: weight} mapping (sorted by term id).
572def python_type_to_uni(type_hint: Any, *, nullable: bool = False) -> tuple[str, bool]: 573 """ 574 Convert a Python type hint to a Uni DataType string. 575 576 Args: 577 type_hint: The Python type hint to convert. 578 nullable: Whether the field is explicitly nullable. 579 580 Returns: 581 Tuple of (uni_data_type, is_nullable) 582 583 Raises: 584 TypeMappingError: If the type cannot be mapped. 585 """ 586 # Unwrap Annotated if present 587 type_hint, _ = unwrap_annotated(type_hint) 588 589 # Check for optional (T | None) 590 is_opt, inner_type = is_optional(type_hint) 591 if is_opt: 592 uni_type, _ = python_type_to_uni(inner_type) 593 return uni_type, True 594 595 # Check for SparseVector types (before dense Vector: distinct marker attr). 596 sparse_dims = get_sparse_vector_dimensions(type_hint) 597 if sparse_dims is not None: 598 return f"sparse_vector:{sparse_dims}", nullable 599 600 # Check for Vector types 601 dims = get_vector_dimensions(type_hint) 602 if dims is not None: 603 return f"vector:{dims}", nullable 604 605 # Check for list types 606 is_lst, elem_type = is_list_type(type_hint) 607 if is_lst: 608 if elem_type in (str, int, float, bool): 609 # Simple list types 610 elem_uni = TYPE_MAP.get(elem_type, "string") 611 return f"list:{elem_uni}", nullable 612 # list[Vector[N]] (multi-vector / ColBERT) -> list:vector:N 613 elem_dims = get_vector_dimensions(elem_type) 614 if elem_dims is not None: 615 return f"list:vector:{elem_dims}", nullable 616 # Complex list types stored as JSON 617 return "json", nullable 618 619 # Direct type mapping 620 if type_hint in TYPE_MAP: 621 return TYPE_MAP[type_hint], nullable 622 623 # Handle generic dict types -> typed MAP<STRING, V> when the key is `str` and the 624 # value type maps to a concrete Uni type; otherwise schemaless JSON. Keys must be 625 # `str` because the storage value model (Value::Map) is string-keyed. 626 origin = get_origin(type_hint) 627 if origin is dict: 628 args = get_args(type_hint) 629 if len(args) == 2 and args[0] is str: 630 try: 631 val_uni, _ = python_type_to_uni(args[1]) 632 except TypeMappingError: 633 val_uni = "json" 634 # Recurse handles nested values: dict[str, list[int]] -> map:string:list:int64, 635 # dict[str, Vector[N]] -> map:string:vector:N, dict[str, dict[str,int]] -> nested. 636 if val_uni != "json": 637 return f"map:string:{val_uni}", nullable 638 return "json", nullable 639 640 # Handle forward references: a quoted annotation (a plain string) or a 641 # ``ForwardRef`` -- which is what pydantic leaves on an unresolved field, and 642 # what Python 3.14's lazy annotations (PEP 649) produce for a name that is 643 # not yet defined. Both carry the same source text; neither can be resolved 644 # here, so report the reference itself rather than an opaque repr. 645 if isinstance(type_hint, (str, ForwardRef)): 646 ref = type_hint if isinstance(type_hint, str) else type_hint.__forward_arg__ 647 raise TypeMappingError( 648 type_hint, 649 f"Cannot resolve forward reference {ref!r}. " 650 "Ensure the referenced class is defined before schema sync.", 651 ) 652 653 raise TypeMappingError(type_hint)
Convert a Python type hint to a Uni DataType string.
Args: type_hint: The Python type hint to convert. nullable: Whether the field is explicitly nullable.
Returns: Tuple of (uni_data_type, is_nullable)
Raises: TypeMappingError: If the type cannot be mapped.
656def uni_to_python_type(uni_type: str) -> type: 657 """ 658 Convert a Uni DataType string to a Python type. 659 660 Args: 661 uni_type: The Uni data type string. 662 663 Returns: 664 The corresponding Python type. 665 """ 666 # Reverse mapping — manually constructed to avoid bytes overwriting str for "string" 667 _REVERSE_MAP: dict[str, type] = { 668 "string": str, 669 "int64": int, 670 "float64": float, 671 "bool": bool, 672 "datetime": datetime, 673 "date": date, 674 "time": time, 675 "duration": timedelta, 676 "json": dict, 677 "btic": Btic, 678 "bytes": bytes, 679 } 680 681 # Handle vector types 682 if uni_type.startswith("vector:"): 683 return list # Vectors are stored as list[float] 684 685 # Handle list types 686 if uni_type.startswith("list:"): 687 return list 688 689 return _REVERSE_MAP.get(uni_type.lower(), str)
Convert a Uni DataType string to a Python type.
Args: uni_type: The Uni data type string.
Returns: The corresponding Python type.
158def get_vector_dimensions(type_hint: Any) -> int | None: 159 """Extract vector dimensions from a Vector[N] type hint.""" 160 if hasattr(type_hint, "__dimensions__"): 161 dims: int = type_hint.__dimensions__ 162 return dims 163 origin = get_origin(type_hint) 164 if origin is Vector: 165 args = get_args(type_hint) 166 if args and isinstance(args[0], int): 167 return args[0] 168 return None
Extract vector dimensions from a Vector[N] type hint.
283def get_sparse_vector_dimensions(type_hint: Any) -> int | None: 284 """Extract the vocabulary size from a SparseVector[N] type hint.""" 285 if hasattr(type_hint, "__sparse_dimensions__"): 286 dims: int = type_hint.__sparse_dimensions__ 287 return dims 288 origin = get_origin(type_hint) 289 if origin is SparseVector: 290 args = get_args(type_hint) 291 if args and isinstance(args[0], int): 292 return args[0] 293 return None
Extract the vocabulary size from a SparseVector[N] type hint.
417def is_optional(type_hint: Any) -> tuple[bool, Any]: 418 """ 419 Check if a type hint is Optional (T | None). 420 421 Returns: 422 Tuple of (is_optional, inner_type) 423 """ 424 origin = get_origin(type_hint) 425 426 # Handle Union types (including T | None which is Union[T, None]) 427 if origin is Union: 428 args = get_args(type_hint) 429 non_none_args = [arg for arg in args if arg is not type(None)] 430 if len(non_none_args) == 1 and type(None) in args: 431 return True, non_none_args[0] 432 433 # Python 3.10+ uses types.UnionType for X | Y syntax 434 if isinstance(type_hint, types.UnionType): 435 args = get_args(type_hint) 436 non_none_args = [arg for arg in args if arg is not type(None)] 437 if len(non_none_args) == 1 and type(None) in args: 438 return True, non_none_args[0] 439 440 return False, type_hint
Check if a type hint is Optional (T | None).
Returns: Tuple of (is_optional, inner_type)
443def is_list_type(type_hint: Any) -> tuple[bool, Any | None]: 444 """ 445 Check if a type hint is a list type. 446 447 Returns: 448 Tuple of (is_list, element_type) 449 """ 450 origin = get_origin(type_hint) 451 if origin is list: 452 args = get_args(type_hint) 453 return True, args[0] if args else Any 454 return False, None
Check if a type hint is a list type.
Returns: Tuple of (is_list, element_type)
457def unwrap_annotated(type_hint: Any) -> tuple[Any, tuple[Any, ...]]: 458 """ 459 Unwrap an Annotated type. 460 461 Returns: 462 Tuple of (base_type, metadata_tuple) 463 """ 464 origin = get_origin(type_hint) 465 if origin is Annotated: 466 args = get_args(type_hint) 467 return args[0], args[1:] 468 return type_hint, ()
Unwrap an Annotated type.
Returns: Tuple of (base_type, metadata_tuple)
475def python_to_db_value(value: Any, type_hint: Any) -> Any: 476 """Convert a Python value to a database-compatible value. 477 478 Passes datetime/date/time/timedelta through to the Rust layer which 479 converts them to proper Value::Temporal types. Converts Vector to 480 list[float] and passes through everything else. 481 """ 482 if value is None: 483 return None 484 485 # list[Vector[N]] → list[list[float]] (multi-vector / ColBERT) 486 if isinstance(value, list) and value and isinstance(value[0], Vector): 487 return [v.values if isinstance(v, Vector) else v for v in value] 488 489 # Vector → list[float] 490 if isinstance(value, Vector): 491 return value.values 492 493 # Btic → unwrap to the Rust PyBtic for py_object_to_value 494 if isinstance(value, Btic): 495 return value._inner 496 497 # datetime/date/time/timedelta pass through — the Rust py_object_to_value 498 # handles conversion to Value::Temporal with proper type information. 499 return value
Convert a Python value to a database-compatible value.
Passes datetime/date/time/timedelta through to the Rust layer which converts them to proper Value::Temporal types. Converts Vector to list[float] and passes through everything else.
502def db_to_python_value(value: Any, type_hint: Any) -> Any: 503 """Convert a database value back to a Python value. 504 505 The Rust layer now returns proper Python datetime/date/time objects 506 via Value::Temporal, so in most cases values pass through directly. 507 """ 508 if value is None: 509 return None 510 511 # Unwrap Optional 512 _, inner = is_optional(type_hint) 513 if inner is not type_hint: 514 type_hint = inner 515 516 # Unwrap Annotated 517 type_hint, _ = unwrap_annotated(type_hint) 518 519 # If value is already the right Python type, pass through 520 if type_hint is datetime and isinstance(value, datetime): 521 return value 522 if type_hint is date and isinstance(value, date): 523 return value 524 if type_hint is time and isinstance(value, time): 525 return value 526 if type_hint is timedelta and isinstance(value, timedelta): 527 return value 528 529 # Btic — wrap Rust PyBtic in the pydantic Btic wrapper 530 if type_hint is Btic and _PyBtic is not None and isinstance(value, _PyBtic): 531 return Btic(value) 532 533 # Handle struct dict from Arrow deserialization (e.g. datetime struct) 534 if type_hint is datetime and isinstance(value, dict): 535 nanos = value.get("nanos_since_epoch") 536 if nanos is not None: 537 return datetime.fromtimestamp(nanos / 1_000_000_000) 538 return None 539 540 # list[Vector[N]] fields: list[list[float]] → list[Vector[N]] (multi-vector) 541 is_lst, elem_type = is_list_type(type_hint) 542 if is_lst: 543 elem_dims = get_vector_dimensions(elem_type) 544 if elem_dims is not None and isinstance(value, list): 545 elem_cls = vector_class(elem_dims) 546 return [elem_cls(v) if isinstance(v, list) else v for v in value] 547 548 # Vector fields: list[float] → Vector 549 dims = get_vector_dimensions(type_hint) 550 if dims is not None and isinstance(value, list): 551 return vector_class(dims)(value) 552 553 return value
Convert a database value back to a Python value.
The Rust layer now returns proper Python datetime/date/time objects via Value::Temporal, so in most cases values pass through directly.
1009class QueryBuilder(_QueryBuilderBase[NodeT]): 1010 """ 1011 Immutable, type-safe query builder for graph queries. 1012 1013 Each method returns a **new** QueryBuilder instance. The original is 1014 never mutated. Provides a fluent API for building Cypher queries 1015 with type checking and IDE autocomplete support. 1016 1017 Example: 1018 >>> adults = ( 1019 ... session.query(Person) 1020 ... .filter(Person.age >= 18) 1021 ... .order_by(Person.name) 1022 ... .limit(10) 1023 ... .all() 1024 ... ) 1025 """ 1026 1027 def __init__(self, session: UniSession, model: type[NodeT]) -> None: 1028 self._init_state(session, model) 1029 1030 def _execute_query( 1031 self, cypher: str, params: dict[str, Any] 1032 ) -> list[dict[str, Any]]: 1033 """Execute a query, using query_with if timeout/max_memory is set.""" 1034 if self._timeout is not None or self._max_memory is not None: 1035 builder = self._session._db_session.query_with(cypher) 1036 if params: 1037 builder = builder.params(params) 1038 if self._timeout is not None: 1039 builder = builder.timeout(self._timeout) 1040 if self._max_memory is not None: 1041 builder = builder.max_memory(self._max_memory) 1042 result = builder.fetch_all() 1043 else: 1044 result = self._session._db_session.query(cypher, params) 1045 return [row.to_dict() for row in result] 1046 1047 def all(self) -> list[NodeT]: 1048 """Execute the query and return all results.""" 1049 cypher, params = self._build_cypher() 1050 results = self._execute_query(cypher, params) 1051 if self._is_search(): 1052 instances = self._rows_to_scored_instances(results) 1053 else: 1054 instances = self._rows_to_instances(results) 1055 if self._eager_load and instances: 1056 self._session._eager_load_relationships(instances, self._eager_load) 1057 return instances 1058 1059 def first(self) -> NodeT | None: 1060 """Execute the query and return the first result.""" 1061 clone = self._clone() 1062 clone._limit = 1 1063 results = clone.all() 1064 return results[0] if results else None 1065 1066 def one(self) -> NodeT: 1067 """Execute the query and return exactly one result. 1068 1069 Raises QueryError if no results or more than one result. 1070 """ 1071 clone = self._clone() 1072 clone._limit = 2 1073 results = clone.all() 1074 if not results: 1075 raise QueryError("Query returned no results") 1076 if len(results) > 1: 1077 raise QueryError("Query returned more than one result") 1078 return results[0] 1079 1080 def count(self) -> int: 1081 """Execute the query and return the count of results.""" 1082 cypher, params = self._build_count_cypher() 1083 results = self._execute_query(cypher, params) 1084 return cast(int, results[0]["count"]) if results else 0 1085 1086 def exists(self) -> bool: 1087 """Check if any matching records exist.""" 1088 cypher, params = self._build_exists_cypher() 1089 results = self._execute_query(cypher, params) 1090 return len(results) > 0 1091 1092 def delete(self) -> int: 1093 """Delete all matching records (DETACH DELETE).""" 1094 cypher, params = self._build_delete_cypher() 1095 with self._session._db_session.tx() as tx: 1096 results = tx.query(cypher, params) 1097 tx.commit() 1098 return results[0].to_dict()["count"] if results else 0 1099 1100 def update(self, **kwargs: Any) -> int: 1101 """Update all matching records.""" 1102 cypher, params = self._build_update_cypher(**kwargs) 1103 with self._session._db_session.tx() as tx: 1104 results = tx.query(cypher, params) 1105 tx.commit() 1106 return results[0].to_dict()["count"] if results else 0
Immutable, type-safe query builder for graph queries.
Each method returns a new QueryBuilder instance. The original is never mutated. Provides a fluent API for building Cypher queries with type checking and IDE autocomplete support.
Example:
adults = ( ... session.query(Person) ... .filter(Person.age >= 18) ... .order_by(Person.name) ... .limit(10) ... .all() ... )
1047 def all(self) -> list[NodeT]: 1048 """Execute the query and return all results.""" 1049 cypher, params = self._build_cypher() 1050 results = self._execute_query(cypher, params) 1051 if self._is_search(): 1052 instances = self._rows_to_scored_instances(results) 1053 else: 1054 instances = self._rows_to_instances(results) 1055 if self._eager_load and instances: 1056 self._session._eager_load_relationships(instances, self._eager_load) 1057 return instances
Execute the query and return all results.
1059 def first(self) -> NodeT | None: 1060 """Execute the query and return the first result.""" 1061 clone = self._clone() 1062 clone._limit = 1 1063 results = clone.all() 1064 return results[0] if results else None
Execute the query and return the first result.
1066 def one(self) -> NodeT: 1067 """Execute the query and return exactly one result. 1068 1069 Raises QueryError if no results or more than one result. 1070 """ 1071 clone = self._clone() 1072 clone._limit = 2 1073 results = clone.all() 1074 if not results: 1075 raise QueryError("Query returned no results") 1076 if len(results) > 1: 1077 raise QueryError("Query returned more than one result") 1078 return results[0]
Execute the query and return exactly one result.
Raises QueryError if no results or more than one result.
1080 def count(self) -> int: 1081 """Execute the query and return the count of results.""" 1082 cypher, params = self._build_count_cypher() 1083 results = self._execute_query(cypher, params) 1084 return cast(int, results[0]["count"]) if results else 0
Execute the query and return the count of results.
1086 def exists(self) -> bool: 1087 """Check if any matching records exist.""" 1088 cypher, params = self._build_exists_cypher() 1089 results = self._execute_query(cypher, params) 1090 return len(results) > 0
Check if any matching records exist.
1092 def delete(self) -> int: 1093 """Delete all matching records (DETACH DELETE).""" 1094 cypher, params = self._build_delete_cypher() 1095 with self._session._db_session.tx() as tx: 1096 results = tx.query(cypher, params) 1097 tx.commit() 1098 return results[0].to_dict()["count"] if results else 0
Delete all matching records (DETACH DELETE).
1100 def update(self, **kwargs: Any) -> int: 1101 """Update all matching records.""" 1102 cypher, params = self._build_update_cypher(**kwargs) 1103 with self._session._db_session.tx() as tx: 1104 results = tx.query(cypher, params) 1105 tx.commit() 1106 return results[0].to_dict()["count"] if results else 0
Update all matching records.
26class AsyncQueryBuilder(_QueryBuilderBase[NodeT]): 27 """ 28 Immutable, async query builder for graph queries. 29 30 Inherits all Cypher-building and immutable builder methods from 31 ``_QueryBuilderBase``. Only the execution methods are async. 32 """ 33 34 def __init__(self, session: AsyncUniSession, model: type[NodeT]) -> None: 35 self._init_state(session, model) 36 37 async def _execute_query( 38 self, cypher: str, params: dict[str, Any] 39 ) -> list[dict[str, Any]]: 40 """Execute a query, using query_with if timeout/max_memory is set.""" 41 if self._timeout is not None or self._max_memory is not None: 42 builder = self._session._db_session.query_with(cypher) 43 if params: 44 builder = builder.params(params) 45 if self._timeout is not None: 46 builder = builder.timeout(self._timeout) 47 if self._max_memory is not None: 48 builder = builder.max_memory(self._max_memory) 49 result = await builder.fetch_all() 50 else: 51 result = await self._session._db_session.query(cypher, params) 52 return [row.to_dict() for row in result] 53 54 async def all(self) -> list[NodeT]: 55 """Execute the query and return all results.""" 56 cypher, params = self._build_cypher() 57 results = await self._execute_query(cypher, params) 58 if self._is_search(): 59 instances = self._rows_to_scored_instances(results) 60 else: 61 instances = self._rows_to_instances(results) 62 if self._eager_load and instances: 63 await self._session._async_eager_load_relationships( 64 instances, self._eager_load 65 ) 66 return instances 67 68 async def first(self) -> NodeT | None: 69 """Execute the query and return the first result.""" 70 clone = self._clone() 71 clone._limit = 1 72 results = await clone.all() 73 return results[0] if results else None 74 75 async def one(self) -> NodeT: 76 """Execute the query and return exactly one result. 77 78 Raises QueryError if no results or more than one result. 79 """ 80 clone = self._clone() 81 clone._limit = 2 82 results = await clone.all() 83 if not results: 84 raise QueryError("Query returned no results") 85 if len(results) > 1: 86 raise QueryError("Query returned more than one result") 87 return results[0] 88 89 async def count(self) -> int: 90 """Execute the query and return the count of results.""" 91 cypher, params = self._build_count_cypher() 92 results = await self._execute_query(cypher, params) 93 return cast(int, results[0]["count"]) if results else 0 94 95 async def exists(self) -> bool: 96 """Check if any matching records exist.""" 97 cypher, params = self._build_exists_cypher() 98 results = await self._execute_query(cypher, params) 99 return len(results) > 0 100 101 async def delete(self) -> int: 102 """Delete all matching records (DETACH DELETE).""" 103 cypher, params = self._build_delete_cypher() 104 async with await self._session._db_session.tx() as tx: 105 results = await tx.query(cypher, params) 106 await tx.commit() 107 return results[0].to_dict()["count"] if results else 0 108 109 async def update(self, **kwargs: Any) -> int: 110 """Update all matching records.""" 111 cypher, params = self._build_update_cypher(**kwargs) 112 async with await self._session._db_session.tx() as tx: 113 results = await tx.query(cypher, params) 114 await tx.commit() 115 return results[0].to_dict()["count"] if results else 0
Immutable, async query builder for graph queries.
Inherits all Cypher-building and immutable builder methods from
_QueryBuilderBase. Only the execution methods are async.
54 async def all(self) -> list[NodeT]: 55 """Execute the query and return all results.""" 56 cypher, params = self._build_cypher() 57 results = await self._execute_query(cypher, params) 58 if self._is_search(): 59 instances = self._rows_to_scored_instances(results) 60 else: 61 instances = self._rows_to_instances(results) 62 if self._eager_load and instances: 63 await self._session._async_eager_load_relationships( 64 instances, self._eager_load 65 ) 66 return instances
Execute the query and return all results.
68 async def first(self) -> NodeT | None: 69 """Execute the query and return the first result.""" 70 clone = self._clone() 71 clone._limit = 1 72 results = await clone.all() 73 return results[0] if results else None
Execute the query and return the first result.
75 async def one(self) -> NodeT: 76 """Execute the query and return exactly one result. 77 78 Raises QueryError if no results or more than one result. 79 """ 80 clone = self._clone() 81 clone._limit = 2 82 results = await clone.all() 83 if not results: 84 raise QueryError("Query returned no results") 85 if len(results) > 1: 86 raise QueryError("Query returned more than one result") 87 return results[0]
Execute the query and return exactly one result.
Raises QueryError if no results or more than one result.
89 async def count(self) -> int: 90 """Execute the query and return the count of results.""" 91 cypher, params = self._build_count_cypher() 92 results = await self._execute_query(cypher, params) 93 return cast(int, results[0]["count"]) if results else 0
Execute the query and return the count of results.
95 async def exists(self) -> bool: 96 """Check if any matching records exist.""" 97 cypher, params = self._build_exists_cypher() 98 results = await self._execute_query(cypher, params) 99 return len(results) > 0
Check if any matching records exist.
101 async def delete(self) -> int: 102 """Delete all matching records (DETACH DELETE).""" 103 cypher, params = self._build_delete_cypher() 104 async with await self._session._db_session.tx() as tx: 105 results = await tx.query(cypher, params) 106 await tx.commit() 107 return results[0].to_dict()["count"] if results else 0
Delete all matching records (DETACH DELETE).
109 async def update(self, **kwargs: Any) -> int: 110 """Update all matching records.""" 111 cypher, params = self._build_update_cypher(**kwargs) 112 async with await self._session._db_session.tx() as tx: 113 results = await tx.query(cypher, params) 114 await tx.commit() 115 return results[0].to_dict()["count"] if results else 0
Update all matching records.
150@dataclass 151class FilterExpr: 152 """A filter expression for a query.""" 153 154 property_name: str 155 op: FilterOp 156 value: Any = None 157 158 def to_cypher(self, node_var: str, param_name: str) -> tuple[str, dict[str, Any]]: 159 """Convert to Cypher WHERE clause fragment.""" 160 prop = f"{node_var}.{self.property_name}" 161 162 if self.op == FilterOp.IS_NULL: 163 return f"{prop} IS NULL", {} 164 elif self.op == FilterOp.IS_NOT_NULL: 165 return f"{prop} IS NOT NULL", {} 166 elif self.op == FilterOp.IN: 167 return f"{prop} IN ${param_name}", {param_name: self.value} 168 elif self.op == FilterOp.NOT_IN: 169 return f"NOT {prop} IN ${param_name}", {param_name: self.value} 170 elif self.op == FilterOp.LIKE: 171 return f"{prop} =~ ${param_name}", {param_name: self.value} 172 elif self.op == FilterOp.STARTS_WITH: 173 return f"{prop} STARTS WITH ${param_name}", {param_name: self.value} 174 elif self.op == FilterOp.ENDS_WITH: 175 return f"{prop} ENDS WITH ${param_name}", {param_name: self.value} 176 elif self.op == FilterOp.CONTAINS: 177 return f"{prop} CONTAINS ${param_name}", {param_name: self.value} 178 else: 179 return f"{prop} {self.op.value} ${param_name}", {param_name: self.value}
A filter expression for a query.
158 def to_cypher(self, node_var: str, param_name: str) -> tuple[str, dict[str, Any]]: 159 """Convert to Cypher WHERE clause fragment.""" 160 prop = f"{node_var}.{self.property_name}" 161 162 if self.op == FilterOp.IS_NULL: 163 return f"{prop} IS NULL", {} 164 elif self.op == FilterOp.IS_NOT_NULL: 165 return f"{prop} IS NOT NULL", {} 166 elif self.op == FilterOp.IN: 167 return f"{prop} IN ${param_name}", {param_name: self.value} 168 elif self.op == FilterOp.NOT_IN: 169 return f"NOT {prop} IN ${param_name}", {param_name: self.value} 170 elif self.op == FilterOp.LIKE: 171 return f"{prop} =~ ${param_name}", {param_name: self.value} 172 elif self.op == FilterOp.STARTS_WITH: 173 return f"{prop} STARTS WITH ${param_name}", {param_name: self.value} 174 elif self.op == FilterOp.ENDS_WITH: 175 return f"{prop} ENDS WITH ${param_name}", {param_name: self.value} 176 elif self.op == FilterOp.CONTAINS: 177 return f"{prop} CONTAINS ${param_name}", {param_name: self.value} 178 else: 179 return f"{prop} {self.op.value} ${param_name}", {param_name: self.value}
Convert to Cypher WHERE clause fragment.
131class FilterOp(Enum): 132 """Filter operation types.""" 133 134 EQ = "=" 135 NE = "<>" 136 LT = "<" 137 LE = "<=" 138 GT = ">" 139 GE = ">=" 140 IN = "IN" 141 NOT_IN = "NOT IN" 142 LIKE = "=~" 143 IS_NULL = "IS NULL" 144 IS_NOT_NULL = "IS NOT NULL" 145 STARTS_WITH = "STARTS WITH" 146 ENDS_WITH = "ENDS WITH" 147 CONTAINS = "CONTAINS"
Filter operation types.
182class PropertyProxy(Generic[T]): 183 """ 184 Proxy for model properties that enables filter expressions. 185 186 Used in query builder to create type-safe filter conditions. 187 188 Example: 189 >>> query.filter(Person.age >= 18) 190 >>> query.filter(Person.name.starts_with("A")) 191 """ 192 193 def __init__( 194 self, property_name: str, model: type[UniNode] | type[UniEdge] 195 ) -> None: 196 self._property_name = property_name 197 self._model = model 198 199 def __eq__(self, other: Any) -> FilterExpr: # type: ignore[override] 200 return FilterExpr(self._property_name, FilterOp.EQ, other) 201 202 def __ne__(self, other: Any) -> FilterExpr: # type: ignore[override] 203 return FilterExpr(self._property_name, FilterOp.NE, other) 204 205 def __lt__(self, other: Any) -> FilterExpr: 206 return FilterExpr(self._property_name, FilterOp.LT, other) 207 208 def __le__(self, other: Any) -> FilterExpr: 209 return FilterExpr(self._property_name, FilterOp.LE, other) 210 211 def __gt__(self, other: Any) -> FilterExpr: 212 return FilterExpr(self._property_name, FilterOp.GT, other) 213 214 def __ge__(self, other: Any) -> FilterExpr: 215 return FilterExpr(self._property_name, FilterOp.GE, other) 216 217 def in_(self, values: Sequence[T]) -> FilterExpr: 218 """Check if value is in a list.""" 219 return FilterExpr(self._property_name, FilterOp.IN, list(values)) 220 221 def not_in(self, values: Sequence[T]) -> FilterExpr: 222 """Check if value is not in a list.""" 223 return FilterExpr(self._property_name, FilterOp.NOT_IN, list(values)) 224 225 def like(self, pattern: str) -> FilterExpr: 226 """Match a regex pattern against the whole value (Cypher ``=~``). 227 228 The pattern must match the entire string, as in Neo4j: use 229 ``".*foo.*"`` to find ``foo`` anywhere. 230 """ 231 return FilterExpr(self._property_name, FilterOp.LIKE, pattern) 232 233 def is_null(self) -> FilterExpr: 234 """Check if value is null.""" 235 return FilterExpr(self._property_name, FilterOp.IS_NULL) 236 237 def is_not_null(self) -> FilterExpr: 238 """Check if value is not null.""" 239 return FilterExpr(self._property_name, FilterOp.IS_NOT_NULL) 240 241 def starts_with(self, prefix: str) -> FilterExpr: 242 """Check if string starts with prefix.""" 243 return FilterExpr(self._property_name, FilterOp.STARTS_WITH, prefix) 244 245 def ends_with(self, suffix: str) -> FilterExpr: 246 """Check if string ends with suffix.""" 247 return FilterExpr(self._property_name, FilterOp.ENDS_WITH, suffix) 248 249 def contains(self, substring: str) -> FilterExpr: 250 """Check if string contains substring.""" 251 return FilterExpr(self._property_name, FilterOp.CONTAINS, substring)
Proxy for model properties that enables filter expressions.
Used in query builder to create type-safe filter conditions.
Example:
query.filter(Person.age >= 18) query.filter(Person.name.starts_with("A"))
217 def in_(self, values: Sequence[T]) -> FilterExpr: 218 """Check if value is in a list.""" 219 return FilterExpr(self._property_name, FilterOp.IN, list(values))
Check if value is in a list.
221 def not_in(self, values: Sequence[T]) -> FilterExpr: 222 """Check if value is not in a list.""" 223 return FilterExpr(self._property_name, FilterOp.NOT_IN, list(values))
Check if value is not in a list.
225 def like(self, pattern: str) -> FilterExpr: 226 """Match a regex pattern against the whole value (Cypher ``=~``). 227 228 The pattern must match the entire string, as in Neo4j: use 229 ``".*foo.*"`` to find ``foo`` anywhere. 230 """ 231 return FilterExpr(self._property_name, FilterOp.LIKE, pattern)
Match a regex pattern against the whole value (Cypher =~).
The pattern must match the entire string, as in Neo4j: use
".*foo.*" to find foo anywhere.
233 def is_null(self) -> FilterExpr: 234 """Check if value is null.""" 235 return FilterExpr(self._property_name, FilterOp.IS_NULL)
Check if value is null.
237 def is_not_null(self) -> FilterExpr: 238 """Check if value is not null.""" 239 return FilterExpr(self._property_name, FilterOp.IS_NOT_NULL)
Check if value is not null.
241 def starts_with(self, prefix: str) -> FilterExpr: 242 """Check if string starts with prefix.""" 243 return FilterExpr(self._property_name, FilterOp.STARTS_WITH, prefix)
Check if string starts with prefix.
245 def ends_with(self, suffix: str) -> FilterExpr: 246 """Check if string ends with suffix.""" 247 return FilterExpr(self._property_name, FilterOp.ENDS_WITH, suffix)
Check if string ends with suffix.
254class ModelProxy(Generic[NodeT]): 255 """ 256 Proxy for model classes that provides property proxies. 257 258 Enables type-safe property access in query filters. 259 260 Example: 261 >>> Person.name # Returns PropertyProxy for 'name' 262 >>> query.filter(Person.age >= 18) 263 """ 264 265 def __init__(self, model: type[NodeT]) -> None: 266 self._model = model 267 268 def __getattr__(self, name: str) -> PropertyProxy[Any]: 269 if name.startswith("_"): 270 raise AttributeError(name) 271 return PropertyProxy(name, self._model)
Proxy for model classes that provides property proxies.
Enables type-safe property access in query filters.
Example:
Person.name # Returns PropertyProxy for 'name' query.filter(Person.age >= 18)
274@dataclass 275class OrderByClause: 276 """An ORDER BY clause.""" 277 278 property_name: str 279 descending: bool = False
An ORDER BY clause.
282@dataclass 283class TraversalStep: 284 """A relationship traversal step.""" 285 286 edge_type: str 287 direction: Literal["outgoing", "incoming", "both"] 288 target_label: str | None = None
A relationship traversal step.
291@dataclass 292class VectorSearchConfig: 293 """Configuration for vector similarity search.""" 294 295 property_name: str 296 query_vector: list[float] 297 k: int 298 threshold: float | None = None 299 pre_filter: str | None = None
Configuration for vector similarity search.
302@dataclass 303class SparseSearchConfig: 304 """Configuration for learned-sparse (SPLADE) similarity search.""" 305 306 property_name: str 307 query_indices: list[int] 308 query_values: list[float] 309 k: int 310 threshold: float | None = None 311 pre_filter: str | None = None
Configuration for learned-sparse (SPLADE) similarity search.
314@dataclass 315class HybridSearchConfig: 316 """Configuration for three-way fused hybrid search (``uni.search``). 317 318 Each ``*_property`` is ``None`` when that retrieval arm is off. ``query_text`` 319 is the shared string that drives both FTS matching and dense auto-embed; 320 ``query_vector`` holds a precomputed dense vector (``None`` ⇒ auto-embed from 321 ``query_text``). ``sparse_query`` is the coerced ``(indices, values)`` pair 322 (``None`` ⇒ sparse arm off). 323 """ 324 325 query_text: str 326 k: int 327 vector_property: str | None = None 328 fts_property: str | None = None 329 sparse_property: str | None = None 330 query_vector: list[float] | None = None 331 sparse_query: tuple[list[int], list[float]] | None = None 332 method: str = "rrf" 333 alpha: float | None = None 334 weights: list[float] | None = None 335 rrf_k: int | None = None 336 over_fetch: float | None = None 337 filter: str | None = None
Configuration for three-way fused hybrid search (uni.search).
Each *_property is None when that retrieval arm is off. query_text
is the shared string that drives both FTS matching and dense auto-embed;
query_vector holds a precomputed dense vector (None ⇒ auto-embed from
query_text). sparse_query is the coerced (indices, values) pair
(None ⇒ sparse arm off).
66class SchemaGenerator: 67 """Generates Uni database schema from registered models.""" 68 69 def __init__(self) -> None: 70 self._node_models: dict[str, type[UniNode]] = {} 71 self._edge_models: dict[str, type[UniEdge]] = {} 72 self._schema: DatabaseSchema | None = None 73 74 def register_node(self, model: type[UniNode]) -> None: 75 """Register a node model for schema generation.""" 76 label = model.__label__ 77 if not label: 78 raise SchemaError(f"Model {model.__name__} has no __label__", model) 79 self._node_models[label] = model 80 self._schema = None # Invalidate cached schema 81 82 def register_edge(self, model: type[UniEdge]) -> None: 83 """Register an edge model for schema generation.""" 84 edge_type = model.__edge_type__ 85 if not edge_type: 86 raise SchemaError(f"Model {model.__name__} has no __edge_type__", model) 87 self._edge_models[edge_type] = model 88 self._schema = None 89 90 def register(self, *models: type[UniNode] | type[UniEdge]) -> None: 91 """Register multiple models.""" 92 for model in models: 93 if issubclass(model, UniEdge): 94 self.register_edge(model) 95 elif issubclass(model, UniNode): 96 self.register_node(model) 97 else: 98 raise SchemaError( 99 f"Model {model.__name__} must be a subclass of UniNode or UniEdge" 100 ) 101 102 def _generate_property_schema( 103 self, 104 model: type[UniNode] | type[UniEdge], 105 field_name: str, 106 ) -> PropertySchema: 107 """Generate schema for a single property field.""" 108 field_info = model.model_fields[field_name] 109 110 # Get type hints with forward refs resolved. A bare `get_type_hints` 111 # always raised here (NameError on the TYPE_CHECKING-only private-attr 112 # annotations of UniNode/UniEdge), so only pydantic's annotation was 113 # ever used; `_resolve_type_hints` supplies those names. 114 type_hint = _resolve_type_hints(model).get(field_name, field_info.annotation) 115 116 # Check for nullability 117 is_nullable, inner_type = is_optional(type_hint) 118 119 # Get Uni data type 120 data_type, nullable = python_type_to_uni(type_hint, nullable=is_nullable) 121 122 # Check for vector dimensions 123 vec_dims = get_vector_dimensions(inner_type if is_nullable else type_hint) 124 if vec_dims: 125 data_type = f"vector:{vec_dims}" 126 127 # Check for sparse-vector dimensions (vocabulary size) 128 sparse_dims = get_sparse_vector_dimensions( 129 inner_type if is_nullable else type_hint 130 ) 131 if sparse_dims: 132 data_type = f"sparse_vector:{sparse_dims}" 133 134 # Get field config for index settings 135 config = get_field_config(field_info) 136 index_type = config.index if config else None 137 unique = config.unique if config else False 138 tokenizer = config.tokenizer if config else None 139 metric = config.metric if config else None 140 141 # Auto-create vector index for Vector fields (regardless of Field config) 142 if vec_dims and not index_type: 143 index_type = "vector" 144 145 # Auto-create sparse index for SparseVector fields 146 if sparse_dims and not index_type: 147 index_type = "sparse" 148 149 return PropertySchema( 150 name=field_name, 151 data_type=data_type, 152 nullable=nullable, 153 index_type=index_type, 154 unique=unique, 155 tokenizer=tokenizer, 156 metric=metric, 157 ) 158 159 def _generate_label_schema(self, model: type[UniNode]) -> LabelSchema: 160 """Generate schema for a node model.""" 161 label = model.__label__ 162 163 properties = {} 164 for field_name in model.get_property_fields(): 165 prop_schema = self._generate_property_schema(model, field_name) 166 properties[field_name] = prop_schema 167 168 return LabelSchema( 169 name=label, 170 properties=properties, 171 ) 172 173 def _generate_edge_type_schema(self, model: type[UniEdge]) -> EdgeTypeSchema: 174 """Generate schema for an edge model.""" 175 edge_type = model.__edge_type__ 176 from_labels = model.get_from_labels() 177 to_labels = model.get_to_labels() 178 179 # If from/to not specified, allow any labels 180 if not from_labels: 181 from_labels = list(self._node_models.keys()) 182 if not to_labels: 183 to_labels = list(self._node_models.keys()) 184 185 properties = {} 186 for field_name in model.get_property_fields(): 187 prop_schema = self._generate_property_schema(model, field_name) 188 properties[field_name] = prop_schema 189 190 return EdgeTypeSchema( 191 name=edge_type, 192 from_labels=from_labels, 193 to_labels=to_labels, 194 properties=properties, 195 ) 196 197 def generate(self) -> DatabaseSchema: 198 """Generate the complete database schema.""" 199 if self._schema is not None: 200 return self._schema 201 202 schema = DatabaseSchema() 203 204 # Generate label schemas 205 for label, model in self._node_models.items(): 206 schema.labels[label] = self._generate_label_schema(model) 207 208 # Generate edge type schemas 209 for edge_type_name, edge_model in self._edge_models.items(): 210 schema.edge_types[edge_type_name] = self._generate_edge_type_schema( 211 edge_model 212 ) 213 214 # Edge types implied by `Relationship(...)` fields, for which no 215 # explicit `UniEdge` model was registered. 216 # 217 # These used to declare *every* registered label on both endpoints, 218 # discarding the two things the declaration actually states: the model 219 # that owns the field, and the model its annotation points at. That is 220 # not merely imprecise -- an edge type whose endpoints span several 221 # labels makes `properties(b)` on an unlabelled `b` come back empty, so 222 # every relationship target loaded as a propertyless node. 223 for model in self._node_models.values(): 224 for rel_name, rel_config in model.get_relationship_fields().items(): 225 edge_type = rel_config.edge_type 226 if edge_type in self._edge_models: 227 # An explicit UniEdge model declares its own endpoints. 228 continue 229 230 owner = model.__label__ 231 target = self._relationship_target_label(model, rel_name) 232 if target is None: 233 # Unresolvable annotation (e.g. a forward reference to a 234 # model that was never registered). Fall back to the old 235 # permissive shape rather than guessing wrong. 236 src, dst = set(self._node_models), set(self._node_models) 237 elif rel_config.direction == "incoming": 238 src, dst = {target}, {owner} 239 elif rel_config.direction == "both": 240 src, dst = {owner, target}, {owner, target} 241 else: 242 src, dst = {owner}, {target} 243 244 existing = schema.edge_types.get(edge_type) 245 if existing is None: 246 schema.edge_types[edge_type] = EdgeTypeSchema( 247 name=edge_type, 248 from_labels=sorted(src), 249 to_labels=sorted(dst), 250 ) 251 else: 252 # Several models may declare the same edge type; the 253 # endpoint sets union. 254 existing.from_labels = sorted(set(existing.from_labels) | src) 255 existing.to_labels = sorted(set(existing.to_labels) | dst) 256 257 self._schema = schema 258 return schema 259 260 def _relationship_target_label(self, model: type[Any], rel_name: str) -> str | None: 261 """Resolve the label a relationship field points at. 262 263 The descriptor carries `target_type` as either a model class or an 264 unresolved forward-reference string; a string is matched against 265 registered models by class name, since `__label__` may differ from it. 266 Returns None when the target cannot be resolved. 267 """ 268 descriptor = getattr(model, rel_name, None) 269 target = getattr(descriptor, "target_type", None) 270 if target is None: 271 return None 272 if isinstance(target, str): 273 # A quoted annotation may be a bare name (`"Book"`) or a whole 274 # expression the metaclass could not evaluate (`"Bio | None"`, 275 # `"list[Book]"`). Pull identifiers out and match any of them 276 # against registered models, skipping typing spelling. 277 noise = {"None", "Optional", "Union", "list", "List", "set", "Set"} 278 for token in re.findall(r"[A-Za-z_][A-Za-z0-9_]*", target): 279 if token in noise: 280 continue 281 for label, candidate in self._node_models.items(): 282 if candidate.__name__ == token or label == token: 283 return label 284 return None 285 return getattr(target, "__label__", None) 286 287 def apply_to_database(self, db: uni_db.Uni) -> None: 288 """Apply the generated schema to a database using SchemaBuilder. 289 290 Uses db.schema() for atomic schema application with additive-only 291 semantics. Creates labels, edge types, properties, and indexes. 292 """ 293 schema = self.generate() 294 295 # Build the full schema using SchemaBuilder, skipping existing labels/edge types 296 builder = db.schema() 297 has_changes = False 298 299 for label, label_schema in schema.labels.items(): 300 if db.label_exists(label): 301 continue # Additive-only: skip existing labels 302 lb = builder.label(label) 303 for prop in label_schema.properties.values(): 304 # Check for vector type 305 if prop.data_type.startswith("vector:"): 306 dims = int(prop.data_type.split(":")[1]) 307 lb = lb.vector(prop.name, dims) 308 elif prop.nullable: 309 lb = lb.property_nullable(prop.name, prop.data_type) 310 else: 311 lb = lb.property(prop.name, prop.data_type) 312 313 # Add indexes (not vector — vector is handled by .vector()) 314 if prop.index_type and prop.index_type in ("btree", "hash"): 315 lb = lb.index(prop.name, prop.index_type) 316 builder = lb.done() 317 has_changes = True 318 319 for edge_type, edge_schema in schema.edge_types.items(): 320 if db.edge_type_exists(edge_type): 321 continue # Skip existing edge types 322 eb = builder.edge_type( 323 edge_type, edge_schema.from_labels, edge_schema.to_labels 324 ) 325 for prop in edge_schema.properties.values(): 326 if prop.nullable: 327 eb = eb.property_nullable(prop.name, prop.data_type) 328 else: 329 eb = eb.property(prop.name, prop.data_type) 330 builder = eb.done() 331 has_changes = True 332 333 if has_changes: 334 builder.apply() 335 336 # Create vector and fulltext indexes via schema builder 337 for label, label_schema in schema.labels.items(): 338 for prop in label_schema.properties.values(): 339 if prop.index_type == "vector": 340 metric = prop.metric or "l2" 341 try: 342 db.schema().label(label).index( 343 prop.name, {"type": "vector", "metric": metric} 344 ).apply() 345 except Exception: 346 pass # Index may already exist 347 elif prop.index_type == "sparse": 348 try: 349 cfg: dict[str, Any] = {"type": "sparse"} 350 if prop.data_type.startswith("sparse_vector:"): 351 cfg["dimensions"] = int(prop.data_type.split(":")[1]) 352 db.schema().label(label).index(prop.name, cfg).apply() 353 except Exception: 354 pass # Index may already exist 355 elif prop.index_type == "fulltext": 356 try: 357 db.schema().label(label).index(prop.name, "fulltext").apply() 358 except Exception: 359 pass # Index may already exist 360 361 async def async_apply_to_database(self, db: uni_db.AsyncUni) -> None: 362 """Apply the generated schema to an async database. 363 364 Async variant of apply_to_database using AsyncSchemaBuilder. 365 """ 366 schema = self.generate() 367 368 # Build the full schema using AsyncSchemaBuilder, skipping existing labels/edge types 369 builder = db.schema() 370 has_changes = False 371 372 for label, label_schema in schema.labels.items(): 373 if await db.label_exists(label): 374 continue 375 lb = builder.label(label) 376 for prop in label_schema.properties.values(): 377 if prop.data_type.startswith("vector:"): 378 dims = int(prop.data_type.split(":")[1]) 379 lb = lb.vector(prop.name, dims) 380 elif prop.nullable: 381 lb = lb.property_nullable(prop.name, prop.data_type) 382 else: 383 lb = lb.property(prop.name, prop.data_type) 384 385 if prop.index_type and prop.index_type in ("btree", "hash"): 386 lb = lb.index(prop.name, prop.index_type) 387 builder = lb.done() 388 has_changes = True 389 390 for edge_type, edge_schema in schema.edge_types.items(): 391 if await db.edge_type_exists(edge_type): 392 continue 393 eb = builder.edge_type( 394 edge_type, edge_schema.from_labels, edge_schema.to_labels 395 ) 396 for prop in edge_schema.properties.values(): 397 if prop.nullable: 398 eb = eb.property_nullable(prop.name, prop.data_type) 399 else: 400 eb = eb.property(prop.name, prop.data_type) 401 builder = eb.done() 402 has_changes = True 403 404 if has_changes: 405 await builder.apply() 406 407 # Create vector and fulltext indexes via schema builder 408 for label, label_schema in schema.labels.items(): 409 for prop in label_schema.properties.values(): 410 if prop.index_type == "vector": 411 metric = prop.metric or "l2" 412 try: 413 await ( 414 db.schema() 415 .label(label) 416 .index(prop.name, {"type": "vector", "metric": metric}) 417 .apply() 418 ) 419 except Exception: 420 pass # Index may already exist 421 elif prop.index_type == "sparse": 422 try: 423 cfg: dict[str, Any] = {"type": "sparse"} 424 if prop.data_type.startswith("sparse_vector:"): 425 cfg["dimensions"] = int(prop.data_type.split(":")[1]) 426 await db.schema().label(label).index(prop.name, cfg).apply() 427 except Exception: 428 pass # Index may already exist 429 elif prop.index_type == "fulltext": 430 try: 431 await ( 432 db.schema() 433 .label(label) 434 .index(prop.name, "fulltext") 435 .apply() 436 ) 437 except Exception: 438 pass # Index may already exist
Generates Uni database schema from registered models.
74 def register_node(self, model: type[UniNode]) -> None: 75 """Register a node model for schema generation.""" 76 label = model.__label__ 77 if not label: 78 raise SchemaError(f"Model {model.__name__} has no __label__", model) 79 self._node_models[label] = model 80 self._schema = None # Invalidate cached schema
Register a node model for schema generation.
82 def register_edge(self, model: type[UniEdge]) -> None: 83 """Register an edge model for schema generation.""" 84 edge_type = model.__edge_type__ 85 if not edge_type: 86 raise SchemaError(f"Model {model.__name__} has no __edge_type__", model) 87 self._edge_models[edge_type] = model 88 self._schema = None
Register an edge model for schema generation.
90 def register(self, *models: type[UniNode] | type[UniEdge]) -> None: 91 """Register multiple models.""" 92 for model in models: 93 if issubclass(model, UniEdge): 94 self.register_edge(model) 95 elif issubclass(model, UniNode): 96 self.register_node(model) 97 else: 98 raise SchemaError( 99 f"Model {model.__name__} must be a subclass of UniNode or UniEdge" 100 )
Register multiple models.
197 def generate(self) -> DatabaseSchema: 198 """Generate the complete database schema.""" 199 if self._schema is not None: 200 return self._schema 201 202 schema = DatabaseSchema() 203 204 # Generate label schemas 205 for label, model in self._node_models.items(): 206 schema.labels[label] = self._generate_label_schema(model) 207 208 # Generate edge type schemas 209 for edge_type_name, edge_model in self._edge_models.items(): 210 schema.edge_types[edge_type_name] = self._generate_edge_type_schema( 211 edge_model 212 ) 213 214 # Edge types implied by `Relationship(...)` fields, for which no 215 # explicit `UniEdge` model was registered. 216 # 217 # These used to declare *every* registered label on both endpoints, 218 # discarding the two things the declaration actually states: the model 219 # that owns the field, and the model its annotation points at. That is 220 # not merely imprecise -- an edge type whose endpoints span several 221 # labels makes `properties(b)` on an unlabelled `b` come back empty, so 222 # every relationship target loaded as a propertyless node. 223 for model in self._node_models.values(): 224 for rel_name, rel_config in model.get_relationship_fields().items(): 225 edge_type = rel_config.edge_type 226 if edge_type in self._edge_models: 227 # An explicit UniEdge model declares its own endpoints. 228 continue 229 230 owner = model.__label__ 231 target = self._relationship_target_label(model, rel_name) 232 if target is None: 233 # Unresolvable annotation (e.g. a forward reference to a 234 # model that was never registered). Fall back to the old 235 # permissive shape rather than guessing wrong. 236 src, dst = set(self._node_models), set(self._node_models) 237 elif rel_config.direction == "incoming": 238 src, dst = {target}, {owner} 239 elif rel_config.direction == "both": 240 src, dst = {owner, target}, {owner, target} 241 else: 242 src, dst = {owner}, {target} 243 244 existing = schema.edge_types.get(edge_type) 245 if existing is None: 246 schema.edge_types[edge_type] = EdgeTypeSchema( 247 name=edge_type, 248 from_labels=sorted(src), 249 to_labels=sorted(dst), 250 ) 251 else: 252 # Several models may declare the same edge type; the 253 # endpoint sets union. 254 existing.from_labels = sorted(set(existing.from_labels) | src) 255 existing.to_labels = sorted(set(existing.to_labels) | dst) 256 257 self._schema = schema 258 return schema
Generate the complete database schema.
287 def apply_to_database(self, db: uni_db.Uni) -> None: 288 """Apply the generated schema to a database using SchemaBuilder. 289 290 Uses db.schema() for atomic schema application with additive-only 291 semantics. Creates labels, edge types, properties, and indexes. 292 """ 293 schema = self.generate() 294 295 # Build the full schema using SchemaBuilder, skipping existing labels/edge types 296 builder = db.schema() 297 has_changes = False 298 299 for label, label_schema in schema.labels.items(): 300 if db.label_exists(label): 301 continue # Additive-only: skip existing labels 302 lb = builder.label(label) 303 for prop in label_schema.properties.values(): 304 # Check for vector type 305 if prop.data_type.startswith("vector:"): 306 dims = int(prop.data_type.split(":")[1]) 307 lb = lb.vector(prop.name, dims) 308 elif prop.nullable: 309 lb = lb.property_nullable(prop.name, prop.data_type) 310 else: 311 lb = lb.property(prop.name, prop.data_type) 312 313 # Add indexes (not vector — vector is handled by .vector()) 314 if prop.index_type and prop.index_type in ("btree", "hash"): 315 lb = lb.index(prop.name, prop.index_type) 316 builder = lb.done() 317 has_changes = True 318 319 for edge_type, edge_schema in schema.edge_types.items(): 320 if db.edge_type_exists(edge_type): 321 continue # Skip existing edge types 322 eb = builder.edge_type( 323 edge_type, edge_schema.from_labels, edge_schema.to_labels 324 ) 325 for prop in edge_schema.properties.values(): 326 if prop.nullable: 327 eb = eb.property_nullable(prop.name, prop.data_type) 328 else: 329 eb = eb.property(prop.name, prop.data_type) 330 builder = eb.done() 331 has_changes = True 332 333 if has_changes: 334 builder.apply() 335 336 # Create vector and fulltext indexes via schema builder 337 for label, label_schema in schema.labels.items(): 338 for prop in label_schema.properties.values(): 339 if prop.index_type == "vector": 340 metric = prop.metric or "l2" 341 try: 342 db.schema().label(label).index( 343 prop.name, {"type": "vector", "metric": metric} 344 ).apply() 345 except Exception: 346 pass # Index may already exist 347 elif prop.index_type == "sparse": 348 try: 349 cfg: dict[str, Any] = {"type": "sparse"} 350 if prop.data_type.startswith("sparse_vector:"): 351 cfg["dimensions"] = int(prop.data_type.split(":")[1]) 352 db.schema().label(label).index(prop.name, cfg).apply() 353 except Exception: 354 pass # Index may already exist 355 elif prop.index_type == "fulltext": 356 try: 357 db.schema().label(label).index(prop.name, "fulltext").apply() 358 except Exception: 359 pass # Index may already exist
Apply the generated schema to a database using SchemaBuilder.
Uses db.schema() for atomic schema application with additive-only semantics. Creates labels, edge types, properties, and indexes.
361 async def async_apply_to_database(self, db: uni_db.AsyncUni) -> None: 362 """Apply the generated schema to an async database. 363 364 Async variant of apply_to_database using AsyncSchemaBuilder. 365 """ 366 schema = self.generate() 367 368 # Build the full schema using AsyncSchemaBuilder, skipping existing labels/edge types 369 builder = db.schema() 370 has_changes = False 371 372 for label, label_schema in schema.labels.items(): 373 if await db.label_exists(label): 374 continue 375 lb = builder.label(label) 376 for prop in label_schema.properties.values(): 377 if prop.data_type.startswith("vector:"): 378 dims = int(prop.data_type.split(":")[1]) 379 lb = lb.vector(prop.name, dims) 380 elif prop.nullable: 381 lb = lb.property_nullable(prop.name, prop.data_type) 382 else: 383 lb = lb.property(prop.name, prop.data_type) 384 385 if prop.index_type and prop.index_type in ("btree", "hash"): 386 lb = lb.index(prop.name, prop.index_type) 387 builder = lb.done() 388 has_changes = True 389 390 for edge_type, edge_schema in schema.edge_types.items(): 391 if await db.edge_type_exists(edge_type): 392 continue 393 eb = builder.edge_type( 394 edge_type, edge_schema.from_labels, edge_schema.to_labels 395 ) 396 for prop in edge_schema.properties.values(): 397 if prop.nullable: 398 eb = eb.property_nullable(prop.name, prop.data_type) 399 else: 400 eb = eb.property(prop.name, prop.data_type) 401 builder = eb.done() 402 has_changes = True 403 404 if has_changes: 405 await builder.apply() 406 407 # Create vector and fulltext indexes via schema builder 408 for label, label_schema in schema.labels.items(): 409 for prop in label_schema.properties.values(): 410 if prop.index_type == "vector": 411 metric = prop.metric or "l2" 412 try: 413 await ( 414 db.schema() 415 .label(label) 416 .index(prop.name, {"type": "vector", "metric": metric}) 417 .apply() 418 ) 419 except Exception: 420 pass # Index may already exist 421 elif prop.index_type == "sparse": 422 try: 423 cfg: dict[str, Any] = {"type": "sparse"} 424 if prop.data_type.startswith("sparse_vector:"): 425 cfg["dimensions"] = int(prop.data_type.split(":")[1]) 426 await db.schema().label(label).index(prop.name, cfg).apply() 427 except Exception: 428 pass # Index may already exist 429 elif prop.index_type == "fulltext": 430 try: 431 await ( 432 db.schema() 433 .label(label) 434 .index(prop.name, "fulltext") 435 .apply() 436 ) 437 except Exception: 438 pass # Index may already exist
Apply the generated schema to an async database.
Async variant of apply_to_database using AsyncSchemaBuilder.
58@dataclass 59class DatabaseSchema: 60 """Complete database schema generated from models.""" 61 62 labels: dict[str, LabelSchema] = field(default_factory=dict) 63 edge_types: dict[str, EdgeTypeSchema] = field(default_factory=dict)
Complete database schema generated from models.
40@dataclass 41class LabelSchema: 42 """Schema for a vertex label.""" 43 44 name: str 45 properties: dict[str, PropertySchema] = field(default_factory=dict)
Schema for a vertex label.
48@dataclass 49class EdgeTypeSchema: 50 """Schema for an edge type.""" 51 52 name: str 53 from_labels: list[str] = field(default_factory=list) 54 to_labels: list[str] = field(default_factory=list) 55 properties: dict[str, PropertySchema] = field(default_factory=dict)
Schema for an edge type.
27@dataclass 28class PropertySchema: 29 """Schema for a single property.""" 30 31 name: str 32 data_type: str 33 nullable: bool = False 34 index_type: str | None = None 35 unique: bool = False 36 tokenizer: str | None = None 37 metric: str | None = None
Schema for a single property.
441def generate_schema(*models: type[UniNode] | type[UniEdge]) -> DatabaseSchema: 442 """Generate a database schema from the given models.""" 443 generator = SchemaGenerator() 444 generator.register(*models) 445 return generator.generate()
Generate a database schema from the given models.
15class UniDatabase: 16 """ 17 Thin wrapper around uni-db UniBuilder for ergonomic database creation. 18 19 Example: 20 >>> db = UniDatabase.open("./path").cache_size(1024*1024).build() 21 >>> db = UniDatabase.temporary().build() 22 >>> db = UniDatabase.in_memory().build() 23 """ 24 25 def __init__(self, builder: uni_db.UniBuilder) -> None: 26 self._builder = builder 27 28 @classmethod 29 def open(cls, path: str) -> UniDatabase: 30 """Open or create a database at the given path.""" 31 import uni_db 32 33 return cls(uni_db.UniBuilder.open(path)) 34 35 @classmethod 36 def create(cls, path: str) -> UniDatabase: 37 """Create a new database at the given path.""" 38 import uni_db 39 40 return cls(uni_db.UniBuilder.create(path)) 41 42 @classmethod 43 def open_existing(cls, path: str) -> UniDatabase: 44 """Open an existing database (must already exist).""" 45 import uni_db 46 47 return cls(uni_db.UniBuilder.open_existing(path)) 48 49 @classmethod 50 def temporary(cls) -> UniDatabase: 51 """Create an ephemeral in-memory database.""" 52 import uni_db 53 54 return cls(uni_db.UniBuilder.temporary()) 55 56 @classmethod 57 def in_memory(cls) -> UniDatabase: 58 """Create a persistent in-memory database.""" 59 import uni_db 60 61 return cls(uni_db.UniBuilder.in_memory()) 62 63 def cache_size(self, bytes_: int) -> UniDatabase: 64 """Set the cache size in bytes.""" 65 self._builder = self._builder.cache_size(bytes_) 66 return self 67 68 def parallelism(self, n: int) -> UniDatabase: 69 """Set the parallelism level.""" 70 self._builder = self._builder.parallelism(n) 71 return self 72 73 def build(self) -> uni_db.Uni: 74 """Build and return the database instance.""" 75 return self._builder.build()
Thin wrapper around uni-db UniBuilder for ergonomic database creation.
Example:
db = UniDatabase.open("./path").cache_size(1024*1024).build() db = UniDatabase.temporary().build() db = UniDatabase.in_memory().build()
28 @classmethod 29 def open(cls, path: str) -> UniDatabase: 30 """Open or create a database at the given path.""" 31 import uni_db 32 33 return cls(uni_db.UniBuilder.open(path))
Open or create a database at the given path.
35 @classmethod 36 def create(cls, path: str) -> UniDatabase: 37 """Create a new database at the given path.""" 38 import uni_db 39 40 return cls(uni_db.UniBuilder.create(path))
Create a new database at the given path.
42 @classmethod 43 def open_existing(cls, path: str) -> UniDatabase: 44 """Open an existing database (must already exist).""" 45 import uni_db 46 47 return cls(uni_db.UniBuilder.open_existing(path))
Open an existing database (must already exist).
49 @classmethod 50 def temporary(cls) -> UniDatabase: 51 """Create an ephemeral in-memory database.""" 52 import uni_db 53 54 return cls(uni_db.UniBuilder.temporary())
Create an ephemeral in-memory database.
56 @classmethod 57 def in_memory(cls) -> UniDatabase: 58 """Create a persistent in-memory database.""" 59 import uni_db 60 61 return cls(uni_db.UniBuilder.in_memory())
Create a persistent in-memory database.
63 def cache_size(self, bytes_: int) -> UniDatabase: 64 """Set the cache size in bytes.""" 65 self._builder = self._builder.cache_size(bytes_) 66 return self
Set the cache size in bytes.
78class AsyncUniDatabase: 79 """ 80 Thin wrapper around uni-db AsyncUniBuilder for ergonomic async database creation. 81 82 Example: 83 >>> db = await AsyncUniDatabase.open("./path").build() 84 >>> db = await AsyncUniDatabase.temporary().build() 85 """ 86 87 def __init__(self, builder: uni_db.AsyncUniBuilder) -> None: 88 self._builder = builder 89 90 @classmethod 91 def open(cls, path: str) -> AsyncUniDatabase: 92 """Open or create a database at the given path.""" 93 import uni_db 94 95 return cls(uni_db.AsyncUniBuilder.open(path)) 96 97 @classmethod 98 def temporary(cls) -> AsyncUniDatabase: 99 """Create an ephemeral in-memory database.""" 100 import uni_db 101 102 return cls(uni_db.AsyncUniBuilder.temporary()) 103 104 @classmethod 105 def in_memory(cls) -> AsyncUniDatabase: 106 """Create a persistent in-memory database.""" 107 import uni_db 108 109 return cls(uni_db.AsyncUniBuilder.in_memory()) 110 111 def cache_size(self, bytes_: int) -> AsyncUniDatabase: 112 """Set the cache size in bytes.""" 113 self._builder = self._builder.cache_size(bytes_) 114 return self 115 116 def parallelism(self, n: int) -> AsyncUniDatabase: 117 """Set the parallelism level.""" 118 self._builder = self._builder.parallelism(n) 119 return self 120 121 async def build(self) -> uni_db.AsyncUni: 122 """Build and return the async database instance.""" 123 return await self._builder.build()
Thin wrapper around uni-db AsyncUniBuilder for ergonomic async database creation.
Example:
db = await AsyncUniDatabase.open("./path").build() db = await AsyncUniDatabase.temporary().build()
90 @classmethod 91 def open(cls, path: str) -> AsyncUniDatabase: 92 """Open or create a database at the given path.""" 93 import uni_db 94 95 return cls(uni_db.AsyncUniBuilder.open(path))
Open or create a database at the given path.
97 @classmethod 98 def temporary(cls) -> AsyncUniDatabase: 99 """Create an ephemeral in-memory database.""" 100 import uni_db 101 102 return cls(uni_db.AsyncUniBuilder.temporary())
Create an ephemeral in-memory database.
104 @classmethod 105 def in_memory(cls) -> AsyncUniDatabase: 106 """Create a persistent in-memory database.""" 107 import uni_db 108 109 return cls(uni_db.AsyncUniBuilder.in_memory())
Create a persistent in-memory database.
111 def cache_size(self, bytes_: int) -> AsyncUniDatabase: 112 """Set the cache size in bytes.""" 113 self._builder = self._builder.cache_size(bytes_) 114 return self
Set the cache size in bytes.
40def before_create(func: F) -> F: 41 """ 42 Mark a method to be called before the entity is created in the database. 43 44 The method is called after validation but before the INSERT operation. 45 Useful for setting timestamps, generating IDs, or final validation. 46 47 Example: 48 >>> class Person(UniNode): 49 ... name: str 50 ... created_at: datetime | None = None 51 ... 52 ... @before_create 53 ... def set_created_at(self): 54 ... self.created_at = datetime.now() 55 """ 56 return _mark_hook(_BEFORE_CREATE)(func)
Mark a method to be called before the entity is created in the database.
The method is called after validation but before the INSERT operation. Useful for setting timestamps, generating IDs, or final validation.
Example:
class Person(UniNode): ... name: str ... created_at: datetime | None = None ... ... @before_create ... def set_created_at(self): ... self.created_at = datetime.now()
59def after_create(func: F) -> F: 60 """ 61 Mark a method to be called after the entity is created in the database. 62 63 The method is called after the INSERT operation completes successfully. 64 The entity will have its vid/eid assigned at this point. 65 66 Example: 67 >>> class Person(UniNode): 68 ... name: str 69 ... 70 ... @after_create 71 ... def log_creation(self): 72 ... logger.info(f"Created person {self.name} with vid={self.vid}") 73 """ 74 return _mark_hook(_AFTER_CREATE)(func)
Mark a method to be called after the entity is created in the database.
The method is called after the INSERT operation completes successfully. The entity will have its vid/eid assigned at this point.
Example:
class Person(UniNode): ... name: str ... ... @after_create ... def log_creation(self): ... logger.info(f"Created person {self.name} with vid={self.vid}")
77def before_update(func: F) -> F: 78 """ 79 Mark a method to be called before the entity is updated in the database. 80 81 The method is called before the UPDATE operation. 82 Useful for validation or updating timestamps. 83 84 Example: 85 >>> class Person(UniNode): 86 ... name: str 87 ... updated_at: datetime | None = None 88 ... 89 ... @before_update 90 ... def validate_and_timestamp(self): 91 ... if not self.name: 92 ... raise ValueError("Name cannot be empty") 93 ... self.updated_at = datetime.now() 94 """ 95 return _mark_hook(_BEFORE_UPDATE)(func)
Mark a method to be called before the entity is updated in the database.
The method is called before the UPDATE operation. Useful for validation or updating timestamps.
Example:
class Person(UniNode): ... name: str ... updated_at: datetime | None = None ... ... @before_update ... def validate_and_timestamp(self): ... if not self.name: ... raise ValueError("Name cannot be empty") ... self.updated_at = datetime.now()
98def after_update(func: F) -> F: 99 """ 100 Mark a method to be called after the entity is updated in the database. 101 102 The method is called after the UPDATE operation completes successfully. 103 104 Example: 105 >>> class Person(UniNode): 106 ... name: str 107 ... 108 ... @after_update 109 ... def notify_change(self): 110 ... events.emit("person_updated", self.vid) 111 """ 112 return _mark_hook(_AFTER_UPDATE)(func)
Mark a method to be called after the entity is updated in the database.
The method is called after the UPDATE operation completes successfully.
Example:
class Person(UniNode): ... name: str ... ... @after_update ... def notify_change(self): ... events.emit("person_updated", self.vid)
115def before_delete(func: F) -> F: 116 """ 117 Mark a method to be called before the entity is deleted from the database. 118 119 The method is called before the DELETE operation. 120 Useful for cleanup or validation. 121 122 Example: 123 >>> class Person(UniNode): 124 ... name: str 125 ... 126 ... @before_delete 127 ... def cleanup(self): 128 ... # Remove related data 129 ... pass 130 """ 131 return _mark_hook(_BEFORE_DELETE)(func)
Mark a method to be called before the entity is deleted from the database.
The method is called before the DELETE operation. Useful for cleanup or validation.
Example:
class Person(UniNode): ... name: str ... ... @before_delete ... def cleanup(self): ... # Remove related data ... pass
134def after_delete(func: F) -> F: 135 """ 136 Mark a method to be called after the entity is deleted from the database. 137 138 The method is called after the DELETE operation completes successfully. 139 The entity's vid/eid will be cleared at this point. 140 141 Example: 142 >>> class Person(UniNode): 143 ... name: str 144 ... 145 ... @after_delete 146 ... def log_deletion(self): 147 ... logger.info(f"Deleted person {self.name}") 148 """ 149 return _mark_hook(_AFTER_DELETE)(func)
Mark a method to be called after the entity is deleted from the database.
The method is called after the DELETE operation completes successfully. The entity's vid/eid will be cleared at this point.
Example:
class Person(UniNode): ... name: str ... ... @after_delete ... def log_deletion(self): ... logger.info(f"Deleted person {self.name}")
152def before_load(func: F) -> F: 153 """ 154 Mark a method to be called before the entity is loaded from the database. 155 156 This is a class method that receives the raw property dictionary. 157 Can be used to transform data before model instantiation. 158 159 Example: 160 >>> class Person(UniNode): 161 ... name: str 162 ... 163 ... @classmethod 164 ... @before_load 165 ... def transform_data(cls, props: dict) -> dict: 166 ... # Normalize name 167 ... if 'name' in props: 168 ... props['name'] = props['name'].strip() 169 ... return props 170 """ 171 return _mark_hook(_BEFORE_LOAD)(func)
Mark a method to be called before the entity is loaded from the database.
This is a class method that receives the raw property dictionary. Can be used to transform data before model instantiation.
Example:
class Person(UniNode): ... name: str ... ... @classmethod ... @before_load ... def transform_data(cls, props: dict) -> dict: ... # Normalize name ... if 'name' in props: ... props['name'] = props['name'].strip() ... return props
174def after_load(func: F) -> F: 175 """ 176 Mark a method to be called after the entity is loaded from the database. 177 178 The method is called after the entity is instantiated from database data. 179 Useful for computing derived values or initializing non-persisted state. 180 181 Example: 182 >>> class Person(UniNode): 183 ... first_name: str 184 ... last_name: str 185 ... full_name: str | None = None 186 ... 187 ... @after_load 188 ... def compute_full_name(self): 189 ... self.full_name = f"{self.first_name} {self.last_name}" 190 """ 191 return _mark_hook(_AFTER_LOAD)(func)
Mark a method to be called after the entity is loaded from the database.
The method is called after the entity is instantiated from database data. Useful for computing derived values or initializing non-persisted state.
Example:
class Person(UniNode): ... first_name: str ... last_name: str ... full_name: str | None = None ... ... @after_load ... def compute_full_name(self): ... self.full_name = f"{self.first_name} {self.last_name}"
Base exception for all uni-pydantic errors.
19class SchemaError(UniPydanticError): 20 """Error related to schema definition or generation.""" 21 22 def __init__(self, message: str, model: type | None = None) -> None: 23 self.model = model 24 super().__init__(message)
Error related to schema definition or generation.
27class TypeMappingError(SchemaError): 28 """Error mapping Python type to Uni DataType.""" 29 30 def __init__(self, python_type: Any, message: str | None = None) -> None: 31 self.python_type = python_type 32 msg = message or f"Cannot map Python type {python_type!r} to Uni DataType" 33 super().__init__(msg)
Error mapping Python type to Uni DataType.
Validation error for model instances.
Error related to session operations.
44class NotRegisteredError(SessionError): 45 """Model type not registered with session.""" 46 47 def __init__(self, model: type[UniNode] | type[UniEdge]) -> None: 48 self.model = model 49 super().__init__( 50 f"Model {model.__name__!r} is not registered with this session. " 51 f"Call session.register({model.__name__}) first." 52 )
Model type not registered with session.
55class NotPersisted(SessionError): 56 """Operation requires a persisted entity.""" 57 58 def __init__(self, entity: UniNode | UniEdge) -> None: 59 self.entity = entity 60 super().__init__( 61 f"Entity {entity!r} is not persisted. Call session.add() and commit() first." 62 )
Operation requires a persisted entity.
Entity is not tracked by this session.
Error related to transaction operations.
Error executing a query.
Error related to relationship operations.
81class LazyLoadError(RelationshipError): 82 """Error lazy-loading a relationship.""" 83 84 def __init__(self, field_name: str, reason: str) -> None: 85 self.field_name = field_name 86 super().__init__(f"Cannot lazy-load relationship '{field_name}': {reason}")
Error lazy-loading a relationship.
89class BulkLoadError(UniPydanticError): 90 """A bulk load failed before its commit point: nothing of it was applied. 91 92 Retrying the load is safe. A load that *did* reach its commit point is never 93 reported as this error: ``uni_db.UniBulkCommitIncompleteError`` (committed, 94 completed on the next open -- do not retry) and 95 ``uni_db.UniBulkCommitOutcomeUnknownError`` (check 96 ``bulk_load_applied(load_id)`` before retrying) propagate unchanged. 97 """
A bulk load failed before its commit point: nothing of it was applied.
Retrying the load is safe. A load that did reach its commit point is never
reported as this error: uni_db.UniBulkCommitIncompleteError (committed,
completed on the next open -- do not retry) and
uni_db.UniBulkCommitOutcomeUnknownError (check
bulk_load_applied(load_id) before retrying) propagate unchanged.
100class CypherInjectionError(QueryError): 101 """Property name validation failure — potential Cypher injection.""" 102 103 def __init__(self, name: str, reason: str | None = None) -> None: 104 self.name = name 105 msg = reason or f"Invalid property name {name!r}: possible Cypher injection" 106 super().__init__(msg)
Property name validation failure — potential Cypher injection.