ormantism


Nameormantism JSON
Version 0.3.0 PyPI version JSON
download
home_pageNone
SummaryA lightweight ORM built on Pydantic for simple CRUD operations with minimal code
upload_time2025-07-12 13:13:45
maintainerNone
docs_urlNone
authorMathieu Rodic
requires_python>=3.12
licenseMIT
keywords orm pydantic sqlite sqlite mysql postgresql
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Ormantism

A tiny, simple ORM built on top of Pydantic.

When you need to perform simple CRUD operations with minimal code.

Offers support for PostgreSQL, MySQL, SQLite (database URL syntax is the same as in SQLAlchemy).

## Features

- **Simple Model Declaration**: Define your models using familiar Pydantic syntax
- **Automatic Table Creation**: Tables are created automatically when first accessed
- **Lazy Loading**: Relationships are loaded on-demand for optimal performance
- **Transaction Support**: Built-in transaction management with automatic rollback
- **Preloading**: Efficiently load related data with JOIN queries
- **Optional Timestamps**: Add created_at, updated_at, deleted_at fields automatically

## Installation

```bash
pip install ormantism
```

## Quick Start

### 1. Connect to Database

```python
import ormantism

# Connect to a file database
ormantism.connect("sqlite:///my_app.db")

# Or use in-memory database for testing
ormantism.connect("sqlite://:memory:")

# MySQL
ormantism.connect("mysql://login:password@host:port/database")

# PostgresSQL
ormantism.connect("postgresql://login:password@host:port/database")
```

### 2. Define Models

```python
from ormantism import Base
from typing import Optional

class User(Base):
    name: str
    email: str
    age: Optional[int] = None

class Post(Base, with_timestamps=True):
    title: str
    content: str
    author: User
```

### 3. Create and Save Records

```python
# Create a user
user = User(name="Alice", email="alice@example.com", age=30)
# The record is automatically saved to the database

# Create a post linked to the user
post = Post(title="My First Post", content="Hello World!", author=user)
```

### 4. Query Records

```python
# Load by ID
user = User.load(id=1)

# Load by criteria
user = User.load(name="Alice")
user = User.load(email="alice@example.com")

# Load latest post from alice@example.com
latest_post = Post.load(user_id=user.id, last_created=True)

# Load all records
users = User.load_all()

# Load with criteria
users_named_alice = User.load_all(name="Alice")
```

### 5. Update Records

```python
user = User.load(id=1)
user.age = 31  # Automatically saved to database
# or
user.update(age=31, email="alice.updated@example.com")
```

### 6. Delete Records

```python
user = User.load(id=1)
user.delete()
```

## Advanced Features

### Timestamps

Add automatic timestamp tracking to your models:

```python
class Post(Base, with_timestamps=True):
    title: str
    content: str
```

This adds `created_at`, `updated_at`, and `deleted_at` fields. Soft deletes are used when timestamps are enabled.

### Relationships and Lazy Loading

```python
class Author(Base):
    name: str

class Book(Base):
    title: str
    author: Author

# Create records
author = Author(name="Jane Doe")
book = Book(title="My Book", author=author)

# Lazy loading - author is loaded from DB when accessed
book = Book.load(id=1)
print(book.author.name)  # Database query happens here
```

### Preloading (Eager Loading)

Avoid N+1 queries by preloading relationships:

```python
# Load book with author in a single query
book = Book.load(id=1, preload="author")
print(book.author.name)  # No additional database query

# Preload nested relationships
book = Book.load(id=1, preload="author.publisher")

# Preload multiple relationships
book = Book.load(id=1, preload=["author", "category"])
```

### Transactions

```python
from ormantism import transaction

try:
    with transaction() as t:
        user1 = User(name="Alice", email="alice@example.com")
        user2 = User(name="Bob", email="bob@example.com")
        # Both users are saved automatically
        # Transaction commits when exiting the context
except Exception:
    # Transaction is automatically rolled back on any exception
    pass
```

### Querying Examples

```python
# Load single record
user = User.load(name="Alice")
latest_user = User.load(last_created=True)

# Load multiple records
all_users = User.load_all()
users_named_alice = User.load_all(name="Alice")

# Include soft-deleted records (when using timestamps)
all_including_deleted = User.load_all(with_deleted=True)
```

## Model Definition

### Basic Model

```python
class User(Base):
    name: str
    email: str
    age: int = 25  # Default value
    bio: Optional[str] = None  # Nullable field
```

### With Timestamps

```python
class Post(Base, with_timestamps=True):
    title: str
    content: str
    # Automatically adds: created_at, updated_at, deleted_at
```

### Supported Field Types

- `int`, `float`, `str`
- `Optional[T]` for nullable fields
- `list`, `dict` (stored as JSON)
- `datetime.datetime`
- `enum.Enum`
- Pydantic models (stored as JSON)
- References to other Base models

### Relationships

```python
class Category(Base):
    name: str

class Post(Base):
    title: str
    category: Category  # Foreign key relationship
    tags: Optional[Category] = None  # Nullable relationship
```

## API Reference

### Base Class Methods

#### Creating Records
- `Model()` - Create and automatically save a new record

#### Querying
- `Model.load(**criteria)` - Load single record
- `Model.load(last_created=True)` - Load most recently created record
- `Model.load_all(**criteria)` - Load multiple records
- `Model.load(preload="relationship")` - Eager load relationships
- `Model.load(with_deleted=True)` - Include soft-deleted records

#### Updating
- `instance.update(**kwargs)` - Update multiple fields
- `instance.field = value` - Update single field (auto-saves)

#### Deleting
- `instance.delete()` - Delete record (soft delete if timestamps enabled)

### Database Functions

- `ormantism.connect(database_url)` - Connect to database
- `ormantism.transaction()` - Get transaction context manager

## Limitations

- **Simple Queries**: Complex queries may require raw SQL
- **No Migrations**: Schema changes require manual handling
- **Basic Relationships**: Only supports simple foreign key relationships

## Requirements

- Python 3.12+
- Pydantic

## License

MIT License

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "ormantism",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.12",
    "maintainer_email": null,
    "keywords": "orm, pydantic, sqlite, SQLite, MySQL, PostgreSQL",
    "author": "Mathieu Rodic",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/33/c1/a9eee05c6999c38dd8335d5b290c093fe7febc2e8e381a19c082ad1b9cec/ormantism-0.3.0.tar.gz",
    "platform": null,
    "description": "# Ormantism\n\nA tiny, simple ORM built on top of Pydantic.\n\nWhen you need to perform simple CRUD operations with minimal code.\n\nOffers support for PostgreSQL, MySQL, SQLite (database URL syntax is the same as in SQLAlchemy).\n\n## Features\n\n- **Simple Model Declaration**: Define your models using familiar Pydantic syntax\n- **Automatic Table Creation**: Tables are created automatically when first accessed\n- **Lazy Loading**: Relationships are loaded on-demand for optimal performance\n- **Transaction Support**: Built-in transaction management with automatic rollback\n- **Preloading**: Efficiently load related data with JOIN queries\n- **Optional Timestamps**: Add created_at, updated_at, deleted_at fields automatically\n\n## Installation\n\n```bash\npip install ormantism\n```\n\n## Quick Start\n\n### 1. Connect to Database\n\n```python\nimport ormantism\n\n# Connect to a file database\normantism.connect(\"sqlite:///my_app.db\")\n\n# Or use in-memory database for testing\normantism.connect(\"sqlite://:memory:\")\n\n# MySQL\normantism.connect(\"mysql://login:password@host:port/database\")\n\n# PostgresSQL\normantism.connect(\"postgresql://login:password@host:port/database\")\n```\n\n### 2. Define Models\n\n```python\nfrom ormantism import Base\nfrom typing import Optional\n\nclass User(Base):\n    name: str\n    email: str\n    age: Optional[int] = None\n\nclass Post(Base, with_timestamps=True):\n    title: str\n    content: str\n    author: User\n```\n\n### 3. Create and Save Records\n\n```python\n# Create a user\nuser = User(name=\"Alice\", email=\"alice@example.com\", age=30)\n# The record is automatically saved to the database\n\n# Create a post linked to the user\npost = Post(title=\"My First Post\", content=\"Hello World!\", author=user)\n```\n\n### 4. Query Records\n\n```python\n# Load by ID\nuser = User.load(id=1)\n\n# Load by criteria\nuser = User.load(name=\"Alice\")\nuser = User.load(email=\"alice@example.com\")\n\n# Load latest post from alice@example.com\nlatest_post = Post.load(user_id=user.id, last_created=True)\n\n# Load all records\nusers = User.load_all()\n\n# Load with criteria\nusers_named_alice = User.load_all(name=\"Alice\")\n```\n\n### 5. Update Records\n\n```python\nuser = User.load(id=1)\nuser.age = 31  # Automatically saved to database\n# or\nuser.update(age=31, email=\"alice.updated@example.com\")\n```\n\n### 6. Delete Records\n\n```python\nuser = User.load(id=1)\nuser.delete()\n```\n\n## Advanced Features\n\n### Timestamps\n\nAdd automatic timestamp tracking to your models:\n\n```python\nclass Post(Base, with_timestamps=True):\n    title: str\n    content: str\n```\n\nThis adds `created_at`, `updated_at`, and `deleted_at` fields. Soft deletes are used when timestamps are enabled.\n\n### Relationships and Lazy Loading\n\n```python\nclass Author(Base):\n    name: str\n\nclass Book(Base):\n    title: str\n    author: Author\n\n# Create records\nauthor = Author(name=\"Jane Doe\")\nbook = Book(title=\"My Book\", author=author)\n\n# Lazy loading - author is loaded from DB when accessed\nbook = Book.load(id=1)\nprint(book.author.name)  # Database query happens here\n```\n\n### Preloading (Eager Loading)\n\nAvoid N+1 queries by preloading relationships:\n\n```python\n# Load book with author in a single query\nbook = Book.load(id=1, preload=\"author\")\nprint(book.author.name)  # No additional database query\n\n# Preload nested relationships\nbook = Book.load(id=1, preload=\"author.publisher\")\n\n# Preload multiple relationships\nbook = Book.load(id=1, preload=[\"author\", \"category\"])\n```\n\n### Transactions\n\n```python\nfrom ormantism import transaction\n\ntry:\n    with transaction() as t:\n        user1 = User(name=\"Alice\", email=\"alice@example.com\")\n        user2 = User(name=\"Bob\", email=\"bob@example.com\")\n        # Both users are saved automatically\n        # Transaction commits when exiting the context\nexcept Exception:\n    # Transaction is automatically rolled back on any exception\n    pass\n```\n\n### Querying Examples\n\n```python\n# Load single record\nuser = User.load(name=\"Alice\")\nlatest_user = User.load(last_created=True)\n\n# Load multiple records\nall_users = User.load_all()\nusers_named_alice = User.load_all(name=\"Alice\")\n\n# Include soft-deleted records (when using timestamps)\nall_including_deleted = User.load_all(with_deleted=True)\n```\n\n## Model Definition\n\n### Basic Model\n\n```python\nclass User(Base):\n    name: str\n    email: str\n    age: int = 25  # Default value\n    bio: Optional[str] = None  # Nullable field\n```\n\n### With Timestamps\n\n```python\nclass Post(Base, with_timestamps=True):\n    title: str\n    content: str\n    # Automatically adds: created_at, updated_at, deleted_at\n```\n\n### Supported Field Types\n\n- `int`, `float`, `str`\n- `Optional[T]` for nullable fields\n- `list`, `dict` (stored as JSON)\n- `datetime.datetime`\n- `enum.Enum`\n- Pydantic models (stored as JSON)\n- References to other Base models\n\n### Relationships\n\n```python\nclass Category(Base):\n    name: str\n\nclass Post(Base):\n    title: str\n    category: Category  # Foreign key relationship\n    tags: Optional[Category] = None  # Nullable relationship\n```\n\n## API Reference\n\n### Base Class Methods\n\n#### Creating Records\n- `Model()` - Create and automatically save a new record\n\n#### Querying\n- `Model.load(**criteria)` - Load single record\n- `Model.load(last_created=True)` - Load most recently created record\n- `Model.load_all(**criteria)` - Load multiple records\n- `Model.load(preload=\"relationship\")` - Eager load relationships\n- `Model.load(with_deleted=True)` - Include soft-deleted records\n\n#### Updating\n- `instance.update(**kwargs)` - Update multiple fields\n- `instance.field = value` - Update single field (auto-saves)\n\n#### Deleting\n- `instance.delete()` - Delete record (soft delete if timestamps enabled)\n\n### Database Functions\n\n- `ormantism.connect(database_url)` - Connect to database\n- `ormantism.transaction()` - Get transaction context manager\n\n## Limitations\n\n- **Simple Queries**: Complex queries may require raw SQL\n- **No Migrations**: Schema changes require manual handling\n- **Basic Relationships**: Only supports simple foreign key relationships\n\n## Requirements\n\n- Python 3.12+\n- Pydantic\n\n## License\n\nMIT License\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A lightweight ORM built on Pydantic for simple CRUD operations with minimal code",
    "version": "0.3.0",
    "project_urls": {
        "Homepage": "https://github.com/mathieurodic/ormantism"
    },
    "split_keywords": [
        "orm",
        " pydantic",
        " sqlite",
        " sqlite",
        " mysql",
        " postgresql"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "f41a5e873338e633e930ed50599d9528e1d0ab5d342644c415c2e59d87ce8086",
                "md5": "0d2753ae403069848a8f1b77f00dbba8",
                "sha256": "b02f583a06d27352ca776661d72c7d797e154d3a54dcde4c09bde5beddc2dc8c"
            },
            "downloads": -1,
            "filename": "ormantism-0.3.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "0d2753ae403069848a8f1b77f00dbba8",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.12",
            "size": 16007,
            "upload_time": "2025-07-12T13:13:44",
            "upload_time_iso_8601": "2025-07-12T13:13:44.629023Z",
            "url": "https://files.pythonhosted.org/packages/f4/1a/5e873338e633e930ed50599d9528e1d0ab5d342644c415c2e59d87ce8086/ormantism-0.3.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "33c1a9eee05c6999c38dd8335d5b290c093fe7febc2e8e381a19c082ad1b9cec",
                "md5": "dee4fc5da08703fe8b8e5a8104369f67",
                "sha256": "55c867d71d8e315053382e2375955899534518a0a537e55479baa79a6a023e2b"
            },
            "downloads": -1,
            "filename": "ormantism-0.3.0.tar.gz",
            "has_sig": false,
            "md5_digest": "dee4fc5da08703fe8b8e5a8104369f67",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.12",
            "size": 15577,
            "upload_time": "2025-07-12T13:13:45",
            "upload_time_iso_8601": "2025-07-12T13:13:45.401967Z",
            "url": "https://files.pythonhosted.org/packages/33/c1/a9eee05c6999c38dd8335d5b290c093fe7febc2e8e381a19c082ad1b9cec/ormantism-0.3.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-12 13:13:45",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "mathieurodic",
    "github_project": "ormantism",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "ormantism"
}
        
Elapsed time: 0.44157s