| Name | sqlobjects JSON |
| Version |
1.0.9
JSON |
| download |
| home_page | None |
| Summary | Django-style async ORM library based on SQLAlchemy with chainable queries, Q objects, and relationship loading |
| upload_time | 2025-11-14 03:05:18 |
| maintainer | None |
| docs_url | None |
| author | None |
| requires_python | >=3.12 |
| license | MIT |
| keywords |
python
orm
async
django-style
database
query
|
| VCS |
 |
| bugtrack_url |
|
| requirements |
No requirements were recorded.
|
| Travis-CI |
No Travis.
|
| coveralls test coverage |
No coveralls.
|
# SQLObjects
[English](README.md) | [δΈζ](README.zh-CN.md)
[](https://www.python.org/downloads/)
[](https://opensource.org/licenses/MIT)
[](https://github.com/astral-sh/ruff)
[](https://github.com/microsoft/pyright)
A modern, Django-style async ORM library built on SQLAlchemy Core with chainable queries, Q objects, and relationship
loading. SQLObjects combines the familiar Django ORM API with the performance and flexibility of SQLAlchemy Core.
## β¨ Key Features
- **π Django-style API** - Familiar and intuitive interface for Django developers
- **β‘ Async-first design** - Built for modern async Python applications
- **π Chainable queries** - Fluent query building with method chaining
- **π― Type safety** - Full type annotations and runtime validation
- **π High performance** - Built on SQLAlchemy Core for optimal performance
- **π Smart operations** - Automatic CREATE/UPDATE detection and bulk operations
- **π£ Lifecycle hooks** - Comprehensive signal system for database operations
- **ποΈ Multi-database support** - Seamless multi-database configuration and routing
## π Quick Start
### Installation
```bash
pip install sqlobjects
```
### Basic Usage
```python
from sqlobjects.model import ObjectModel
from sqlobjects.fields import Column, StringColumn, IntegerColumn, BooleanColumn
from sqlobjects.database import init_db, create_tables
# Define your models
class User(ObjectModel):
username: Column[str] = StringColumn(length=50, unique=True)
email: Column[str] = StringColumn(length=100, unique=True)
age: Column[int] = IntegerColumn(nullable=True)
is_active: Column[bool] = BooleanColumn(default=True)
# Initialize database
await init_db("sqlite+aiosqlite:///app.db")
await create_tables(ObjectModel)
# Create and query data
user = await User.objects.create(
username="alice",
email="alice@example.com",
age=25
)
# Chainable queries with Django-style API
active_users = await User.objects.filter(
User.is_active == True
).order_by("-age").limit(10).all()
# Complex queries with Q objects
from sqlobjects.queries import Q
users = await User.objects.filter(
Q(User.age >= 18) & (Q(User.username.like("%admin%")) | Q(User.is_active == True))
).all()
```
## π Core Concepts
### Model Definition
SQLObjects uses a Django-style model definition with automatic table generation:
```python
from sqlobjects.model import ObjectModel
from sqlobjects.fields import Column, StringColumn, DateTimeColumn, foreign_key
from datetime import datetime
class Post(ObjectModel):
title: Column[str] = StringColumn(length=200)
content: Column[str] = StringColumn(type="text")
author_id: Column[int] = foreign_key("users.id")
created_at: Column[datetime] = DateTimeColumn(default_factory=datetime.now)
class Config:
table_name = "blog_posts" # Custom table name
ordering = ["-created_at"] # Default ordering
```
### Query Building
Build complex queries with chainable methods:
```python
# Basic filtering and ordering
posts = await Post.objects.filter(
Post.title.like("%python%")
).order_by("-created_at").limit(5).all()
# Aggregation and annotation
from sqlobjects.expressions import func
user_stats = await User.objects.annotate(
post_count=func.count(User.posts),
latest_post=func.max(User.posts.created_at)
).filter(User.post_count > 0).all()
# Relationship loading
posts = await Post.objects.select_related("author").prefetch_related("comments").all()
```
### Bulk Operations
High-performance bulk operations for large datasets:
```python
# Bulk create (10-100x faster than individual creates)
users_data = [
{"username": f"user{i}", "email": f"user{i}@example.com"}
for i in range(1000)
]
await User.objects.bulk_create(users_data, batch_size=500)
# Bulk update
mappings = [
{"id": 1, "is_active": False},
{"id": 2, "is_active": True},
]
await User.objects.bulk_update(mappings, match_fields=["id"])
# Bulk delete
user_ids = [1, 2, 3, 4, 5]
await User.objects.bulk_delete(user_ids, id_field="id")
```
### Session Management
Flexible session and transaction management:
```python
from sqlobjects.session import ctx_session, ctx_sessions
# Single database transaction
async with ctx_session() as session:
user = await User.objects.using(session).create(username="bob")
posts = await user.posts.using(session).all()
# Automatic commit on success, rollback on error
# Multi-database transactions
async with ctx_sessions("main", "analytics") as sessions:
user = await User.objects.using(sessions["main"]).create(username="alice")
await Log.objects.using(sessions["analytics"]).create(message="User created")
```
### Lifecycle Hooks
Comprehensive signal system for database operations:
```python
class User(ObjectModel):
username: Column[str] = StringColumn(length=50)
async def before_save(self, context):
"""Called before any save operation"""
self.updated_at = datetime.now()
async def after_create(self, context):
"""Called only after creation"""
await self.send_welcome_email()
async def before_delete(self, context):
"""Called before deletion"""
await self.cleanup_related_data()
```
## ποΈ Architecture
SQLObjects is built on a solid foundation with clear architectural principles:
- **SQLAlchemy Core** - Maximum performance and control over SQL generation
- **Async-first** - Native async/await support throughout the library
- **Type safety** - Comprehensive type annotations and runtime validation
- **Modular design** - Clean separation of concerns and extensible architecture
## π Documentation
### Feature Documentation
- [Database Setup](docs/features/01-database-setup.md) - Database configuration and connection management
- [Model Definition](docs/features/02-model-definition.md) - Model creation, fields, and validation
- [Querying Data](docs/features/03-querying-data.md) - Query building, filtering, and aggregation
- [CRUD Operations](docs/features/04-crud-operations.md) - Create, read, update, delete operations
- [Relationships](docs/features/05-relationships.md) - Model relationships and loading strategies
- [Validation & Signals](docs/features/06-validation-signals.md) - Data validation and lifecycle hooks
- [Performance Optimization](docs/features/07-performance-optimization.md) - Performance tuning and best practices
### Design Documentation
- [Core Architecture](docs/design/01-core-architecture.md) - System architecture and design principles
- [Data Operations](docs/design/02-data-operations.md) - Query execution and data processing
- [Field System](docs/design/03-field-system.md) - Field types and type system
- [Relationships](docs/design/04-relationships.md) - Relationship implementation details
- [Extensions](docs/design/05-extensions.md) - Extension points and customization
## π§ Advanced Features
### Multi-Database Support
```python
from sqlobjects.database import init_dbs
# Configure multiple databases
main_db, analytics_db = await init_dbs({
"main": {"url": "postgresql+asyncpg://user:pass@localhost/main"},
"analytics": {"url": "sqlite+aiosqlite:///analytics.db"}
}, default="main")
# Use specific databases
user = await User.objects.using("analytics").create(username="analyst")
```
### Performance Optimization
```python
# Memory-efficient iteration for large datasets
async for user in User.objects.iterator(chunk_size=1000):
await process_user(user)
# Field selection for performance
users = await User.objects.only("id", "username", "email").all() # Load only needed fields
live_data = await User.objects.defer("bio", "profile_image").all() # Defer heavy fields
# Field-level performance optimization
class User(ObjectModel):
bio: Column[str] = column(type="text", deferred=True) # Lazy loading
profile_image: Column[bytes] = column(type="binary", deferred=True)
```
### Advanced Querying
```python
# Subqueries and complex conditions
avg_age = User.objects.aggregate(avg_age=func.avg(User.age)).subquery(query_type="scalar")
older_users = await User.objects.filter(User.age > avg_age).all()
# Manual joins and locking
posts = await Post.objects.join(
User.__table__,
Post.author_id == User.id
).select_for_update(nowait=True).all()
# Raw SQL when needed
users = await User.objects.raw(
"SELECT * FROM users WHERE age > :age",
{"age": 18}
)
```
## π§ͺ Testing
SQLObjects includes comprehensive test coverage:
```bash
# Run all tests
uv run pytest
# Run specific test categories
uv run pytest tests/unit/ # Unit tests
uv run pytest tests/integration/ # Integration tests
uv run pytest tests/performance/ # Performance tests
# Run with coverage
uv run pytest --cov=sqlobjects
```
## π€ Contributing
We welcome contributions! Please see our development guidelines:
1. **Design-first approach** - All changes start with design analysis
2. **Type safety** - Maintain comprehensive type annotations
3. **Test coverage** - Include tests for all new functionality
4. **Documentation** - Update docs for any API changes
### Development Setup
```bash
# Clone the repository
git clone https://github.com/XtraVisionsAI/sqlobjects.git
cd sqlobjects
# Install development dependencies
uv sync --group dev --group test
# Run pre-commit hooks
uv run pre-commit install
# Run tests
uv run pytest
```
## π Roadmap
See our [TODO.md](TODO.md) for planned features:
- **v2.0**: Database health checks, window functions, advanced bulk operations
- **v2.1**: Advanced field optimization, query performance tools
- **v2.2+**: CTE support, advanced SQL functions
## π License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## π Acknowledgments
- Built on the excellent [SQLAlchemy](https://www.sqlalchemy.org/) library
- Inspired by [Django ORM](https://docs.djangoproject.com/en/stable/topics/db/) API design
- Thanks to all contributors and the Python async ecosystem
---
**SQLObjects** - Modern async ORM for Python 3.12+
Raw data
{
"_id": null,
"home_page": null,
"name": "sqlobjects",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.12",
"maintainer_email": "XtraVisions <gitadmin@xtravisions.com>, Chen Hao <chenhao@xtravisions.com>",
"keywords": "python, orm, async, django-style, database, query",
"author": null,
"author_email": "XtraVisions <gitadmin@xtravisions.com>, Chen Hao <chenhao@xtravisions.com>",
"download_url": "https://files.pythonhosted.org/packages/46/5b/6108f3126324f47776354be7a99fd4887fde9a146507abb2cb7bbf8f061c/sqlobjects-1.0.9.tar.gz",
"platform": null,
"description": "# SQLObjects\n\n[English](README.md) | [\u4e2d\u6587](README.zh-CN.md)\n\n[](https://www.python.org/downloads/)\n[](https://opensource.org/licenses/MIT)\n[](https://github.com/astral-sh/ruff)\n[](https://github.com/microsoft/pyright)\n\nA modern, Django-style async ORM library built on SQLAlchemy Core with chainable queries, Q objects, and relationship\nloading. SQLObjects combines the familiar Django ORM API with the performance and flexibility of SQLAlchemy Core.\n\n## \u2728 Key Features\n\n- **\ud83d\ude80 Django-style API** - Familiar and intuitive interface for Django developers\n- **\u26a1 Async-first design** - Built for modern async Python applications\n- **\ud83d\udd17 Chainable queries** - Fluent query building with method chaining\n- **\ud83c\udfaf Type safety** - Full type annotations and runtime validation\n- **\ud83d\udcca High performance** - Built on SQLAlchemy Core for optimal performance\n- **\ud83d\udd04 Smart operations** - Automatic CREATE/UPDATE detection and bulk operations\n- **\ud83c\udfa3 Lifecycle hooks** - Comprehensive signal system for database operations\n- **\ud83d\uddc4\ufe0f Multi-database support** - Seamless multi-database configuration and routing\n\n## \ud83d\ude80 Quick Start\n\n### Installation\n\n```bash\npip install sqlobjects\n```\n\n### Basic Usage\n\n```python\nfrom sqlobjects.model import ObjectModel\nfrom sqlobjects.fields import Column, StringColumn, IntegerColumn, BooleanColumn\nfrom sqlobjects.database import init_db, create_tables\n\n# Define your models\nclass User(ObjectModel):\n username: Column[str] = StringColumn(length=50, unique=True)\n email: Column[str] = StringColumn(length=100, unique=True)\n age: Column[int] = IntegerColumn(nullable=True)\n is_active: Column[bool] = BooleanColumn(default=True)\n\n# Initialize database\nawait init_db(\"sqlite+aiosqlite:///app.db\")\nawait create_tables(ObjectModel)\n\n# Create and query data\nuser = await User.objects.create(\n username=\"alice\", \n email=\"alice@example.com\", \n age=25\n)\n\n# Chainable queries with Django-style API\nactive_users = await User.objects.filter(\n User.is_active == True\n).order_by(\"-age\").limit(10).all()\n\n# Complex queries with Q objects\nfrom sqlobjects.queries import Q\n\nusers = await User.objects.filter(\n Q(User.age >= 18) & (Q(User.username.like(\"%admin%\")) | Q(User.is_active == True))\n).all()\n```\n\n## \ud83d\udcda Core Concepts\n\n### Model Definition\n\nSQLObjects uses a Django-style model definition with automatic table generation:\n\n```python\nfrom sqlobjects.model import ObjectModel\nfrom sqlobjects.fields import Column, StringColumn, DateTimeColumn, foreign_key\nfrom datetime import datetime\n\nclass Post(ObjectModel):\n title: Column[str] = StringColumn(length=200)\n content: Column[str] = StringColumn(type=\"text\")\n author_id: Column[int] = foreign_key(\"users.id\")\n created_at: Column[datetime] = DateTimeColumn(default_factory=datetime.now)\n \n class Config:\n table_name = \"blog_posts\" # Custom table name\n ordering = [\"-created_at\"] # Default ordering\n```\n\n### Query Building\n\nBuild complex queries with chainable methods:\n\n```python\n# Basic filtering and ordering\nposts = await Post.objects.filter(\n Post.title.like(\"%python%\")\n).order_by(\"-created_at\").limit(5).all()\n\n# Aggregation and annotation\nfrom sqlobjects.expressions import func\n\nuser_stats = await User.objects.annotate(\n post_count=func.count(User.posts),\n latest_post=func.max(User.posts.created_at)\n).filter(User.post_count > 0).all()\n\n# Relationship loading\nposts = await Post.objects.select_related(\"author\").prefetch_related(\"comments\").all()\n```\n\n### Bulk Operations\n\nHigh-performance bulk operations for large datasets:\n\n```python\n# Bulk create (10-100x faster than individual creates)\nusers_data = [\n {\"username\": f\"user{i}\", \"email\": f\"user{i}@example.com\"} \n for i in range(1000)\n]\nawait User.objects.bulk_create(users_data, batch_size=500)\n\n# Bulk update\nmappings = [\n {\"id\": 1, \"is_active\": False},\n {\"id\": 2, \"is_active\": True},\n]\nawait User.objects.bulk_update(mappings, match_fields=[\"id\"])\n\n# Bulk delete\nuser_ids = [1, 2, 3, 4, 5]\nawait User.objects.bulk_delete(user_ids, id_field=\"id\")\n```\n\n### Session Management\n\nFlexible session and transaction management:\n\n```python\nfrom sqlobjects.session import ctx_session, ctx_sessions\n\n# Single database transaction\nasync with ctx_session() as session:\n user = await User.objects.using(session).create(username=\"bob\")\n posts = await user.posts.using(session).all()\n # Automatic commit on success, rollback on error\n\n# Multi-database transactions\nasync with ctx_sessions(\"main\", \"analytics\") as sessions:\n user = await User.objects.using(sessions[\"main\"]).create(username=\"alice\")\n await Log.objects.using(sessions[\"analytics\"]).create(message=\"User created\")\n```\n\n### Lifecycle Hooks\n\nComprehensive signal system for database operations:\n\n```python\nclass User(ObjectModel):\n username: Column[str] = StringColumn(length=50)\n \n async def before_save(self, context):\n \"\"\"Called before any save operation\"\"\"\n self.updated_at = datetime.now()\n \n async def after_create(self, context):\n \"\"\"Called only after creation\"\"\"\n await self.send_welcome_email()\n \n async def before_delete(self, context):\n \"\"\"Called before deletion\"\"\"\n await self.cleanup_related_data()\n```\n\n## \ud83c\udfd7\ufe0f Architecture\n\nSQLObjects is built on a solid foundation with clear architectural principles:\n\n- **SQLAlchemy Core** - Maximum performance and control over SQL generation\n- **Async-first** - Native async/await support throughout the library\n- **Type safety** - Comprehensive type annotations and runtime validation\n- **Modular design** - Clean separation of concerns and extensible architecture\n\n## \ud83d\udcd6 Documentation\n\n### Feature Documentation\n\n- [Database Setup](docs/features/01-database-setup.md) - Database configuration and connection management\n- [Model Definition](docs/features/02-model-definition.md) - Model creation, fields, and validation\n- [Querying Data](docs/features/03-querying-data.md) - Query building, filtering, and aggregation\n- [CRUD Operations](docs/features/04-crud-operations.md) - Create, read, update, delete operations\n- [Relationships](docs/features/05-relationships.md) - Model relationships and loading strategies\n- [Validation & Signals](docs/features/06-validation-signals.md) - Data validation and lifecycle hooks\n- [Performance Optimization](docs/features/07-performance-optimization.md) - Performance tuning and best practices\n\n### Design Documentation\n\n- [Core Architecture](docs/design/01-core-architecture.md) - System architecture and design principles\n- [Data Operations](docs/design/02-data-operations.md) - Query execution and data processing\n- [Field System](docs/design/03-field-system.md) - Field types and type system\n- [Relationships](docs/design/04-relationships.md) - Relationship implementation details\n- [Extensions](docs/design/05-extensions.md) - Extension points and customization\n\n## \ud83d\udd27 Advanced Features\n\n### Multi-Database Support\n\n```python\nfrom sqlobjects.database import init_dbs\n\n# Configure multiple databases\nmain_db, analytics_db = await init_dbs({\n \"main\": {\"url\": \"postgresql+asyncpg://user:pass@localhost/main\"},\n \"analytics\": {\"url\": \"sqlite+aiosqlite:///analytics.db\"}\n}, default=\"main\")\n\n# Use specific databases\nuser = await User.objects.using(\"analytics\").create(username=\"analyst\")\n```\n\n### Performance Optimization\n\n```python\n# Memory-efficient iteration for large datasets\nasync for user in User.objects.iterator(chunk_size=1000):\n await process_user(user)\n\n# Field selection for performance\nusers = await User.objects.only(\"id\", \"username\", \"email\").all() # Load only needed fields\nlive_data = await User.objects.defer(\"bio\", \"profile_image\").all() # Defer heavy fields\n\n# Field-level performance optimization\nclass User(ObjectModel):\n bio: Column[str] = column(type=\"text\", deferred=True) # Lazy loading\n profile_image: Column[bytes] = column(type=\"binary\", deferred=True)\n```\n\n### Advanced Querying\n\n```python\n# Subqueries and complex conditions\navg_age = User.objects.aggregate(avg_age=func.avg(User.age)).subquery(query_type=\"scalar\")\nolder_users = await User.objects.filter(User.age > avg_age).all()\n\n# Manual joins and locking\nposts = await Post.objects.join(\n User.__table__, \n Post.author_id == User.id\n).select_for_update(nowait=True).all()\n\n# Raw SQL when needed\nusers = await User.objects.raw(\n \"SELECT * FROM users WHERE age > :age\", \n {\"age\": 18}\n)\n```\n\n## \ud83e\uddea Testing\n\nSQLObjects includes comprehensive test coverage:\n\n```bash\n# Run all tests\nuv run pytest\n\n# Run specific test categories\nuv run pytest tests/unit/ # Unit tests\nuv run pytest tests/integration/ # Integration tests\nuv run pytest tests/performance/ # Performance tests\n\n# Run with coverage\nuv run pytest --cov=sqlobjects\n```\n\n## \ud83e\udd1d Contributing\n\nWe welcome contributions! Please see our development guidelines:\n\n1. **Design-first approach** - All changes start with design analysis\n2. **Type safety** - Maintain comprehensive type annotations\n3. **Test coverage** - Include tests for all new functionality\n4. **Documentation** - Update docs for any API changes\n\n### Development Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/XtraVisionsAI/sqlobjects.git\ncd sqlobjects\n\n# Install development dependencies\nuv sync --group dev --group test\n\n# Run pre-commit hooks\nuv run pre-commit install\n\n# Run tests\nuv run pytest\n```\n\n## \ud83d\udccb Roadmap\n\nSee our [TODO.md](TODO.md) for planned features:\n\n- **v2.0**: Database health checks, window functions, advanced bulk operations\n- **v2.1**: Advanced field optimization, query performance tools\n- **v2.2+**: CTE support, advanced SQL functions\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## \ud83d\ude4f Acknowledgments\n\n- Built on the excellent [SQLAlchemy](https://www.sqlalchemy.org/) library\n- Inspired by [Django ORM](https://docs.djangoproject.com/en/stable/topics/db/) API design\n- Thanks to all contributors and the Python async ecosystem\n\n---\n\n**SQLObjects** - Modern async ORM for Python 3.12+\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Django-style async ORM library based on SQLAlchemy with chainable queries, Q objects, and relationship loading",
"version": "1.0.9",
"project_urls": {
"Bug Tracker": "https://github.com/XtraVisionsAI/sqlobjects/issues",
"Changelog": "https://github.com/XtraVisionsAI/sqlobjects/blob/main/CHANGELOG.md",
"Documentation": "https://github.com/XtraVisionsAI/sqlobjects#readme",
"Homepage": "https://github.com/XtraVisionsAI/sqlobjects",
"Repository": "https://github.com/XtraVisionsAI/sqlobjects.git"
},
"split_keywords": [
"python",
" orm",
" async",
" django-style",
" database",
" query"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "c44c88f6a5f1e095982627ea2b8f74fc8e0c74a28e129a19cf8f2a6ee4157fa1",
"md5": "20225bbe679c89fa4cb0a0eb2c41288c",
"sha256": "e3f6e586f4a3a4de3e2fae2ed53ac2474324f5c6f04521bdc3248b65be8ed195"
},
"downloads": -1,
"filename": "sqlobjects-1.0.9-py3-none-any.whl",
"has_sig": false,
"md5_digest": "20225bbe679c89fa4cb0a0eb2c41288c",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.12",
"size": 149250,
"upload_time": "2025-11-14T03:05:16",
"upload_time_iso_8601": "2025-11-14T03:05:16.774367Z",
"url": "https://files.pythonhosted.org/packages/c4/4c/88f6a5f1e095982627ea2b8f74fc8e0c74a28e129a19cf8f2a6ee4157fa1/sqlobjects-1.0.9-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "465b6108f3126324f47776354be7a99fd4887fde9a146507abb2cb7bbf8f061c",
"md5": "453f46e21bb80a3f2d87f1b1b8053a69",
"sha256": "932baafad57c4a9bfcae33f72254a4a2c1805a1da4d991c1c7f27f9ec45bd563"
},
"downloads": -1,
"filename": "sqlobjects-1.0.9.tar.gz",
"has_sig": false,
"md5_digest": "453f46e21bb80a3f2d87f1b1b8053a69",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.12",
"size": 135101,
"upload_time": "2025-11-14T03:05:18",
"upload_time_iso_8601": "2025-11-14T03:05:18.627908Z",
"url": "https://files.pythonhosted.org/packages/46/5b/6108f3126324f47776354be7a99fd4887fde9a146507abb2cb7bbf8f061c/sqlobjects-1.0.9.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-11-14 03:05:18",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "XtraVisionsAI",
"github_project": "sqlobjects",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "sqlobjects"
}