lunarphase-orm 0.1.0__cp39-abi3-win_amd64.whl
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/__init__.py +47 -0
- lunarphase/_lunarphase_rs.pyd +0 -0
- lunarphase/cli/main.py +47 -0
- lunarphase/core/ast.py +53 -0
- lunarphase/core/fields.py +108 -0
- lunarphase/core/model.py +178 -0
- lunarphase/core/relations.py +113 -0
- lunarphase/core/state.py +53 -0
- lunarphase/core/uow.py +97 -0
- lunarphase/db/engine.py +103 -0
- lunarphase/query/batcher.py +53 -0
- lunarphase/query/builder.py +151 -0
- lunarphase_orm-0.1.0.dist-info/METADATA +186 -0
- lunarphase_orm-0.1.0.dist-info/RECORD +18 -0
- lunarphase_orm-0.1.0.dist-info/WHEEL +4 -0
- lunarphase_orm-0.1.0.dist-info/entry_points.txt +2 -0
- lunarphase_orm-0.1.0.dist-info/licenses/LICENSE +21 -0
- lunarphase_orm-0.1.0.dist-info/sboms/lunarphase_rs.cyclonedx.json +1075 -0
lunarphase/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""
|
|
2
|
+
LunarPhaseORM: Smart, Async-Native, High-Performance Python & Rust Object-Relational Mapper
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from lunarphase.core.model import Model, ModelBase
|
|
6
|
+
from lunarphase.core.fields import (
|
|
7
|
+
FieldDescriptor,
|
|
8
|
+
PrimaryKeyField,
|
|
9
|
+
IntegerField,
|
|
10
|
+
StringField,
|
|
11
|
+
FloatField,
|
|
12
|
+
BooleanField,
|
|
13
|
+
DateTimeField,
|
|
14
|
+
JSONField,
|
|
15
|
+
)
|
|
16
|
+
from lunarphase.core.relations import HasMany, BelongsTo, HasOne
|
|
17
|
+
from lunarphase.core.uow import UnitOfWork, IdentityMap
|
|
18
|
+
from lunarphase.db.engine import create_engine, set_engine, get_engine, SQLiteEngine
|
|
19
|
+
from lunarphase.query.builder import QueryBuilder
|
|
20
|
+
from lunarphase.query.batcher import DeferredAutoBatcher
|
|
21
|
+
from lunarphase.migrations.runner import MigrationRunner
|
|
22
|
+
|
|
23
|
+
__version__ = "0.1.0"
|
|
24
|
+
__all__ = [
|
|
25
|
+
"Model",
|
|
26
|
+
"ModelBase",
|
|
27
|
+
"FieldDescriptor",
|
|
28
|
+
"PrimaryKeyField",
|
|
29
|
+
"IntegerField",
|
|
30
|
+
"StringField",
|
|
31
|
+
"FloatField",
|
|
32
|
+
"BooleanField",
|
|
33
|
+
"DateTimeField",
|
|
34
|
+
"JSONField",
|
|
35
|
+
"HasMany",
|
|
36
|
+
"BelongsTo",
|
|
37
|
+
"HasOne",
|
|
38
|
+
"UnitOfWork",
|
|
39
|
+
"IdentityMap",
|
|
40
|
+
"create_engine",
|
|
41
|
+
"set_engine",
|
|
42
|
+
"get_engine",
|
|
43
|
+
"SQLiteEngine",
|
|
44
|
+
"QueryBuilder",
|
|
45
|
+
"DeferredAutoBatcher",
|
|
46
|
+
"MigrationRunner",
|
|
47
|
+
]
|
|
Binary file
|
lunarphase/cli/main.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import asyncio
|
|
3
|
+
import sys
|
|
4
|
+
from lunarphase.migrations.runner import MigrationRunner
|
|
5
|
+
from lunarphase.db.engine import get_engine
|
|
6
|
+
|
|
7
|
+
async def run_cli():
|
|
8
|
+
parser = argparse.ArgumentParser(prog="lunarphase", description="LunarPhaseORM CLI Tool")
|
|
9
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
10
|
+
|
|
11
|
+
make_mig = subparsers.add_parser("make:migration", help="Generate a new DDL schema migration file")
|
|
12
|
+
make_mig.add_argument("name", help="Name of the migration e.g. create_users_table")
|
|
13
|
+
|
|
14
|
+
subparsers.add_parser("migrate", help="Apply pending database migrations")
|
|
15
|
+
subparsers.add_parser("rollback", help="Rollback the last applied migration")
|
|
16
|
+
subparsers.add_parser("status", help="Show migration status")
|
|
17
|
+
|
|
18
|
+
args = parser.parse_args()
|
|
19
|
+
runner = MigrationRunner()
|
|
20
|
+
|
|
21
|
+
if args.command == "make:migration":
|
|
22
|
+
# Imports user models registered in current working directory if available
|
|
23
|
+
await runner.make_migration(args.name, [])
|
|
24
|
+
elif args.command == "migrate":
|
|
25
|
+
await runner.migrate()
|
|
26
|
+
elif args.command == "rollback":
|
|
27
|
+
await runner.rollback()
|
|
28
|
+
elif args.command == "status":
|
|
29
|
+
engine = get_engine()
|
|
30
|
+
await runner.init_migration_table()
|
|
31
|
+
rows = await engine.fetch_all("SELECT name, applied_at FROM _lunarphase_migrations ORDER BY id ASC;")
|
|
32
|
+
print("\n--- LunarPhaseORM Migration Status ---")
|
|
33
|
+
if not rows:
|
|
34
|
+
print("No migrations applied yet.")
|
|
35
|
+
else:
|
|
36
|
+
for r in rows:
|
|
37
|
+
print(f" [X] {r['name']} (applied: {r['applied_at']})")
|
|
38
|
+
print("--------------------------------------\n")
|
|
39
|
+
else:
|
|
40
|
+
parser.print_help()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def cli_entrypoint():
|
|
44
|
+
asyncio.run(run_cli())
|
|
45
|
+
|
|
46
|
+
if __name__ == "__main__":
|
|
47
|
+
cli_entrypoint()
|
lunarphase/core/ast.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from typing import Any, List, Optional, Tuple, Dict, Union
|
|
2
|
+
|
|
3
|
+
class ASTNode:
|
|
4
|
+
"""Base class for all Abstract Syntax Tree nodes."""
|
|
5
|
+
pass
|
|
6
|
+
|
|
7
|
+
class ColumnRef(ASTNode):
|
|
8
|
+
def __init__(self, column_name: str, table_name: Optional[str] = None):
|
|
9
|
+
self.column_name = column_name
|
|
10
|
+
self.table_name = table_name
|
|
11
|
+
|
|
12
|
+
def full_name(self) -> str:
|
|
13
|
+
if self.table_name:
|
|
14
|
+
return f"{self.table_name}.{self.column_name}"
|
|
15
|
+
return self.column_name
|
|
16
|
+
|
|
17
|
+
def __repr__(self) -> str:
|
|
18
|
+
return f"<ColumnRef {self.full_name()}>"
|
|
19
|
+
|
|
20
|
+
class Literal(ASTNode):
|
|
21
|
+
def __init__(self, value: Any):
|
|
22
|
+
self.value = value
|
|
23
|
+
|
|
24
|
+
def __repr__(self) -> str:
|
|
25
|
+
return f"<Literal {self.value!r}>"
|
|
26
|
+
|
|
27
|
+
class BinaryOp(ASTNode):
|
|
28
|
+
def __init__(self, left: ASTNode, op: str, right: ASTNode):
|
|
29
|
+
self.left = left
|
|
30
|
+
self.op = op
|
|
31
|
+
self.right = right
|
|
32
|
+
|
|
33
|
+
def __repr__(self) -> str:
|
|
34
|
+
return f"<BinaryOp ({self.left} {self.op} {self.right})>"
|
|
35
|
+
|
|
36
|
+
class SelectQuery(ASTNode):
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
table_name: str,
|
|
40
|
+
columns: Optional[List[str]] = None,
|
|
41
|
+
wheres: Optional[List[BinaryOp]] = None,
|
|
42
|
+
joins: Optional[List[Tuple[str, str, str]]] = None,
|
|
43
|
+
order_bys: Optional[List[Tuple[str, str]]] = None,
|
|
44
|
+
limit: Optional[int] = None,
|
|
45
|
+
offset: Optional[int] = None,
|
|
46
|
+
):
|
|
47
|
+
self.table_name = table_name
|
|
48
|
+
self.columns = columns or []
|
|
49
|
+
self.wheres = wheres or []
|
|
50
|
+
self.joins = joins or []
|
|
51
|
+
self.order_bys = order_bys or []
|
|
52
|
+
self.limit = limit
|
|
53
|
+
self.offset = offset
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
from typing import Any, Optional, Dict
|
|
2
|
+
from lunarphase.core.ast import ColumnRef, Literal, BinaryOp
|
|
3
|
+
|
|
4
|
+
class FieldDescriptor:
|
|
5
|
+
def __init__(
|
|
6
|
+
self,
|
|
7
|
+
name: Optional[str] = None,
|
|
8
|
+
primary_key: bool = False,
|
|
9
|
+
nullable: bool = True,
|
|
10
|
+
default: Any = None,
|
|
11
|
+
data_type: str = "TEXT",
|
|
12
|
+
):
|
|
13
|
+
self.name = name
|
|
14
|
+
self.primary_key = primary_key
|
|
15
|
+
self.nullable = nullable
|
|
16
|
+
self.default = default
|
|
17
|
+
self.data_type = data_type
|
|
18
|
+
self.owner_class = None
|
|
19
|
+
|
|
20
|
+
def __set_name__(self, owner, name: str):
|
|
21
|
+
if not self.name:
|
|
22
|
+
self.name = name
|
|
23
|
+
self.owner_class = owner
|
|
24
|
+
|
|
25
|
+
def __get__(self, instance, owner):
|
|
26
|
+
if instance is None:
|
|
27
|
+
return self
|
|
28
|
+
return instance._state.get_field(self.name)
|
|
29
|
+
|
|
30
|
+
def __set__(self, instance, value):
|
|
31
|
+
if instance is None:
|
|
32
|
+
return
|
|
33
|
+
instance._state.set_field(self.name, value)
|
|
34
|
+
|
|
35
|
+
# Operator overloading for AST query generation
|
|
36
|
+
def _col_ref(self) -> ColumnRef:
|
|
37
|
+
table_name = getattr(self.owner_class, "__tablename__", None) if self.owner_class else None
|
|
38
|
+
return ColumnRef(self.name, table_name)
|
|
39
|
+
|
|
40
|
+
def __eq__(self, other: Any) -> BinaryOp:
|
|
41
|
+
if other is None:
|
|
42
|
+
return BinaryOp(self._col_ref(), "IS", Literal(None))
|
|
43
|
+
return BinaryOp(self._col_ref(), "=", Literal(other))
|
|
44
|
+
|
|
45
|
+
def __ne__(self, other: Any) -> BinaryOp:
|
|
46
|
+
if other is None:
|
|
47
|
+
return BinaryOp(self._col_ref(), "IS NOT", Literal(None))
|
|
48
|
+
return BinaryOp(self._col_ref(), "!=", Literal(other))
|
|
49
|
+
|
|
50
|
+
def __lt__(self, other: Any) -> BinaryOp:
|
|
51
|
+
return BinaryOp(self._col_ref(), "<", Literal(other))
|
|
52
|
+
|
|
53
|
+
def __le__(self, other: Any) -> BinaryOp:
|
|
54
|
+
return BinaryOp(self._col_ref(), "<=", Literal(other))
|
|
55
|
+
|
|
56
|
+
def __gt__(self, other: Any) -> BinaryOp:
|
|
57
|
+
return BinaryOp(self._col_ref(), ">", Literal(other))
|
|
58
|
+
|
|
59
|
+
def __ge__(self, other: Any) -> BinaryOp:
|
|
60
|
+
return BinaryOp(self._col_ref(), ">=", Literal(other))
|
|
61
|
+
|
|
62
|
+
def in_(self, values: list) -> BinaryOp:
|
|
63
|
+
return BinaryOp(self._col_ref(), "IN", Literal(values))
|
|
64
|
+
|
|
65
|
+
def like(self, pattern: str) -> BinaryOp:
|
|
66
|
+
return BinaryOp(self._col_ref(), "LIKE", Literal(pattern))
|
|
67
|
+
|
|
68
|
+
def is_null(self) -> BinaryOp:
|
|
69
|
+
return BinaryOp(self._col_ref(), "IS", Literal(None))
|
|
70
|
+
|
|
71
|
+
def is_not_null(self) -> BinaryOp:
|
|
72
|
+
return BinaryOp(self._col_ref(), "IS NOT", Literal(None))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class PrimaryKeyField(FieldDescriptor):
|
|
76
|
+
def __init__(self, name: Optional[str] = None, auto_increment: bool = True):
|
|
77
|
+
super().__init__(name=name, primary_key=True, nullable=False, data_type="INTEGER")
|
|
78
|
+
self.auto_increment = auto_increment
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class IntegerField(FieldDescriptor):
|
|
82
|
+
def __init__(self, name: Optional[str] = None, primary_key: bool = False, nullable: bool = True, default: Any = None):
|
|
83
|
+
super().__init__(name=name, primary_key=primary_key, nullable=nullable, default=default, data_type="INTEGER")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class StringField(FieldDescriptor):
|
|
87
|
+
def __init__(self, name: Optional[str] = None, primary_key: bool = False, nullable: bool = True, default: Any = None):
|
|
88
|
+
super().__init__(name=name, primary_key=primary_key, nullable=nullable, default=default, data_type="VARCHAR(255)")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class FloatField(FieldDescriptor):
|
|
92
|
+
def __init__(self, name: Optional[str] = None, primary_key: bool = False, nullable: bool = True, default: Any = None):
|
|
93
|
+
super().__init__(name=name, primary_key=primary_key, nullable=nullable, default=default, data_type="REAL")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class BooleanField(FieldDescriptor):
|
|
97
|
+
def __init__(self, name: Optional[str] = None, primary_key: bool = False, nullable: bool = True, default: Any = None):
|
|
98
|
+
super().__init__(name=name, primary_key=primary_key, nullable=nullable, default=default, data_type="BOOLEAN")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class DateTimeField(FieldDescriptor):
|
|
102
|
+
def __init__(self, name: Optional[str] = None, primary_key: bool = False, nullable: bool = True, default: Any = None):
|
|
103
|
+
super().__init__(name=name, primary_key=primary_key, nullable=nullable, default=default, data_type="DATETIME")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class JSONField(FieldDescriptor):
|
|
107
|
+
def __init__(self, name: Optional[str] = None, nullable: bool = True, default: Any = None):
|
|
108
|
+
super().__init__(name=name, primary_key=False, nullable=nullable, default=default, data_type="JSON")
|
lunarphase/core/model.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
from typing import Any, Dict, List, Optional, Set, Type, TypeVar
|
|
2
|
+
from lunarphase.core.fields import FieldDescriptor, PrimaryKeyField
|
|
3
|
+
from lunarphase.core.state import create_state_tracker
|
|
4
|
+
from lunarphase.db.engine import get_engine
|
|
5
|
+
from lunarphase.query.builder import QueryBuilder
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
from lunarphase._lunarphase_rs import QueryCompiler as RustQueryCompiler
|
|
9
|
+
HAS_RUST_COMPILER = True
|
|
10
|
+
except ImportError:
|
|
11
|
+
HAS_RUST_COMPILER = False
|
|
12
|
+
|
|
13
|
+
M = TypeVar("M", bound="Model")
|
|
14
|
+
|
|
15
|
+
class ModelBase(type):
|
|
16
|
+
def __new__(cls, name: str, bases: tuple, attrs: dict):
|
|
17
|
+
fields: Dict[str, FieldDescriptor] = {}
|
|
18
|
+
primary_key_name = "id"
|
|
19
|
+
|
|
20
|
+
# Inherit fields from parent base classes
|
|
21
|
+
for base in bases:
|
|
22
|
+
if hasattr(base, "_fields"):
|
|
23
|
+
fields.update(base._fields)
|
|
24
|
+
|
|
25
|
+
# Collect fields from current class attrs
|
|
26
|
+
for k, v in list(attrs.items()):
|
|
27
|
+
if isinstance(v, FieldDescriptor):
|
|
28
|
+
v.name = k
|
|
29
|
+
fields[k] = v
|
|
30
|
+
if v.primary_key:
|
|
31
|
+
primary_key_name = k
|
|
32
|
+
|
|
33
|
+
# If no primary key declared, add default PrimaryKeyField 'id'
|
|
34
|
+
if primary_key_name not in fields and name != "Model":
|
|
35
|
+
pk_field = PrimaryKeyField("id")
|
|
36
|
+
pk_field.name = "id"
|
|
37
|
+
fields["id"] = pk_field
|
|
38
|
+
attrs["id"] = pk_field
|
|
39
|
+
primary_key_name = "id"
|
|
40
|
+
|
|
41
|
+
attrs["_fields"] = fields
|
|
42
|
+
attrs["_primary_key_name"] = primary_key_name
|
|
43
|
+
|
|
44
|
+
if "__tablename__" not in attrs and name != "Model":
|
|
45
|
+
attrs["__tablename__"] = f"{name.lower()}s"
|
|
46
|
+
|
|
47
|
+
new_cls = super().__new__(cls, name, bases, attrs)
|
|
48
|
+
|
|
49
|
+
# Bind owner class to descriptors
|
|
50
|
+
for field in fields.values():
|
|
51
|
+
field.owner_class = new_cls
|
|
52
|
+
|
|
53
|
+
return new_cls
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Model(metaclass=ModelBase):
|
|
57
|
+
_fields: Dict[str, FieldDescriptor]
|
|
58
|
+
_primary_key_name: str
|
|
59
|
+
__tablename__: str
|
|
60
|
+
|
|
61
|
+
def __init__(self, **kwargs: Any):
|
|
62
|
+
self._state = create_state_tracker()
|
|
63
|
+
initial_data = {}
|
|
64
|
+
|
|
65
|
+
for name, field in self._fields.items():
|
|
66
|
+
val = kwargs.get(name, field.default)
|
|
67
|
+
initial_data[name] = val
|
|
68
|
+
|
|
69
|
+
self._state.set_initial_state(initial_data)
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def is_dirty(self) -> bool:
|
|
73
|
+
return self._state.is_dirty()
|
|
74
|
+
|
|
75
|
+
def get_dirty_changes(self) -> Dict[str, Any]:
|
|
76
|
+
return self._state.get_dirty_changes()
|
|
77
|
+
|
|
78
|
+
def _hydrate_snapshot(self):
|
|
79
|
+
self._state.hydrate_snapshot()
|
|
80
|
+
|
|
81
|
+
@classmethod
|
|
82
|
+
def hydrate(cls: Type[M], row: Dict[str, Any]) -> M:
|
|
83
|
+
instance = cls.__new__(cls)
|
|
84
|
+
instance._state = create_state_tracker()
|
|
85
|
+
instance._state.set_initial_state(row)
|
|
86
|
+
return instance
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def query(cls: Type[M]) -> QueryBuilder[M]:
|
|
90
|
+
return QueryBuilder(cls)
|
|
91
|
+
|
|
92
|
+
@classmethod
|
|
93
|
+
def where(cls: Type[M], *conditions: Any, **kwargs: Any) -> QueryBuilder[M]:
|
|
94
|
+
return QueryBuilder(cls).where(*conditions, **kwargs)
|
|
95
|
+
|
|
96
|
+
@classmethod
|
|
97
|
+
def all(cls: Type[M]):
|
|
98
|
+
return QueryBuilder(cls).all()
|
|
99
|
+
|
|
100
|
+
@classmethod
|
|
101
|
+
def first(cls: Type[M]):
|
|
102
|
+
return QueryBuilder(cls).first()
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
async def create(cls: Type[M], **kwargs: Any) -> M:
|
|
106
|
+
instance = cls(**kwargs)
|
|
107
|
+
await instance.save()
|
|
108
|
+
return instance
|
|
109
|
+
|
|
110
|
+
async def save(self) -> bool:
|
|
111
|
+
engine = get_engine()
|
|
112
|
+
pk_name = self._primary_key_name
|
|
113
|
+
pk_val = getattr(self, pk_name, None)
|
|
114
|
+
|
|
115
|
+
# Case 1: New record (INSERT)
|
|
116
|
+
if pk_val is None:
|
|
117
|
+
data = self._state.get_current_dict()
|
|
118
|
+
if pk_name in data and data[pk_name] is None:
|
|
119
|
+
del data[pk_name]
|
|
120
|
+
|
|
121
|
+
cols = list(data.keys())
|
|
122
|
+
vals = [data[c] for c in cols]
|
|
123
|
+
|
|
124
|
+
if HAS_RUST_COMPILER:
|
|
125
|
+
compiler = RustQueryCompiler()
|
|
126
|
+
sql = compiler.compile_insert(self.__tablename__, cols, engine.dialect)
|
|
127
|
+
else:
|
|
128
|
+
ph = ", ".join(["?"] * len(cols))
|
|
129
|
+
sql = f"INSERT INTO {self.__tablename__} ({', '.join(cols)}) VALUES ({ph})"
|
|
130
|
+
|
|
131
|
+
last_id = await engine.execute_insert(sql, tuple(vals))
|
|
132
|
+
if last_id and pk_name in self._fields:
|
|
133
|
+
setattr(self, pk_name, last_id)
|
|
134
|
+
self._hydrate_snapshot()
|
|
135
|
+
return True
|
|
136
|
+
|
|
137
|
+
# Case 2: Existing record (UPDATE dirty fields only)
|
|
138
|
+
if not self.is_dirty:
|
|
139
|
+
return False # Zero unnecessary SQL execution
|
|
140
|
+
|
|
141
|
+
changes = self.get_dirty_changes()
|
|
142
|
+
if not changes:
|
|
143
|
+
return False
|
|
144
|
+
|
|
145
|
+
cols = list(changes.keys())
|
|
146
|
+
vals = [changes[c] for c in cols]
|
|
147
|
+
vals.append(pk_val) # Primary key parameter for WHERE clause
|
|
148
|
+
|
|
149
|
+
if HAS_RUST_COMPILER:
|
|
150
|
+
compiler = RustQueryCompiler()
|
|
151
|
+
sql = compiler.compile_update(self.__tablename__, cols, pk_name, engine.dialect)
|
|
152
|
+
else:
|
|
153
|
+
set_str = ", ".join([f"{c} = ?" for c in cols])
|
|
154
|
+
sql = f"UPDATE {self.__tablename__} SET {set_str} WHERE {pk_name} = ?"
|
|
155
|
+
|
|
156
|
+
await engine.execute(sql, tuple(vals))
|
|
157
|
+
self._hydrate_snapshot()
|
|
158
|
+
return True
|
|
159
|
+
|
|
160
|
+
async def delete(self) -> bool:
|
|
161
|
+
engine = get_engine()
|
|
162
|
+
pk_name = self._primary_key_name
|
|
163
|
+
pk_val = getattr(self, pk_name, None)
|
|
164
|
+
if pk_val is None:
|
|
165
|
+
return False
|
|
166
|
+
|
|
167
|
+
if HAS_RUST_COMPILER:
|
|
168
|
+
compiler = RustQueryCompiler()
|
|
169
|
+
sql = compiler.compile_delete(self.__tablename__, pk_name, engine.dialect)
|
|
170
|
+
else:
|
|
171
|
+
sql = f"DELETE FROM {self.__tablename__} WHERE {pk_name} = ?"
|
|
172
|
+
|
|
173
|
+
await engine.execute(sql, (pk_val,))
|
|
174
|
+
return True
|
|
175
|
+
|
|
176
|
+
def __repr__(self) -> str:
|
|
177
|
+
pk_val = getattr(self, self._primary_key_name, None)
|
|
178
|
+
return f"<{self.__class__.__name__} id={pk_val}>"
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
from typing import Any, Dict, List, Optional, Type, Union
|
|
2
|
+
import asyncio
|
|
3
|
+
from lunarphase.query.batcher import DeferredAutoBatcher
|
|
4
|
+
|
|
5
|
+
class RelationDescriptor:
|
|
6
|
+
def __init__(self, target_model_getter: Any, foreign_key: Optional[str] = None):
|
|
7
|
+
self._target_model_raw = target_model_getter
|
|
8
|
+
self.foreign_key = foreign_key
|
|
9
|
+
self.name = ""
|
|
10
|
+
self.owner_class = None
|
|
11
|
+
|
|
12
|
+
def __set_name__(self, owner, name: str):
|
|
13
|
+
self.name = name
|
|
14
|
+
self.owner_class = owner
|
|
15
|
+
|
|
16
|
+
@property
|
|
17
|
+
def target_model(self) -> Type[Any]:
|
|
18
|
+
if callable(self._target_model_raw) and not isinstance(self._target_model_raw, type):
|
|
19
|
+
return self._target_model_raw()
|
|
20
|
+
return self._target_model_raw
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class HasMany(RelationDescriptor):
|
|
24
|
+
def __init__(self, target_model_getter: Any, foreign_key: Optional[str] = None):
|
|
25
|
+
super().__init__(target_model_getter, foreign_key)
|
|
26
|
+
self._batcher: Optional[DeferredAutoBatcher] = None
|
|
27
|
+
|
|
28
|
+
def _get_batcher(self) -> DeferredAutoBatcher:
|
|
29
|
+
if self._batcher is None:
|
|
30
|
+
fk = self.foreign_key or f"{self.owner_class.__name__.lower()}_id"
|
|
31
|
+
|
|
32
|
+
async def fetch_batch(keys: List[Any]) -> Dict[Any, List[Any]]:
|
|
33
|
+
target_cls = self.target_model
|
|
34
|
+
# Batch query: SELECT * FROM target_table WHERE fk IN (1, 2, 3...)
|
|
35
|
+
records = await target_cls.where(**{f"{fk}__in": keys} if hasattr(target_cls, "where") else {}).all()
|
|
36
|
+
grouped: Dict[Any, List[Any]] = {k: [] for k in keys}
|
|
37
|
+
for rec in records:
|
|
38
|
+
owner_id = getattr(rec, fk, None)
|
|
39
|
+
if owner_id in grouped:
|
|
40
|
+
grouped[owner_id].append(rec)
|
|
41
|
+
return grouped
|
|
42
|
+
|
|
43
|
+
self._batcher = DeferredAutoBatcher(fetch_batch)
|
|
44
|
+
return self._batcher
|
|
45
|
+
|
|
46
|
+
def __get__(self, instance, owner):
|
|
47
|
+
if instance is None:
|
|
48
|
+
return self
|
|
49
|
+
|
|
50
|
+
fk = self.foreign_key or f"{owner.__name__.lower()}_id"
|
|
51
|
+
owner_pk = getattr(instance, owner._primary_key_name, None)
|
|
52
|
+
if owner_pk is None:
|
|
53
|
+
async def empty():
|
|
54
|
+
return []
|
|
55
|
+
return empty()
|
|
56
|
+
|
|
57
|
+
target_cls = self.target_model
|
|
58
|
+
return target_cls.where(**{fk: owner_pk}).all()
|
|
59
|
+
|
|
60
|
+
async def eager_load(self, instances: List[Any]):
|
|
61
|
+
if not instances:
|
|
62
|
+
return
|
|
63
|
+
owner_cls = instances[0].__class__
|
|
64
|
+
fk = self.foreign_key or f"{owner_cls.__name__.lower()}_id"
|
|
65
|
+
owner_ids = [getattr(inst, owner_cls._primary_key_name) for inst in instances if getattr(inst, owner_cls._primary_key_name, None) is not None]
|
|
66
|
+
|
|
67
|
+
target_cls = self.target_model
|
|
68
|
+
related_records = await target_cls.where(**{f"{fk}__in": owner_ids} if hasattr(target_cls, "where") else {}).all()
|
|
69
|
+
|
|
70
|
+
grouped = {id_val: [] for id_val in owner_ids}
|
|
71
|
+
for rec in related_records:
|
|
72
|
+
owner_id = getattr(rec, fk, None)
|
|
73
|
+
if owner_id in grouped:
|
|
74
|
+
grouped[owner_id].append(rec)
|
|
75
|
+
|
|
76
|
+
for inst in instances:
|
|
77
|
+
pk = getattr(inst, owner_cls._primary_key_name, None)
|
|
78
|
+
setattr(inst, f"_{self.name}_cached", grouped.get(pk, []))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class BelongsTo(RelationDescriptor):
|
|
82
|
+
def __init__(self, target_model_getter: Any, foreign_key: Optional[str] = None):
|
|
83
|
+
super().__init__(target_model_getter, foreign_key)
|
|
84
|
+
|
|
85
|
+
def __get__(self, instance, owner):
|
|
86
|
+
if instance is None:
|
|
87
|
+
return self
|
|
88
|
+
|
|
89
|
+
target_cls = self.target_model
|
|
90
|
+
fk = self.foreign_key or f"{target_cls.__name__.lower()}_id"
|
|
91
|
+
fk_val = getattr(instance, fk, None)
|
|
92
|
+
if fk_val is None:
|
|
93
|
+
async def empty():
|
|
94
|
+
return None
|
|
95
|
+
return empty()
|
|
96
|
+
|
|
97
|
+
return target_cls.where(**{target_cls._primary_key_name: fk_val}).first()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class HasOne(RelationDescriptor):
|
|
101
|
+
def __get__(self, instance, owner):
|
|
102
|
+
if instance is None:
|
|
103
|
+
return self
|
|
104
|
+
|
|
105
|
+
fk = self.foreign_key or f"{owner.__name__.lower()}_id"
|
|
106
|
+
owner_pk = getattr(instance, owner._primary_key_name, None)
|
|
107
|
+
if owner_pk is None:
|
|
108
|
+
async def empty():
|
|
109
|
+
return None
|
|
110
|
+
return empty()
|
|
111
|
+
|
|
112
|
+
target_cls = self.target_model
|
|
113
|
+
return target_cls.where(**{fk: owner_pk}).first()
|
lunarphase/core/state.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
from typing import Dict, Any, Set, List
|
|
3
|
+
|
|
4
|
+
try:
|
|
5
|
+
from lunarphase._lunarphase_rs import StateTracker as RustStateTracker
|
|
6
|
+
HAS_RUST_CORE = True
|
|
7
|
+
except ImportError:
|
|
8
|
+
HAS_RUST_CORE = False
|
|
9
|
+
|
|
10
|
+
class PyStateTracker:
|
|
11
|
+
"""Pure Python fallback for StateTracker when Rust binary is unavailable."""
|
|
12
|
+
def __init__(self):
|
|
13
|
+
self._snapshot: Dict[str, Any] = {}
|
|
14
|
+
self._current: Dict[str, Any] = {}
|
|
15
|
+
|
|
16
|
+
def set_initial_state(self, data: Dict[str, Any]):
|
|
17
|
+
self._snapshot = copy.deepcopy(data)
|
|
18
|
+
self._current = copy.deepcopy(data)
|
|
19
|
+
|
|
20
|
+
def set_field(self, field: str, value: Any):
|
|
21
|
+
self._current[field] = value
|
|
22
|
+
|
|
23
|
+
def get_field(self, field: str) -> Any:
|
|
24
|
+
return self._current.get(field)
|
|
25
|
+
|
|
26
|
+
def is_dirty(self) -> bool:
|
|
27
|
+
for k, v in self._current.items():
|
|
28
|
+
if k not in self._snapshot or self._snapshot[k] != v:
|
|
29
|
+
return True
|
|
30
|
+
return False
|
|
31
|
+
|
|
32
|
+
def dirty_fields(self) -> List[str]:
|
|
33
|
+
dirty = []
|
|
34
|
+
for k, v in self._current.items():
|
|
35
|
+
if k not in self._snapshot or self._snapshot[k] != v:
|
|
36
|
+
dirty.append(k)
|
|
37
|
+
return dirty
|
|
38
|
+
|
|
39
|
+
def get_dirty_changes(self) -> Dict[str, Any]:
|
|
40
|
+
return {k: self._current[k] for k in self.dirty_fields()}
|
|
41
|
+
|
|
42
|
+
def hydrate_snapshot(self):
|
|
43
|
+
self._snapshot = copy.deepcopy(self._current)
|
|
44
|
+
|
|
45
|
+
def get_current_dict(self) -> Dict[str, Any]:
|
|
46
|
+
return copy.deepcopy(self._current)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def create_state_tracker():
|
|
50
|
+
"""Factory function returning RustStateTracker if available, otherwise PyStateTracker."""
|
|
51
|
+
if HAS_RUST_CORE:
|
|
52
|
+
return RustStateTracker()
|
|
53
|
+
return PyStateTracker()
|