Skip to content

Commit 7f0e640

Browse files
committed
add DBOperator
1 parent 66a61c9 commit 7f0e640

File tree

7 files changed

+39
-23
lines changed

7 files changed

+39
-23
lines changed

fastapi-postgres/app/service/auth.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from common.config import conf
88
from common.db_model.models import TeacherModel
9+
from common.enums import DBOperator
910
from common.serializers import DBQuery, FilterQuery, Token
1011

1112
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
@@ -23,7 +24,7 @@ def _inject_user_filter(
2324
user_auth: TeacherModel.table = Depends(Auth.jwt_required),
2425
) -> FilterQuery:
2526
filter_query.query.append(
26-
DBQuery(key=field_name, opt="eq", value=int(user_auth.id))
27+
DBQuery(key=field_name, opt=DBOperator.eq, value=int(user_auth.id))
2728
)
2829
return filter_query
2930

@@ -41,8 +42,8 @@ def error_authenticate(cls) -> HTTPException:
4142
async def authenticate_user(cls, _id: int, phone: int) -> Token:
4243
filter_query = FilterQuery(
4344
query=[
44-
DBQuery(key="id", opt="eq", value=_id),
45-
DBQuery(key="phone", opt="eq", value=phone),
45+
DBQuery(key="id", opt=DBOperator.eq, value=_id),
46+
DBQuery(key="phone", opt=DBOperator.eq, value=phone),
4647
]
4748
)
4849

fastapi-postgres/app/service/create_data.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class FactoryModel:
1616
def teacher(cls) -> dict:
1717
return {
1818
"id": randint(10, 900),
19-
"phone": float(randint(10_000_000, 9_999_999_999))
19+
"phone": float(randint(10_000_000, 9_999_999_999)),
2020
}
2121

2222
@classmethod

fastapi-postgres/common/config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
23
from pydantic_settings import BaseSettings
34

45
# load .env locally if present (won't affect server)

fastapi-postgres/common/db_model/__init__.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,24 +8,24 @@
88
from sqlmodel.ext.asyncio.session import AsyncSession
99

1010
from common.config import conf
11-
from common.enums import ModelType
11+
from common.enums import DBOperator, ModelType
1212
from common.serializers import BaseTable, DBQuery, FilterQuery, RowLike
1313
from common.utils.errors import ErrorService
1414
from common.utils.log import logger
1515
from common.utils.parse_obj import set_elements_by_dict
1616

1717
opts = {
18-
"eq": "__eq__",
19-
"ne": "__ne__",
20-
"lt": "__lt__",
21-
"le": "__le__",
22-
"gt": "__gt__",
23-
"ge": "__ge__",
24-
"like": "like",
25-
"ilike": "ilike", # PostgreSQL only
26-
"in": "in_",
27-
"not_in": "notin_",
28-
"is_null": "is_",
18+
DBOperator.eq: "__eq__",
19+
DBOperator.ne: "__ne__",
20+
DBOperator.lt: "__lt__",
21+
DBOperator.le: "__le__",
22+
DBOperator.gt: "__gt__",
23+
DBOperator.ge: "__ge__",
24+
DBOperator.like: "like",
25+
DBOperator.ilike: "ilike", # PostgreSQL only
26+
DBOperator.in_: "in_",
27+
DBOperator.not_in: "notin_",
28+
DBOperator.is_null: "is_",
2929
}
3030

3131

@@ -195,7 +195,7 @@ async def delete_rows(
195195
@classmethod
196196
async def get_by_id(cls, _id: str | int, **kwargs):
197197
filter_query = FilterQuery(
198-
query=[DBQuery(key=cls.table.id.key, opt="eq", value=int(_id))],
198+
query=[DBQuery(key=cls.table.id.key, opt=DBOperator.eq, value=int(_id))],
199199
relation_model=kwargs.get("relation_model", False),
200200
)
201201
return await cls.fetch_rows(filter_query=filter_query, limit=1)

fastapi-postgres/common/enums/__init__.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,20 @@ class ModelType(EnumBase):
1717
assignment = "assignment"
1818

1919

20+
class DBOperator(EnumBase):
21+
eq = "eq"
22+
ne = "ne"
23+
lt = "lt"
24+
le = "le"
25+
gt = "gt"
26+
ge = "ge"
27+
like = "like"
28+
ilike = "ilike" # PostgreSQL only
29+
in_ = "in_"
30+
not_in = "not_in"
31+
is_null = "is_null"
32+
33+
2034
class Grade(EnumBase):
2135
A = "A"
2236
B = "B"

fastapi-postgres/common/serializers/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
from __future__ import annotations
2-
3-
from typing import Any, List, Optional, Set, TypeAlias
1+
from typing import Any, List, Optional, Set, TypeAlias
42

53
from pydantic import BaseModel
64
from pydantic import Field as PydanticField
75
from sqlalchemy.inspection import inspect as sa_inspect
86
from sqlalchemy.orm.attributes import NO_VALUE
97
from sqlmodel import Field, SQLModel
108

9+
from common.enums import DBOperator
10+
1111

1212
class BaseTable(SQLModel):
1313
def model_dump(
@@ -87,7 +87,7 @@ def __eq__(self, other):
8787

8888

8989
class DBQuery(BaseModel):
90-
opt: str
90+
opt: DBOperator
9191
key: str
9292
value: Any
9393

fastapi-postgres/tests/test_all.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from httpx import AsyncClient
55

66
from app.service.create_data import FactoryModel
7-
from common.enums import ModelType
7+
from common.enums import DBOperator, ModelType
88

99

1010
class Api:
@@ -47,7 +47,7 @@ async def fetch_rows(self, *, model: ModelType, body: dict | None = None) -> lis
4747
return data
4848

4949
async def delete_row(self, *, model: ModelType, _id: int | str) -> None:
50-
body = {"query": [{"key": "id", "value": _id, "opt": "eq"}]}
50+
body = {"query": [{"key": "id", "value": _id, "opt": DBOperator.eq}]}
5151
r = await self.client.request(
5252
"DELETE", f"/{model}", content=json.dumps(body), headers=self.headers
5353
)

0 commit comments

Comments
 (0)