Skip to content

Commit b18f150

Browse files
committed
move compile_sql_or_scalar meth to decorators.py
1 parent adfb049 commit b18f150

File tree

2 files changed

+43
-17
lines changed

2 files changed

+43
-17
lines changed

app/models/stuff.py

Lines changed: 1 addition & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,13 @@
11
import uuid
22

3-
from sqlalchemy.dialects import postgresql
43
from sqlalchemy import String, select, ForeignKey
54
from sqlalchemy.dialects.postgresql import UUID
65
from sqlalchemy.ext.asyncio import AsyncSession
76
from sqlalchemy.orm import mapped_column, Mapped, relationship, joinedload
87

98
from app.models.base import Base
109
from app.models.nonsense import Nonsense
11-
12-
from functools import wraps
13-
14-
15-
def compile_sql_or_scalar(func):
16-
@wraps(func)
17-
async def wrapper(cls, db_session, name, compile_sql=False, *args, **kwargs):
18-
stmt = await func(cls, db_session, name, *args, **kwargs)
19-
if compile_sql:
20-
return stmt.compile(
21-
dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True}
22-
)
23-
result = await db_session.execute(stmt)
24-
return result.scalars().first()
25-
26-
return wrapper
10+
from app.utils.decorators import compile_sql_or_scalar
2711

2812

2913
class Stuff(Base):

app/utils/decorators.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from sqlalchemy.dialects import postgresql
2+
from sqlalchemy.ext.asyncio import AsyncSession
3+
4+
from functools import wraps
5+
6+
7+
def compile_sql_or_scalar(func):
8+
"""
9+
A decorator that compiles an SQL statement or executes it and returns the first scalar result.
10+
11+
Args:
12+
func (Callable): The function to be decorated. It should return an SQLAlchemy statement.
13+
14+
Returns:
15+
Callable: A wrapper function that either compiles the SQL statement or executes it and returns the first scalar result.
16+
"""
17+
18+
@wraps(func)
19+
async def wrapper(cls, db_session, name, compile_sql=False, *args, **kwargs):
20+
"""
21+
Wrapper function that either compiles the SQL statement or executes it.
22+
23+
Args:
24+
cls (Type): The class on which the method is called.
25+
db_session (AsyncSession): The SQLAlchemy async session.
26+
name (str): The name to be used in the SQL statement.
27+
compile_sql (bool, optional): If True, compiles the SQL statement. Defaults to False.
28+
*args: Additional positional arguments.
29+
**kwargs: Additional keyword arguments.
30+
31+
Returns:
32+
Compiled SQL statement or the first scalar result of the executed statement.
33+
"""
34+
stmt = await func(cls, db_session, name, *args, **kwargs)
35+
if compile_sql:
36+
return stmt.compile(
37+
dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True}
38+
)
39+
result = await db_session.execute(stmt)
40+
return result.scalars().first()
41+
42+
return wrapper

0 commit comments

Comments
 (0)