alch-dc 0.1.0__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.
alch_dc-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.3
2
+ Name: alch-dc
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ Author: minhdenthedev
6
+ Author-email: minhdenthedev <hminh100304@gmail.com>
7
+ Requires-Dist: sqlalchemy>=2.1.9
8
+ Requires-Python: >=3.12
9
+ Description-Content-Type: text/markdown
10
+
11
+ # `Alch-DC`: Converting between SQLAlchemy ORM models and dataclass objects
12
+
13
+ Tired of manually converting dataclass objects to SQLAlchemy ORM models and backward?
14
+ If yes, `alch-dc` (Alchemy - Dataclass) is for you. It validates and maps between the
15
+ two paradigms for you.
16
+
17
+ ## Installation
18
+
19
+ If you're using `uv` then
20
+ ```commandline
21
+ uv add alch-dc
22
+ ```
23
+
24
+ or install with `pip`:
25
+ ```commandline
26
+ pip install alch-dc
27
+ ```
28
+
29
+
30
+ ## Quick start
31
+
32
+ ```python
33
+ from dataclasses import dataclass
34
+ from uuid import UUID, uuid4
35
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
36
+
37
+
38
+ # --- DATACLASS MODEL --- #
39
+ @dataclass
40
+ class Person:
41
+ id: UUID
42
+ name: str
43
+ age: int
44
+
45
+
46
+ # --- SQLALCHEMY MODEL --- #
47
+ class Base(DeclarativeBase):
48
+ pass
49
+
50
+
51
+ class PersonModel(Base):
52
+ __tablename__ = "people"
53
+
54
+ id: Mapped[UUID] = mapped_column(primary_key=True)
55
+ name: Mapped[str]
56
+ age: Mapped[int]
57
+
58
+
59
+ # --- ALCH-DC --- #
60
+ from alch_dc import Converter
61
+
62
+ # Create a converter to use throughout the project
63
+ converter = Converter(Person, PersonModel)
64
+
65
+ # Map dataclass object to ORM object
66
+ p = Person(id=uuid4(), name="minhdenthedev", age=22)
67
+ orm_p = converter.to_orm(p)
68
+
69
+ # Map ORM object to dataclass object
70
+ orm_p = PersonModel(id=uuid4(), name="minhdenthedev", age=22)
71
+ p = converter.from_orm(orm_p)
72
+ ```
73
+
74
+ ## Best practices
75
+
76
+ When instantiating, the `converter` would validate the schema to make sure the two
77
+ classes are convertible. This operation is time-consuming and only needs to be checked
78
+ once, so it's best to instantiate the `Converter` class once and then use it throughout
79
+ your code.
@@ -0,0 +1,69 @@
1
+ # `Alch-DC`: Converting between SQLAlchemy ORM models and dataclass objects
2
+
3
+ Tired of manually converting dataclass objects to SQLAlchemy ORM models and backward?
4
+ If yes, `alch-dc` (Alchemy - Dataclass) is for you. It validates and maps between the
5
+ two paradigms for you.
6
+
7
+ ## Installation
8
+
9
+ If you're using `uv` then
10
+ ```commandline
11
+ uv add alch-dc
12
+ ```
13
+
14
+ or install with `pip`:
15
+ ```commandline
16
+ pip install alch-dc
17
+ ```
18
+
19
+
20
+ ## Quick start
21
+
22
+ ```python
23
+ from dataclasses import dataclass
24
+ from uuid import UUID, uuid4
25
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
26
+
27
+
28
+ # --- DATACLASS MODEL --- #
29
+ @dataclass
30
+ class Person:
31
+ id: UUID
32
+ name: str
33
+ age: int
34
+
35
+
36
+ # --- SQLALCHEMY MODEL --- #
37
+ class Base(DeclarativeBase):
38
+ pass
39
+
40
+
41
+ class PersonModel(Base):
42
+ __tablename__ = "people"
43
+
44
+ id: Mapped[UUID] = mapped_column(primary_key=True)
45
+ name: Mapped[str]
46
+ age: Mapped[int]
47
+
48
+
49
+ # --- ALCH-DC --- #
50
+ from alch_dc import Converter
51
+
52
+ # Create a converter to use throughout the project
53
+ converter = Converter(Person, PersonModel)
54
+
55
+ # Map dataclass object to ORM object
56
+ p = Person(id=uuid4(), name="minhdenthedev", age=22)
57
+ orm_p = converter.to_orm(p)
58
+
59
+ # Map ORM object to dataclass object
60
+ orm_p = PersonModel(id=uuid4(), name="minhdenthedev", age=22)
61
+ p = converter.from_orm(orm_p)
62
+ ```
63
+
64
+ ## Best practices
65
+
66
+ When instantiating, the `converter` would validate the schema to make sure the two
67
+ classes are convertible. This operation is time-consuming and only needs to be checked
68
+ once, so it's best to instantiate the `Converter` class once and then use it throughout
69
+ your code.
@@ -0,0 +1,18 @@
1
+ [project]
2
+ name = "alch-dc"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = ["sqlalchemy>=2.1.9"]
8
+
9
+ [[project.authors]]
10
+ name = "minhdenthedev"
11
+ email = "hminh100304@gmail.com"
12
+
13
+ [project.scripts]
14
+ alch-dc = "alch_dc:main"
15
+
16
+ [build-system]
17
+ requires = ["uv_build>=0.13.7,<0.14.0"]
18
+ build-backend = "uv_build"
@@ -0,0 +1,19 @@
1
+ [project]
2
+ name = "alch-dc"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "minhdenthedev", email = "hminh100304@gmail.com" }
8
+ ]
9
+ requires-python = ">=3.12"
10
+ dependencies = [
11
+ "sqlalchemy>=2.1.9",
12
+ ]
13
+
14
+ [project.scripts]
15
+ alch-dc = "alch_dc:main"
16
+
17
+ [build-system]
18
+ requires = ["uv_build>=0.13.7,<0.14.0"]
19
+ build-backend = "uv_build"
@@ -0,0 +1,13 @@
1
+ from alch_dc.converter import Converter
2
+ from alch_dc.internal_field import InternalField
3
+
4
+ __all__ = [
5
+ "Converter",
6
+ "InternalField"
7
+ ]
8
+
9
+ def main() -> None:
10
+ print("Hello from alch-dc!")
11
+
12
+
13
+
@@ -0,0 +1,101 @@
1
+ from dataclasses import fields, asdict
2
+ from types import UnionType, NoneType
3
+ from typing import cast, Any, get_origin, Union, get_args
4
+
5
+ from sqlalchemy import inspect, JSON
6
+ from sqlalchemy.orm import DeclarativeBase, Mapper
7
+
8
+ from alch_dc.exc.fields_mismatch import FieldsMismatch
9
+ from alch_dc.internal_field import InternalField
10
+
11
+
12
+ class Converter:
13
+ def __init__(self, dataclass_cls: type, orm_cls: type[DeclarativeBase]):
14
+ self._dataclass_cls = dataclass_cls
15
+ self._orm_cls = orm_cls
16
+ self._orm_mapper: Mapper = cast(Mapper, cast(object, inspect(self._orm_cls)))
17
+ if not self.is_convertable():
18
+ raise FieldsMismatch(
19
+ dataclass_cls,
20
+ self._dataclass_fields(),
21
+ orm_cls,
22
+ self._orm_fields(),
23
+ )
24
+
25
+ def is_convertable(self) -> bool:
26
+ """Validate whether the dataclass cls and orm cls is convertable"""
27
+ return self._orm_fields() == self._dataclass_fields()
28
+
29
+ def set_dataclass(self, dataclass_cls: type):
30
+ self._dataclass_cls = dataclass_cls
31
+ if not self.is_convertable():
32
+ raise FieldsMismatch(
33
+ self._dataclass_cls,
34
+ self._dataclass_fields(),
35
+ self._orm_cls,
36
+ self._orm_fields(),
37
+ )
38
+
39
+ def set_orm(self, orm_cls: type[DeclarativeBase]):
40
+ self._orm_cls = orm_cls
41
+ self._orm_mapper: Mapper = cast(Mapper, cast(object, inspect(self._orm_cls)))
42
+ if not self.is_convertable():
43
+ raise FieldsMismatch(
44
+ self._dataclass_cls,
45
+ self._dataclass_fields(),
46
+ self._orm_cls,
47
+ self._orm_fields(),
48
+ )
49
+
50
+ # noinspection bad-argument-type,dataclass
51
+ def _dataclass_fields(self) -> set[InternalField]:
52
+ answers = set()
53
+ for field in fields(self._dataclass_cls):
54
+ nullable = False
55
+ if field.type is dict or get_origin(field.type) is dict:
56
+ field_type = dict
57
+ elif get_origin(field.type) in (UnionType, Union):
58
+ types = list(get_args(field.type))
59
+ if NoneType in types:
60
+ nullable = True
61
+ types.remove(NoneType)
62
+ if len(types) == 1:
63
+ field_type = types[0]
64
+ else:
65
+ raise NotImplementedError(
66
+ f"Union and UnionType are not supported. Field: {field.name}",
67
+ )
68
+ else:
69
+ field_type = field.type
70
+ answers.add(
71
+ InternalField(name=field.name, type=field_type, nullable=nullable),
72
+ )
73
+ return answers
74
+
75
+ def _orm_fields(self) -> set[InternalField]:
76
+ answers = set()
77
+ for col in self._orm_mapper.columns:
78
+ nullable = False
79
+ if isinstance(col.type, JSON):
80
+ python_type = dict
81
+ else:
82
+ python_type = col.type.python_type
83
+ field = InternalField(name=col.key, type=python_type, nullable=nullable)
84
+ answers.add(field)
85
+
86
+ return answers
87
+
88
+ def get_dataclass(self) -> type:
89
+ return self._dataclass_cls
90
+
91
+ def get_orm(self) -> type[DeclarativeBase]:
92
+ return self._orm_cls
93
+
94
+ def to_orm(self, dataclass_ins) -> DeclarativeBase:
95
+ return self._orm_cls(**asdict(dataclass_ins))
96
+
97
+ def get_orm_dict(self, orm_ins) -> dict[str, Any]:
98
+ return {a.key: getattr(orm_ins, a.key) for a in self._orm_mapper.column_attrs}
99
+
100
+ def from_orm(self, orm_ins):
101
+ return self._dataclass_cls(**self.get_orm_dict(orm_ins))
File without changes
@@ -0,0 +1,27 @@
1
+ from sqlalchemy.orm import DeclarativeBase
2
+
3
+ from alch_dc.internal_field import InternalField
4
+
5
+
6
+ class FieldsMismatch(Exception):
7
+ def __init__(
8
+ self,
9
+ dataclass_cls: type,
10
+ dataclass_fields: set[InternalField],
11
+ orm_cls: type[DeclarativeBase],
12
+ orm_fields: set[InternalField],
13
+ ):
14
+
15
+ msg = (
16
+ "Cannot convert between two classes. Fields mismatch:\n"
17
+ f"Class `{dataclass_cls.__name__}` has the following fields:\n"
18
+ f" +) {self.build_fields_msg(dataclass_fields)}\n"
19
+ f"Meanwhile, class `{orm_cls.__name__}` has the following fields:\n"
20
+ f" +) {self.build_fields_msg(orm_fields)}\n"
21
+ )
22
+
23
+ super().__init__(msg)
24
+
25
+ @classmethod
26
+ def build_fields_msg(cls, fields: set[InternalField]):
27
+ return "\n +) ".join(str(field) for field in fields)
@@ -0,0 +1,23 @@
1
+ from __future__ import annotations
2
+ from typing import NamedTuple
3
+
4
+
5
+ class InternalField(NamedTuple):
6
+ name: str
7
+ type: type
8
+ nullable: bool
9
+
10
+ def __hash__(self) -> int:
11
+ return hash((self.name, self.type))
12
+
13
+ def __ne__(self, other: object) -> bool:
14
+ return not self == other
15
+
16
+ def __eq__(self, value: object, /) -> bool:
17
+ if isinstance(value, InternalField):
18
+ return self.name == value.name and self.type == value.type
19
+ else:
20
+ return False
21
+
22
+ def __str__(self) -> str:
23
+ return f"`{self.name}` ({self.type.__name__})"