lunarphase-orm 0.1.0__tar.gz → 0.1.2__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.
Files changed (47) hide show
  1. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/.gitignore +1 -1
  2. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/Cargo.lock +1 -1
  3. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/Cargo.toml +1 -1
  4. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/PKG-INFO +2 -1
  5. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/README.md +1 -0
  6. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/lunarphase/__init__.py +3 -1
  7. lunarphase_orm-0.1.2/lunarphase/cli/__init__.py +1 -0
  8. lunarphase_orm-0.1.2/lunarphase/core/__init__.py +1 -0
  9. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/lunarphase/core/model.py +1 -0
  10. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/lunarphase/core/relations.py +1 -0
  11. lunarphase_orm-0.1.2/lunarphase/db/__init__.py +1 -0
  12. lunarphase_orm-0.1.2/lunarphase/migrations/__init__.py +1 -0
  13. lunarphase_orm-0.1.2/lunarphase/migrations/diff.py +60 -0
  14. lunarphase_orm-0.1.2/lunarphase/migrations/runner.py +111 -0
  15. lunarphase_orm-0.1.2/lunarphase/migrations/schema.py +34 -0
  16. lunarphase_orm-0.1.2/lunarphase/query/__init__.py +1 -0
  17. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/lunarphase/query/builder.py +3 -2
  18. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/pyproject.toml +2 -1
  19. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/.github/workflows/ci.yml +0 -0
  20. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/.github/workflows/pypi-publish.yml +0 -0
  21. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/BENCHMARK.md +0 -0
  22. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/DOCUMENTATION.md +0 -0
  23. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/LICENSE +0 -0
  24. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/ROADMAP.md +0 -0
  25. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/benchmarks/advanced_scale_benchmark.py +0 -0
  26. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/benchmarks/comprehensive_orm_benchmark.py +0 -0
  27. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/benchmarks/diagnostic_3way_benchmark.py +0 -0
  28. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/lunarphase/cli/main.py +0 -0
  29. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/lunarphase/core/ast.py +0 -0
  30. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/lunarphase/core/fields.py +0 -0
  31. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/lunarphase/core/state.py +0 -0
  32. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/lunarphase/core/uow.py +0 -0
  33. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/lunarphase/db/engine.py +0 -0
  34. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/lunarphase/query/batcher.py +0 -0
  35. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/src/batcher.rs +0 -0
  36. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/src/compiler.rs +0 -0
  37. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/src/lib.rs +0 -0
  38. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/src/migration_diff.rs +0 -0
  39. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/src/state_tracker.rs +0 -0
  40. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/tests/test_benchmarks.py +0 -0
  41. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/tests/test_coverage_boost.py +0 -0
  42. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/tests/test_fase1_core_ast.py +0 -0
  43. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/tests/test_fase2_async_drivers.py +0 -0
  44. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/tests/test_fase3_auto_batching_relations.py +0 -0
  45. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/tests/test_fase4_dirty_tracking_uow.py +0 -0
  46. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/tests/test_fase5_auto_migrations_cli.py +0 -0
  47. {lunarphase_orm-0.1.0 → lunarphase_orm-0.1.2}/tests/test_rust_performance.py +0 -0
@@ -35,7 +35,7 @@ htmlcov/
35
35
  *.sqlite
36
36
  *.sqlite3
37
37
  test_cov.db
38
- migrations/
38
+ /migrations/
39
39
 
40
40
  # OS & IDE Files
41
41
  .DS_Store
@@ -43,7 +43,7 @@ checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
43
43
 
44
44
  [[package]]
45
45
  name = "lunarphase_rs"
46
- version = "0.1.0"
46
+ version = "0.1.2"
47
47
  dependencies = [
48
48
  "pyo3",
49
49
  "rustc-hash",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "lunarphase_rs"
3
- version = "0.1.0"
3
+ version = "0.1.2"
4
4
  edition = "2021"
5
5
  readme = "README.md"
6
6
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lunarphase-orm
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Classifier: Programming Language :: Python :: 3
5
5
  Classifier: Programming Language :: Rust
6
6
  Classifier: Framework :: AsyncIO
@@ -20,6 +20,7 @@ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
20
20
 
21
21
  > **Smart Sync. Zero N+1. High-Performance Python & Rust ORM.**
22
22
 
23
+ [![PyPI version](https://img.shields.io/pypi/v/lunarphase-orm.svg?color=blue&nocache=1)](https://pypi.org/project/lunarphase-orm/)
23
24
  [![Python 3.9+](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://www.python.org/downloads/)
24
25
  [![Rust Engine](https://img.shields.io/badge/core-Rust%20%2F%20PyO3-orange.svg)](https://www.rust-lang.org/)
25
26
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
@@ -5,6 +5,7 @@
5
5
 
6
6
  > **Smart Sync. Zero N+1. High-Performance Python & Rust ORM.**
7
7
 
8
+ [![PyPI version](https://img.shields.io/pypi/v/lunarphase-orm.svg?color=blue&nocache=1)](https://pypi.org/project/lunarphase-orm/)
8
9
  [![Python 3.9+](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://www.python.org/downloads/)
9
10
  [![Rust Engine](https://img.shields.io/badge/core-Rust%20%2F%20PyO3-orange.svg)](https://www.rust-lang.org/)
10
11
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
@@ -2,6 +2,8 @@
2
2
  LunarPhaseORM: Smart, Async-Native, High-Performance Python & Rust Object-Relational Mapper
3
3
  """
4
4
 
5
+ from __future__ import annotations
6
+
5
7
  from lunarphase.core.model import Model, ModelBase
6
8
  from lunarphase.core.fields import (
7
9
  FieldDescriptor,
@@ -20,7 +22,7 @@ from lunarphase.query.builder import QueryBuilder
20
22
  from lunarphase.query.batcher import DeferredAutoBatcher
21
23
  from lunarphase.migrations.runner import MigrationRunner
22
24
 
23
- __version__ = "0.1.0"
25
+ __version__ = "0.1.2"
24
26
  __all__ = [
25
27
  "Model",
26
28
  "ModelBase",
@@ -0,0 +1 @@
1
+ """CLI package for LunarPhaseORM."""
@@ -0,0 +1 @@
1
+ """Core ORM package for LunarPhaseORM."""
@@ -1,3 +1,4 @@
1
+ from __future__ import annotations
1
2
  from typing import Any, Dict, List, Optional, Set, Type, TypeVar
2
3
  from lunarphase.core.fields import FieldDescriptor, PrimaryKeyField
3
4
  from lunarphase.core.state import create_state_tracker
@@ -1,3 +1,4 @@
1
+ from __future__ import annotations
1
2
  from typing import Any, Dict, List, Optional, Type, Union
2
3
  import asyncio
3
4
  from lunarphase.query.batcher import DeferredAutoBatcher
@@ -0,0 +1 @@
1
+ """Database engines package for LunarPhaseORM."""
@@ -0,0 +1 @@
1
+ """Migrations package for LunarPhaseORM."""
@@ -0,0 +1,60 @@
1
+ from __future__ import annotations
2
+ from typing import Any, Dict, List, Tuple, Type
3
+ from lunarphase.core.model import Model
4
+ from lunarphase.migrations.schema import SchemaExtractor
5
+ from lunarphase.db.engine import get_engine
6
+
7
+ try:
8
+ from lunarphase._lunarphase_rs import SchemaDiffEngine as RustSchemaDiffEngine
9
+ HAS_RUST_DIFF = True
10
+ except ImportError:
11
+ HAS_RUST_DIFF = False
12
+
13
+ class MigrationDiff:
14
+ @staticmethod
15
+ async def generate_diff(models: List[Type[Model]]) -> Tuple[List[str], List[str]]:
16
+ engine = get_engine()
17
+ upgrade_all = []
18
+ downgrade_all = []
19
+
20
+ for model_cls in models:
21
+ model_schema = SchemaExtractor.extract_from_model(model_cls)
22
+ table_name = model_schema["table_name"]
23
+ db_schema = await SchemaExtractor.extract_from_db(table_name)
24
+
25
+ if HAS_RUST_DIFF:
26
+ rust_engine = RustSchemaDiffEngine()
27
+ up, down = rust_engine.diff_table(
28
+ table_name,
29
+ model_schema["fields"],
30
+ db_schema["columns"],
31
+ engine.dialect,
32
+ )
33
+ upgrade_all.extend(up)
34
+ downgrade_all.extend(down)
35
+ else:
36
+ # Python Fallback Schema Diff
37
+ fields = model_schema["fields"]
38
+ cols = db_schema["columns"]
39
+ if not cols:
40
+ col_defs = []
41
+ for name, meta in fields.items():
42
+ d = f"{name} {meta['data_type']}"
43
+ if meta["primary_key"]:
44
+ d += " PRIMARY KEY"
45
+ elif not meta["nullable"]:
46
+ d += " NOT NULL"
47
+ col_defs.append(d)
48
+ up = f"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join(col_defs)});"
49
+ down = f"DROP TABLE IF EXISTS {table_name};"
50
+ upgrade_all.append(up)
51
+ downgrade_all.append(down)
52
+ else:
53
+ for name, meta in fields.items():
54
+ if name not in cols:
55
+ up = f"ALTER TABLE {table_name} ADD COLUMN {name} {meta['data_type']};"
56
+ down = f"ALTER TABLE {table_name} DROP COLUMN {name};"
57
+ upgrade_all.append(up)
58
+ downgrade_all.append(down)
59
+
60
+ return upgrade_all, downgrade_all
@@ -0,0 +1,111 @@
1
+ import importlib.util
2
+ import os
3
+ import time
4
+ from typing import List, Optional
5
+ from lunarphase.db.engine import get_engine
6
+ from lunarphase.migrations.diff import MigrationDiff
7
+
8
+ MIGRATIONS_DIR = "migrations"
9
+
10
+ TEMPLATE = '''"""
11
+ Migration generated automatically by LunarPhaseORM
12
+ Timestamp: {timestamp}
13
+ """
14
+
15
+ async def upgrade(engine):
16
+ sql_statements = {upgrade_sql!r}
17
+ for sql in sql_statements:
18
+ await engine.execute(sql)
19
+
20
+ async def downgrade(engine):
21
+ sql_statements = {downgrade_sql!r}
22
+ for sql in sql_statements:
23
+ await engine.execute(sql)
24
+ '''
25
+
26
+ class MigrationRunner:
27
+ def __init__(self, migrations_dir: str = MIGRATIONS_DIR):
28
+ self.migrations_dir = migrations_dir
29
+ os.makedirs(self.migrations_dir, exist_ok=True)
30
+
31
+ async def init_migration_table(self):
32
+ engine = get_engine()
33
+ sql = """
34
+ CREATE TABLE IF NOT EXISTS _lunarphase_migrations (
35
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
36
+ name VARCHAR(255) NOT NULL,
37
+ applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
38
+ );
39
+ """
40
+ await engine.execute(sql)
41
+
42
+ async def make_migration(self, name: str, models: list) -> Optional[str]:
43
+ upgrade_sql, downgrade_sql = await MigrationDiff.generate_diff(models)
44
+ if not upgrade_sql:
45
+ print("No schema changes detected.")
46
+ return None
47
+
48
+ timestamp = int(time.time())
49
+ filename = f"{timestamp}_{name}.py"
50
+ filepath = os.path.join(self.migrations_dir, filename)
51
+
52
+ content = TEMPLATE.format(
53
+ timestamp=timestamp,
54
+ upgrade_sql=upgrade_sql,
55
+ downgrade_sql=downgrade_sql,
56
+ )
57
+
58
+ with open(filepath, "w") as f:
59
+ f.write(content)
60
+
61
+ print(f"Created migration file: {filepath}")
62
+ return filepath
63
+
64
+ async def migrate(self):
65
+ await self.init_migration_table()
66
+ engine = get_engine()
67
+
68
+ applied_rows = await engine.fetch_all("SELECT name FROM _lunarphase_migrations;")
69
+ applied_names = {r["name"] for r in applied_rows}
70
+
71
+ files = sorted([f for f in os.listdir(self.migrations_dir) if f.endswith(".py") and not f.startswith("__")])
72
+
73
+ for fname in files:
74
+ if fname not in applied_names:
75
+ print(f"Applying migration: {fname}")
76
+ fpath = os.path.join(self.migrations_dir, fname)
77
+ spec = importlib.util.spec_from_file_location(fname[:-3], fpath)
78
+ mod = importlib.util.module_from_spec(spec)
79
+ spec.loader.exec_module(mod)
80
+
81
+ await mod.upgrade(engine)
82
+ await engine.execute(
83
+ "INSERT INTO _lunarphase_migrations (name) VALUES (?);", (fname,)
84
+ )
85
+ print(f"Successfully applied: {fname}")
86
+
87
+ async def rollback(self):
88
+ await self.init_migration_table()
89
+ engine = get_engine()
90
+
91
+ applied_rows = await engine.fetch_all(
92
+ "SELECT name FROM _lunarphase_migrations ORDER BY id DESC LIMIT 1;"
93
+ )
94
+ if not applied_rows:
95
+ print("No migrations to rollback.")
96
+ return
97
+
98
+ last_fname = applied_rows[0]["name"]
99
+ print(f"Rolling back migration: {last_fname}")
100
+ fpath = os.path.join(self.migrations_dir, last_fname)
101
+
102
+ if os.path.exists(fpath):
103
+ spec = importlib.util.spec_from_file_location(last_fname[:-3], fpath)
104
+ mod = importlib.util.module_from_spec(spec)
105
+ spec.loader.exec_module(mod)
106
+
107
+ await mod.downgrade(engine)
108
+ await engine.execute(
109
+ "DELETE FROM _lunarphase_migrations WHERE name = ?;", (last_fname,)
110
+ )
111
+ print(f"Successfully rolled back: {last_fname}")
@@ -0,0 +1,34 @@
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
+ rows = await engine.fetch_all(f"PRAGMA table_info('{table_name}');")
30
+ for r in rows:
31
+ # r: cid, name, type, notnull, dflt_value, pk
32
+ col_name = r.get("name")
33
+ columns[col_name] = r.get("type", "TEXT")
34
+ return {"table_name": table_name, "columns": columns}
@@ -0,0 +1 @@
1
+ """Query builder and batcher package for LunarPhaseORM."""
@@ -1,4 +1,5 @@
1
- from typing import Any, List, Optional, Tuple, Type, TypeVar, Dict
1
+ from __future__ import annotations
2
+ from typing import Any, Generic, List, Optional, Tuple, Type, TypeVar, Dict
2
3
  import math
3
4
  from lunarphase.core.ast import BinaryOp, ColumnRef, Literal
4
5
  from lunarphase.db.engine import get_engine
@@ -11,7 +12,7 @@ except ImportError:
11
12
 
12
13
  T = TypeVar("T", bound="Model")
13
14
 
14
- class QueryBuilder:
15
+ class QueryBuilder(Generic[T]):
15
16
  def __init__(self, model_cls: Type[T]):
16
17
  self.model_cls = model_cls
17
18
  self.table_name = getattr(model_cls, "__tablename__", model_cls.__name__.lower())
@@ -4,7 +4,7 @@ build-backend = "maturin"
4
4
 
5
5
  [project]
6
6
  name = "lunarphase-orm"
7
- version = "0.1.0"
7
+ version = "0.1.2"
8
8
  description = "Smart, Async-Native, High-Performance Python & Rust Object-Relational Mapper"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -29,3 +29,4 @@ lunarphase = "lunarphase.cli.main:cli_entrypoint"
29
29
  features = ["pyo3/extension-module"]
30
30
  python-source = "."
31
31
  module-name = "lunarphase._lunarphase_rs"
32
+ python-packages = ["lunarphase"]
File without changes