{"id":33620554,"url":"https://github.com/ds1sqe/type-bridge","last_synced_at":"2026-03-04T12:05:00.463Z","repository":{"id":321339278,"uuid":"1085407082","full_name":"ds1sqe/type-bridge","owner":"ds1sqe","description":"A modern, Pythonic ORM for TypeDB with an Attribute-based API that aligns with TypeDB's type system.","archived":false,"fork":false,"pushed_at":"2026-02-01T08:51:32.000Z","size":1493,"stargazers_count":18,"open_issues_count":2,"forks_count":4,"subscribers_count":0,"default_branch":"master","last_synced_at":"2026-02-01T19:17:34.354Z","etag":null,"topics":["graphdatabase","graphdb","orm","pydantic","python","typedb","typeql"],"latest_commit_sha":null,"homepage":"https://pypi.org/project/type-bridge/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ds1sqe.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2025-10-29T02:03:19.000Z","updated_at":"2026-02-01T08:51:21.000Z","dependencies_parsed_at":"2025-10-29T06:12:42.768Z","dependency_job_id":"6e4fe420-5d83-4259-8207-17a31d7455f0","html_url":"https://github.com/ds1sqe/type-bridge","commit_stats":null,"previous_names":["ds1sqe/type-bridge"],"tags_count":26,"template":false,"template_full_name":null,"purl":"pkg:github/ds1sqe/type-bridge","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ds1sqe%2Ftype-bridge","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ds1sqe%2Ftype-bridge/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ds1sqe%2Ftype-bridge/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ds1sqe%2Ftype-bridge/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ds1sqe","download_url":"https://codeload.github.com/ds1sqe/type-bridge/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ds1sqe%2Ftype-bridge/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29252682,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-08T22:49:53.206Z","status":"ssl_error","status_checked_at":"2026-02-08T22:49:51.384Z","response_time":57,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graphdatabase","graphdb","orm","pydantic","python","typedb","typeql"],"created_at":"2025-12-01T13:00:29.630Z","updated_at":"2026-02-20T06:04:38.288Z","avatar_url":"https://github.com/ds1sqe.png","language":"Python","readme":"# TypeBridge\n\n[![CI](https://github.com/ds1sqe/type-bridge/actions/workflows/ci.yml/badge.svg)](https://github.com/ds1sqe/type-bridge/actions/workflows/ci.yml)\n[![PyPI](https://img.shields.io/pypi/v/type-bridge.svg)](https://pypi.org/project/type-bridge/)\n[![Downloads](https://img.shields.io/pypi/dm/type-bridge.svg)](https://pypi.org/project/type-bridge/)\n[![Python 3.13+](https://img.shields.io/badge/python-3.13+-blue.svg)](https://www.python.org/downloads/)\n[![TypeDB 3.x](https://img.shields.io/badge/TypeDB-3.x-orange.svg)](https://typedb.com/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)\n[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)\n\nA modern, Pythonic ORM for [TypeDB](https://github.com/typedb/typedb) with an Attribute-based API that aligns with TypeDB's type system.\n\n## Features\n\n- **True TypeDB Semantics**: Attributes are independent types that entities and relations own\n- **Complete Type Support**: All TypeDB value types - String, Integer, Double, Decimal, Boolean, Date, DateTime, DateTimeTZ, Duration\n- **Flag System**: Clean API for `@key`, `@unique`, and `@card` annotations\n- **Flexible Cardinality**: Express any cardinality constraint with `Card(min, max)`\n- **Pydantic Integration**: Built on Pydantic v2 for automatic validation, serialization, and type safety\n- **Type-Safe**: Full Python type hints and IDE autocomplete support\n- **Declarative Models**: Define entities and relations using Python classes\n- **Automatic Schema Generation**: Generate TypeQL schemas from your Python models\n- **Code Generator**: Generate Python models from TypeQL schema files (`.tql`)\n- **Schema Conflict Detection**: Automatic detection of breaking schema changes to prevent data loss\n- **Data Validation**: Automatic type checking and coercion via Pydantic, including keyword validation\n- **JSON Support**: Seamless JSON serialization/deserialization\n- **CRUD Operations**: Full CRUD with fetching API (get, filter, all, update) for entities and relations\n- **Chainable Operations**: Filter, delete, and bulk update with method chaining and lambda functions\n- **Query Builder**: Pythonic interface for building TypeQL queries\n- **Multi-player Roles**: A single role can accept multiple entity types via `Role.multi(...)`\n- **Transaction Context**: Share transactions across multiple operations with `TransactionContext`\n- **Django-style Lookups**: Filter with `__contains`, `__gt`, `__in`, `__isnull` and more\n- **Dict Helpers**: `to_dict()` and `from_dict()` for easy serialization and API integration\n- **Bulk Operations**: `update_many()` and `delete_many()` for efficient batch processing\n\n## Installation\n\n```bash\n# Clone the repository\ngit clone https://github.com/ds1sqe/type-bridge.git\ncd type_bridge\n\n# Install with uv\nuv sync\n\n# Or with pip\npip install -e .\n\n# Or add to project with uv\nuv add type-bridge\n```\n\n## Quick Start\n\n### 1. Define Attribute Types\n\nTypeBridge supports all TypeDB value types:\n\n```python\nfrom type_bridge import String, Integer, Double, Decimal, Boolean, Date, DateTime, DateTimeTZ, Duration\n\nclass Name(String):\n    pass\n\nclass Age(Integer):\n    pass\n\nclass Balance(Decimal):  # High-precision fixed-point numbers\n    pass\n\nclass BirthDate(Date):  # Date-only values\n    pass\n\nclass UpdatedAt(DateTimeTZ):  # Timezone-aware datetime\n    pass\n```\n\n**Configuring Attribute Type Names:**\n\n```python\nfrom type_bridge import AttributeFlags, TypeNameCase\n\n# Option 1: Explicit name override\nclass Name(String):\n    flags = AttributeFlags(name=\"person_name\")\n# TypeDB: attribute person_name, value string;\n\n# Option 2: Case formatting\nclass UserEmail(String):\n    flags = AttributeFlags(case=TypeNameCase.SNAKE_CASE)\n# TypeDB: attribute user_email, value string;\n```\n\n### 2. Define Entities\n\n```python\nfrom type_bridge import Entity, TypeFlags, Flag, Key, Card\n\nclass Person(Entity):\n    flags = TypeFlags(name=\"person\")  # Optional, defaults to lowercase class name\n\n    # Use Flag() for key/unique markers and Card for cardinality\n    name: Name = Flag(Key)                   # @key (implies @card(1..1))\n    age: Age | None = None                   # @card(0..1) - optional field (explicit default)\n    email: Email                             # @card(1..1) - default cardinality\n    tags: list[Tag] = Flag(Card(min=2))      # @card(2..) - two or more (unordered set)\n```\n\n\u003e **Note**: `list[Type]` represents an **unordered set** in TypeDB. TypeDB has no list type - order is never preserved.\n\n### 3. Create Instances\n\n```python\n# Create entity instances with attribute values (keyword arguments required)\nalice = Person(\n    name=Name(\"Alice\"),\n    age=Age(30),\n    email=Email(\"alice@example.com\")\n)\n\n# Pydantic handles validation and type coercion automatically\nprint(alice.name.value)  # \"Alice\"\n```\n\n### 4. Work with Data\n\n```python\nfrom type_bridge import Database, SchemaManager\n\n# Connect to database\ndb = Database(address=\"localhost:1729\", database=\"mydb\")\ndb.connect()\ndb.create_database()\n\n# Define schema\nschema_manager = SchemaManager(db)\nschema_manager.register(Person, Company, Employment)\nschema_manager.sync_schema()\n\n# Insert entities - use typed instances\nalice = Person(\n    name=Name(\"Alice\"),\n    age=Age(30),\n    email=Email(\"alice@example.com\")\n)\nPerson.manager(db).insert(alice)\n\n# Or use PUT for idempotent insert (safe to run multiple times!)\nPerson.manager(db).put(alice)  # Won't create duplicates\n\n# Insert relations - use typed instances\nemployment = Employment(\n    employee=alice,\n    employer=techcorp,\n    position=Position(\"Engineer\"),\n    salary=Salary(100000)\n)\nEmployment.manager(db).insert(employment)\n```\n\n### 5. Cardinality Constraints\n\n```python\nfrom type_bridge import Card, Flag\n\nclass Person(Entity):\n    flags = TypeFlags(name=\"person\")\n\n    # Cardinality options:\n    name: Name                              # @card(1..1) - exactly one (default)\n    age: Age | None = None                  # @card(0..1) - zero or one (explicit default)\n    tags: list[Tag] = Flag(Card(min=2))     # @card(2..) - two or more (unbounded)\n    skills: list[Skill] = Flag(Card(max=5)) # @card(0..5) - zero to five\n    jobs: list[Job] = Flag(Card(1, 3))      # @card(1..3) - one to three\n```\n\n### 6. Define Relations\n\n```python\nfrom type_bridge import Relation, TypeFlags, Role\n\nclass Employment(Relation):\n    flags = TypeFlags(name=\"employment\")\n\n    # Define roles with type-safe Role[T] syntax\n    employee: Role[Person] = Role(\"employee\", Person)\n    employer: Role[Company] = Role(\"employer\", Company)\n\n    # Relations can own attributes\n    position: Position                   # @card(1..1)\n    salary: Salary | None = None         # @card(0..1) - explicit default\n\n# Multi-player role example (one role, multiple entity types)\nclass Document(Entity):\n    flags = TypeFlags(name=\"document\")\n    name: Name = Flag(Key)\n\nclass Email(Entity):\n    flags = TypeFlags(name=\"email\")\n    name: Name = Flag(Key)\n\nclass Trace(Relation):\n    flags = TypeFlags(name=\"trace\")\n    origin: Role[Document | Email] = Role.multi(\"origin\", Document, Email)\n```\n\n### 7. Using Python Inheritance\n\n```python\nclass Animal(Entity):\n    flags = TypeFlags(abstract=True)  # Abstract entity\n    name: Name\n\nclass Dog(Animal):  # Automatically: dog sub animal in TypeDB\n    breed: Breed\n```\n\n### 8. Generate Models from TypeQL Schema\n\nInstead of writing Python classes manually, generate them from your TypeQL schema:\n\n```bash\n# Generate Python models from a schema file\npython -m type_bridge.generator schema.tql -o ./myapp/models/\n```\n\nOr programmatically:\n\n```python\nfrom type_bridge.generator import generate_models\n\ngenerate_models(\"schema.tql\", \"./myapp/models/\")\n```\n\nThis generates a complete Python package:\n\n```text\nmyapp/models/\n├── __init__.py      # Package exports, SCHEMA_VERSION, schema_text()\n├── attributes.py    # Attribute class definitions\n├── entities.py      # Entity class definitions\n├── relations.py     # Relation class definitions\n├── registry.py      # Schema metadata, JSON Schema fragments, lookup functions\n└── schema.tql       # Copy of original schema\n```\n\nThe generator supports:\n\n- Entity/relation/attribute inheritance (`sub` keyword)\n- `@key`, `@unique`, `@card` constraints (including on `plays` and `relates`)\n- `@regex` and `@values` constraints\n- `@abstract` and `@independent` types\n- `@range(min..max)` constraints (integers, floats, dates, datetimes)\n- Role overrides (`relates X as Y`)\n- TypeDB function definitions with precise return type hints\n- Registry module generation for schema metadata and JSON Schema fragments\n- Both `#` and `//` comment styles\n\nSee the [Code Generator guide](https://ds1sqe.github.io/type-bridge/guide/generator/) for full documentation.\n\n## Documentation\n\n**[https://ds1sqe.github.io/type-bridge/](https://ds1sqe.github.io/type-bridge/)** — Full documentation site with user guide, API reference, and development guides.\n\n- [Getting Started](https://ds1sqe.github.io/type-bridge/getting-started/) — Installation and quick start\n- [User Guide](https://ds1sqe.github.io/type-bridge/guide/) — Attributes, entities, relations, CRUD, queries, and more\n- [API Reference](https://ds1sqe.github.io/type-bridge/reference/) — Auto-generated from source docstrings\n- [Development](https://ds1sqe.github.io/type-bridge/development/) — Setup, testing, and internals\n\n## Pydantic Integration\n\nTypeBridge is built on Pydantic v2, giving you powerful features:\n\n```python\nclass Person(Entity):\n    flags = TypeFlags(name=\"person\")\n    name: Name = Flag(Key)\n    age: Age\n\n# Automatic validation and type coercion\nalice = Person(name=Name(\"Alice\"), age=Age(30))\n\n# JSON serialization\njson_data = alice.model_dump_json()\n\n# JSON deserialization\nbob = Person.model_validate_json('{\"name\": \"Bob\", \"age\": 25}')\n\n# Model copying\nalice_copy = alice.model_copy(update={\"age\": Age(31)})\n```\n\n## Running Examples\n\nTypeBridge includes comprehensive examples organized by complexity:\n\n```bash\n# Basic CRUD examples (start here!)\nuv run python examples/basic/crud_01_define.py  # Schema definition\nuv run python examples/basic/crud_02_insert.py  # Data insertion\nuv run python examples/basic/crud_03_read.py    # Fetching API\nuv run python examples/basic/crud_04_update.py  # Update operations\n\n# Additional basic examples\nuv run python examples/basic/crud_05_filter.py    # Advanced filtering\nuv run python examples/basic/crud_06_aggregate.py # Aggregations\nuv run python examples/basic/crud_07_delete.py    # Delete operations\nuv run python examples/basic/crud_08_put.py       # Idempotent PUT operations\n\n# Advanced examples\nuv run python examples/advanced/schema_01_manager.py       # Schema operations\nuv run python examples/advanced/schema_02_comparison.py    # Schema comparison\nuv run python examples/advanced/schema_03_conflict.py      # Conflict detection\nuv run python examples/advanced/features_01_pydantic.py    # Pydantic integration\nuv run python examples/advanced/features_02_type_safety.py # Literal types\nuv run python examples/advanced/query_01_expressions.py    # Query expressions\nuv run python examples/advanced/validation_01_reserved_words.py  # Keyword validation\n```\n\n## Running Tests\n\nTypeBridge uses a two-tier testing approach with **100% test pass rate**:\n\n```bash\n# Unit tests (fast, no external dependencies) - DEFAULT\nuv run pytest                              # Run unit tests (0.3s)\nuv run pytest tests/unit/attributes/ -v   # Test all 9 attribute types\nuv run pytest tests/unit/core/ -v         # Test core functionality\nuv run pytest tests/unit/flags/ -v        # Test flag system\nuv run pytest tests/unit/expressions/ -v  # Test query expressions\n\n# Integration tests (requires running TypeDB server)\n# Option 1: Use Docker (recommended)\n./test-integration.sh                     # Starts Docker, runs tests, stops Docker\n\n# Option 2: Use existing TypeDB server\nUSE_DOCKER=false uv run pytest -m integration -v  # Run integration tests (~60s)\n\n# Run specific integration test categories\nuv run pytest tests/integration/crud/entities/ -v      # Entity CRUD tests\nuv run pytest tests/integration/crud/relations/ -v    # Relation CRUD tests\nuv run pytest tests/integration/queries/ -v           # Query expression tests\nuv run pytest tests/integration/schema/ -v            # Schema operation tests\n\n# All tests\nuv run pytest -m \"\" -v                    # Run all tests\n./test.sh                                 # Run full test suite with detailed output\n./check.sh                                # Run linting and type checking\n```\n\n## Rust Core\n\nThe project includes a Rust core (`type-bridge-core/`) that provides high-performance implementations of the query compiler, validation engine, and value coercer. When the native extension is installed, Python automatically delegates to Rust for:\n\n- **Validation** — ~8.6x faster schema-aware query validation\n- **Compilation** — ~1.3x faster AST-to-TypeQL compilation via serde bridge\n- **Value coercion** — Type-safe value coercion and TypeQL literal formatting\n\nThe Rust core is a Cargo workspace with three crates:\n\n| Crate | Description |\n|-------|-------------|\n| `type-bridge-core-lib` | Pure-Rust AST, schema parser, query compiler, and validation engine |\n| `type-bridge-core` | PyO3 bindings exposing the Rust core to Python |\n| `type-bridge-server` | Transport-agnostic query pipeline with HTTP API |\n\nSee [`type-bridge-core/README.md`](type-bridge-core/README.md) for build instructions and architecture details.\n\n## Requirements\n\n- Python 3.13+\n- TypeDB 3.7.0-rc0 server (fully compatible)\n- typedb-driver\u003e=3.7.0\n- pydantic\u003e=2.12.4\n- isodate==0.7.2 (for Duration type support)\n- lark\u003e=1.1.9 (for schema parsing)\n- jinja2\u003e=3.1.0 (for code generation)\n- typer\u003e=0.15.0 (for CLI)\n\n## Release Notes\n\nSee the [CHANGELOG.md](CHANGELOG.md) for detailed release notes and version history.\n\n## License\n\nMIT License\n","funding_links":[],"categories":["Open source projects using TypeDB"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fds1sqe%2Ftype-bridge","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fds1sqe%2Ftype-bridge","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fds1sqe%2Ftype-bridge/lists"}