lunarphase-orm 0.1.1__tar.gz → 0.1.3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/.github/workflows/pypi-publish.yml +1 -3
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/.gitignore +1 -1
- lunarphase_orm-0.1.3/.readthedocs.yaml +13 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/Cargo.lock +1 -1
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/Cargo.toml +1 -1
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/PKG-INFO +2 -1
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/README.md +1 -0
- lunarphase_orm-0.1.3/docs/architecture.md +89 -0
- lunarphase_orm-0.1.3/docs/getting-started.md +202 -0
- lunarphase_orm-0.1.3/docs/index.md +53 -0
- lunarphase_orm-0.1.3/docs/migrations-cli.md +98 -0
- lunarphase_orm-0.1.3/docs/models-and-fields.md +142 -0
- lunarphase_orm-0.1.3/docs/query-builder.md +117 -0
- lunarphase_orm-0.1.3/docs/relations-and-batching.md +110 -0
- lunarphase_orm-0.1.3/docs/requirements.txt +3 -0
- lunarphase_orm-0.1.3/docs/syntax-cheatsheet.md +242 -0
- lunarphase_orm-0.1.3/docs/unit-of-work.md +87 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/lunarphase/__init__.py +1 -1
- lunarphase_orm-0.1.3/lunarphase/cli/__init__.py +1 -0
- lunarphase_orm-0.1.3/lunarphase/cli/main.py +51 -0
- lunarphase_orm-0.1.3/lunarphase/core/__init__.py +1 -0
- lunarphase_orm-0.1.3/lunarphase/db/__init__.py +1 -0
- lunarphase_orm-0.1.3/lunarphase/migrations/__init__.py +1 -0
- lunarphase_orm-0.1.3/lunarphase/migrations/diff.py +60 -0
- lunarphase_orm-0.1.3/lunarphase/migrations/runner.py +111 -0
- lunarphase_orm-0.1.3/lunarphase/migrations/schema.py +34 -0
- lunarphase_orm-0.1.3/lunarphase/query/__init__.py +1 -0
- lunarphase_orm-0.1.3/mkdocs.yml +42 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/pyproject.toml +2 -1
- lunarphase_orm-0.1.3/site/404.html +562 -0
- lunarphase_orm-0.1.3/site/architecture/index.html +836 -0
- lunarphase_orm-0.1.3/site/assets/images/favicon.png +0 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/bundle.d7400e89.min.js +16 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/bundle.d7400e89.min.js.map +7 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.ar.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.da.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.de.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.du.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.el.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.es.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.fi.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.fr.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.he.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.hi.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.hu.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.hy.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.it.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.ja.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.jp.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.kn.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.ko.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.multi.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.nl.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.no.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.pt.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.ro.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.ru.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.sa.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.stemmer.support.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.sv.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.ta.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.te.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.th.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.tr.min.js +18 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.vi.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/min/lunr.zh.min.js +1 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/tinyseg.js +206 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/lunr/wordcut.js +6708 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/workers/search.2c215733.min.js +42 -0
- lunarphase_orm-0.1.3/site/assets/javascripts/workers/search.2c215733.min.js.map +7 -0
- lunarphase_orm-0.1.3/site/assets/stylesheets/main.ec1eaa64.min.css +1 -0
- lunarphase_orm-0.1.3/site/assets/stylesheets/main.ec1eaa64.min.css.map +1 -0
- lunarphase_orm-0.1.3/site/assets/stylesheets/palette.ab4e12ef.min.css +1 -0
- lunarphase_orm-0.1.3/site/assets/stylesheets/palette.ab4e12ef.min.css.map +1 -0
- lunarphase_orm-0.1.3/site/getting-started/index.html +1050 -0
- lunarphase_orm-0.1.3/site/index.html +790 -0
- lunarphase_orm-0.1.3/site/migrations-cli/index.html +958 -0
- lunarphase_orm-0.1.3/site/models-and-fields/index.html +1083 -0
- lunarphase_orm-0.1.3/site/query-builder/index.html +991 -0
- lunarphase_orm-0.1.3/site/relations-and-batching/index.html +886 -0
- lunarphase_orm-0.1.3/site/requirements.txt +3 -0
- lunarphase_orm-0.1.3/site/search/search_index.json +1 -0
- lunarphase_orm-0.1.3/site/sitemap.xml +3 -0
- lunarphase_orm-0.1.3/site/sitemap.xml.gz +0 -0
- lunarphase_orm-0.1.3/site/syntax-cheatsheet/index.html +1099 -0
- lunarphase_orm-0.1.3/site/unit-of-work/index.html +856 -0
- lunarphase_orm-0.1.1/lunarphase/cli/main.py +0 -47
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/.github/workflows/ci.yml +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/BENCHMARK.md +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/DOCUMENTATION.md +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/LICENSE +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/ROADMAP.md +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/benchmarks/advanced_scale_benchmark.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/benchmarks/comprehensive_orm_benchmark.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/benchmarks/diagnostic_3way_benchmark.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/lunarphase/core/ast.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/lunarphase/core/fields.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/lunarphase/core/model.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/lunarphase/core/relations.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/lunarphase/core/state.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/lunarphase/core/uow.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/lunarphase/db/engine.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/lunarphase/query/batcher.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/lunarphase/query/builder.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/src/batcher.rs +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/src/compiler.rs +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/src/lib.rs +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/src/migration_diff.rs +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/src/state_tracker.rs +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/tests/test_benchmarks.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/tests/test_coverage_boost.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/tests/test_fase1_core_ast.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/tests/test_fase2_async_drivers.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/tests/test_fase3_auto_batching_relations.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/tests/test_fase4_dirty_tracking_uow.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/tests/test_fase5_auto_migrations_cli.py +0 -0
- {lunarphase_orm-0.1.1 → lunarphase_orm-0.1.3}/tests/test_rust_performance.py +0 -0
|
@@ -3,9 +3,6 @@ name: Publish to PyPI
|
|
|
3
3
|
on:
|
|
4
4
|
release:
|
|
5
5
|
types: [published]
|
|
6
|
-
push:
|
|
7
|
-
tags:
|
|
8
|
-
- 'v*'
|
|
9
6
|
workflow_dispatch:
|
|
10
7
|
|
|
11
8
|
permissions:
|
|
@@ -100,3 +97,4 @@ jobs:
|
|
|
100
97
|
user: __token__
|
|
101
98
|
password: ${{ secrets.PYPI_API_TOKEN }}
|
|
102
99
|
packages-dir: dist/
|
|
100
|
+
skip-existing: true
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: lunarphase-orm
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.3
|
|
4
4
|
Classifier: Programming Language :: Python :: 3
|
|
5
5
|
Classifier: Programming Language :: Rust
|
|
6
6
|
Classifier: Framework :: AsyncIO
|
|
@@ -21,6 +21,7 @@ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
|
|
|
21
21
|
> **Smart Sync. Zero N+1. High-Performance Python & Rust ORM.**
|
|
22
22
|
|
|
23
23
|
[](https://pypi.org/project/lunarphase-orm/)
|
|
24
|
+
[](https://pepy.tech/projects/lunarphase-orm)
|
|
24
25
|
[](https://www.python.org/downloads/)
|
|
25
26
|
[](https://www.rust-lang.org/)
|
|
26
27
|
[](LICENSE)
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
> **Smart Sync. Zero N+1. High-Performance Python & Rust ORM.**
|
|
7
7
|
|
|
8
8
|
[](https://pypi.org/project/lunarphase-orm/)
|
|
9
|
+
[](https://pepy.tech/projects/lunarphase-orm)
|
|
9
10
|
[](https://www.python.org/downloads/)
|
|
10
11
|
[](https://www.rust-lang.org/)
|
|
11
12
|
[](LICENSE)
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# Core Architecture
|
|
2
|
+
|
|
3
|
+
This document describes the internal design of LunarPhaseORM, including the PyO3 C-extension boundary, Rust memory layouts, state isolation mechanisms, and fallback systems.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## C-Extension Interoperability (`_lunarphase_rs`)
|
|
8
|
+
|
|
9
|
+
The core execution engine uses a native C-extension compiled from Rust via PyO3. The module is registered under the standard Python C-API ABI3 framework (`abi3-py39`), permitting a single compiled binary wheel to execute across CPython versions 3.9 through 3.14+.
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
+-------------------------------------------------------------+
|
|
13
|
+
| Python Layer |
|
|
14
|
+
| - lunarphase/core/state.py (State Tracker Facade) |
|
|
15
|
+
+-------------------------------------------------------------+
|
|
16
|
+
│
|
|
17
|
+
PyO3 FFI Boundary (abi3-py39)
|
|
18
|
+
│
|
|
19
|
+
▼
|
|
20
|
+
+-------------------------------------------------------------+
|
|
21
|
+
| Native Rust Extension Module |
|
|
22
|
+
| |
|
|
23
|
+
| +-------------------------------------------------------+ |
|
|
24
|
+
| | StateTracker Struct | |
|
|
25
|
+
| | - fields: FxHashMap<String, FieldEntry> | |
|
|
26
|
+
| +-------------------------------------------------------+ |
|
|
27
|
+
| | BatchAggregator Struct | |
|
|
28
|
+
| | - int_keys: FxHashSet<i64> | |
|
|
29
|
+
| | - str_keys: FxHashSet<String> | |
|
|
30
|
+
| +-------------------------------------------------------+ |
|
|
31
|
+
| | QueryCompiler Struct | |
|
|
32
|
+
| | - Buffer String Pre-allocation & Dialect Placeholders | |
|
|
33
|
+
| +-------------------------------------------------------+ |
|
|
34
|
+
| | SchemaDiffEngine Struct | |
|
|
35
|
+
| | - Model vs Database Table Introspection Diffing | |
|
|
36
|
+
| +-------------------------------------------------------+ |
|
|
37
|
+
+-------------------------------------------------------------+
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## State Isolation & Memory Layout
|
|
43
|
+
|
|
44
|
+
### StateTracker Struct
|
|
45
|
+
|
|
46
|
+
The Rust `StateTracker` struct manages instance property state. Each field entry is encapsulated inside a single contiguous struct:
|
|
47
|
+
|
|
48
|
+
```rust
|
|
49
|
+
struct FieldEntry {
|
|
50
|
+
snapshot: String, // Serialized state at hydration / commit
|
|
51
|
+
current: String, // Current mutated state
|
|
52
|
+
py_obj: PyObject, // Reference back to Python object
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
#[pyclass]
|
|
56
|
+
pub struct StateTracker {
|
|
57
|
+
fields: FxHashMap<String, FieldEntry>,
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Memory Allocation Impact
|
|
62
|
+
|
|
63
|
+
Standard Python ORM implementations store instance attribute graphs inside Python dictionaries (`__dict__`). For an object graph with $N$ instances and $M$ fields, Python allocates $N$ dictionary objects on the heap.
|
|
64
|
+
|
|
65
|
+
LunarPhaseORM consolidates instance state into Rust-managed C structs utilizing `rustc_hash::FxHashMap` (a non-cryptographic hashing algorithm designed for short string keys). This reduces Python heap allocations by 66% per instance.
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## Pure Python Fallback System
|
|
70
|
+
|
|
71
|
+
If the native `_lunarphase_rs` extension module is unavailable in the execution environment, LunarPhaseORM automatically switches to a pure Python fallback implementation (`PyStateTracker`):
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
# lunarphase/core/state.py
|
|
75
|
+
try:
|
|
76
|
+
from lunarphase._lunarphase_rs import StateTracker as RustStateTracker
|
|
77
|
+
HAS_RUST = True
|
|
78
|
+
except ImportError:
|
|
79
|
+
HAS_RUST = False
|
|
80
|
+
|
|
81
|
+
class StateTrackerFacade:
|
|
82
|
+
def __init__(self):
|
|
83
|
+
if HAS_RUST:
|
|
84
|
+
self._impl = RustStateTracker()
|
|
85
|
+
else:
|
|
86
|
+
self._impl = PyStateTracker()
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The fallback implementation maintains API equivalence, ensuring tests and execution continue without binary extensions, albeit without C-level memory compaction.
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
# Getting Started Tutorial
|
|
2
|
+
|
|
3
|
+
Welcome to **LunarPhaseORM**! This step-by-step tutorial guides you through setting up your environment, connecting to a database engine, defining models, performing CRUD operations, and building a full runnable application.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Installation
|
|
8
|
+
|
|
9
|
+
Install **LunarPhaseORM** from PyPI using `pip`:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install lunarphase-orm
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
### Installation Verification
|
|
16
|
+
|
|
17
|
+
Verify the package installation in Python:
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
import lunarphase
|
|
21
|
+
print(lunarphase.__version__)
|
|
22
|
+
# Output: 0.1.3
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## 2. Database Connection Setup
|
|
28
|
+
|
|
29
|
+
LunarPhaseORM connects to databases via async drivers (`aiosqlite`, `asyncpg`, `aiomysql`). Initialize your engine using `create_engine()`:
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from lunarphase import create_engine
|
|
33
|
+
|
|
34
|
+
# SQLite (In-Memory for testing/prototyping)
|
|
35
|
+
engine = create_engine("sqlite:///:memory:")
|
|
36
|
+
|
|
37
|
+
# SQLite (File-based database)
|
|
38
|
+
engine = create_engine("sqlite:///app.db")
|
|
39
|
+
|
|
40
|
+
# PostgreSQL
|
|
41
|
+
engine = create_engine("postgres://user:password@localhost:5432/my_database")
|
|
42
|
+
|
|
43
|
+
# MySQL
|
|
44
|
+
engine = create_engine("mysql://user:password@localhost:3306/my_database")
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## 3. Defining Your First Model
|
|
50
|
+
|
|
51
|
+
Models derive from `lunarphase.Model`. Declare database table attributes using field descriptors (`PrimaryKeyField`, `StringField`, `IntegerField`, etc.):
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from lunarphase import Model, PrimaryKeyField, StringField, IntegerField, BooleanField
|
|
55
|
+
|
|
56
|
+
class User(Model):
|
|
57
|
+
__tablename__ = "users" # Database table name
|
|
58
|
+
|
|
59
|
+
id = PrimaryKeyField()
|
|
60
|
+
name = StringField(nullable=False)
|
|
61
|
+
email = StringField(nullable=False)
|
|
62
|
+
age = IntegerField(default=18)
|
|
63
|
+
is_active = BooleanField(default=True)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## 4. Complete CRUD Syntax Tutorial
|
|
69
|
+
|
|
70
|
+
### Step 4.1: Creating Records (`INSERT`)
|
|
71
|
+
|
|
72
|
+
You can create records using `Model.create()` or by instantiating the model class and calling `await user.save()`:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
async def create_users_tutorial():
|
|
76
|
+
# Method A: Classmethod creation (Saves directly to DB)
|
|
77
|
+
alice = await User.create(name="Alice", email="alice@example.com", age=25)
|
|
78
|
+
print(f"Created Alice with ID: {alice.id}")
|
|
79
|
+
|
|
80
|
+
# Method B: Instantiate first, then save
|
|
81
|
+
bob = User(name="Bob", email="bob@example.com", age=30)
|
|
82
|
+
await bob.save()
|
|
83
|
+
print(f"Created Bob with ID: {bob.id}")
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Step 4.2: Querying Records (`SELECT`)
|
|
87
|
+
|
|
88
|
+
Fetch records using the fluent `QueryBuilder` API:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
async def query_users_tutorial():
|
|
92
|
+
# Fetch all records
|
|
93
|
+
all_users = await User.all()
|
|
94
|
+
print("Total users:", len(all_users))
|
|
95
|
+
|
|
96
|
+
# Single record lookup by condition
|
|
97
|
+
alice = await User.where(User.name == "Alice").first()
|
|
98
|
+
print("Found Alice:", alice.email)
|
|
99
|
+
|
|
100
|
+
# Filtered dataset lookup
|
|
101
|
+
adults = await User.where(User.age >= 21).order_by("age", "desc").all()
|
|
102
|
+
for user in adults:
|
|
103
|
+
print(f"User: {user.name}, Age: {user.age}")
|
|
104
|
+
|
|
105
|
+
# List filter using __in
|
|
106
|
+
selected = await User.where(id__in=[1, 2, 3]).all()
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Step 4.3: Updating Records (`UPDATE`)
|
|
110
|
+
|
|
111
|
+
LunarPhaseORM includes **Rust-Powered Selective Field Tracking**. Only attributes you modify are included in the SQL `UPDATE` statement:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
async def update_user_tutorial():
|
|
115
|
+
# 1. Fetch user from DB
|
|
116
|
+
user = await User.where(User.name == "Alice").first()
|
|
117
|
+
|
|
118
|
+
# 2. Modify attribute
|
|
119
|
+
user.age = 26
|
|
120
|
+
|
|
121
|
+
# 3. Save modifications
|
|
122
|
+
# Executes: UPDATE users SET age = 26 WHERE id = 1;
|
|
123
|
+
await user.save()
|
|
124
|
+
print("Alice updated successfully!")
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
> **Performance Note**: Calling `user.save()` without modifying any attributes executes **zero** SQL queries!
|
|
128
|
+
|
|
129
|
+
### Step 4.4: Deleting Records (`DELETE`)
|
|
130
|
+
|
|
131
|
+
Delete records from the database using `.delete()`:
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
async def delete_user_tutorial():
|
|
135
|
+
user = await User.where(User.name == "Bob").first()
|
|
136
|
+
if user:
|
|
137
|
+
await user.delete()
|
|
138
|
+
print("Bob deleted successfully!")
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
---
|
|
142
|
+
|
|
143
|
+
## 5. Full Runnable Quickstart Example
|
|
144
|
+
|
|
145
|
+
Copy and run this complete script to see LunarPhaseORM in action:
|
|
146
|
+
|
|
147
|
+
```python
|
|
148
|
+
import asyncio
|
|
149
|
+
from lunarphase import (
|
|
150
|
+
Model, PrimaryKeyField, StringField, IntegerField,
|
|
151
|
+
create_engine, get_engine
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
# 1. Define Model
|
|
155
|
+
class Product(Model):
|
|
156
|
+
__tablename__ = "products"
|
|
157
|
+
|
|
158
|
+
id = PrimaryKeyField()
|
|
159
|
+
name = StringField(nullable=False)
|
|
160
|
+
price = IntegerField(default=0)
|
|
161
|
+
|
|
162
|
+
async def main():
|
|
163
|
+
# 2. Setup In-Memory SQLite Engine
|
|
164
|
+
engine = create_engine("sqlite:///:memory:")
|
|
165
|
+
|
|
166
|
+
# 3. Create table schema manually for testing
|
|
167
|
+
await engine.execute("""
|
|
168
|
+
CREATE TABLE products (
|
|
169
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
170
|
+
name VARCHAR(255) NOT NULL,
|
|
171
|
+
price INTEGER DEFAULT 0
|
|
172
|
+
);
|
|
173
|
+
""")
|
|
174
|
+
|
|
175
|
+
# 4. Create Products
|
|
176
|
+
p1 = await Product.create(name="Laptop", price=1200)
|
|
177
|
+
p2 = await Product.create(name="Smartphone", price=800)
|
|
178
|
+
p3 = await Product.create(name="Headphones", price=150)
|
|
179
|
+
|
|
180
|
+
print(f"Created products: {p1.name}, {p2.name}, {p3.name}")
|
|
181
|
+
|
|
182
|
+
# 5. Query Products with Filter & Order
|
|
183
|
+
items = await Product.where(Product.price >= 500).order_by("price", "desc").all()
|
|
184
|
+
print("\nProducts priced >= 500:")
|
|
185
|
+
for item in items:
|
|
186
|
+
print(f" - {item.name}: ${item.price}")
|
|
187
|
+
|
|
188
|
+
# 6. Update Product (Selective Field Update)
|
|
189
|
+
p1.price = 1100
|
|
190
|
+
await p1.save()
|
|
191
|
+
print(f"\nUpdated {p1.name} price to ${p1.price}")
|
|
192
|
+
|
|
193
|
+
# 7. Count Products
|
|
194
|
+
total_count = await Product.where(Product.price > 0).count()
|
|
195
|
+
print(f"\nTotal products count: {total_count}")
|
|
196
|
+
|
|
197
|
+
# 8. Clean up engine connection
|
|
198
|
+
await engine.disconnect()
|
|
199
|
+
|
|
200
|
+
if __name__ == "__main__":
|
|
201
|
+
asyncio.run(main())
|
|
202
|
+
```
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# Technical Manual — LunarPhaseORM
|
|
2
|
+
|
|
3
|
+
LunarPhaseORM is an async-first Object-Relational Mapping (ORM) framework for Python 3.9+ accelerated by a native C-extension compiled from Rust (`_lunarphase_rs`).
|
|
4
|
+
|
|
5
|
+
The framework combines an Active Record interface (`model.save()`, `Model.create()`) with a Data Mapper architecture utilizing a Unit of Work transaction engine, an Identity Map, and an event-loop micro-task queue for relationship batching.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Technical Overview
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
+-------------------------------------------------------------------+
|
|
13
|
+
| Python Application |
|
|
14
|
+
| - Async Engine Driver (aiosqlite / asyncpg / aiomysql) |
|
|
15
|
+
| - Model Classes (ModelBase Metaclass & Field Descriptors) |
|
|
16
|
+
| - Identity Map & UnitOfWork Transaction Management |
|
|
17
|
+
| - DeferredAutoBatcher Micro-Task Loop Scheduler |
|
|
18
|
+
+-------------------------------------------------------------------+
|
|
19
|
+
│
|
|
20
|
+
PyO3 / C-API FFI Boundary (abi3-py39)
|
|
21
|
+
│
|
|
22
|
+
▼
|
|
23
|
+
+-------------------------------------------------------------------+
|
|
24
|
+
| Native Rust Extension (_lunarphase_rs) |
|
|
25
|
+
| - StateTracker (FxHashMap<String, FieldEntry> Snapshot) |
|
|
26
|
+
| - BatchAggregator (FxHashSet<i64> & FxHashSet<String>) |
|
|
27
|
+
| - QueryCompiler (Pre-allocated String Buffers & Dialects) |
|
|
28
|
+
| - SchemaDiffEngine (Model vs Database DDL Comparison) |
|
|
29
|
+
+-------------------------------------------------------------------+
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## Architectural Objectives
|
|
35
|
+
|
|
36
|
+
1. **Memory Allocation Efficiency**: Model snapshot tracking and dirty field comparisons are offloaded to C-contiguous Rust memory structures (`FxHashMap`), avoiding per-instance Python dictionary graph creation.
|
|
37
|
+
2. **N+1 Query Resolution**: Relationship queries are deferred and batched into single `WHERE id IN (...)` operations via `asyncio.get_running_loop().call_soon()`.
|
|
38
|
+
3. **Selective Field Updates**: Dirty attribute tracking ensures SQL `UPDATE` statements format only fields modified since the last snapshot hydration.
|
|
39
|
+
4. **C-API Compatibility**: Rust modules are compiled using standard `PyO3` bindings under Python C-API ABI3 specifications (`cp39-abi3`), enabling binary wheel execution across CPython 3.9 through 3.14+.
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## Module Breakdown
|
|
44
|
+
|
|
45
|
+
| Module Path | Primary Responsibility | Core Classes / Types |
|
|
46
|
+
|---|---|---|
|
|
47
|
+
| [`lunarphase.core.model`](models-and-fields.md) | Metaclass attribute registration and Active Record API | `ModelBase`, `Model` |
|
|
48
|
+
| [`lunarphase.core.fields`](models-and-fields.md) | Attribute descriptors and AST expression construction | `FieldDescriptor`, `PrimaryKeyField`, `StringField`, `IntegerField` |
|
|
49
|
+
| [`lunarphase.core.state`](architecture.md) | Snapshot management and dirty field identification | `StateTracker` (Rust bridge), `PyStateTracker` (Fallback) |
|
|
50
|
+
| [`lunarphase.query.builder`](query-builder.md) | AST compilation and parameter binding | `QueryBuilder`, `ColumnRef`, `BinaryOp` |
|
|
51
|
+
| [`lunarphase.query.batcher`](relations-and-batching.md) | Event loop micro-task batching scheduler | `DeferredAutoBatcher`, `BatchAggregator` |
|
|
52
|
+
| [`lunarphase.core.uow`](unit-of-work.md) | Transaction boundaries and identity mapping | `UnitOfWork`, `IdentityMap` |
|
|
53
|
+
| [`lunarphase.migrations`](migrations-cli.md) | Schema extraction, diffing, and CLI execution | `SchemaDiffEngine`, `MigrationRunner`, `CLI` |
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# Migrations & CLI Reference Tutorial
|
|
2
|
+
|
|
3
|
+
This document covers automated database schema diffing (`SchemaDiffEngine`), migration file generation, and CLI terminal commands.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Command Line Tool (`lunarphase`)
|
|
8
|
+
|
|
9
|
+
The `lunarphase` CLI manages database schema migrations, status inspections, and rollbacks.
|
|
10
|
+
|
|
11
|
+
### CLI Commands Summary
|
|
12
|
+
|
|
13
|
+
| Command Syntax | Description | Example Usage |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `lunarphase status` | Displays current migration status and pending files | `lunarphase status` |
|
|
16
|
+
| `lunarphase make:migration <name>` | Generates a new DDL schema migration file | `lunarphase make:migration "create_users_table"` |
|
|
17
|
+
| `lunarphase migrate` | Applies all pending migrations sequentially | `lunarphase migrate` |
|
|
18
|
+
| `lunarphase rollback` | Rolls back the most recently applied migration | `lunarphase rollback` |
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## 2. Step-by-Step CLI Migration Walkthrough
|
|
23
|
+
|
|
24
|
+
### Step 2.1: Checking Migration Status
|
|
25
|
+
|
|
26
|
+
Check current database migration state:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
$ lunarphase status
|
|
30
|
+
|
|
31
|
+
--- LunarPhaseORM Migration Status ---
|
|
32
|
+
No migrations applied yet.
|
|
33
|
+
--------------------------------------
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Step 2.2: Generating Migration Files
|
|
37
|
+
|
|
38
|
+
Generate a new migration script based on your defined models:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
$ lunarphase make:migration "create_users_table"
|
|
42
|
+
Created migration file: migrations/1723872000_create_users_table.py
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Step 2.3: Generated Migration File Structure
|
|
46
|
+
|
|
47
|
+
The CLI creates a Python migration script exporting `upgrade(engine)` and `downgrade(engine)` functions:
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
"""
|
|
51
|
+
Migration generated automatically by LunarPhaseORM
|
|
52
|
+
Timestamp: 1723872000
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
async def upgrade(engine):
|
|
56
|
+
sql_statements = [
|
|
57
|
+
"CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255) NOT NULL, age INTEGER DEFAULT 18);"
|
|
58
|
+
]
|
|
59
|
+
for sql in sql_statements:
|
|
60
|
+
await engine.execute(sql)
|
|
61
|
+
|
|
62
|
+
async def downgrade(engine):
|
|
63
|
+
sql_statements = [
|
|
64
|
+
"DROP TABLE IF EXISTS users;"
|
|
65
|
+
]
|
|
66
|
+
for sql in sql_statements:
|
|
67
|
+
await engine.execute(sql)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Step 2.4: Applying Migrations (`lunarphase migrate`)
|
|
71
|
+
|
|
72
|
+
Execute pending migrations:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
$ lunarphase migrate
|
|
76
|
+
Applying migration: 1723872000_create_users_table.py
|
|
77
|
+
Successfully applied: 1723872000_create_users_table.py
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### Step 2.5: Verifying Updated Status
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
$ lunarphase status
|
|
84
|
+
|
|
85
|
+
--- LunarPhaseORM Migration Status ---
|
|
86
|
+
[X] 1723872000_create_users_table.py (applied: 2026-08-17 10:15:00)
|
|
87
|
+
--------------------------------------
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Step 2.6: Rolling Back Migrations (`lunarphase rollback`)
|
|
91
|
+
|
|
92
|
+
Revert the last applied migration:
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
$ lunarphase rollback
|
|
96
|
+
Rolling back migration: 1723872000_create_users_table.py
|
|
97
|
+
Successfully rolled back: 1723872000_create_users_table.py
|
|
98
|
+
```
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# Models & Fields Tutorial
|
|
2
|
+
|
|
3
|
+
This document details model definition mechanics, field descriptor configurations, active record methods, and AST operator overloading syntax.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Model Definition (`lunarphase.Model`)
|
|
8
|
+
|
|
9
|
+
Models represent database tables. To create a model, inherit from `lunarphase.Model`:
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from lunarphase import Model, PrimaryKeyField, StringField, IntegerField
|
|
13
|
+
|
|
14
|
+
class Article(Model):
|
|
15
|
+
__tablename__ = "articles" # Explicit table name specification
|
|
16
|
+
|
|
17
|
+
id = PrimaryKeyField()
|
|
18
|
+
title = StringField(nullable=False)
|
|
19
|
+
views = IntegerField(default=0)
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
### Table Name Resolution Rules
|
|
23
|
+
|
|
24
|
+
1. **Explicit Specification**: Set `__tablename__ = "custom_table_name"`.
|
|
25
|
+
2. **Automatic Default**: If `__tablename__` is omitted, the metaclass (`ModelBase`) automatically converts the class name to lowercase plural (e.g. `User` -> `"users"`).
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 2. Field Descriptors Syntax Reference
|
|
30
|
+
|
|
31
|
+
Field descriptors define column data types, constraints, and defaults.
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from lunarphase import (
|
|
35
|
+
PrimaryKeyField,
|
|
36
|
+
StringField,
|
|
37
|
+
IntegerField,
|
|
38
|
+
FloatField,
|
|
39
|
+
BooleanField,
|
|
40
|
+
DateTimeField,
|
|
41
|
+
JSONField
|
|
42
|
+
)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Field Type Options & Constructor Reference
|
|
46
|
+
|
|
47
|
+
| Field Descriptor | Parameters | SQL Data Type | Usage Example |
|
|
48
|
+
|---|---|---|---|
|
|
49
|
+
| `PrimaryKeyField` | `name=None`, `auto_increment=True` | `INTEGER PRIMARY KEY AUTOINCREMENT` | `id = PrimaryKeyField()` |
|
|
50
|
+
| `StringField` | `name=None`, `nullable=True`, `default=None` | `VARCHAR(255)` | `title = StringField(nullable=False)` |
|
|
51
|
+
| `IntegerField` | `name=None`, `nullable=True`, `default=None` | `INTEGER` | `views = IntegerField(default=0)` |
|
|
52
|
+
| `FloatField` | `name=None`, `nullable=True`, `default=None` | `REAL` / `FLOAT` | `price = FloatField(default=0.0)` |
|
|
53
|
+
| `BooleanField` | `name=None`, `nullable=True`, `default=None` | `BOOLEAN` | `is_published = BooleanField(default=False)` |
|
|
54
|
+
| `DateTimeField` | `name=None`, `nullable=True`, `default=None` | `DATETIME` | `created_at = DateTimeField()` |
|
|
55
|
+
| `JSONField` | `name=None`, `nullable=True`, `default=None` | `JSON` / `TEXT` | `tags = JSONField(default=[])` |
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## 3. Active Record Methods Tutorial
|
|
60
|
+
|
|
61
|
+
Every model instance inherits essential active record methods:
|
|
62
|
+
|
|
63
|
+
### `.create(**kwargs) -> Model`
|
|
64
|
+
|
|
65
|
+
Instantiates and saves a model record in a single operation:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
article = await Article.create(title="LunarPhaseORM Release", views=100)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### `.save() -> bool`
|
|
72
|
+
|
|
73
|
+
Persists changes to the database. Uses Rust `StateTracker` to diff current attributes against initial snapshots:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
article = Article(title="Draft Article", views=0)
|
|
77
|
+
await article.save() # Executes INSERT
|
|
78
|
+
|
|
79
|
+
article.views = 5 # Mark field as dirty
|
|
80
|
+
await article.save() # Executes UPDATE articles SET views = 5 WHERE id = 1;
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### `.delete() -> bool`
|
|
84
|
+
|
|
85
|
+
Deletes the model instance from the database:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
article = await Article.where(id=1).first()
|
|
89
|
+
await article.delete() # Executes DELETE FROM articles WHERE id = 1;
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### `.hydrate(row: dict) -> Model`
|
|
93
|
+
|
|
94
|
+
Hydrates a dictionary row into a tracked model instance without triggering database SQL:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
raw_row = {"id": 10, "title": "Hydrated Article", "views": 500}
|
|
98
|
+
article = Article.hydrate(raw_row)
|
|
99
|
+
print(article.title) # "Hydrated Article"
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 4. AST Operator Overloading Syntax
|
|
105
|
+
|
|
106
|
+
Accessing a field descriptor on a Model class returns a `ColumnRef` node. Python operators are overloaded to produce AST filter expressions:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
# Returns ColumnRef("views")
|
|
110
|
+
Article.views
|
|
111
|
+
|
|
112
|
+
# Returns BinaryOp(ColumnRef("views"), ">=", Literal(50))
|
|
113
|
+
Article.views >= 50
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Complete AST Expression Operators
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
# Equality (==) -> "title = 'Python'"
|
|
120
|
+
Article.title == "Python"
|
|
121
|
+
|
|
122
|
+
# Inequality (!=) -> "views != 0"
|
|
123
|
+
Article.views != 0
|
|
124
|
+
|
|
125
|
+
# Less than (<) & Less than or equal (<=)
|
|
126
|
+
Article.views < 100
|
|
127
|
+
Article.views <= 100
|
|
128
|
+
|
|
129
|
+
# Greater than (>) & Greater than or equal (>=)
|
|
130
|
+
Article.views > 10
|
|
131
|
+
Article.views >= 10
|
|
132
|
+
|
|
133
|
+
# IN List (.in_([val1, val2]))
|
|
134
|
+
Article.id.in_([1, 2, 3])
|
|
135
|
+
|
|
136
|
+
# SQL LIKE Pattern (.like(pattern))
|
|
137
|
+
Article.title.like("%ORM%")
|
|
138
|
+
|
|
139
|
+
# Null Checks (.is_null() / .is_not_null())
|
|
140
|
+
Article.title.is_null()
|
|
141
|
+
Article.title.is_not_null()
|
|
142
|
+
```
|