FastSpine 1.0.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.
- fastspine/__init__.py +48 -0
- fastspine/abstract/owner_base.py +16 -0
- fastspine/alembic/__init__.py +4 -0
- fastspine/alembic/alembic.py +95 -0
- fastspine/alembic/config.py +40 -0
- fastspine/boostrap.py +78 -0
- fastspine/cache/cache_decorater.py +264 -0
- fastspine/cache/cache_encoder.py +87 -0
- fastspine/cache/cache_exception.py +4 -0
- fastspine/cache/cache_model.py +32 -0
- fastspine/cache/cache_service.py +144 -0
- fastspine/cache/key_builder.py +134 -0
- fastspine/cache/redis_cache.py +158 -0
- fastspine/celery/base_task.py +106 -0
- fastspine/celery/engine.py +52 -0
- fastspine/cli/scoped_typer.py +47 -0
- fastspine/ctx/ctx_pool.py +73 -0
- fastspine/database/engine.py +131 -0
- fastspine/decorators/contextualize_decorator.py +54 -0
- fastspine/decorators/retry_decorator.py +66 -0
- fastspine/decorators/upsert_decorator.py +107 -0
- fastspine/dependencies/database.py +193 -0
- fastspine/dependencies/profiler.py +37 -0
- fastspine/dependencies/repository_manager.py +202 -0
- fastspine/dependencies/services.py +140 -0
- fastspine/exception/access_exception.py +13 -0
- fastspine/exception/action_not_allowed_exception.py +13 -0
- fastspine/exception/base_app_exception.py +28 -0
- fastspine/exception/exception_handler.py +9 -0
- fastspine/exception/not_found_exception.py +13 -0
- fastspine/exception/security_exception.py +13 -0
- fastspine/exception/soft_delete_exception.py +13 -0
- fastspine/lib/__init__.py +4 -0
- fastspine/lib/contextualize.py +352 -0
- fastspine/lib/profiler.py +284 -0
- fastspine/mailer/mailer_service.py +44 -0
- fastspine/middleware/request_middleware.py +67 -0
- fastspine/middleware/session_middleware.py +38 -0
- fastspine/mixins/__init__.py +4 -0
- fastspine/mixins/representable.py +12 -0
- fastspine/mixins/soft_delete.py +41 -0
- fastspine/mixins/timestamps.py +35 -0
- fastspine/models/base.py +18 -0
- fastspine/redis/client.py +23 -0
- fastspine/repositories/abstract_repository.py +267 -0
- fastspine/repositories/base_repository.py +422 -0
- fastspine/repositories/external_base_repository.py +12 -0
- fastspine/repositories/repository_manager.py +101 -0
- fastspine/schemas/pagination_model.py +26 -0
- fastspine/services/api_service.py +292 -0
- fastspine/services/base_service.py +18 -0
- fastspine/settings/__init__.py +74 -0
- fastspine/settings/app_settings.py +5 -0
- fastspine/settings/cache_settings.py +32 -0
- fastspine/settings/celery_settings.py +10 -0
- fastspine/settings/mailer_settings.py +12 -0
- fastspine/settings/profiler_settings.py +10 -0
- fastspine/types/__init__.py +3 -0
- fastspine/types/types.py +6 -0
- fastspine/util/class_util.py +110 -0
- fastspine/util/conversion.py +37 -0
- fastspine/util/dataframe_util.py +30 -0
- fastspine/util/dates.py +34 -0
- fastspine/util/debug_util.py +29 -0
- fastspine/util/emails.py +14 -0
- fastspine/util/files.py +29 -0
- fastspine/util/math.py +3 -0
- fastspine-1.0.0.dist-info/METADATA +372 -0
- fastspine-1.0.0.dist-info/RECORD +71 -0
- fastspine-1.0.0.dist-info/WHEEL +4 -0
- fastspine-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
from contextvars import ContextVar
|
|
3
|
+
|
|
4
|
+
from fastapi import Request
|
|
5
|
+
from starlette.middleware.base import BaseHTTPMiddleware
|
|
6
|
+
from starlette.requests import Request as StarletteRequest
|
|
7
|
+
from starlette.types import ASGIApp, Receive, Scope, Send
|
|
8
|
+
|
|
9
|
+
from fastspine.lib.contextualize import contextualize
|
|
10
|
+
from fastspine.lib.profiler import Profiler
|
|
11
|
+
|
|
12
|
+
from ..ctx.ctx_pool import ctxpool
|
|
13
|
+
|
|
14
|
+
request_context: ContextVar = ctxpool.new("request_context", default=None)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class RequestMiddleware(BaseHTTPMiddleware):
|
|
18
|
+
"""Middleware for managing the database session per request."""
|
|
19
|
+
|
|
20
|
+
async def dispatch(self, request: Request, call_next):
|
|
21
|
+
"""Process the request and set up the context for logging and profiling."""
|
|
22
|
+
correlation_id = str(uuid.uuid4())
|
|
23
|
+
|
|
24
|
+
request.state.profiler = Profiler()
|
|
25
|
+
ctxpool.set("request_context", request)
|
|
26
|
+
logger_context = {
|
|
27
|
+
"correlation_id": correlation_id,
|
|
28
|
+
"endpoint_path": request.url.path,
|
|
29
|
+
"method": request.method,
|
|
30
|
+
}
|
|
31
|
+
if hasattr(request.state, "user"):
|
|
32
|
+
logger_context["user"] = request.state.user.email
|
|
33
|
+
# Set logger in context and automatically clean up after request
|
|
34
|
+
with contextualize(**logger_context):
|
|
35
|
+
return await call_next(request)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class RequestMiddlewareASGI:
|
|
39
|
+
"""Pure ASGI middleware for managing request context and profiling."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, app: ASGIApp) -> None:
|
|
42
|
+
self.app = app
|
|
43
|
+
|
|
44
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
45
|
+
"""Handle ASGI requests with request context management and profiling."""
|
|
46
|
+
if scope["type"] != "http":
|
|
47
|
+
await self.app(scope, receive, send)
|
|
48
|
+
return
|
|
49
|
+
|
|
50
|
+
correlation_id = str(uuid.uuid4())
|
|
51
|
+
|
|
52
|
+
# Create request object to access state
|
|
53
|
+
request = StarletteRequest(scope, receive)
|
|
54
|
+
request.state.profiler = Profiler()
|
|
55
|
+
ctxpool.set("request_context", request)
|
|
56
|
+
|
|
57
|
+
logger_context = {
|
|
58
|
+
"correlation_id": correlation_id,
|
|
59
|
+
"endpoint_path": request.url.path,
|
|
60
|
+
"method": request.method,
|
|
61
|
+
}
|
|
62
|
+
if hasattr(request.state, "user"):
|
|
63
|
+
logger_context["user"] = request.state.user.email
|
|
64
|
+
|
|
65
|
+
# Set logger in context and automatically clean up after request
|
|
66
|
+
with contextualize(**logger_context):
|
|
67
|
+
await self.app(scope, receive, send)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from fastapi import Request
|
|
2
|
+
from starlette.middleware.base import BaseHTTPMiddleware
|
|
3
|
+
from starlette.types import ASGIApp, Receive, Scope, Send
|
|
4
|
+
|
|
5
|
+
from ..ctx.ctx_pool import ctxpool
|
|
6
|
+
from ..dependencies.repository_manager import _close_sessions
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class DBSessionMiddleware(BaseHTTPMiddleware):
|
|
10
|
+
"""Middleware for managing the database session per request."""
|
|
11
|
+
|
|
12
|
+
async def dispatch(self, request: Request, call_next):
|
|
13
|
+
"""Dispatch method for the middleware."""
|
|
14
|
+
try:
|
|
15
|
+
return await call_next(request) # Process request
|
|
16
|
+
finally:
|
|
17
|
+
await _close_sessions()
|
|
18
|
+
ctxpool.clear()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class DBSessionMiddlewareASGI:
|
|
22
|
+
"""Pure ASGI middleware for managing database sessions per request."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, app: ASGIApp) -> None:
|
|
25
|
+
"""Initialize the ASGI middleware with the application."""
|
|
26
|
+
self.app = app
|
|
27
|
+
|
|
28
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
29
|
+
"""Handle ASGI requests with database session management."""
|
|
30
|
+
if scope["type"] != "http":
|
|
31
|
+
await self.app(scope, receive, send)
|
|
32
|
+
return
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
await self.app(scope, receive, send)
|
|
36
|
+
finally:
|
|
37
|
+
await _close_sessions()
|
|
38
|
+
ctxpool.clear()
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
class RepresentableMixin:
|
|
2
|
+
"""Mixin class to provide a __repr__ method for classes."""
|
|
3
|
+
|
|
4
|
+
def __repr__(self):
|
|
5
|
+
"""Return a string representation of the instance."""
|
|
6
|
+
cls_name = self.__class__.__name__
|
|
7
|
+
attrs = ", ".join(f"{k}={v!r}" for k, v in self.__dict__.items())
|
|
8
|
+
return f"{cls_name}({attrs})"
|
|
9
|
+
|
|
10
|
+
def __str__(self):
|
|
11
|
+
"""Return a string representation of the instance."""
|
|
12
|
+
return self.__repr__()
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from sqlalchemy import Column, DateTime, event
|
|
2
|
+
from sqlalchemy.orm import declared_attr
|
|
3
|
+
|
|
4
|
+
from ..exception.soft_delete_exception import SoftDeleteError
|
|
5
|
+
from ..util.dates import now
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SoftDeleteMixin:
|
|
9
|
+
"""Mixin to add a deleted_at column to a SQLAlchemy model for soft deletion."""
|
|
10
|
+
|
|
11
|
+
@declared_attr
|
|
12
|
+
def deleted_at(cls):
|
|
13
|
+
"""Creates a deleted_at column with timezone support, defaulting to None."""
|
|
14
|
+
return Column(
|
|
15
|
+
DateTime(timezone=True),
|
|
16
|
+
default=None,
|
|
17
|
+
nullable=True,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
@classmethod
|
|
21
|
+
def __declare_last__(cls):
|
|
22
|
+
"""Intercept delete operations and convert them into soft deletes."""
|
|
23
|
+
|
|
24
|
+
@event.listens_for(cls, "before_delete", propagate=True)
|
|
25
|
+
def prevent_delete(mapper, connection, target):
|
|
26
|
+
raise RuntimeError(
|
|
27
|
+
f"Direct deletion of {target.__class__.__name__} is not allowed. Use soft_delete() method instead."
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def is_deleted(self):
|
|
32
|
+
"""Check if the instance is soft deleted."""
|
|
33
|
+
return self.deleted_at is not None
|
|
34
|
+
|
|
35
|
+
def set_deleted(self) -> "SoftDeleteMixin":
|
|
36
|
+
"""Set the instance as soft deleted."""
|
|
37
|
+
if self.is_deleted:
|
|
38
|
+
raise SoftDeleteError(f"{self.__class__.__name__} is already soft deleted.")
|
|
39
|
+
self.deleted_at = now()
|
|
40
|
+
|
|
41
|
+
return self
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
|
|
3
|
+
from sqlalchemy import Column, DateTime
|
|
4
|
+
from sqlalchemy.orm import declared_attr
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class CreatedAtMixin:
|
|
8
|
+
"""Mixin to add a created_at column to a SQLAlchemy model."""
|
|
9
|
+
|
|
10
|
+
@declared_attr
|
|
11
|
+
def created_at(cls):
|
|
12
|
+
"""Creates a created_at column with the current UTC time as default."""
|
|
13
|
+
return Column(
|
|
14
|
+
DateTime(timezone=True),
|
|
15
|
+
default=lambda: datetime.datetime.now(datetime.timezone.utc),
|
|
16
|
+
nullable=False,
|
|
17
|
+
onupdate=None,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class UpdatedAtMixin:
|
|
22
|
+
"""Mixin to add an updated_at column to a SQLAlchemy model."""
|
|
23
|
+
|
|
24
|
+
@declared_attr
|
|
25
|
+
def updated_at(cls):
|
|
26
|
+
"""Creates an updated_at column with the current UTC time as default."""
|
|
27
|
+
return Column(
|
|
28
|
+
DateTime, default=None, onupdate=lambda: datetime.datetime.now(datetime.timezone.utc), nullable=True
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class TimestampMixin(CreatedAtMixin, UpdatedAtMixin):
|
|
33
|
+
"""Mixin to add created_at and updated_at columns to a SQLAlchemy model."""
|
|
34
|
+
|
|
35
|
+
pass
|
fastspine/models/base.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from abc import ABCMeta
|
|
2
|
+
|
|
3
|
+
from sqlalchemy import Integer
|
|
4
|
+
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class CombinedMeta(type(DeclarativeBase), ABCMeta): # type: ignore[misc]
|
|
8
|
+
"""Metaclass that combines DeclarativeBase and ABCMeta."""
|
|
9
|
+
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Base(DeclarativeBase, metaclass=CombinedMeta):
|
|
14
|
+
"""Base class for SQLAlchemy models."""
|
|
15
|
+
|
|
16
|
+
__abstract__ = True
|
|
17
|
+
|
|
18
|
+
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True, autoincrement=True)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from functools import lru_cache
|
|
2
|
+
|
|
3
|
+
from redis import Redis as SyncRedis
|
|
4
|
+
from redis.asyncio import Redis
|
|
5
|
+
|
|
6
|
+
from ..settings import get_core_settings
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@lru_cache
|
|
10
|
+
def get_redis_client() -> Redis | None:
|
|
11
|
+
"""Get the Redis client instance."""
|
|
12
|
+
if get_core_settings().CACHE_ENABLED:
|
|
13
|
+
return Redis.from_url(get_core_settings().get_redis_url())
|
|
14
|
+
|
|
15
|
+
return None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@lru_cache
|
|
19
|
+
def get_sync_redis_client() -> SyncRedis | None:
|
|
20
|
+
"""Get the synchronous Redis client instance."""
|
|
21
|
+
if get_core_settings().CACHE_ENABLED:
|
|
22
|
+
return SyncRedis.from_url(get_core_settings().get_redis_url())
|
|
23
|
+
return None
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from abc import ABC
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
import polars as pl
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
from sqlalchemy import text
|
|
9
|
+
from sqlalchemy.sql.elements import TextClause
|
|
10
|
+
from sqlalchemy.sql.expression import Selectable
|
|
11
|
+
|
|
12
|
+
from ..lib.profiler import Profiler
|
|
13
|
+
from ..schemas.pagination_model import PaginatedData, PaginatedList, PaginationParams
|
|
14
|
+
from ..types import DBSessions
|
|
15
|
+
from ..util.dataframe_util import map_data_to_model
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AbstractRepository(ABC): # noqa: B024
|
|
19
|
+
"""Base repository class for external database operations.
|
|
20
|
+
|
|
21
|
+
This class provides a common interface for all repository classes for externale db.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, db: DBSessions, profiler: Profiler):
|
|
25
|
+
self.db = db
|
|
26
|
+
self.profiler = profiler
|
|
27
|
+
|
|
28
|
+
def _get_limit_offset(self, pagination: PaginationParams) -> str:
|
|
29
|
+
"""Returns the LIMIT and OFFSET clause for a SQL query."""
|
|
30
|
+
return f" LIMIT {pagination.limit} OFFSET {pagination.offset}"
|
|
31
|
+
|
|
32
|
+
def _only_select_validation(self, query: str | TextClause | Selectable) -> None:
|
|
33
|
+
"""Validates that the query is a SELECT query."""
|
|
34
|
+
if isinstance(query, str):
|
|
35
|
+
cleaned_query = query.strip().lower()
|
|
36
|
+
contains_with = re.match(r"^\s*with\b", cleaned_query)
|
|
37
|
+
|
|
38
|
+
starts_with_select = re.match(r"^\(*\s*select\b", cleaned_query)
|
|
39
|
+
contains_union = " union " in cleaned_query
|
|
40
|
+
if not (starts_with_select or contains_union or contains_with):
|
|
41
|
+
raise ValueError("Only SELECT or UNION or WITH queries are allowed for fetching data.")
|
|
42
|
+
|
|
43
|
+
def sync_fetch_paginated(
|
|
44
|
+
self,
|
|
45
|
+
query: str,
|
|
46
|
+
pagination: PaginationParams,
|
|
47
|
+
params: dict[str, Any] | None = None,
|
|
48
|
+
) -> PaginatedList:
|
|
49
|
+
"""Executes a native SQL query and returns the result as PaginatedList."""
|
|
50
|
+
self._only_select_validation(query)
|
|
51
|
+
if params is None:
|
|
52
|
+
params = {}
|
|
53
|
+
|
|
54
|
+
count_query = f"SELECT COUNT(*) FROM ({query}) AS subquery"
|
|
55
|
+
count_result = self.db.execute(text(count_query), params)
|
|
56
|
+
total_count = count_result.scalar() # Get the total count of records
|
|
57
|
+
query += self._get_limit_offset(pagination)
|
|
58
|
+
params["limit"] = pagination.limit
|
|
59
|
+
params["offset"] = pagination.offset
|
|
60
|
+
|
|
61
|
+
results = self.db.execute(text(query), params).mappings().all()
|
|
62
|
+
results = [dict(row) for row in results]
|
|
63
|
+
|
|
64
|
+
return PaginatedList(count=total_count, rows=results)
|
|
65
|
+
|
|
66
|
+
async def fetch_paginated(
|
|
67
|
+
self,
|
|
68
|
+
query: str,
|
|
69
|
+
pagination: PaginationParams,
|
|
70
|
+
params: dict[str, Any] | None = None,
|
|
71
|
+
) -> PaginatedList:
|
|
72
|
+
"""Executes a native SQL query and returns the result as PaginatedList (async version)."""
|
|
73
|
+
self._only_select_validation(query)
|
|
74
|
+
if params is None:
|
|
75
|
+
params = {}
|
|
76
|
+
|
|
77
|
+
count_query = f"SELECT COUNT(*) FROM ({query}) AS subquery"
|
|
78
|
+
count_result = await self.db.execute(text(count_query), params)
|
|
79
|
+
total_count = count_result.scalar() # Get the total count of records
|
|
80
|
+
query += self._get_limit_offset(pagination)
|
|
81
|
+
params["limit"] = pagination.limit
|
|
82
|
+
params["offset"] = pagination.offset
|
|
83
|
+
|
|
84
|
+
results = await self.db.execute(text(query), params)
|
|
85
|
+
results = results.mappings().all()
|
|
86
|
+
results = [dict(row) for row in results]
|
|
87
|
+
|
|
88
|
+
return PaginatedList(count=total_count, rows=results)
|
|
89
|
+
|
|
90
|
+
def sync_fetch_dataframe(
|
|
91
|
+
self,
|
|
92
|
+
query: str,
|
|
93
|
+
params: dict[str, Any] | None = None,
|
|
94
|
+
pagination: PaginationParams | None = None,
|
|
95
|
+
model: type[BaseModel] | None = None,
|
|
96
|
+
response_model: type[PaginatedData] | None = None,
|
|
97
|
+
) -> PaginatedData:
|
|
98
|
+
"""Executes a native SQL query and returns the result as PaginatedList."""
|
|
99
|
+
self._only_select_validation(query)
|
|
100
|
+
if params is None:
|
|
101
|
+
params = {}
|
|
102
|
+
if pagination is None:
|
|
103
|
+
raise ValueError("Pagination parameters must be provided.")
|
|
104
|
+
if model is None or response_model is None:
|
|
105
|
+
raise ValueError("Model and response_model must be provided to map the data to the model.")
|
|
106
|
+
|
|
107
|
+
count_query = f"SELECT COUNT(*) FROM ({query}) AS subquery"
|
|
108
|
+
count_result = self.db.execute(text(count_query), params)
|
|
109
|
+
total_count = count_result.scalar() # Get the total count of records
|
|
110
|
+
query += self._get_limit_offset(pagination)
|
|
111
|
+
params["limit"] = pagination.limit
|
|
112
|
+
params["offset"] = pagination.offset
|
|
113
|
+
|
|
114
|
+
result = self.db.execute(text(query), params)
|
|
115
|
+
data = pd.DataFrame(result.fetchall(), columns=result.keys())
|
|
116
|
+
data = map_data_to_model(data, model)
|
|
117
|
+
|
|
118
|
+
return response_model(data=data, count=total_count)
|
|
119
|
+
|
|
120
|
+
async def fetch_dataframe(
|
|
121
|
+
self,
|
|
122
|
+
query: str,
|
|
123
|
+
params: dict[str, Any] | None = None,
|
|
124
|
+
pagination: PaginationParams | None = None,
|
|
125
|
+
model: type[BaseModel] | None = None,
|
|
126
|
+
response_model: type[PaginatedData] | None = None,
|
|
127
|
+
) -> PaginatedData:
|
|
128
|
+
"""Executes a native SQL query and returns the result as PaginatedList (async version)."""
|
|
129
|
+
self._only_select_validation(query)
|
|
130
|
+
if params is None:
|
|
131
|
+
params = {}
|
|
132
|
+
if pagination is None:
|
|
133
|
+
raise ValueError("Pagination parameters must be provided.")
|
|
134
|
+
if model is None or response_model is None:
|
|
135
|
+
raise ValueError("Model and response_model must be provided to map the data to the model.")
|
|
136
|
+
|
|
137
|
+
count_query = f"SELECT COUNT(*) FROM ({query}) AS subquery"
|
|
138
|
+
count_result = await self.db.execute(text(count_query), params)
|
|
139
|
+
total_count = count_result.scalar() # Get the total count of records
|
|
140
|
+
query += self._get_limit_offset(pagination)
|
|
141
|
+
params["limit"] = pagination.limit
|
|
142
|
+
params["offset"] = pagination.offset
|
|
143
|
+
|
|
144
|
+
result = await self.db.execute(text(query), params)
|
|
145
|
+
data = pd.DataFrame(result.fetchall(), columns=result.keys())
|
|
146
|
+
data = map_data_to_model(data, model)
|
|
147
|
+
|
|
148
|
+
return response_model(data=data, count=total_count)
|
|
149
|
+
|
|
150
|
+
def sync_fetch_list(self, query: str, params: dict[str, Any] | None = None) -> list[dict[str, Any]]:
|
|
151
|
+
"""Executes a native SQL query and returns the result as a list of models or dicts."""
|
|
152
|
+
self._only_select_validation(query)
|
|
153
|
+
if params is None:
|
|
154
|
+
params = {}
|
|
155
|
+
results = self.db.execute(text(query), params).mappings().all()
|
|
156
|
+
return [dict(row) for row in results]
|
|
157
|
+
|
|
158
|
+
async def fetch_list(self, query: str, params: dict[str, Any] | None = None) -> list[dict[str, Any]]:
|
|
159
|
+
"""Executes a native SQL query and returns the result as a list of models or dicts."""
|
|
160
|
+
self._only_select_validation(query)
|
|
161
|
+
if params is None:
|
|
162
|
+
params = {}
|
|
163
|
+
result = await self.db.execute(text(query), params)
|
|
164
|
+
results = result.mappings().all()
|
|
165
|
+
return [dict(row) for row in results]
|
|
166
|
+
|
|
167
|
+
def sync_fetchone(
|
|
168
|
+
self,
|
|
169
|
+
query: str,
|
|
170
|
+
params: dict[str, Any] | None = None,
|
|
171
|
+
model: type[BaseModel] | None = None,
|
|
172
|
+
dataframe: bool = False,
|
|
173
|
+
) -> Any:
|
|
174
|
+
"""Executes a native SQL query and returns the first row of the result."""
|
|
175
|
+
self._only_select_validation(query)
|
|
176
|
+
query = text(query)
|
|
177
|
+
if params is None:
|
|
178
|
+
params = {}
|
|
179
|
+
res = self.db.execute(query, params).fetchone()
|
|
180
|
+
if dataframe:
|
|
181
|
+
return pd.DataFrame([dict(res)], columns=res.keys())
|
|
182
|
+
|
|
183
|
+
if model is not None and res is not None:
|
|
184
|
+
return model(**dict(res))
|
|
185
|
+
|
|
186
|
+
return res
|
|
187
|
+
|
|
188
|
+
async def fetchone(
|
|
189
|
+
self,
|
|
190
|
+
query: str,
|
|
191
|
+
params: dict[str, Any] | None = None,
|
|
192
|
+
model: type[BaseModel] | None = None,
|
|
193
|
+
) -> Any:
|
|
194
|
+
"""Executes a native SQL query and returns the first row of the result."""
|
|
195
|
+
self._only_select_validation(query)
|
|
196
|
+
query_stmt = text(query)
|
|
197
|
+
if params is None:
|
|
198
|
+
params = {}
|
|
199
|
+
|
|
200
|
+
result = await self.db.execute(query_stmt, params)
|
|
201
|
+
res = result.mappings().fetchone()
|
|
202
|
+
|
|
203
|
+
if model is not None and res is not None:
|
|
204
|
+
return model(**dict(res))
|
|
205
|
+
|
|
206
|
+
return res
|
|
207
|
+
|
|
208
|
+
def sync_execute_df_query(
|
|
209
|
+
self,
|
|
210
|
+
query: str,
|
|
211
|
+
params: dict[str, Any] | None = None,
|
|
212
|
+
return_type: type[pd.DataFrame | pl.DataFrame] = pd,
|
|
213
|
+
) -> pd.DataFrame | pl.DataFrame:
|
|
214
|
+
"""Executes a native SQL query and returns the result as a pandas or polars DataFrame."""
|
|
215
|
+
self._only_select_validation(query)
|
|
216
|
+
if params is None:
|
|
217
|
+
params = {}
|
|
218
|
+
result = self.db.execute(text(query), params)
|
|
219
|
+
data = result.fetchall()
|
|
220
|
+
columns = result.keys()
|
|
221
|
+
|
|
222
|
+
if return_type is pl:
|
|
223
|
+
return pl.DataFrame([dict(row._mapping) for row in data])
|
|
224
|
+
|
|
225
|
+
return pd.DataFrame(data, columns=columns)
|
|
226
|
+
|
|
227
|
+
async def execute_df_query(
|
|
228
|
+
self,
|
|
229
|
+
query: str,
|
|
230
|
+
params: dict[str, Any] | None = None,
|
|
231
|
+
return_type: type[pd.DataFrame | pl.DataFrame] = pd,
|
|
232
|
+
) -> pd.DataFrame | pl.DataFrame:
|
|
233
|
+
"""Executes a native SQL query and returns the result as a pandas or polars DataFrame (async version)."""
|
|
234
|
+
self._only_select_validation(query)
|
|
235
|
+
if params is None:
|
|
236
|
+
params = {}
|
|
237
|
+
result = await self.db.execute(text(query), params)
|
|
238
|
+
data = result.fetchall()
|
|
239
|
+
columns = result.keys()
|
|
240
|
+
|
|
241
|
+
if return_type is pl:
|
|
242
|
+
return pl.DataFrame([dict(row._mapping) for row in data])
|
|
243
|
+
|
|
244
|
+
return pd.DataFrame(data, columns=columns)
|
|
245
|
+
|
|
246
|
+
def _placeholders_and_params(self, values: list, prefix: str, params: dict) -> tuple[list[str], dict]:
|
|
247
|
+
placeholders = []
|
|
248
|
+
for idx, value in enumerate(values):
|
|
249
|
+
key = f"{prefix}_{idx}"
|
|
250
|
+
placeholders.append(f":{key}")
|
|
251
|
+
params[key] = value
|
|
252
|
+
return placeholders, params
|
|
253
|
+
|
|
254
|
+
def _create_filter_condition(self, filters: list[str], global_filters: list[str]) -> str:
|
|
255
|
+
"""Creates a filter condition string based on the provided filters and global filters."""
|
|
256
|
+
clauses = []
|
|
257
|
+
where_clause = ""
|
|
258
|
+
if filters:
|
|
259
|
+
clauses.append("(" + " AND ".join(filters) + ")")
|
|
260
|
+
|
|
261
|
+
if global_filters:
|
|
262
|
+
clauses.append("(" + " AND ".join(global_filters) + ")")
|
|
263
|
+
|
|
264
|
+
if clauses:
|
|
265
|
+
where_clause = " WHERE " + " OR ".join(clauses)
|
|
266
|
+
|
|
267
|
+
return where_clause
|