crudman-fastapi 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.
crudman/__init__.py ADDED
@@ -0,0 +1,133 @@
1
+ """crudman-fastapi: zero-boilerplate CRUD for FastAPI and SQLAlchemy.
2
+
3
+ from crudman import Crudman, CrudmanOptions, crud_router
4
+
5
+ Crudman.init(app, CrudmanOptions(session_dependency=get_session))
6
+ app.include_router(crud_router(Company))
7
+ """
8
+
9
+ from .adapters.sqlalchemy import FilterValueError, SqlAlchemyAdapter
10
+ from .cache import CacheAdapter, MemoryCache, RedisCache
11
+ from .context import CrudAbort, CrudRequest, CrudResult, HookContext, Repository, UploadedFile
12
+ from .errors import CrudmanConfigError, CrudmanError
13
+ from .naming import (
14
+ apply_path_style,
15
+ default_path,
16
+ normalize_path,
17
+ resolve_path,
18
+ section_name_for,
19
+ table_name_of,
20
+ )
21
+ from .options import (
22
+ ActionConfig,
23
+ CacheOptions,
24
+ CrudmanOptions,
25
+ DeleteAction,
26
+ DetailsAction,
27
+ Keyword,
28
+ ListAction,
29
+ OpenApiOptions,
30
+ Pagination,
31
+ Section,
32
+ UploadConfig,
33
+ UploadMap,
34
+ UploadResponseOptions,
35
+ WriteAction,
36
+ )
37
+ from .query import (
38
+ FilterItem,
39
+ KeywordOptions,
40
+ PaginationInfo,
41
+ PaginationOptions,
42
+ PaginationResult,
43
+ QueryParamNames,
44
+ SortItem,
45
+ finalize_pagination,
46
+ keyword_paths,
47
+ parse_filters,
48
+ parse_keyword,
49
+ parse_pagination,
50
+ parse_sorting,
51
+ )
52
+ from .response import (
53
+ DELETE_PAYLOAD,
54
+ FormatInput,
55
+ default_response_formatter,
56
+ empty_pagination,
57
+ error_body,
58
+ )
59
+ from .routing import CrudController, Crudman, crud, crud_router, crudman_session, get_crud
60
+ from .schemas import PydanticValidator, generate_rules, rules_to_model, serialize
61
+ from .service import CrudmanService
62
+ from .uploads import PRESETS, LocalStorage, S3Storage
63
+
64
+ __version__ = "0.1.0"
65
+
66
+ __all__ = [
67
+ "DELETE_PAYLOAD",
68
+ "PRESETS",
69
+ "ActionConfig",
70
+ "CacheAdapter",
71
+ "CacheOptions",
72
+ "CrudAbort",
73
+ "CrudController",
74
+ "CrudRequest",
75
+ "CrudResult",
76
+ "Crudman",
77
+ "CrudmanConfigError",
78
+ "CrudmanError",
79
+ "CrudmanOptions",
80
+ "CrudmanService",
81
+ "DeleteAction",
82
+ "DetailsAction",
83
+ "FilterItem",
84
+ "FilterValueError",
85
+ "FormatInput",
86
+ "HookContext",
87
+ "Keyword",
88
+ "KeywordOptions",
89
+ "ListAction",
90
+ "LocalStorage",
91
+ "MemoryCache",
92
+ "OpenApiOptions",
93
+ "Pagination",
94
+ "PaginationInfo",
95
+ "PaginationOptions",
96
+ "PaginationResult",
97
+ "PydanticValidator",
98
+ "QueryParamNames",
99
+ "RedisCache",
100
+ "Repository",
101
+ "S3Storage",
102
+ "Section",
103
+ "SortItem",
104
+ "SqlAlchemyAdapter",
105
+ "UploadConfig",
106
+ "UploadMap",
107
+ "UploadResponseOptions",
108
+ "UploadedFile",
109
+ "WriteAction",
110
+ "__version__",
111
+ "apply_path_style",
112
+ "crud",
113
+ "crud_router",
114
+ "crudman_session",
115
+ "default_path",
116
+ "default_response_formatter",
117
+ "empty_pagination",
118
+ "error_body",
119
+ "finalize_pagination",
120
+ "generate_rules",
121
+ "get_crud",
122
+ "keyword_paths",
123
+ "normalize_path",
124
+ "parse_filters",
125
+ "parse_keyword",
126
+ "parse_pagination",
127
+ "parse_sorting",
128
+ "resolve_path",
129
+ "rules_to_model",
130
+ "section_name_for",
131
+ "serialize",
132
+ "table_name_of",
133
+ ]
File without changes
@@ -0,0 +1,326 @@
1
+ """SQLAlchemy 2.0 (async) adapter.
2
+
3
+ Every list request is built as one ``Select``: filters, keyword search, fixed conditions, ownership and
4
+ sorting all go into the same statement, and ``on_before_query`` sees that statement. Keyword search on
5
+ relations uses ``EXISTS`` (``any()`` / ``has()``), so rows are never duplicated and counts stay correct.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import datetime as dt
11
+ import decimal
12
+ import uuid
13
+ from collections.abc import Iterable, Mapping, Sequence
14
+ from dataclasses import dataclass
15
+ from typing import Any
16
+
17
+ from sqlalchemy import ColumnElement, Select, String, and_, cast, func, or_, select
18
+ from sqlalchemy.ext.asyncio import AsyncSession
19
+ from sqlalchemy.orm import selectinload
20
+ from sqlalchemy.orm.strategy_options import _AbstractLoad
21
+
22
+ from ..errors import CrudmanError
23
+ from ..query import FilterItem, SortItem
24
+ from ..schemas import ColumnInfo, columns_of, primary_key_of, relations_of
25
+
26
+
27
+ class FilterValueError(CrudmanError):
28
+ """A query-string value could not be converted to the column type."""
29
+
30
+ def __init__(self, field: str, value: Any, expected: str) -> None:
31
+ super().__init__(f"Invalid value {value!r} for '{field}': expected {expected}")
32
+ self.field = field
33
+ self.value = value
34
+ self.expected = expected
35
+
36
+
37
+ _TRUE = {"true", "1", "yes", "on"}
38
+ _FALSE = {"false", "0", "no", "off"}
39
+
40
+
41
+ def _is_date_only(text: str) -> bool:
42
+ return len(text.strip()) == 10 and text.count("-") == 2
43
+
44
+
45
+ def cast_value(info: ColumnInfo, raw: Any, *, end_of_day: bool = False) -> Any:
46
+ """Convert a query-string value to the column's Python type."""
47
+ if raw is None:
48
+ return None
49
+ py = info.python_type
50
+ text = str(raw).strip()
51
+ try:
52
+ if info.enum_values is not None:
53
+ enum_class = getattr(info.column.type, "enum_class", None)
54
+ if enum_class is not None:
55
+ return enum_class(text)
56
+ return text
57
+ if py is bool:
58
+ low = text.lower()
59
+ if low in _TRUE:
60
+ return True
61
+ if low in _FALSE:
62
+ return False
63
+ raise ValueError(text)
64
+ if py is int:
65
+ return int(text)
66
+ if py is float:
67
+ return float(text)
68
+ if py is decimal.Decimal:
69
+ return decimal.Decimal(text)
70
+ if py is dt.datetime:
71
+ if _is_date_only(text):
72
+ day = dt.date.fromisoformat(text)
73
+ moment = dt.time.max if end_of_day else dt.time.min
74
+ return dt.datetime.combine(day, moment)
75
+ return dt.datetime.fromisoformat(text.replace("Z", "+00:00"))
76
+ if py is dt.date:
77
+ return dt.date.fromisoformat(text[:10])
78
+ if py is uuid.UUID:
79
+ return uuid.UUID(text)
80
+ except (ValueError, decimal.InvalidOperation) as exc:
81
+ name = getattr(py, "__name__", str(py))
82
+ raise FilterValueError(info.key, raw, name) from exc
83
+ if isinstance(raw, (int, float)) and py is str:
84
+ return text
85
+ return raw
86
+
87
+
88
+ @dataclass
89
+ class ListQuery:
90
+ filters: list[FilterItem]
91
+ sorting: list[SortItem]
92
+ keyword: str | None
93
+ keyword_paths: list[str]
94
+ keyword_case_sensitive: bool
95
+ offset: int | None
96
+ limit: int | None
97
+ relations: list[str]
98
+ where: list[Any]
99
+
100
+
101
+ class SqlAlchemyAdapter:
102
+ """Default ORM adapter."""
103
+
104
+ # ── relations ─────────────────────────────────────────────────────────
105
+
106
+ def resolve_relations(self, model: Any, spec: Any, required: Iterable[str] = ()) -> list[str]:
107
+ all_rels = list(relations_of(model))
108
+ if spec is None or spec == "*":
109
+ base = all_rels
110
+ elif isinstance(spec, str):
111
+ base = [spec]
112
+ elif isinstance(spec, (list, tuple)):
113
+ base = list(spec)
114
+ elif isinstance(spec, Mapping):
115
+ if spec.get("include") and spec["include"] != "*":
116
+ base = list(spec["include"])
117
+ elif spec.get("exclude"):
118
+ base = [r for r in all_rels if r not in spec["exclude"]]
119
+ else:
120
+ base = all_rels
121
+ else:
122
+ base = []
123
+ out: list[str] = []
124
+ for path in [*base, *required]:
125
+ if path not in out:
126
+ out.append(path)
127
+ return out
128
+
129
+ def loader_options(self, model: Any, paths: Sequence[str]) -> list[_AbstractLoad]:
130
+ options: list[_AbstractLoad] = []
131
+ for path in paths:
132
+ current_model = model
133
+ loader: Any = None
134
+ for segment in path.split("."):
135
+ rels = relations_of(current_model)
136
+ if segment not in rels:
137
+ loader = None
138
+ break
139
+ attr = getattr(current_model, segment)
140
+ loader = selectinload(attr) if loader is None else loader.selectinload(attr)
141
+ current_model = rels[segment].target
142
+ if loader is not None:
143
+ options.append(loader)
144
+ return options
145
+
146
+ # ── expressions ───────────────────────────────────────────────────────
147
+
148
+ def filter_clause(self, model: Any, item: FilterItem) -> ColumnElement[bool]:
149
+ infos = {c.key: c for c in columns_of(model)}
150
+ info = infos.get(item.field)
151
+ if info is None:
152
+ raise FilterValueError(item.field, item.value, "a column of this model")
153
+ col = getattr(model, item.field)
154
+ if item.op == "eq":
155
+ return col == cast_value(info, item.value) # type: ignore[no-any-return]
156
+ if item.op == "like":
157
+ target = col if info.python_type is str else cast(col, String)
158
+ return target.icontains(str(item.value), autoescape=True)
159
+ if item.op == "between":
160
+ start, end = item.value
161
+ return col.between(cast_value(info, start), cast_value(info, end, end_of_day=True)) # type: ignore[no-any-return]
162
+ value = cast_value(info, item.value, end_of_day=item.op == "lte")
163
+ if item.op == "gte":
164
+ return col >= value # type: ignore[no-any-return]
165
+ if item.op == "lte":
166
+ return col <= value # type: ignore[no-any-return]
167
+ if item.op == "gt":
168
+ return col > value # type: ignore[no-any-return]
169
+ return col < value # type: ignore[no-any-return]
170
+
171
+ _SEARCHABLE = (str, int, float, decimal.Decimal, uuid.UUID)
172
+
173
+ def keyword_clause(
174
+ self, model: Any, paths: Sequence[str], keyword: str, case_sensitive: bool
175
+ ) -> ColumnElement[bool] | None:
176
+ clauses: list[ColumnElement[bool]] = []
177
+ for path in paths:
178
+ clause = self._keyword_path(model, path.split("."), keyword, case_sensitive)
179
+ if clause is not None:
180
+ clauses.append(clause)
181
+ return or_(*clauses) if clauses else None
182
+
183
+ def _keyword_path(
184
+ self, model: Any, segments: list[str], keyword: str, case_sensitive: bool
185
+ ) -> ColumnElement[bool] | None:
186
+ head, rest = segments[0], segments[1:]
187
+ if not rest:
188
+ infos = {c.key: c for c in columns_of(model)}
189
+ info = infos.get(head)
190
+ if info is None or (info.python_type not in self._SEARCHABLE and not info.enum_values):
191
+ return None
192
+ col = getattr(model, head)
193
+ target = col if info.python_type is str else cast(col, String)
194
+ if case_sensitive:
195
+ return target.contains(keyword, autoescape=True)
196
+ return target.icontains(keyword, autoescape=True)
197
+ rels = relations_of(model)
198
+ if head not in rels:
199
+ return None
200
+ inner = self._keyword_path(rels[head].target, rest, keyword, case_sensitive)
201
+ if inner is None:
202
+ return None
203
+ attr = getattr(model, head)
204
+ return attr.any(inner) if rels[head].uselist else attr.has(inner) # type: ignore[no-any-return]
205
+
206
+ def default_sorting(self, model: Any) -> list[SortItem]:
207
+ keys = {c.key for c in columns_of(model)}
208
+ pk = primary_key_of(model)
209
+ for name in ("created_at", "createdAt"):
210
+ if name in keys:
211
+ return [SortItem(name, "DESC")] + ([SortItem(pk, "DESC")] if pk != name else [])
212
+ return [SortItem(pk, "DESC")]
213
+
214
+ def order_clauses(self, model: Any, sorting: Sequence[SortItem]) -> list[Any]:
215
+ out: list[Any] = []
216
+ keys = {c.key for c in columns_of(model)}
217
+ for item in sorting:
218
+ if item.field not in keys:
219
+ continue
220
+ col = getattr(model, item.field)
221
+ out.append(col.asc() if item.order == "ASC" else col.desc())
222
+ return out
223
+
224
+ # ── reads ─────────────────────────────────────────────────────────────
225
+
226
+ def build_list_statement(self, model: Any, q: ListQuery) -> Select[Any]:
227
+ stmt = select(model)
228
+ conditions: list[Any] = list(q.where)
229
+ conditions.extend(self.filter_clause(model, f) for f in q.filters)
230
+ if q.keyword and q.keyword_paths:
231
+ clause = self.keyword_clause(model, q.keyword_paths, q.keyword, q.keyword_case_sensitive)
232
+ if clause is not None:
233
+ conditions.append(clause)
234
+ if conditions:
235
+ stmt = stmt.where(and_(*conditions))
236
+ order = self.order_clauses(model, q.sorting)
237
+ if order:
238
+ stmt = stmt.order_by(*order)
239
+ return stmt.options(*self.loader_options(model, q.relations))
240
+
241
+ async def run_list(
242
+ self, session: AsyncSession, stmt: Select[Any], offset: int | None, limit: int | None
243
+ ) -> tuple[list[Any], int]:
244
+ count_stmt = select(func.count()).select_from(
245
+ stmt.order_by(None).limit(None).offset(None).subquery()
246
+ )
247
+ total = int((await session.execute(count_stmt)).scalar_one())
248
+ if offset is not None:
249
+ stmt = stmt.offset(offset)
250
+ if limit is not None:
251
+ stmt = stmt.limit(limit)
252
+ rows = (await session.execute(stmt)).scalars().unique().all()
253
+ return list(rows), total
254
+
255
+ def build_one_statement(
256
+ self, model: Any, field: str, value: Any, relations: Sequence[str], where: Sequence[Any] = ()
257
+ ) -> Select[Any]:
258
+ infos = {c.key: c for c in columns_of(model)}
259
+ info = infos.get(field)
260
+ if info is None:
261
+ raise FilterValueError(field, value, "a column of this model")
262
+ stmt = select(model).where(getattr(model, field) == cast_value(info, value), *where)
263
+ return stmt.options(*self.loader_options(model, relations))
264
+
265
+ async def run_one(self, session: AsyncSession, stmt: Select[Any]) -> Any | None:
266
+ return (await session.execute(stmt)).scalars().first()
267
+
268
+ # ── writes ────────────────────────────────────────────────────────────
269
+
270
+ async def create(self, session: AsyncSession, model: Any, data: Mapping[str, Any]) -> Any:
271
+ obj = model(**data)
272
+ session.add(obj)
273
+ await session.flush()
274
+ return obj
275
+
276
+ async def update(self, session: AsyncSession, obj: Any, data: Mapping[str, Any]) -> Any:
277
+ for key, value in data.items():
278
+ setattr(obj, key, value)
279
+ await session.flush()
280
+ return obj
281
+
282
+ async def delete(self, session: AsyncSession, obj: Any) -> None:
283
+ await session.delete(obj)
284
+ await session.flush()
285
+
286
+ async def reload(self, session: AsyncSession, model: Any, obj: Any, relations: Sequence[str]) -> Any:
287
+ pk = primary_key_of(model)
288
+ ident = getattr(obj, pk)
289
+ # Expire so the select below refreshes server defaults and relations. (populate_existing
290
+ # would reset collections when a nested loader points back at the parent.)
291
+ session.expire(obj)
292
+ stmt = select(model).where(getattr(model, pk) == ident)
293
+ stmt = stmt.options(*self.loader_options(model, relations))
294
+ return await self.run_one(session, stmt)
295
+
296
+ async def unique_conflicts(
297
+ self,
298
+ session: AsyncSession,
299
+ model: Any,
300
+ fields: Sequence[str],
301
+ values: Mapping[str, Any],
302
+ condition: str,
303
+ exclude: Any = None,
304
+ ) -> list[str]:
305
+ """Fields whose values already exist. Only fields present in ``values`` are checked."""
306
+ pk = primary_key_of(model)
307
+ pk_col = getattr(model, pk)
308
+ present = [f for f in fields if f in values and values[f] is not None]
309
+ if not present:
310
+ return []
311
+
312
+ async def exists(clause: ColumnElement[bool]) -> bool:
313
+ stmt = select(pk_col).where(clause)
314
+ if exclude is not None:
315
+ stmt = stmt.where(pk_col != exclude)
316
+ return (await session.execute(stmt.limit(1))).first() is not None
317
+
318
+ if condition == "and":
319
+ if len(present) != len(fields):
320
+ return []
321
+ clause = and_(*(getattr(model, f) == values[f] for f in present))
322
+ return list(present) if await exists(clause) else []
323
+ return [f for f in present if await exists(getattr(model, f) == values[f])]
324
+
325
+
326
+ __all__ = ["FilterValueError", "ListQuery", "SqlAlchemyAdapter", "cast_value"]
crudman/cache.py ADDED
@@ -0,0 +1,100 @@
1
+ """Caching for list and details responses.
2
+
3
+ Keys are prefixed with the section name, so a write can invalidate only its own section
4
+ (crudman-nestjs flushes the whole cache).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import time
11
+ from collections import OrderedDict
12
+ from typing import Any, Protocol, runtime_checkable
13
+
14
+
15
+ @runtime_checkable
16
+ class CacheAdapter(Protocol):
17
+ async def get(self, key: str) -> Any | None: ...
18
+ async def set(self, key: str, value: Any, ttl: int | None = None) -> None: ...
19
+ async def invalidate_section(self, section: str) -> None: ...
20
+ async def clear(self) -> None: ...
21
+
22
+
23
+ class MemoryCache:
24
+ """In-process TTL cache with a size limit (oldest entries are evicted first)."""
25
+
26
+ def __init__(self, ttl: int = 60, max_keys: int = 10_000) -> None:
27
+ self.ttl = ttl
28
+ self.max_keys = max_keys
29
+ self._data: OrderedDict[str, tuple[float, Any]] = OrderedDict()
30
+
31
+ async def get(self, key: str) -> Any | None:
32
+ item = self._data.get(key)
33
+ if item is None:
34
+ return None
35
+ expires, value = item
36
+ if expires < time.monotonic():
37
+ self._data.pop(key, None)
38
+ return None
39
+ return value
40
+
41
+ async def set(self, key: str, value: Any, ttl: int | None = None) -> None:
42
+ seconds = self.ttl if ttl is None else ttl
43
+ self._data[key] = (time.monotonic() + seconds, value)
44
+ self._data.move_to_end(key)
45
+ while len(self._data) > self.max_keys:
46
+ self._data.popitem(last=False)
47
+
48
+ async def invalidate_section(self, section: str) -> None:
49
+ prefix = f"{section}:"
50
+ for key in [k for k in self._data if k.startswith(prefix)]:
51
+ self._data.pop(key, None)
52
+
53
+ async def clear(self) -> None:
54
+ self._data.clear()
55
+
56
+ def __len__(self) -> int:
57
+ return len(self._data)
58
+
59
+
60
+ class RedisCache:
61
+ """Redis-backed cache (``pip install "crudman-fastapi[redis]"``). Values are stored as JSON."""
62
+
63
+ def __init__(self, url: str = "redis://localhost:6379/0", ttl: int = 60, namespace: str = "crudman") -> None:
64
+ try:
65
+ from redis import asyncio as redis_asyncio
66
+ except ImportError as exc: # pragma: no cover - optional dependency
67
+ raise ImportError('RedisCache needs the redis extra: pip install "crudman-fastapi[redis]"') from exc
68
+ self.ttl = ttl
69
+ self.namespace = namespace
70
+ self._client = redis_asyncio.from_url(url)
71
+
72
+ def _key(self, key: str) -> str:
73
+ return f"{self.namespace}:{key}"
74
+
75
+ async def get(self, key: str) -> Any | None: # pragma: no cover - needs a Redis server
76
+ raw = await self._client.get(self._key(key))
77
+ return None if raw is None else json.loads(raw)
78
+
79
+ async def set(self, key: str, value: Any, ttl: int | None = None) -> None: # pragma: no cover
80
+ await self._client.set(self._key(key), json.dumps(value, default=str), ex=ttl or self.ttl)
81
+
82
+ async def invalidate_section(self, section: str) -> None: # pragma: no cover
83
+ async for key in self._client.scan_iter(match=self._key(f"{section}:*")):
84
+ await self._client.delete(key)
85
+
86
+ async def clear(self) -> None: # pragma: no cover
87
+ async for key in self._client.scan_iter(match=self._key("*")):
88
+ await self._client.delete(key)
89
+
90
+
91
+ def default_cache_key(section: str, action: str, params: Any, query: Any, relations: Any, identity: Any) -> str:
92
+ payload = json.dumps(
93
+ {"p": params, "q": sorted((str(k), str(v)) for k, v in dict(query).items()), "r": relations, "i": identity},
94
+ sort_keys=True,
95
+ default=str,
96
+ )
97
+ return f"{section}:{action}:{payload}"
98
+
99
+
100
+ __all__ = ["CacheAdapter", "MemoryCache", "RedisCache", "default_cache_key"]