# 🚀 Ormax ORM — The Fastest Async ORM for Python
[](https://www.python.org/downloads/)
[](LICENSE)
[](https://docs.python.org/3/library/asyncio.html)
> **Ormax ORM** is a **high-performance**, **secure**, and **feature-rich** asynchronous Object-Relational Mapping (ORM) library for Python. Built for modern web applications, APIs, and microservices, Ormax delivers **unmatched speed** and supports multiple databases, including **MariaDB**, **MySQL**, **PostgreSQL**, **SQLite3**, **Microsoft SQL Server**, **Oracle**, and **Amazon Aurora**.
---
## 🌟 Why Choose Ormax ORM?
- **🚀 Blazing Fast**: Up to **2× faster** than other popular ORMs like SQLAlchemy and Tortoise ORM (see [Benchmarks](#-benchmarks)).
- **🔌 Multi-Database Support**: Seamlessly works with MariaDB, MySQL, PostgreSQL, SQLite3, MSSQL, Oracle, and Aurora.
- **⚡ Fully Asynchronous**: Built on `asyncio` for optimal performance in async applications.
- **🛡️ Secure by Design**: Robust input validation and protection against SQL injection.
- **📦 Intuitive API**: Inspired by Django ORM, but optimized for async workflows with a simple, Pythonic syntax.
- **🔗 Advanced Relationships**: Supports `ForeignKey`, reverse relationships, `select_related`, and `prefetch_related`.
- **💾 Connection Pooling**: Efficient connection management for high-concurrency workloads.
- **📊 Powerful QuerySet**: Chaining filters, annotations, aggregations, and bulk operations.
- **🔄 Transaction Support**: ACID-compliant transactions for reliable data operations.
- **🛠️ Flexible Field Types**: Comprehensive field types like `CharField`, `JSONField`, `UUIDField`, and more.
---
## 📈 Benchmarks
Ormax ORM consistently outperforms other Python ORMs in async CRUD operations, making it ideal for high-performance applications.
| ORM | Insert 10k Rows | Select 10k Rows | Update 10k Rows |
|---------------|-----------------|-----------------|-----------------|
| **Ormax ORM** | **0.82s** | **0.65s** | **0.78s** |
| Tortoise ORM | 1.45s | 1.10s | 1.50s |
| SQLAlchemy | 1.60s | 1.25s | 1.62s |
> Full benchmark details available in [docs/benchmark.md](docs/benchmark.md).
---
## 📦 Installation
Install Ormax ORM using pip:
```bash
pip install -U ormax
```
Or install from source:
```bash
git clone https://github.com/shayanheidari01/ormax.git
cd ormax
pip install -e .
```
### Dependencies
Depending on your database, install the required async driver:
```bash
# For MySQL/MariaDB/Amazon Aurora
pip install aiomysql
# For PostgreSQL
pip install asyncpg
# For SQLite
pip install aiosqlite
# For Microsoft SQL Server
pip install aioodbc
# For Oracle Database
pip install async-oracledb
```
---
## 🚀 Quick Start
Get started with Ormax in just a few lines of code:
```python
import asyncio
from ormax import Database, Model
from ormax.fields import AutoField, CharField, ForeignKeyField
# Define models
class Author(Model):
id = AutoField()
name = CharField(max_length=100)
class Book(Model):
id = AutoField()
title = CharField(max_length=200)
author = ForeignKeyField(Author, related_name='books')
# Initialize database
db = Database("sqlite:///example.db")
async def main():
# Connect to database and register models
await db.connect()
db.register_model(Author)
db.register_model(Book)
await db.create_tables()
# Create instances
author = await Author.create(name="J.K. Rowling")
book = await Book.create(title="Harry Potter", author=author)
# Query data
books = await Book.objects().filter(author=author).all()
print(books)
# Run the async application
asyncio.run(main())
```
---
## 🛠️ Key Features
### 1. **Model Definition**
Define database models using a clean, class-based syntax. Ormax supports a wide range of field types for flexible data modeling.
```python
from ormax import Model
from ormax.fields import *
class User(Model):
table_name = "users_table" # Optional custom table name
id = AutoField()
username = CharField(max_length=50, unique=True)
email = EmailField(unique=True)
password_hash = CharField(max_length=128)
is_active = BooleanField(default=True)
created_at = DateTimeField(auto_now_add=True)
updated_at = DateTimeField(auto_now=True)
```
### 2. **Supported Field Types**
Ormax provides a comprehensive set of field types, each with built-in validation:
- **Basic Types**: `CharField`, `TextField`, `IntegerField`, `BigIntegerField`, `SmallIntegerField`, `FloatField`, `DecimalField`, `BooleanField`
- **Date/Time**: `DateTimeField`, `DateField`, `TimeField`
- **Specialized**: `EmailField`, `URLField`, `UUIDField`, `IPAddressField`, `SlugField`, `JSONField`, `BinaryField`
- **Auto-Incrementing**: `AutoField`, `BigAutoField`, `SmallAutoField`
- **Relationships**: `ForeignKeyField` (with `related_name` and `on_delete` options)
- **Positive Variants**: `PositiveIntegerField`, `PositiveSmallIntegerField`
Example:
```python
class Post(Model):
_meta = {'table_name': 'blog_posts'} # Alternative way to set table name
id = AutoField()
title = CharField(max_length=200)
content = TextField()
# ForeignKey with on_delete option
author = ForeignKeyField(User, related_name='posts', nullable=True, on_delete="SET NULL")
published = BooleanField(default=False)
created_at = DateTimeField(auto_now_add=True)
updated_at = DateTimeField(auto_now=True)
```
### 3. **QuerySet API**
Ormax's `QuerySet` provides a powerful and chainable interface for querying data:
```python
# Get all users
all_users = await User.objects().all()
# Filter users
active_users = await User.objects().filter(is_active=True)
# Get user by username
user = await User.objects().get(username="john_doe")
# Update user
user.email = "newemail@example.com"
await user.save()
# Count posts
post_count = await Post.objects().count()
# Update multiple records
updated_count = await Post.objects().filter(published=False).update(published=True)
# Prefetch related objects
users = await User.objects().prefetch_related('posts').all()
for user in users:
posts = await user.posts.all()
print(f"{user.username} has {len(posts)} posts")
```
### 4. **Relationships**
Ormax supports `ForeignKeyField` for forward and reverse relationships:
```python
# Forward relationship
post = await Post.objects().get(id=1)
author = await post.author.get() # Access related User
# Reverse relationship
user = await User.objects().get(id=1)
posts = await user.posts.all() # Get all Posts by this User
```
### 5. **Bulk Operations**
Efficiently create, update, or delete multiple records:
```python
# Bulk create
users_data = [
{"username": f"user{i}", "email": f"user{i}@example.com", "password_hash": f"hash{i}"}
for i in range(10)
]
created_users = await User.bulk_create(users_data)
# Bulk update
await Post.objects().filter(published=False).update(published=True)
```
### 6. **Transactions**
Use transactions for atomic operations:
```python
# Transaction context manager
async with db.transaction():
new_user = await User.create(
username="transaction_user",
email="transaction@example.com",
password_hash="transaction_hash"
)
new_post = await Post.create(
title="Transaction Post",
content="Created in transaction",
author=new_user
)
```
### 7. **Connection Pooling**
Ormax uses connection pooling for efficient database access, optimized for high-concurrency workloads. Each database type has specific connection settings:
```python
# MySQL/Aurora optimized connection
db = Database("mysql://root:password@localhost:3306/mydb")
# PostgreSQL connection
db = Database("postgresql://postgres:password@localhost:5432/mydb")
# SQLite in-memory database
db = Database("sqlite:///:memory:")
```
### 8. **Security Features**
- **Input Sanitization**: Prevents SQL injection with built-in validation
- **Validation**: Robust field validation ensures data integrity
- **Secure Password Handling**: Comprehensive validation for fields like `EmailField`
---
## 📚 Advanced Usage
### Custom QuerySet Methods
Extend `QuerySet` for custom query logic:
```python
class CustomQuerySet(QuerySet):
async def active(self):
return self.filter(is_active=True)
async def by_email_domain(self, domain):
return self.filter(email__endswith=f"@{domain}")
class User(Model):
objects = CustomQuerySet.as_manager()
# Fields here...
# Usage
active_users = await User.objects().active().all()
gmail_users = await User.objects().by_email_domain("gmail.com").all()
```
### Nested Transactions with Savepoints
Ormax supports nested transactions using savepoints:
```python
async with db.transaction():
# Outer transaction
user = await User.create(username="main_user", email="main@example.com")
try:
async with db.transaction():
# Nested transaction (savepoint)
post = await Post.create(title="Nested", content="Nested content", author=user)
# This would roll back only the nested transaction
raise Exception("Simulated error")
except Exception:
pass
# This will still be committed
await Post.create(title="After Nested", content="Content after nested", author=user)
```
### Raw SQL Queries
Execute raw SQL for complex queries:
```python
# Execute raw query
results = await db.connection.execute(
"SELECT * FROM users_table WHERE is_active = %s",
(True,)
)
# Fetch one result
result = await db.connection.fetch_one(
"SELECT * FROM users_table WHERE username = %s",
("john_doe",)
)
# Fetch all results
results = await db.connection.fetch_all(
"SELECT * FROM blog_posts WHERE published = %s ORDER BY created_at DESC",
(True,)
)
```
### Performance Optimization
Ormax includes features for optimizing database performance:
```python
# Prefetch related objects to avoid N+1 queries
users = await User.objects().prefetch_related('posts').all()
# Select only specific fields
users = await User.objects().values('id', 'username').all()
# Limit and offset for pagination
page_2 = await Post.objects().order_by('-created_at').limit(10).offset(10).all()
```
---
## 🔧 Configuration
### Database Connection
Create a `Database` instance with a connection string:
```python
# SQLite
db = Database("sqlite:///example.db")
# PostgreSQL
db = Database("postgresql://user:password@localhost:5432/dbname")
# MySQL/MariaDB
db = Database("mysql://user:password@localhost:3306/dbname")
# Microsoft SQL Server
db = Database("mssql://user:password@localhost:1433/dbname")
# Oracle
db = Database("oracle://user:password@localhost:1521/orcl")
```
### Model Registration
Register models before use:
```python
# Register models
db.register_model(User)
db.register_model(Post)
db.register_model(Category)
# Create tables
await db.create_tables()
# Drop tables (with cascade option)
await db.drop_tables(cascade=True, if_exists=True)
```
---
## 📜 API Reference
### Core Classes
- **Database**: Manages connections, model registration, and table creation.
- `connect()`: Establish database connection
- `disconnect()`: Close database connection
- `register_model(model_class)`: Register a model class
- `create_tables()`: Create tables for all registered models
- `drop_tables(cascade=False, if_exists=False)`: Drop tables for all registered models
- `transaction()`: Context manager for database transactions
- **Model**: Base class for defining database models.
- `create(**kwargs)`: Create and save a new instance
- `save()`: Save the model instance
- `delete()`: Delete the model instance
- `bulk_create(objects, batch_size=1000)`: Bulk create multiple instances
- `objects()`: Get a QuerySet for this model
- **QuerySet**: Chainable query interface for filtering, ordering, and aggregating.
- `filter(**kwargs)`: Add filter conditions
- `exclude(**kwargs)`: Add exclude conditions
- `get(**kwargs)`: Get a single record
- `all()`: Get all records
- `first()`: Get the first record
- `last()`: Get the last record
- `count()`: Count records
- `exists()`: Check if records exist
- `update(**kwargs)`: Bulk update records
- `delete()`: Bulk delete records
- `order_by(*fields)`: Order results
- `limit(n)`: Limit results
- `offset(n)`: Offset results
- `prefetch_related(*relations)`: Prefetch related objects
- `select_related(*relations)`: Select related objects in the same query
- **Field**: Base class for all field types, with validation and SQL generation.
- `primary_key`: Whether this field is a primary key
- `auto_increment`: Whether this field auto-increments
- `nullable`: Whether this field can be NULL
- `default`: Default value for the field
- `unique`: Whether this field must be unique
- `index`: Whether this field should be indexed
- **RelationshipManager**: Handles forward and reverse relationships.
### Field Types
Ormax provides a comprehensive set of field types:
- **AutoField**: Auto-incrementing primary key field
- **CharField**: Character field with max_length
- **TextField**: Large text field
- **IntegerField**: Integer field
- **BigIntegerField**: Large integer field
- **SmallIntegerField**: Small integer field
- **FloatField**: Floating point field
- **DecimalField**: Decimal field for precise calculations
- **BooleanField**: Boolean field
- **DateTimeField**: Date and time field
- **DateField**: Date field
- **TimeField**: Time field
- **EmailField**: Email address field with validation
- **URLField**: URL field with validation
- **UUIDField**: UUID field
- **IPAddressField**: IP address field
- **SlugField**: URL-friendly slug field
- **JSONField**: JSON data field
- **BinaryField**: Binary data field
- **ForeignKeyField**: Foreign key relationship field
### Error Types
Ormax provides specific exceptions for different error scenarios:
- **DatabaseError**: Base database error
- **ValidationError**: Validation error
- **DoesNotExist**: Record does not exist
- **MultipleObjectsReturned**: Multiple records returned when one expected
---
## 🔍 SEO Keywords
`Fastest Python ORM`, `Async Python ORM`, `Best Python ORM 2025`, `High Performance ORM`, `Python asyncio ORM`, `PostgreSQL Async ORM`, `MySQL Async ORM`, `Secure Python ORM`, `ORM for Microservices`, `Python Database Library`
---
## 🤝 Contributing
Contributions are welcome! Please follow these steps:
1. Fork the repository.
2. Create a feature branch (`git checkout -b feature/YourFeature`).
3. Commit your changes (`git commit -m "Add YourFeature"`).
4. Push to the branch (`git push origin feature/YourFeature`).
5. Open a pull request.
---
## 📄 License
Ormax ORM is licensed under the [MIT License](LICENSE).
---
**Made with ❤️ for Python developers who value speed, simplicity, and reliability.**
Raw data
{
"_id": null,
"home_page": "https://github.com/shayanheidari01/ormax",
"name": "ormax",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": null,
"keywords": "orm, async, asyncio, database, sql, mysql, postgresql, sqlite, mariadb, database-orm, mssql, sqlserver, oracle, aurora",
"author": "Shayan Heidari",
"author_email": "shayanheidari01@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/88/2c/54c28d95d0d2dda10af6a59e8b19f161c44d3968ccd93b01baf9a60a0a1a/ormax-1.2.3.tar.gz",
"platform": null,
"description": "# \ud83d\ude80 Ormax ORM \u2014 The Fastest Async ORM for Python\r\n\r\n[](https://www.python.org/downloads/)\r\n[](LICENSE)\r\n[](https://docs.python.org/3/library/asyncio.html)\r\n\r\n> **Ormax ORM** is a **high-performance**, **secure**, and **feature-rich** asynchronous Object-Relational Mapping (ORM) library for Python. Built for modern web applications, APIs, and microservices, Ormax delivers **unmatched speed** and supports multiple databases, including **MariaDB**, **MySQL**, **PostgreSQL**, **SQLite3**, **Microsoft SQL Server**, **Oracle**, and **Amazon Aurora**.\r\n\r\n---\r\n\r\n## \ud83c\udf1f Why Choose Ormax ORM?\r\n\r\n- **\ud83d\ude80 Blazing Fast**: Up to **2\u00d7 faster** than other popular ORMs like SQLAlchemy and Tortoise ORM (see [Benchmarks](#-benchmarks)).\r\n- **\ud83d\udd0c Multi-Database Support**: Seamlessly works with MariaDB, MySQL, PostgreSQL, SQLite3, MSSQL, Oracle, and Aurora.\r\n- **\u26a1 Fully Asynchronous**: Built on `asyncio` for optimal performance in async applications.\r\n- **\ud83d\udee1\ufe0f Secure by Design**: Robust input validation and protection against SQL injection.\r\n- **\ud83d\udce6 Intuitive API**: Inspired by Django ORM, but optimized for async workflows with a simple, Pythonic syntax.\r\n- **\ud83d\udd17 Advanced Relationships**: Supports `ForeignKey`, reverse relationships, `select_related`, and `prefetch_related`.\r\n- **\ud83d\udcbe Connection Pooling**: Efficient connection management for high-concurrency workloads.\r\n- **\ud83d\udcca Powerful QuerySet**: Chaining filters, annotations, aggregations, and bulk operations.\r\n- **\ud83d\udd04 Transaction Support**: ACID-compliant transactions for reliable data operations.\r\n- **\ud83d\udee0\ufe0f Flexible Field Types**: Comprehensive field types like `CharField`, `JSONField`, `UUIDField`, and more.\r\n\r\n---\r\n\r\n## \ud83d\udcc8 Benchmarks\r\n\r\nOrmax ORM consistently outperforms other Python ORMs in async CRUD operations, making it ideal for high-performance applications.\r\n\r\n| ORM | Insert 10k Rows | Select 10k Rows | Update 10k Rows |\r\n|---------------|-----------------|-----------------|-----------------|\r\n| **Ormax ORM** | **0.82s** | **0.65s** | **0.78s** |\r\n| Tortoise ORM | 1.45s | 1.10s | 1.50s |\r\n| SQLAlchemy | 1.60s | 1.25s | 1.62s |\r\n\r\n> Full benchmark details available in [docs/benchmark.md](docs/benchmark.md).\r\n\r\n---\r\n\r\n## \ud83d\udce6 Installation\r\n\r\nInstall Ormax ORM using pip:\r\n\r\n```bash\r\npip install -U ormax\r\n```\r\n\r\nOr install from source:\r\n\r\n```bash\r\ngit clone https://github.com/shayanheidari01/ormax.git\r\ncd ormax\r\npip install -e .\r\n```\r\n\r\n### Dependencies\r\n\r\nDepending on your database, install the required async driver:\r\n\r\n```bash\r\n# For MySQL/MariaDB/Amazon Aurora\r\npip install aiomysql\r\n\r\n# For PostgreSQL\r\npip install asyncpg\r\n\r\n# For SQLite\r\npip install aiosqlite\r\n\r\n# For Microsoft SQL Server\r\npip install aioodbc\r\n\r\n# For Oracle Database\r\npip install async-oracledb\r\n```\r\n\r\n---\r\n\r\n## \ud83d\ude80 Quick Start\r\n\r\nGet started with Ormax in just a few lines of code:\r\n\r\n```python\r\nimport asyncio\r\nfrom ormax import Database, Model\r\nfrom ormax.fields import AutoField, CharField, ForeignKeyField\r\n\r\n# Define models\r\nclass Author(Model):\r\n id = AutoField()\r\n name = CharField(max_length=100)\r\n\r\nclass Book(Model):\r\n id = AutoField()\r\n title = CharField(max_length=200)\r\n author = ForeignKeyField(Author, related_name='books')\r\n\r\n# Initialize database\r\ndb = Database(\"sqlite:///example.db\")\r\n\r\nasync def main():\r\n # Connect to database and register models\r\n await db.connect()\r\n db.register_model(Author)\r\n db.register_model(Book)\r\n await db.create_tables()\r\n\r\n # Create instances\r\n author = await Author.create(name=\"J.K. Rowling\")\r\n book = await Book.create(title=\"Harry Potter\", author=author)\r\n\r\n # Query data\r\n books = await Book.objects().filter(author=author).all()\r\n print(books)\r\n\r\n# Run the async application\r\nasyncio.run(main())\r\n```\r\n\r\n---\r\n\r\n## \ud83d\udee0\ufe0f Key Features\r\n\r\n### 1. **Model Definition**\r\nDefine database models using a clean, class-based syntax. Ormax supports a wide range of field types for flexible data modeling.\r\n\r\n```python\r\nfrom ormax import Model\r\nfrom ormax.fields import *\r\n\r\nclass User(Model):\r\n table_name = \"users_table\" # Optional custom table name\r\n id = AutoField()\r\n username = CharField(max_length=50, unique=True)\r\n email = EmailField(unique=True)\r\n password_hash = CharField(max_length=128)\r\n is_active = BooleanField(default=True)\r\n created_at = DateTimeField(auto_now_add=True)\r\n updated_at = DateTimeField(auto_now=True)\r\n```\r\n\r\n### 2. **Supported Field Types**\r\nOrmax provides a comprehensive set of field types, each with built-in validation:\r\n\r\n- **Basic Types**: `CharField`, `TextField`, `IntegerField`, `BigIntegerField`, `SmallIntegerField`, `FloatField`, `DecimalField`, `BooleanField`\r\n- **Date/Time**: `DateTimeField`, `DateField`, `TimeField`\r\n- **Specialized**: `EmailField`, `URLField`, `UUIDField`, `IPAddressField`, `SlugField`, `JSONField`, `BinaryField`\r\n- **Auto-Incrementing**: `AutoField`, `BigAutoField`, `SmallAutoField`\r\n- **Relationships**: `ForeignKeyField` (with `related_name` and `on_delete` options)\r\n- **Positive Variants**: `PositiveIntegerField`, `PositiveSmallIntegerField`\r\n\r\nExample:\r\n```python\r\nclass Post(Model):\r\n _meta = {'table_name': 'blog_posts'} # Alternative way to set table name\r\n id = AutoField()\r\n title = CharField(max_length=200)\r\n content = TextField()\r\n # ForeignKey with on_delete option\r\n author = ForeignKeyField(User, related_name='posts', nullable=True, on_delete=\"SET NULL\")\r\n published = BooleanField(default=False)\r\n created_at = DateTimeField(auto_now_add=True)\r\n updated_at = DateTimeField(auto_now=True)\r\n```\r\n\r\n### 3. **QuerySet API**\r\nOrmax's `QuerySet` provides a powerful and chainable interface for querying data:\r\n\r\n```python\r\n# Get all users\r\nall_users = await User.objects().all()\r\n\r\n# Filter users\r\nactive_users = await User.objects().filter(is_active=True)\r\n\r\n# Get user by username\r\nuser = await User.objects().get(username=\"john_doe\")\r\n\r\n# Update user\r\nuser.email = \"newemail@example.com\"\r\nawait user.save()\r\n\r\n# Count posts\r\npost_count = await Post.objects().count()\r\n\r\n# Update multiple records\r\nupdated_count = await Post.objects().filter(published=False).update(published=True)\r\n\r\n# Prefetch related objects\r\nusers = await User.objects().prefetch_related('posts').all()\r\nfor user in users:\r\n posts = await user.posts.all()\r\n print(f\"{user.username} has {len(posts)} posts\")\r\n```\r\n\r\n### 4. **Relationships**\r\nOrmax supports `ForeignKeyField` for forward and reverse relationships:\r\n\r\n```python\r\n# Forward relationship\r\npost = await Post.objects().get(id=1)\r\nauthor = await post.author.get() # Access related User\r\n\r\n# Reverse relationship\r\nuser = await User.objects().get(id=1)\r\nposts = await user.posts.all() # Get all Posts by this User\r\n```\r\n\r\n### 5. **Bulk Operations**\r\nEfficiently create, update, or delete multiple records:\r\n\r\n```python\r\n# Bulk create\r\nusers_data = [\r\n {\"username\": f\"user{i}\", \"email\": f\"user{i}@example.com\", \"password_hash\": f\"hash{i}\"} \r\n for i in range(10)\r\n]\r\ncreated_users = await User.bulk_create(users_data)\r\n\r\n# Bulk update\r\nawait Post.objects().filter(published=False).update(published=True)\r\n```\r\n\r\n### 6. **Transactions**\r\nUse transactions for atomic operations:\r\n\r\n```python\r\n# Transaction context manager\r\nasync with db.transaction():\r\n new_user = await User.create(\r\n username=\"transaction_user\",\r\n email=\"transaction@example.com\",\r\n password_hash=\"transaction_hash\"\r\n )\r\n new_post = await Post.create(\r\n title=\"Transaction Post\",\r\n content=\"Created in transaction\",\r\n author=new_user\r\n )\r\n```\r\n\r\n### 7. **Connection Pooling**\r\nOrmax uses connection pooling for efficient database access, optimized for high-concurrency workloads. Each database type has specific connection settings:\r\n\r\n```python\r\n# MySQL/Aurora optimized connection\r\ndb = Database(\"mysql://root:password@localhost:3306/mydb\")\r\n\r\n# PostgreSQL connection\r\ndb = Database(\"postgresql://postgres:password@localhost:5432/mydb\")\r\n\r\n# SQLite in-memory database\r\ndb = Database(\"sqlite:///:memory:\")\r\n```\r\n\r\n### 8. **Security Features**\r\n- **Input Sanitization**: Prevents SQL injection with built-in validation\r\n- **Validation**: Robust field validation ensures data integrity\r\n- **Secure Password Handling**: Comprehensive validation for fields like `EmailField`\r\n\r\n---\r\n\r\n## \ud83d\udcda Advanced Usage\r\n\r\n### Custom QuerySet Methods\r\nExtend `QuerySet` for custom query logic:\r\n\r\n```python\r\nclass CustomQuerySet(QuerySet):\r\n async def active(self):\r\n return self.filter(is_active=True)\r\n \r\n async def by_email_domain(self, domain):\r\n return self.filter(email__endswith=f\"@{domain}\")\r\n\r\nclass User(Model):\r\n objects = CustomQuerySet.as_manager()\r\n \r\n # Fields here...\r\n\r\n# Usage\r\nactive_users = await User.objects().active().all()\r\ngmail_users = await User.objects().by_email_domain(\"gmail.com\").all()\r\n```\r\n\r\n### Nested Transactions with Savepoints\r\nOrmax supports nested transactions using savepoints:\r\n\r\n```python\r\nasync with db.transaction():\r\n # Outer transaction\r\n user = await User.create(username=\"main_user\", email=\"main@example.com\")\r\n \r\n try:\r\n async with db.transaction():\r\n # Nested transaction (savepoint)\r\n post = await Post.create(title=\"Nested\", content=\"Nested content\", author=user)\r\n # This would roll back only the nested transaction\r\n raise Exception(\"Simulated error\")\r\n except Exception:\r\n pass\r\n \r\n # This will still be committed\r\n await Post.create(title=\"After Nested\", content=\"Content after nested\", author=user)\r\n```\r\n\r\n### Raw SQL Queries\r\nExecute raw SQL for complex queries:\r\n\r\n```python\r\n# Execute raw query\r\nresults = await db.connection.execute(\r\n \"SELECT * FROM users_table WHERE is_active = %s\",\r\n (True,)\r\n)\r\n\r\n# Fetch one result\r\nresult = await db.connection.fetch_one(\r\n \"SELECT * FROM users_table WHERE username = %s\",\r\n (\"john_doe\",)\r\n)\r\n\r\n# Fetch all results\r\nresults = await db.connection.fetch_all(\r\n \"SELECT * FROM blog_posts WHERE published = %s ORDER BY created_at DESC\",\r\n (True,)\r\n)\r\n```\r\n\r\n### Performance Optimization\r\nOrmax includes features for optimizing database performance:\r\n\r\n```python\r\n# Prefetch related objects to avoid N+1 queries\r\nusers = await User.objects().prefetch_related('posts').all()\r\n\r\n# Select only specific fields\r\nusers = await User.objects().values('id', 'username').all()\r\n\r\n# Limit and offset for pagination\r\npage_2 = await Post.objects().order_by('-created_at').limit(10).offset(10).all()\r\n```\r\n\r\n---\r\n\r\n## \ud83d\udd27 Configuration\r\n\r\n### Database Connection\r\nCreate a `Database` instance with a connection string:\r\n\r\n```python\r\n# SQLite\r\ndb = Database(\"sqlite:///example.db\")\r\n\r\n# PostgreSQL\r\ndb = Database(\"postgresql://user:password@localhost:5432/dbname\")\r\n\r\n# MySQL/MariaDB\r\ndb = Database(\"mysql://user:password@localhost:3306/dbname\")\r\n\r\n# Microsoft SQL Server\r\ndb = Database(\"mssql://user:password@localhost:1433/dbname\")\r\n\r\n# Oracle\r\ndb = Database(\"oracle://user:password@localhost:1521/orcl\")\r\n```\r\n\r\n### Model Registration\r\nRegister models before use:\r\n\r\n```python\r\n# Register models\r\ndb.register_model(User)\r\ndb.register_model(Post)\r\ndb.register_model(Category)\r\n\r\n# Create tables\r\nawait db.create_tables()\r\n\r\n# Drop tables (with cascade option)\r\nawait db.drop_tables(cascade=True, if_exists=True)\r\n```\r\n\r\n---\r\n\r\n## \ud83d\udcdc API Reference\r\n\r\n### Core Classes\r\n- **Database**: Manages connections, model registration, and table creation.\r\n - `connect()`: Establish database connection\r\n - `disconnect()`: Close database connection\r\n - `register_model(model_class)`: Register a model class\r\n - `create_tables()`: Create tables for all registered models\r\n - `drop_tables(cascade=False, if_exists=False)`: Drop tables for all registered models\r\n - `transaction()`: Context manager for database transactions\r\n\r\n- **Model**: Base class for defining database models.\r\n - `create(**kwargs)`: Create and save a new instance\r\n - `save()`: Save the model instance\r\n - `delete()`: Delete the model instance\r\n - `bulk_create(objects, batch_size=1000)`: Bulk create multiple instances\r\n - `objects()`: Get a QuerySet for this model\r\n\r\n- **QuerySet**: Chainable query interface for filtering, ordering, and aggregating.\r\n - `filter(**kwargs)`: Add filter conditions\r\n - `exclude(**kwargs)`: Add exclude conditions\r\n - `get(**kwargs)`: Get a single record\r\n - `all()`: Get all records\r\n - `first()`: Get the first record\r\n - `last()`: Get the last record\r\n - `count()`: Count records\r\n - `exists()`: Check if records exist\r\n - `update(**kwargs)`: Bulk update records\r\n - `delete()`: Bulk delete records\r\n - `order_by(*fields)`: Order results\r\n - `limit(n)`: Limit results\r\n - `offset(n)`: Offset results\r\n - `prefetch_related(*relations)`: Prefetch related objects\r\n - `select_related(*relations)`: Select related objects in the same query\r\n\r\n- **Field**: Base class for all field types, with validation and SQL generation.\r\n - `primary_key`: Whether this field is a primary key\r\n - `auto_increment`: Whether this field auto-increments\r\n - `nullable`: Whether this field can be NULL\r\n - `default`: Default value for the field\r\n - `unique`: Whether this field must be unique\r\n - `index`: Whether this field should be indexed\r\n\r\n- **RelationshipManager**: Handles forward and reverse relationships.\r\n\r\n### Field Types\r\nOrmax provides a comprehensive set of field types:\r\n\r\n- **AutoField**: Auto-incrementing primary key field\r\n- **CharField**: Character field with max_length\r\n- **TextField**: Large text field\r\n- **IntegerField**: Integer field\r\n- **BigIntegerField**: Large integer field\r\n- **SmallIntegerField**: Small integer field\r\n- **FloatField**: Floating point field\r\n- **DecimalField**: Decimal field for precise calculations\r\n- **BooleanField**: Boolean field\r\n- **DateTimeField**: Date and time field\r\n- **DateField**: Date field\r\n- **TimeField**: Time field\r\n- **EmailField**: Email address field with validation\r\n- **URLField**: URL field with validation\r\n- **UUIDField**: UUID field\r\n- **IPAddressField**: IP address field\r\n- **SlugField**: URL-friendly slug field\r\n- **JSONField**: JSON data field\r\n- **BinaryField**: Binary data field\r\n- **ForeignKeyField**: Foreign key relationship field\r\n\r\n### Error Types\r\nOrmax provides specific exceptions for different error scenarios:\r\n\r\n- **DatabaseError**: Base database error\r\n- **ValidationError**: Validation error\r\n- **DoesNotExist**: Record does not exist\r\n- **MultipleObjectsReturned**: Multiple records returned when one expected\r\n\r\n---\r\n\r\n## \ud83d\udd0d SEO Keywords\r\n`Fastest Python ORM`, `Async Python ORM`, `Best Python ORM 2025`, `High Performance ORM`, `Python asyncio ORM`, `PostgreSQL Async ORM`, `MySQL Async ORM`, `Secure Python ORM`, `ORM for Microservices`, `Python Database Library`\r\n\r\n---\r\n\r\n## \ud83e\udd1d Contributing\r\nContributions are welcome! Please follow these steps:\r\n1. Fork the repository.\r\n2. Create a feature branch (`git checkout -b feature/YourFeature`).\r\n3. Commit your changes (`git commit -m \"Add YourFeature\"`).\r\n4. Push to the branch (`git push origin feature/YourFeature`).\r\n5. Open a pull request.\r\n\r\n---\r\n\r\n## \ud83d\udcc4 License\r\nOrmax ORM is licensed under the [MIT License](LICENSE).\r\n\r\n---\r\n\r\n**Made with \u2764\ufe0f for Python developers who value speed, simplicity, and reliability.**\r\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "High-performance async ORM for all major databases",
"version": "1.2.3",
"project_urls": {
"Bug Tracker": "https://github.com/shayanheidari01/ormax/issues",
"Documentation": "https://github.com/shayanheidari01/ormax#readme",
"Homepage": "https://github.com/shayanheidari01/ormax",
"Source Code": "https://github.com/shayanheidari01/ormax"
},
"split_keywords": [
"orm",
" async",
" asyncio",
" database",
" sql",
" mysql",
" postgresql",
" sqlite",
" mariadb",
" database-orm",
" mssql",
" sqlserver",
" oracle",
" aurora"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "4eabbf58963caa53e0abcd99cb7a230aad928c383d9ee53ee762ec3a119a7f6f",
"md5": "9325667c8971a3a5cdf32ea9f565b357",
"sha256": "587ce556c762c3a9ec7c9f403a241101e3d0c199638d2caebcabda10e3ff9068"
},
"downloads": -1,
"filename": "ormax-1.2.3-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "9325667c8971a3a5cdf32ea9f565b357",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": ">=3.7",
"size": 41680,
"upload_time": "2025-08-23T22:57:51",
"upload_time_iso_8601": "2025-08-23T22:57:51.351952Z",
"url": "https://files.pythonhosted.org/packages/4e/ab/bf58963caa53e0abcd99cb7a230aad928c383d9ee53ee762ec3a119a7f6f/ormax-1.2.3-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "882c54c28d95d0d2dda10af6a59e8b19f161c44d3968ccd93b01baf9a60a0a1a",
"md5": "0bf5a81d7e92408f11c02ed48684c2df",
"sha256": "9e32f5e7481975e18e16b04703f82906a98784dc286ccdb1eddcddb91c6fe0a8"
},
"downloads": -1,
"filename": "ormax-1.2.3.tar.gz",
"has_sig": false,
"md5_digest": "0bf5a81d7e92408f11c02ed48684c2df",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 46967,
"upload_time": "2025-08-23T22:57:53",
"upload_time_iso_8601": "2025-08-23T22:57:53.169783Z",
"url": "https://files.pythonhosted.org/packages/88/2c/54c28d95d0d2dda10af6a59e8b19f161c44d3968ccd93b01baf9a60a0a1a/ormax-1.2.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-23 22:57:53",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "shayanheidari01",
"github_project": "ormax",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "ormax"
}