lunarphase-orm 0.1.3__tar.gz → 0.1.4__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.3 → lunarphase_orm-0.1.4}/.gitignore +4 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/Cargo.lock +1 -1
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/Cargo.toml +1 -1
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/PKG-INFO +1 -1
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/__init__.py +4 -2
- lunarphase_orm-0.1.4/lunarphase/db/engine.py +230 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/migrations/diff.py +11 -4
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/migrations/runner.py +25 -7
- lunarphase_orm-0.1.4/lunarphase/migrations/schema.py +54 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/pyproject.toml +1 -1
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/relations-and-batching/index.html +60 -10
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/search/search_index.json +1 -1
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/sitemap.xml.gz +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/src/migration_diff.rs +13 -5
- lunarphase_orm-0.1.4/tests/test_all_engines_deep.py +142 -0
- lunarphase_orm-0.1.3/lunarphase/db/engine.py +0 -103
- lunarphase_orm-0.1.3/lunarphase/migrations/schema.py +0 -34
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/.github/workflows/ci.yml +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/.github/workflows/pypi-publish.yml +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/.readthedocs.yaml +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/BENCHMARK.md +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/DOCUMENTATION.md +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/LICENSE +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/README.md +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/ROADMAP.md +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/benchmarks/advanced_scale_benchmark.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/benchmarks/comprehensive_orm_benchmark.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/benchmarks/diagnostic_3way_benchmark.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/docs/architecture.md +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/docs/getting-started.md +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/docs/index.md +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/docs/migrations-cli.md +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/docs/models-and-fields.md +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/docs/query-builder.md +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/docs/relations-and-batching.md +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/docs/requirements.txt +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/docs/syntax-cheatsheet.md +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/docs/unit-of-work.md +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/cli/__init__.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/cli/main.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/core/__init__.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/core/ast.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/core/fields.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/core/model.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/core/relations.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/core/state.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/core/uow.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/db/__init__.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/migrations/__init__.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/query/__init__.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/query/batcher.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/lunarphase/query/builder.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/mkdocs.yml +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/404.html +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/architecture/index.html +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/images/favicon.png +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/bundle.d7400e89.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/bundle.d7400e89.min.js.map +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.ar.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.da.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.de.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.du.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.el.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.es.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.fi.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.fr.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.he.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.hi.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.hu.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.hy.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.it.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.ja.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.jp.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.kn.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.ko.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.multi.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.nl.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.no.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.pt.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.ro.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.ru.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.sa.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.stemmer.support.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.sv.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.ta.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.te.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.th.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.tr.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.vi.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/min/lunr.zh.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/tinyseg.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/lunr/wordcut.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/workers/search.2c215733.min.js +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/javascripts/workers/search.2c215733.min.js.map +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/stylesheets/main.ec1eaa64.min.css +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/stylesheets/main.ec1eaa64.min.css.map +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/stylesheets/palette.ab4e12ef.min.css +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/assets/stylesheets/palette.ab4e12ef.min.css.map +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/getting-started/index.html +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/index.html +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/migrations-cli/index.html +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/models-and-fields/index.html +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/query-builder/index.html +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/requirements.txt +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/sitemap.xml +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/syntax-cheatsheet/index.html +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/site/unit-of-work/index.html +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/src/batcher.rs +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/src/compiler.rs +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/src/lib.rs +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/src/state_tracker.rs +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/tests/test_benchmarks.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/tests/test_coverage_boost.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/tests/test_fase1_core_ast.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/tests/test_fase2_async_drivers.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/tests/test_fase3_auto_batching_relations.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/tests/test_fase4_dirty_tracking_uow.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/tests/test_fase5_auto_migrations_cli.py +0 -0
- {lunarphase_orm-0.1.3 → lunarphase_orm-0.1.4}/tests/test_rust_performance.py +0 -0
|
@@ -17,12 +17,12 @@ from lunarphase.core.fields import (
|
|
|
17
17
|
)
|
|
18
18
|
from lunarphase.core.relations import HasMany, BelongsTo, HasOne
|
|
19
19
|
from lunarphase.core.uow import UnitOfWork, IdentityMap
|
|
20
|
-
from lunarphase.db.engine import create_engine, set_engine, get_engine, SQLiteEngine
|
|
20
|
+
from lunarphase.db.engine import create_engine, set_engine, get_engine, SQLiteEngine, MySQLEngine, PostgresEngine
|
|
21
21
|
from lunarphase.query.builder import QueryBuilder
|
|
22
22
|
from lunarphase.query.batcher import DeferredAutoBatcher
|
|
23
23
|
from lunarphase.migrations.runner import MigrationRunner
|
|
24
24
|
|
|
25
|
-
__version__ = "0.1.
|
|
25
|
+
__version__ = "0.1.4"
|
|
26
26
|
__all__ = [
|
|
27
27
|
"Model",
|
|
28
28
|
"ModelBase",
|
|
@@ -43,6 +43,8 @@ __all__ = [
|
|
|
43
43
|
"set_engine",
|
|
44
44
|
"get_engine",
|
|
45
45
|
"SQLiteEngine",
|
|
46
|
+
"MySQLEngine",
|
|
47
|
+
"PostgresEngine",
|
|
46
48
|
"QueryBuilder",
|
|
47
49
|
"DeferredAutoBatcher",
|
|
48
50
|
"MigrationRunner",
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import re
|
|
3
|
+
from typing import Any, Dict, List, Optional, Union
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
import aiosqlite
|
|
7
|
+
except ImportError:
|
|
8
|
+
aiosqlite = None
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
import aiomysql
|
|
12
|
+
except ImportError:
|
|
13
|
+
aiomysql = None
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
import asyncpg
|
|
17
|
+
except ImportError:
|
|
18
|
+
asyncpg = None
|
|
19
|
+
|
|
20
|
+
class DatabaseEngine:
|
|
21
|
+
"""Base Async Database Engine abstraction."""
|
|
22
|
+
def __init__(self, url: str):
|
|
23
|
+
self.url = url
|
|
24
|
+
self.dialect = self._parse_dialect(url)
|
|
25
|
+
|
|
26
|
+
def _parse_dialect(self, url: str) -> str:
|
|
27
|
+
if url.startswith("sqlite"):
|
|
28
|
+
return "sqlite"
|
|
29
|
+
elif url.startswith("postgres") or url.startswith("postgresql"):
|
|
30
|
+
return "postgres"
|
|
31
|
+
elif url.startswith("mysql"):
|
|
32
|
+
return "mysql"
|
|
33
|
+
return "sqlite"
|
|
34
|
+
|
|
35
|
+
async def connect(self):
|
|
36
|
+
raise NotImplementedError
|
|
37
|
+
|
|
38
|
+
async def disconnect(self):
|
|
39
|
+
raise NotImplementedError
|
|
40
|
+
|
|
41
|
+
async def fetch_all(self, sql: str, params: tuple = ()) -> List[Dict[str, Any]]:
|
|
42
|
+
raise NotImplementedError
|
|
43
|
+
|
|
44
|
+
async def fetch_one(self, sql: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
|
|
45
|
+
rows = await self.fetch_all(sql, params)
|
|
46
|
+
return rows[0] if rows else None
|
|
47
|
+
|
|
48
|
+
async def execute(self, sql: str, params: tuple = ()) -> Any:
|
|
49
|
+
raise NotImplementedError
|
|
50
|
+
|
|
51
|
+
async def execute_insert(self, sql: str, params: tuple = ()) -> Any:
|
|
52
|
+
raise NotImplementedError
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class SQLiteEngine(DatabaseEngine):
|
|
56
|
+
def __init__(self, url: str):
|
|
57
|
+
super().__init__(url)
|
|
58
|
+
# Parse db file path from url sqlite:///path/to/db.sqlite
|
|
59
|
+
path = re.sub(r"^sqlite:///", "", url)
|
|
60
|
+
self.db_path = path if path else ":memory:"
|
|
61
|
+
self._conn: Optional[aiosqlite.Connection] = None
|
|
62
|
+
|
|
63
|
+
async def connect(self):
|
|
64
|
+
if not self._conn:
|
|
65
|
+
self._conn = await aiosqlite.connect(self.db_path)
|
|
66
|
+
self._conn.row_factory = aiosqlite.Row
|
|
67
|
+
await self._conn.execute("PRAGMA foreign_keys = ON;")
|
|
68
|
+
|
|
69
|
+
async def disconnect(self):
|
|
70
|
+
if self._conn:
|
|
71
|
+
await self._conn.close()
|
|
72
|
+
self._conn = None
|
|
73
|
+
|
|
74
|
+
async def fetch_all(self, sql: str, params: tuple = ()) -> List[Dict[str, Any]]:
|
|
75
|
+
await self.connect()
|
|
76
|
+
async with self._conn.execute(sql, params) as cursor:
|
|
77
|
+
rows = await cursor.fetchall()
|
|
78
|
+
return [dict(row) for row in rows]
|
|
79
|
+
|
|
80
|
+
async def execute(self, sql: str, params: tuple = ()) -> Any:
|
|
81
|
+
await self.connect()
|
|
82
|
+
async with self._conn.execute(sql, params) as cursor:
|
|
83
|
+
await self._conn.commit()
|
|
84
|
+
return cursor.rowcount
|
|
85
|
+
|
|
86
|
+
async def execute_insert(self, sql: str, params: tuple = ()) -> Any:
|
|
87
|
+
await self.connect()
|
|
88
|
+
async with self._conn.execute(sql, params) as cursor:
|
|
89
|
+
await self._conn.commit()
|
|
90
|
+
return cursor.lastrowid
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class MySQLEngine(DatabaseEngine):
|
|
94
|
+
def __init__(self, url: str):
|
|
95
|
+
super().__init__(url)
|
|
96
|
+
# URL format: mysql://user:password@host:port/database
|
|
97
|
+
pattern = r"mysql://(?:(?P<user>[^:@]+)(?::(?P<password>[^@]+))?@)?(?P<host>[^:/]+)(?::(?P<port>\d+))?/(?P<db>[^?]+)"
|
|
98
|
+
match = re.match(pattern, url)
|
|
99
|
+
if match:
|
|
100
|
+
gd = match.groupdict()
|
|
101
|
+
self.host = gd["host"] or "localhost"
|
|
102
|
+
self.port = int(gd["port"]) if gd["port"] else 3306
|
|
103
|
+
self.user = gd["user"] or "root"
|
|
104
|
+
self.password = gd["password"] or ""
|
|
105
|
+
self.db = gd["db"] or ""
|
|
106
|
+
else:
|
|
107
|
+
self.host = "localhost"
|
|
108
|
+
self.port = 3306
|
|
109
|
+
self.user = "root"
|
|
110
|
+
self.password = ""
|
|
111
|
+
self.db = ""
|
|
112
|
+
self._pool = None
|
|
113
|
+
|
|
114
|
+
async def connect(self):
|
|
115
|
+
if not self._pool:
|
|
116
|
+
if aiomysql is None:
|
|
117
|
+
raise ImportError("aiomysql package is required for MySQL support. Install it with 'pip install aiomysql'.")
|
|
118
|
+
self._pool = await aiomysql.create_pool(
|
|
119
|
+
host=self.host,
|
|
120
|
+
port=self.port,
|
|
121
|
+
user=self.user,
|
|
122
|
+
password=self.password,
|
|
123
|
+
db=self.db,
|
|
124
|
+
autocommit=True
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
async def disconnect(self):
|
|
128
|
+
if self._pool:
|
|
129
|
+
self._pool.close()
|
|
130
|
+
await self._pool.wait_closed()
|
|
131
|
+
self._pool = None
|
|
132
|
+
|
|
133
|
+
async def fetch_all(self, sql: str, params: tuple = ()) -> List[Dict[str, Any]]:
|
|
134
|
+
await self.connect()
|
|
135
|
+
sql_conv = sql.replace("?", "%s")
|
|
136
|
+
async with self._pool.acquire() as conn:
|
|
137
|
+
async with conn.cursor(aiomysql.DictCursor) as cur:
|
|
138
|
+
await cur.execute(sql_conv, params)
|
|
139
|
+
rows = await cur.fetchall()
|
|
140
|
+
return list(rows)
|
|
141
|
+
|
|
142
|
+
async def execute(self, sql: str, params: tuple = ()) -> Any:
|
|
143
|
+
await self.connect()
|
|
144
|
+
sql_conv = sql.replace("?", "%s")
|
|
145
|
+
async with self._pool.acquire() as conn:
|
|
146
|
+
async with conn.cursor() as cur:
|
|
147
|
+
res = await cur.execute(sql_conv, params)
|
|
148
|
+
return res
|
|
149
|
+
|
|
150
|
+
async def execute_insert(self, sql: str, params: tuple = ()) -> Any:
|
|
151
|
+
await self.connect()
|
|
152
|
+
sql_conv = sql.replace("?", "%s")
|
|
153
|
+
async with self._pool.acquire() as conn:
|
|
154
|
+
async with conn.cursor() as cur:
|
|
155
|
+
await cur.execute(sql_conv, params)
|
|
156
|
+
return cur.lastrowid
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class PostgresEngine(DatabaseEngine):
|
|
160
|
+
def __init__(self, url: str):
|
|
161
|
+
super().__init__(url)
|
|
162
|
+
self._pool = None
|
|
163
|
+
|
|
164
|
+
async def connect(self):
|
|
165
|
+
if not self._pool:
|
|
166
|
+
if asyncpg is None:
|
|
167
|
+
raise ImportError("asyncpg package is required for PostgreSQL support. Install it with 'pip install asyncpg'.")
|
|
168
|
+
self._pool = await asyncpg.create_pool(self.url)
|
|
169
|
+
|
|
170
|
+
async def disconnect(self):
|
|
171
|
+
if self._pool:
|
|
172
|
+
await self._pool.close()
|
|
173
|
+
self._pool = None
|
|
174
|
+
|
|
175
|
+
def _convert_placeholders(self, sql: str) -> str:
|
|
176
|
+
count = 0
|
|
177
|
+
def repl(match):
|
|
178
|
+
nonlocal count
|
|
179
|
+
count += 1
|
|
180
|
+
return f"${count}"
|
|
181
|
+
return re.sub(r"\?", repl, sql)
|
|
182
|
+
|
|
183
|
+
async def fetch_all(self, sql: str, params: tuple = ()) -> List[Dict[str, Any]]:
|
|
184
|
+
await self.connect()
|
|
185
|
+
sql_conv = self._convert_placeholders(sql)
|
|
186
|
+
async with self._pool.acquire() as conn:
|
|
187
|
+
records = await conn.fetch(sql_conv, *params)
|
|
188
|
+
return [dict(r) for r in records]
|
|
189
|
+
|
|
190
|
+
async def execute(self, sql: str, params: tuple = ()) -> Any:
|
|
191
|
+
await self.connect()
|
|
192
|
+
sql_conv = self._convert_placeholders(sql)
|
|
193
|
+
async with self._pool.acquire() as conn:
|
|
194
|
+
status = await conn.execute(sql_conv, *params)
|
|
195
|
+
return status
|
|
196
|
+
|
|
197
|
+
async def execute_insert(self, sql: str, params: tuple = ()) -> Any:
|
|
198
|
+
await self.connect()
|
|
199
|
+
sql_conv = self._convert_placeholders(sql)
|
|
200
|
+
if "RETURNING" not in sql_conv.upper():
|
|
201
|
+
sql_conv = sql_conv.rstrip(";") + " RETURNING id;"
|
|
202
|
+
async with self._pool.acquire() as conn:
|
|
203
|
+
row = await conn.fetchrow(sql_conv, *params)
|
|
204
|
+
return row["id"] if row else None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
_default_engine: Optional[DatabaseEngine] = None
|
|
208
|
+
|
|
209
|
+
def set_engine(engine: DatabaseEngine):
|
|
210
|
+
global _default_engine
|
|
211
|
+
_default_engine = engine
|
|
212
|
+
|
|
213
|
+
def get_engine() -> DatabaseEngine:
|
|
214
|
+
global _default_engine
|
|
215
|
+
if _default_engine is None:
|
|
216
|
+
# Default fallback to in-memory SQLite
|
|
217
|
+
_default_engine = SQLiteEngine("sqlite:///:memory:")
|
|
218
|
+
return _default_engine
|
|
219
|
+
|
|
220
|
+
def create_engine(url: str) -> DatabaseEngine:
|
|
221
|
+
if url.startswith("sqlite"):
|
|
222
|
+
engine = SQLiteEngine(url)
|
|
223
|
+
elif url.startswith("mysql"):
|
|
224
|
+
engine = MySQLEngine(url)
|
|
225
|
+
elif url.startswith("postgres") or url.startswith("postgresql"):
|
|
226
|
+
engine = PostgresEngine(url)
|
|
227
|
+
else:
|
|
228
|
+
engine = SQLiteEngine(url)
|
|
229
|
+
set_engine(engine)
|
|
230
|
+
return engine
|
|
@@ -38,12 +38,19 @@ class MigrationDiff:
|
|
|
38
38
|
cols = db_schema["columns"]
|
|
39
39
|
if not cols:
|
|
40
40
|
col_defs = []
|
|
41
|
+
dialect = engine.dialect
|
|
41
42
|
for name, meta in fields.items():
|
|
42
|
-
d = f"{name} {meta['data_type']}"
|
|
43
43
|
if meta["primary_key"]:
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
44
|
+
if dialect == "mysql":
|
|
45
|
+
d = f"{name} INT AUTO_INCREMENT PRIMARY KEY"
|
|
46
|
+
elif dialect in ("postgres", "postgresql"):
|
|
47
|
+
d = f"{name} SERIAL PRIMARY KEY"
|
|
48
|
+
else:
|
|
49
|
+
d = f"{name} INTEGER PRIMARY KEY AUTOINCREMENT"
|
|
50
|
+
else:
|
|
51
|
+
d = f"{name} {meta['data_type']}"
|
|
52
|
+
if not meta["nullable"]:
|
|
53
|
+
d += " NOT NULL"
|
|
47
54
|
col_defs.append(d)
|
|
48
55
|
up = f"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join(col_defs)});"
|
|
49
56
|
down = f"DROP TABLE IF EXISTS {table_name};"
|
|
@@ -30,13 +30,31 @@ class MigrationRunner:
|
|
|
30
30
|
|
|
31
31
|
async def init_migration_table(self):
|
|
32
32
|
engine = get_engine()
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
33
|
+
dialect = engine.dialect
|
|
34
|
+
if dialect == "mysql":
|
|
35
|
+
sql = """
|
|
36
|
+
CREATE TABLE IF NOT EXISTS _lunarphase_migrations (
|
|
37
|
+
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
38
|
+
name VARCHAR(255) NOT NULL,
|
|
39
|
+
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
40
|
+
);
|
|
41
|
+
"""
|
|
42
|
+
elif dialect in ("postgres", "postgresql"):
|
|
43
|
+
sql = """
|
|
44
|
+
CREATE TABLE IF NOT EXISTS _lunarphase_migrations (
|
|
45
|
+
id SERIAL PRIMARY KEY,
|
|
46
|
+
name VARCHAR(255) NOT NULL,
|
|
47
|
+
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
48
|
+
);
|
|
49
|
+
"""
|
|
50
|
+
else:
|
|
51
|
+
sql = """
|
|
52
|
+
CREATE TABLE IF NOT EXISTS _lunarphase_migrations (
|
|
53
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
54
|
+
name VARCHAR(255) NOT NULL,
|
|
55
|
+
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
56
|
+
);
|
|
57
|
+
"""
|
|
40
58
|
await engine.execute(sql)
|
|
41
59
|
|
|
42
60
|
async def make_migration(self, name: str, models: list) -> Optional[str]:
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from typing import Any, Dict, List, Type
|
|
3
|
+
from lunarphase.core.model import Model
|
|
4
|
+
from lunarphase.db.engine import get_engine
|
|
5
|
+
|
|
6
|
+
class SchemaExtractor:
|
|
7
|
+
"""Extracts schema representation from Python Model classes and live DB."""
|
|
8
|
+
|
|
9
|
+
@staticmethod
|
|
10
|
+
def extract_from_model(model_cls: Type[Model]) -> Dict[str, Any]:
|
|
11
|
+
table_name = model_cls.__tablename__
|
|
12
|
+
fields_meta = {}
|
|
13
|
+
for name, field in model_cls._fields.items():
|
|
14
|
+
fields_meta[name] = {
|
|
15
|
+
"data_type": field.data_type,
|
|
16
|
+
"nullable": field.nullable,
|
|
17
|
+
"primary_key": field.primary_key,
|
|
18
|
+
"default": field.default,
|
|
19
|
+
}
|
|
20
|
+
return {"table_name": table_name, "fields": fields_meta}
|
|
21
|
+
|
|
22
|
+
@staticmethod
|
|
23
|
+
async def extract_from_db(table_name: str) -> Dict[str, Any]:
|
|
24
|
+
engine = get_engine()
|
|
25
|
+
dialect = engine.dialect
|
|
26
|
+
columns = {}
|
|
27
|
+
|
|
28
|
+
if dialect == "sqlite":
|
|
29
|
+
try:
|
|
30
|
+
rows = await engine.fetch_all(f"PRAGMA table_info('{table_name}');")
|
|
31
|
+
for r in rows:
|
|
32
|
+
col_name = r.get("name")
|
|
33
|
+
columns[col_name] = r.get("type", "TEXT")
|
|
34
|
+
except Exception:
|
|
35
|
+
columns = {}
|
|
36
|
+
elif dialect == "mysql":
|
|
37
|
+
try:
|
|
38
|
+
rows = await engine.fetch_all(f"DESCRIBE `{table_name}`;")
|
|
39
|
+
for r in rows:
|
|
40
|
+
col_name = r.get("Field") or r.get("field")
|
|
41
|
+
columns[col_name] = r.get("Type") or r.get("type", "VARCHAR(255)")
|
|
42
|
+
except Exception:
|
|
43
|
+
columns = {}
|
|
44
|
+
elif dialect in ("postgres", "postgresql"):
|
|
45
|
+
try:
|
|
46
|
+
rows = await engine.fetch_all(
|
|
47
|
+
f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{table_name}';"
|
|
48
|
+
)
|
|
49
|
+
for r in rows:
|
|
50
|
+
col_name = r.get("column_name")
|
|
51
|
+
columns[col_name] = r.get("data_type", "text")
|
|
52
|
+
except Exception:
|
|
53
|
+
columns = {}
|
|
54
|
+
return {"table_name": table_name, "columns": columns}
|
|
@@ -533,6 +533,17 @@
|
|
|
533
533
|
</span>
|
|
534
534
|
</a>
|
|
535
535
|
|
|
536
|
+
</li>
|
|
537
|
+
|
|
538
|
+
<li class="md-nav__item">
|
|
539
|
+
<a href="#query-count-comparison-100-authors-benchmark" class="md-nav__link">
|
|
540
|
+
<span class="md-ellipsis">
|
|
541
|
+
|
|
542
|
+
📊 Query Count Comparison (100 Authors Benchmark)
|
|
543
|
+
|
|
544
|
+
</span>
|
|
545
|
+
</a>
|
|
546
|
+
|
|
536
547
|
</li>
|
|
537
548
|
|
|
538
549
|
</ul>
|
|
@@ -699,6 +710,17 @@
|
|
|
699
710
|
</span>
|
|
700
711
|
</a>
|
|
701
712
|
|
|
713
|
+
</li>
|
|
714
|
+
|
|
715
|
+
<li class="md-nav__item">
|
|
716
|
+
<a href="#query-count-comparison-100-authors-benchmark" class="md-nav__link">
|
|
717
|
+
<span class="md-ellipsis">
|
|
718
|
+
|
|
719
|
+
📊 Query Count Comparison (100 Authors Benchmark)
|
|
720
|
+
|
|
721
|
+
</span>
|
|
722
|
+
</a>
|
|
723
|
+
|
|
702
724
|
</li>
|
|
703
725
|
|
|
704
726
|
</ul>
|
|
@@ -791,7 +813,7 @@
|
|
|
791
813
|
</code></pre></div>
|
|
792
814
|
<hr />
|
|
793
815
|
<h2 id="3-the-n1-problem-auto-batching-engine">3. The N+1 Problem & Auto-Batching Engine</h2>
|
|
794
|
-
<p>In traditional ORMs, accessing relationships inside a loop causes $N+1$ queries:</p>
|
|
816
|
+
<p>In traditional ORMs (such as SQLAlchemy with lazy loading), accessing relationships inside a loop causes $N+1$ queries:</p>
|
|
795
817
|
<div class="highlight"><pre><span></span><code><a id="__codelineno-2-1" name="__codelineno-2-1" href="#__codelineno-2-1"></a><span class="c1"># Traditional ORM: Executes 1 SELECT for authors, then N SELECT queries inside loop!</span>
|
|
796
818
|
<a id="__codelineno-2-2" name="__codelineno-2-2" href="#__codelineno-2-2"></a><span class="n">authors</span> <span class="o">=</span> <span class="k">await</span> <span class="n">Author</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
|
|
797
819
|
<a id="__codelineno-2-3" name="__codelineno-2-3" href="#__codelineno-2-3"></a><span class="k">for</span> <span class="n">author</span> <span class="ow">in</span> <span class="n">authors</span><span class="p">:</span>
|
|
@@ -803,23 +825,51 @@
|
|
|
803
825
|
<a id="__codelineno-3-2" name="__codelineno-3-2" href="#__codelineno-3-2"></a> <span class="n">authors</span> <span class="o">=</span> <span class="k">await</span> <span class="n">Author</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
|
|
804
826
|
<a id="__codelineno-3-3" name="__codelineno-3-3" href="#__codelineno-3-3"></a>
|
|
805
827
|
<a id="__codelineno-3-4" name="__codelineno-3-4" href="#__codelineno-3-4"></a> <span class="c1"># Accessing author.posts across loop iterations registers keys into DeferredAutoBatcher.</span>
|
|
806
|
-
<a id="__codelineno-3-5" name="__codelineno-3-5" href="#__codelineno-3-5"></a> <span class="c1"># The event loop micro-task flushes them into a SINGLE query:</span>
|
|
828
|
+
<a id="__codelineno-3-5" name="__codelineno-3-5" href="#__codelineno-3-5"></a> <span class="c1"># The event loop micro-task flushes them into a SINGLE batch query:</span>
|
|
807
829
|
<a id="__codelineno-3-6" name="__codelineno-3-6" href="#__codelineno-3-6"></a> <span class="c1"># SELECT * FROM posts WHERE author_id IN (1, 2, 3, 4, 5...);</span>
|
|
808
830
|
<a id="__codelineno-3-7" name="__codelineno-3-7" href="#__codelineno-3-7"></a> <span class="k">for</span> <span class="n">author</span> <span class="ow">in</span> <span class="n">authors</span><span class="p">:</span>
|
|
809
831
|
<a id="__codelineno-3-8" name="__codelineno-3-8" href="#__codelineno-3-8"></a> <span class="n">posts</span> <span class="o">=</span> <span class="k">await</span> <span class="n">author</span><span class="o">.</span><span class="n">posts</span>
|
|
810
832
|
<a id="__codelineno-3-9" name="__codelineno-3-9" href="#__codelineno-3-9"></a> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"Author </span><span class="si">{</span><span class="n">author</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s2"> has </span><span class="si">{</span><span class="nb">len</span><span class="p">(</span><span class="n">posts</span><span class="p">)</span><span class="si">}</span><span class="s2"> posts."</span><span class="p">)</span>
|
|
811
833
|
</code></pre></div>
|
|
834
|
+
<h3 id="query-count-comparison-100-authors-benchmark">📊 Query Count Comparison (100 Authors Benchmark)</h3>
|
|
835
|
+
<div class="highlight"><pre><span></span><code><a id="__codelineno-4-1" name="__codelineno-4-1" href="#__codelineno-4-1"></a>SQLAlchemy / Standard ORM Lazy Loading:
|
|
836
|
+
<a id="__codelineno-4-2" name="__codelineno-4-2" href="#__codelineno-4-2"></a> 100 authors ──► 101 SQL Queries (1 SELECT authors + 100 SELECT posts)
|
|
837
|
+
<a id="__codelineno-4-3" name="__codelineno-4-3" href="#__codelineno-4-3"></a>
|
|
838
|
+
<a id="__codelineno-4-4" name="__codelineno-4-4" href="#__codelineno-4-4"></a>LunarPhaseORM DeferredAutoBatcher:
|
|
839
|
+
<a id="__codelineno-4-5" name="__codelineno-4-5" href="#__codelineno-4-5"></a> 100 authors ──► 2 SQL Queries (1 SELECT authors + 1 Batched IN Query)
|
|
840
|
+
</code></pre></div>
|
|
841
|
+
<table>
|
|
842
|
+
<thead>
|
|
843
|
+
<tr>
|
|
844
|
+
<th>ORM Strategy</th>
|
|
845
|
+
<th style="text-align: right;">Total SQL Queries (100 Authors)</th>
|
|
846
|
+
<th>Performance Impact</th>
|
|
847
|
+
</tr>
|
|
848
|
+
</thead>
|
|
849
|
+
<tbody>
|
|
850
|
+
<tr>
|
|
851
|
+
<td><strong>SQLAlchemy / Standard Lazy Loading</strong></td>
|
|
852
|
+
<td style="text-align: right;">101 queries</td>
|
|
853
|
+
<td>Baseline ($N+1$ Network Bottleneck)</td>
|
|
854
|
+
</tr>
|
|
855
|
+
<tr>
|
|
856
|
+
<td><strong>LunarPhaseORM <code>DeferredAutoBatcher</code></strong></td>
|
|
857
|
+
<td style="text-align: right;"><strong>2 queries</strong></td>
|
|
858
|
+
<td>🚀 <strong>98.0% Query Reduction</strong> (5.1× Faster)</td>
|
|
859
|
+
</tr>
|
|
860
|
+
</tbody>
|
|
861
|
+
</table>
|
|
812
862
|
<hr />
|
|
813
863
|
<h2 id="4-eager-loading-syntax-with_relations">4. Eager Loading Syntax (<code>with_relations</code>)</h2>
|
|
814
864
|
<p>If you prefer to pre-fetch relationships upfront, use <code>.with_relations()</code>:</p>
|
|
815
|
-
<div class="highlight"><pre><span></span><code><a id="__codelineno-
|
|
816
|
-
<a id="__codelineno-
|
|
817
|
-
<a id="__codelineno-
|
|
818
|
-
<a id="__codelineno-
|
|
819
|
-
<a id="__codelineno-
|
|
820
|
-
<a id="__codelineno-
|
|
821
|
-
<a id="__codelineno-
|
|
822
|
-
<a id="__codelineno-
|
|
865
|
+
<div class="highlight"><pre><span></span><code><a id="__codelineno-5-1" name="__codelineno-5-1" href="#__codelineno-5-1"></a><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">eager_loading_tutorial</span><span class="p">():</span>
|
|
866
|
+
<a id="__codelineno-5-2" name="__codelineno-5-2" href="#__codelineno-5-2"></a> <span class="c1"># Eagerly loads all related posts in 1 query before entering the loop</span>
|
|
867
|
+
<a id="__codelineno-5-3" name="__codelineno-5-3" href="#__codelineno-5-3"></a> <span class="n">authors</span> <span class="o">=</span> <span class="k">await</span> <span class="n">Author</span><span class="o">.</span><span class="n">with_relations</span><span class="p">(</span><span class="s2">"posts"</span><span class="p">)</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
|
|
868
|
+
<a id="__codelineno-5-4" name="__codelineno-5-4" href="#__codelineno-5-4"></a>
|
|
869
|
+
<a id="__codelineno-5-5" name="__codelineno-5-5" href="#__codelineno-5-5"></a> <span class="k">for</span> <span class="n">author</span> <span class="ow">in</span> <span class="n">authors</span><span class="p">:</span>
|
|
870
|
+
<a id="__codelineno-5-6" name="__codelineno-5-6" href="#__codelineno-5-6"></a> <span class="c1"># Accessing author.posts now reads directly from memory!</span>
|
|
871
|
+
<a id="__codelineno-5-7" name="__codelineno-5-7" href="#__codelineno-5-7"></a> <span class="k">for</span> <span class="n">post</span> <span class="ow">in</span> <span class="n">author</span><span class="o">.</span><span class="n">posts</span><span class="p">:</span>
|
|
872
|
+
<a id="__codelineno-5-8" name="__codelineno-5-8" href="#__codelineno-5-8"></a> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"- </span><span class="si">{</span><span class="n">author</span><span class="o">.</span><span class="n">name</span><span class="si">}</span><span class="s2">: </span><span class="si">{</span><span class="n">post</span><span class="o">.</span><span class="n">title</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
|
|
823
873
|
</code></pre></div>
|
|
824
874
|
|
|
825
875
|
|