sqlstruct 0.1.0__py3-none-any.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.
sqlstruct/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """SQLModel for msgspec."""
2
+
3
+ from sqlstruct._field import Field
4
+ from sqlstruct._session import Session, col, create_engine, select
5
+ from sqlstruct._struct import SQLStruct
6
+
7
+ __all__ = [
8
+ "Field",
9
+ "SQLStruct",
10
+ "Session",
11
+ "col",
12
+ "create_engine",
13
+ "select",
14
+ ]
sqlstruct/_field.py ADDED
@@ -0,0 +1,75 @@
1
+ """Field descriptor and metadata for SQLStruct models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from sqlalchemy import Column
9
+
10
+ _UNSET: Any = object()
11
+
12
+
13
+ class FieldInfo:
14
+ """Metadata describing a SQLStruct field and its SQLAlchemy column options."""
15
+
16
+ def __init__(
17
+ self,
18
+ default: Any = _UNSET,
19
+ *,
20
+ default_factory: Callable[[], Any] | Any = _UNSET,
21
+ primary_key: bool = False,
22
+ foreign_key: str | None = None,
23
+ ondelete: str | None = None,
24
+ index: bool = False,
25
+ unique: bool = False,
26
+ nullable: bool | None = None,
27
+ max_length: int | None = None,
28
+ sa_column: Column[Any] | None = None,
29
+ sa_column_args: tuple[Any, ...] | None = None,
30
+ sa_column_kwargs: dict[str, Any] | None = None,
31
+ ) -> None:
32
+ self.default = default
33
+ self.default_factory = default_factory
34
+ self.primary_key = primary_key
35
+ self.foreign_key = foreign_key
36
+ self.ondelete = ondelete
37
+ self.index = index
38
+ self.unique = unique
39
+ self.nullable = nullable
40
+ self.max_length = max_length
41
+ self.sa_column = sa_column
42
+ self.sa_column_args = sa_column_args
43
+ self.sa_column_kwargs = sa_column_kwargs
44
+
45
+
46
+ def Field(
47
+ default: Any = _UNSET,
48
+ *,
49
+ default_factory: Callable[[], Any] | Any = _UNSET,
50
+ primary_key: bool = False,
51
+ foreign_key: str | None = None,
52
+ ondelete: str | None = None,
53
+ index: bool = False,
54
+ unique: bool = False,
55
+ nullable: bool | None = None,
56
+ max_length: int | None = None,
57
+ sa_column: Column[Any] | None = None,
58
+ sa_column_args: tuple[Any, ...] | None = None,
59
+ sa_column_kwargs: dict[str, Any] | None = None,
60
+ ) -> Any:
61
+ """Declare a field on a SQLStruct with optional SQLAlchemy column metadata."""
62
+ return FieldInfo(
63
+ default=default,
64
+ default_factory=default_factory,
65
+ primary_key=primary_key,
66
+ foreign_key=foreign_key,
67
+ ondelete=ondelete,
68
+ index=index,
69
+ unique=unique,
70
+ nullable=nullable,
71
+ max_length=max_length,
72
+ sa_column=sa_column,
73
+ sa_column_args=sa_column_args,
74
+ sa_column_kwargs=sa_column_kwargs,
75
+ )
sqlstruct/_session.py ADDED
@@ -0,0 +1,28 @@
1
+ """Session and query helpers for SQLStruct."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, cast
6
+
7
+ from sqlalchemy import create_engine, select
8
+ from sqlalchemy.orm import Mapped
9
+ from sqlalchemy.orm import Session as _SASession
10
+ from sqlalchemy.sql import Select
11
+
12
+
13
+ def col[T](column_expression: T) -> Mapped[T]:
14
+ """Cast a SQLStruct attribute to a SQLAlchemy Mapped column for type checkers."""
15
+ return cast(Mapped[T], column_expression)
16
+
17
+
18
+ class Session(_SASession):
19
+ """SQLAlchemy Session with a SQLModel-style .exec() helper."""
20
+
21
+ def exec(self, statement: Any, **kwargs: Any) -> Any:
22
+ """Execute a statement, returning scalar results for single-entity SELECTs."""
23
+ if isinstance(statement, Select) and len(statement.column_descriptions) == 1:
24
+ return self.scalars(statement, **kwargs)
25
+ return self.execute(statement, **kwargs)
26
+
27
+
28
+ __all__ = ["Session", "col", "create_engine", "select"]
sqlstruct/_struct.py ADDED
@@ -0,0 +1,210 @@
1
+ """Core SQLStruct base class and metaclass bridging msgspec.Struct and SQLAlchemy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, ClassVar, dataclass_transform, get_type_hints
6
+
7
+ import msgspec
8
+ import sqlalchemy as sa
9
+ from sqlalchemy import Column, ForeignKey, MetaData, Table, event
10
+ from sqlalchemy.orm import Mapper, configure_mappers, registry
11
+ from sqlalchemy.orm.base import NEVER_SET, NO_VALUE
12
+
13
+ from sqlstruct._field import _UNSET, Field, FieldInfo
14
+ from sqlstruct._types import get_sqlalchemy_type
15
+
16
+ _default_registry = registry()
17
+
18
+
19
+ def _init_sa_state(obj: Any) -> None:
20
+ """Populate __dict__ from msgspec C slots and attach SQLAlchemy InstanceState."""
21
+ cls = obj.__class__
22
+ mgr = getattr(cls, "_sa_class_manager", None)
23
+ if mgr is None or "_sa_instance_state" in obj.__dict__:
24
+ return
25
+ struct_members: dict[str, Any] = getattr(cls, "_struct_members", {})
26
+ for name, desc in struct_members.items():
27
+ obj.__dict__[name] = desc.__get__(obj, cls)
28
+ mgr.setup_instance(obj)
29
+
30
+
31
+ def _sync_dict_to_struct(target: Any, *args: Any) -> None:
32
+ """Copy SQLAlchemy-populated __dict__ values back into msgspec C struct slots."""
33
+ cls = target.__class__
34
+ struct_members: dict[str, Any] = getattr(cls, "_struct_members", {})
35
+ for name, desc in struct_members.items():
36
+ if name in target.__dict__:
37
+ desc.__set__(target, target.__dict__[name])
38
+
39
+
40
+ def _make_attr_set_listener(desc: Any) -> Any:
41
+ def _on_set(target: Any, value: Any, oldvalue: Any, initiator: Any) -> None:
42
+ if value is not NO_VALUE and value is not NEVER_SET:
43
+ desc.__set__(target, value)
44
+
45
+ return _on_set
46
+
47
+
48
+ def _build_column(name: str, annotation: Any, field_info: FieldInfo) -> Column[Any]:
49
+ """Build a SQLAlchemy Column from a field name, annotation, and FieldInfo."""
50
+ if field_info.sa_column is not None:
51
+ col = field_info.sa_column
52
+ if not col.name:
53
+ col.name = name
54
+ if not col.key:
55
+ col.key = name
56
+ return col
57
+
58
+ sa_type, is_optional = get_sqlalchemy_type(annotation, field_info)
59
+ col_args: list[Any] = []
60
+ if field_info.foreign_key is not None:
61
+ fk_kwargs: dict[str, Any] = {}
62
+ if field_info.ondelete is not None:
63
+ fk_kwargs["ondelete"] = field_info.ondelete
64
+ col_args.append(ForeignKey(field_info.foreign_key, **fk_kwargs))
65
+
66
+ if field_info.sa_column_args:
67
+ col_args.extend(field_info.sa_column_args)
68
+
69
+ if field_info.nullable is not None:
70
+ nullable = field_info.nullable
71
+ elif field_info.primary_key:
72
+ nullable = False
73
+ else:
74
+ nullable = is_optional
75
+
76
+ col_kwargs: dict[str, Any] = {
77
+ "primary_key": field_info.primary_key,
78
+ "index": field_info.index,
79
+ "unique": field_info.unique,
80
+ "nullable": nullable,
81
+ }
82
+ if field_info.sa_column_kwargs:
83
+ col_kwargs.update(field_info.sa_column_kwargs)
84
+
85
+ return Column(name, sa_type, *col_args, **col_kwargs)
86
+
87
+
88
+ _StructMetaBase: type[type] = type(msgspec.Struct)
89
+
90
+
91
+ @dataclass_transform(kw_only_default=True, field_specifiers=(Field, FieldInfo))
92
+ class SQLStructMeta(_StructMetaBase): # type: ignore[misc]
93
+ """Metaclass for SQLStruct translating Field() specs and table=True mapping."""
94
+
95
+ def __new__(
96
+ mcs,
97
+ name: str,
98
+ bases: tuple[type, ...],
99
+ namespace: dict[str, Any],
100
+ *,
101
+ table: bool = False,
102
+ **kwargs: Any,
103
+ ) -> Any:
104
+ kwargs.setdefault("dict", True)
105
+ kwargs.setdefault("weakref", True)
106
+ kwargs.setdefault("kw_only", True)
107
+
108
+ extracted: dict[str, FieldInfo] = {}
109
+ for attr_name, attr_val in list(namespace.items()):
110
+ if isinstance(attr_val, FieldInfo):
111
+ extracted[attr_name] = attr_val
112
+ if attr_val.default is not _UNSET:
113
+ namespace[attr_name] = msgspec.field(default=attr_val.default)
114
+ elif attr_val.default_factory is not _UNSET:
115
+ namespace[attr_name] = msgspec.field(
116
+ default_factory=attr_val.default_factory
117
+ )
118
+ else:
119
+ del namespace[attr_name]
120
+
121
+ cls = super().__new__(mcs, name, bases, namespace, **kwargs)
122
+
123
+ merged_fields: dict[str, FieldInfo] = {}
124
+ for base in reversed(cls.__mro__):
125
+ base_fields = getattr(base, "__sqlstruct_fields__", None)
126
+ if base_fields:
127
+ merged_fields.update(base_fields)
128
+ merged_fields.update(extracted)
129
+ cls_any: Any = cls
130
+ cls_any.__sqlstruct_fields__ = merged_fields
131
+
132
+ if table:
133
+ mcs._configure_table(cls)
134
+
135
+ return cls
136
+
137
+ @staticmethod
138
+ def _configure_table(cls: Any) -> None:
139
+ tablename = cls.__dict__.get("__tablename__") or cls.__name__.lower()
140
+ hints = get_type_hints(cls, include_extras=True)
141
+ field_infos: dict[str, FieldInfo] = cls.__sqlstruct_fields__
142
+
143
+ columns = [
144
+ _build_column(
145
+ field_name,
146
+ hints[field_name],
147
+ field_infos.get(field_name, FieldInfo()),
148
+ )
149
+ for field_name in cls.__struct_fields__
150
+ ]
151
+
152
+ sa_table = Table(tablename, cls.metadata, *columns)
153
+
154
+ # Save msgspec C member_descriptors and remove them so SQLAlchemy can
155
+ # install InstrumentedAttribute descriptors on the class.
156
+ struct_members: dict[str, Any] = {}
157
+ for field_name in cls.__struct_fields__:
158
+ struct_members[field_name] = getattr(cls, field_name)
159
+ if field_name in cls.__dict__:
160
+ delattr(cls, field_name)
161
+ cls._struct_members = struct_members
162
+
163
+ mapper: Mapper[Any] = cls._sa_registry.map_imperatively(cls, sa_table)
164
+ configure_mappers()
165
+
166
+ cls.__table__ = sa_table
167
+ cls.__mapper__ = mapper
168
+
169
+ # SQLAlchemy's default ClassManager.new_instance calls cls.__new__(cls),
170
+ # which raises TypeError on msgspec.Struct C types. Construct via
171
+ # StructMeta.__call__ directly with placeholder Nones instead.
172
+ struct_fields: tuple[str, ...] = cls.__struct_fields__
173
+
174
+ def _new_instance(state: Any = None) -> Any:
175
+ return _StructMetaBase.__call__(cls, **dict.fromkeys(struct_fields, None))
176
+
177
+ cls._sa_class_manager.new_instance = _new_instance
178
+
179
+ event.listen(cls, "load", _sync_dict_to_struct)
180
+ event.listen(cls, "refresh", _sync_dict_to_struct)
181
+ for field_name, desc in struct_members.items():
182
+ event.listen(getattr(cls, field_name), "set", _make_attr_set_listener(desc))
183
+
184
+ def __call__(cls, *args: Any, **kwargs: Any) -> Any:
185
+ obj = super().__call__(*args, **kwargs)
186
+ _init_sa_state(obj)
187
+ return obj
188
+
189
+
190
+ class SQLStruct(
191
+ msgspec.Struct,
192
+ metaclass=SQLStructMeta,
193
+ dict=True,
194
+ weakref=True,
195
+ kw_only=True,
196
+ ):
197
+ """Base class for msgspec-backed SQLAlchemy models and schemas."""
198
+
199
+ _sa_registry: ClassVar[registry] = _default_registry
200
+ metadata: ClassVar[MetaData] = _default_registry.metadata
201
+ __sqlstruct_fields__: ClassVar[dict[str, FieldInfo]] = {}
202
+ __table__: ClassVar[sa.Table]
203
+ __mapper__: ClassVar[Mapper[Any]]
204
+
205
+ if TYPE_CHECKING:
206
+
207
+ def __init_subclass__(cls, *, table: bool = False, **kwargs: Any) -> None: ...
208
+
209
+ def __post_init__(self) -> None:
210
+ _init_sa_state(self)
sqlstruct/_types.py ADDED
@@ -0,0 +1,73 @@
1
+ """Python type annotation to SQLAlchemy column type mapping."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import decimal
7
+ import enum
8
+ import types
9
+ import uuid
10
+ from typing import Annotated, Any, Union, get_args, get_origin
11
+
12
+ import sqlalchemy as sa
13
+ from sqlalchemy.types import TypeEngine
14
+
15
+ from sqlstruct._field import FieldInfo
16
+
17
+ _SIMPLE_TYPE_MAP: dict[type[Any], type[TypeEngine[Any]]] = {
18
+ bool: sa.Boolean,
19
+ int: sa.Integer,
20
+ float: sa.Float,
21
+ bytes: sa.LargeBinary,
22
+ datetime.datetime: sa.DateTime,
23
+ datetime.date: sa.Date,
24
+ datetime.time: sa.Time,
25
+ datetime.timedelta: sa.Interval,
26
+ decimal.Decimal: sa.Numeric,
27
+ uuid.UUID: sa.Uuid,
28
+ }
29
+
30
+
31
+ def unwrap_optional(annotation: Any) -> tuple[Any, bool]:
32
+ """Unwrap Annotated and Optional/Union[T, None] into (inner_type, nullable)."""
33
+ origin = get_origin(annotation)
34
+ if origin is Annotated:
35
+ annotation = get_args(annotation)[0]
36
+ origin = get_origin(annotation)
37
+
38
+ if origin is Union or origin is types.UnionType:
39
+ args = get_args(annotation)
40
+ non_none = [arg for arg in args if arg is not type(None)]
41
+ is_nullable = len(non_none) < len(args)
42
+ if len(non_none) == 1:
43
+ inner, inner_nullable = unwrap_optional(non_none[0])
44
+ return inner, is_nullable or inner_nullable
45
+ return annotation, is_nullable
46
+
47
+ return annotation, False
48
+
49
+
50
+ def get_sqlalchemy_type(
51
+ annotation: Any, field_info: FieldInfo | None = None
52
+ ) -> tuple[TypeEngine[Any] | type[TypeEngine[Any]], bool]:
53
+ """Resolve a Python type annotation to a SQLAlchemy type and nullability."""
54
+ inner_type, is_nullable = unwrap_optional(annotation)
55
+
56
+ if inner_type is str:
57
+ max_length = field_info.max_length if field_info is not None else None
58
+ return (sa.String(length=max_length) if max_length else sa.String), is_nullable
59
+
60
+ if inner_type in _SIMPLE_TYPE_MAP:
61
+ return _SIMPLE_TYPE_MAP[inner_type], is_nullable
62
+
63
+ if isinstance(inner_type, type) and issubclass(inner_type, enum.Enum):
64
+ return sa.Enum(inner_type), is_nullable
65
+
66
+ origin = get_origin(inner_type)
67
+ if inner_type in (dict, list) or origin in (dict, list):
68
+ return sa.JSON, is_nullable
69
+
70
+ raise TypeError(
71
+ f"Unsupported field type {annotation!r} for SQLStruct column mapping. "
72
+ "Pass an explicit sa_column=Column(...) via Field()."
73
+ )
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.5
2
+ Name: sqlstruct
3
+ Version: 0.1.0
4
+ Summary: SQLModel for msgspec
5
+ Requires-Python: >=3.12
6
+ Requires-Dist: msgspec>=0.22.0
7
+ Requires-Dist: sqlalchemy>=2.0
8
+ Description-Content-Type: text/markdown
9
+
10
+ # sqlstruct
11
+
12
+ SQLModel for [msgspec](https://jcristharif.com/msgspec/).
13
+
14
+ ## Development
15
+
16
+ Tooling is [uv](https://docs.astral.sh/uv/), [ruff](https://docs.astral.sh/ruff/) and [ty](https://docs.astral.sh/ty/):
17
+
18
+ ```sh
19
+ uv sync # install dependencies
20
+ uv run pytest # tests
21
+ uv run ruff format . # format
22
+ uv run ruff check . # lint
23
+ uv run ty check # type check
24
+ ```
@@ -0,0 +1,8 @@
1
+ sqlstruct/__init__.py,sha256=X_Q7X9VHsCAeXaDI0GS6HGiRS03bUrfA2LAk-f8l_pI,277
2
+ sqlstruct/_field.py,sha256=5lxUKEem8MacbwwmvyUXC44PCBlOgcUEzrwPxeHai70,2270
3
+ sqlstruct/_session.py,sha256=1mFIIwpo5-nMYF_rPqEedCW0p21IvkSKUO6JForUFF0,945
4
+ sqlstruct/_struct.py,sha256=m0bGQf97fZg5RFu9PRY5tsv-6XwGqJrFcW6LM8nSZxg,7432
5
+ sqlstruct/_types.py,sha256=tLNdQpp32MFhtcrWnN8-8Blq2cjYCipXJThOcGhZ9Y8,2397
6
+ sqlstruct-0.1.0.dist-info/METADATA,sha256=MIqQPlXnTbeqUsejSpaMilAJreZD8bCHMzDivkwVPq4,609
7
+ sqlstruct-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ sqlstruct-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any