Metadata-Version: 2.5
Name: matrx-orm
Version: 3.1.67
Summary: Async-first PostgreSQL ORM with bidirectional migrations, schema introspection, many-to-many relationships, and built-in state caching
Project-URL: Homepage, https://github.com/AI-Matrix-Engine/aidream-current
Project-URL: Repository, https://github.com/AI-Matrix-Engine/aidream-current
Project-URL: Documentation, https://github.com/AI-Matrix-Engine/aidream-current/tree/main/packages/matrx-orm#readme
Project-URL: Bug Tracker, https://github.com/AI-Matrix-Engine/aidream-current/issues
Author-email: Matrx <admin@aimatrx.com>
Maintainer-email: Matrx <admin@aimatrx.com>
License: MIT
Keywords: async,asyncio,asyncpg,database,many-to-many,migrations,orm,postgresql,schema-builder,supabase
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Database :: Front-Ends
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.13
Requires-Dist: asyncpg>=0.31.0
Requires-Dist: cryptography>=43.0
Requires-Dist: gitpython>=3.1.40
Requires-Dist: matrx-utils>=2.0.13
Requires-Dist: psycopg-pool>=3.2.5
Requires-Dist: psycopg[binary]>=3.2.5
Requires-Dist: python-dotenv>=1.0
Requires-Dist: pyyaml>=6.0.3
Provides-Extra: admin
Requires-Dist: fastapi>=0.115; extra == 'admin'
Provides-Extra: api
Requires-Dist: aiohttp>=3.9.0; extra == 'api'
Description-Content-Type: text/markdown

# matrx-orm

Async-first PostgreSQL ORM for Python: typed models, an expressive query builder, bidirectional migrations with dependency-ordered history, schema introspection + code generation, and a mountable FastAPI admin router. Designed for applications that want ORM ergonomics without giving up raw-SQL control.

## Install

```bash
pip install matrx-orm
```

Python 3.13+ required. Needs a PostgreSQL server (or Supabase / any Postgres-compatible backend). The only Matrx sibling it depends on is `matrx-utils`.

## What's in the box

- **Core model layer**: `Model`, `BaseManager`, `BaseDTO`, `ModelView`, `model_registry`, and 50+ field types (`CharField`, `IntegerField`, `UUIDField`, `JSONField`, `ForeignKey`, `ManyToManyField`, …).
- **Query layer**: `QueryBuilder`, expressions (`F`, `Q`), window functions, CTEs, subqueries.
- **Migrations**: `MigrationDB`, `MigrationLoader`, `MigrationExecutor`, `makemigrations`, `migrate` — migrations declare explicit `dependencies` and are applied in topological order. (Note: there is no multiple-head detection or `merge` primitive yet; parallel branches that both create the next sequence number must be reconciled by hand.)
- **Admin router** (FastAPI): `admin_router` exposes a ready-to-mount set of read/write endpoints for every registered model.
- **API layer** (optional `[api]` extra): `APIServer`, `APIConfig`, `TokenAuth`.
- **Adapters**: `AsyncPostgreSQLAdapter`, `SupabaseAdapter`, `PostgRESTClientAdapter`.
- **Signals**: `pre_create`, `post_create`, `pre_save`, `post_save`, `pre_delete`, `post_delete`.
- **Schema builder** (`matrx_orm.schema_builder`): code generation for Python + TypeScript type definitions from the live DB schema — useful for keeping a frontend's row types in sync.

## Usage

### Register a database project

matrx-orm supports multiple named database projects in a single process. Register each at startup, either with an explicit config or by reading env vars:

```python
from matrx_orm import DatabaseProjectConfig, register_database, register_database_from_env

# Explicit config
register_database(DatabaseProjectConfig(
    name="main",
    host="localhost", port=5432,
    database="myapp", user="postgres", password="…",
    default_schema="public",
))

# Or env-driven with a custom prefix
register_database_from_env(name="analytics", env_prefix="ANALYTICS_DB_")
```

### Declare a model and query

```python
from matrx_orm import Model, CharField, UUIDField, TimestampField, DateTimeField

class User(Model):
    class Meta:
        table = "users"
        database = "main"

    id = UUIDField(primary_key=True)
    email = CharField(max_length=320, unique=True)
    display_name = CharField(max_length=120)
    created_at = DateTimeField(auto_now_add=True)

# Querying
user = await User.objects.get(email="alice@example.com")
active = await User.objects.filter(display_name__startswith="A").order_by("-created_at").all()
```

### Migrations

```bash
# Generate migrations from the current model definitions
python -m matrx_orm.migrations.cli makemigrations

# Apply pending migrations
python -m matrx_orm.migrations.cli migrate
```

The migration system tracks which branch a migration originated on and refuses to let two branches create a conflicting sequence.

### Mount the admin router

Rows with composite primary keys expose an opaque `__matrx_row_id` in list
responses and a matching virtual primary-key column descriptor. Pass that value
unchanged to row-detail, update, delete, and cache-eviction routes; the router
decodes it into the complete composite key. This also gives generated read-only
views collision-safe row navigation.

Generated views default to `id` only when they project it. Every other view must
declare bounded, unique columns in
`generate[].output.view_primary_keys`; generation fails instead of guessing a
first column or embedding an unbounded projected row in an identifier.

```python
from fastapi import FastAPI
from matrx_orm import admin_router

app = FastAPI()
app.include_router(admin_router, prefix="/admin")
```

Instantly exposes list/get/create/update/delete endpoints for every registered model. Wrap it in your app's auth middleware.

## Standalone-friendliness

No hidden env-var reads outside `config.py` and the schema-builder CLI. All env-var access goes through `register_database_from_env`, which accepts a `env_prefix` and an `env_var_overrides` map. You can run matrx-orm with zero environment variables — just build a `DatabaseProjectConfig` yourself and call `register_database`.

## Contributing

See [CLAUDE.md](CLAUDE.md) for package-specific rules. [MODEL_API.md](MODEL_API.md) documents the full Model/QueryBuilder API. This package lives in the aidream monorepo at [github.com/AI-Matrix-Engine/aidream-current](https://github.com/AI-Matrix-Engine/aidream-current/tree/main/packages/matrx-orm).

## License

MIT.
