Skip to content

Commit bbea542

Browse files
committed
style: sql and readme
1 parent caaf85d commit bbea542

File tree

8 files changed

+33
-35
lines changed

8 files changed

+33
-35
lines changed

README.md

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ await AccountMgr.select_custom_fields(
3838
"extend ->> '$.last_login.start_datetime' start_datetime",
3939
"CAST(extend ->> '$.last_login.online_sec' AS SIGNED) online_sec"
4040
],
41-
wheres=f"id IN ({', '.join(map(str, aids))}) AND gender = 1", # These 4 ways of `wheres` can work equally
41+
wheres=f"id IN ({','.join(map(str, aids))}) AND gender=1", # These 4 types of `wheres` are equal
4242
# wheres=Q(Q(id__in=aids), Q(gender=1), join_type="AND"),
4343
# wheres={"id__in": aids, "gender": 1},
4444
# wheres=[Q(id__in=aids), Q(gender=1)],
@@ -49,7 +49,7 @@ Generate sql and execute
4949
SELECT
5050
id, extend ->> '$.last_login.ipv4' ipv4, extend ->> '$.last_login.start_datetime' start_datetime, CAST(extend ->> '$.last_login.online_sec' AS SIGNED) online_sec
5151
FROM account
52-
WHERE `id` IN (1,2,3) AND `gender`=1
52+
WHERE id IN (1,2,3) AND gender=1
5353
```
5454

5555
**complex example**
@@ -58,7 +58,7 @@ await AccountMgr.select_custom_fields(
5858
fields=[
5959
"locale", "gender", "COUNT(1) cnt"
6060
],
61-
wheres="id BETWEEN 1 AND 12",
61+
wheres=Q(id__range=[1, 12]),
6262
groups=["locale", "gender"],
6363
having="cnt > 0",
6464
orders=["locale", "-gender"],
@@ -70,7 +70,7 @@ Generate sql and execute
7070
SELECT
7171
locale, gender, COUNT(1) cnt
7272
FROM account
73-
WHERE id BETWEEN 1 AND 12
73+
WHERE `id` BETWEEN 1 AND 12
7474
GROUP BY locale, gender
7575
HAVING cnt > 0
7676
ORDER BY locale ASC, gender DESC
@@ -89,14 +89,14 @@ await AccountMgr.upsert_json_field(
8989
},
9090
"$.uuid": "fd04f7f2-24fc-4a73-a1d7-b6e99a464c5f",
9191
},
92-
wheres=f"id = 8",
92+
wheres=Q(id=8),
9393
)
9494
```
9595
Generate sql and execute
9696
```sql
9797
UPDATE account
9898
SET extend = JSON_SET(COALESCE(extend, '{}'), '$.last_login', CAST('{"ipv4": "209.182.101.161", "start_datetime": "2022-10-16 11:11:05", "online_sec": 4209}' AS JSON), '$.uuid', 'fd04f7f2-24fc-4a73-a1d7-b6e99a464c5f')
99-
WHERE id = 8
99+
WHERE `id`=8
100100
```
101101

102102
### **upsert_on_duplicated**
@@ -124,7 +124,7 @@ Generate sql and execute
124124
### **insert_into_select**
125125
```python
126126
await AccountMgr.insert_into_select(
127-
wheres=f"id IN (4, 5, 6)",
127+
wheres=Q(id__in=[4, 5, 6]),
128128
remain_fields=["gender", "locale"],
129129
assign_field_dict={
130130
"active": False,
@@ -139,7 +139,7 @@ Generate sql and execute
139139
(gender, locale, active, name, extend)
140140
SELECT gender, locale, False active, CONCAT(LEFT(name, 26), ' [NEW]') name, '{}' extend
141141
FROM account
142-
WHERE id IN (4, 5, 6)
142+
WHERE `id` IN (4,5,6)
143143
```
144144

145145
### **bulk_update_with_fly_table**
@@ -161,6 +161,6 @@ Generate sql and execute
161161
VALUES
162162
ROW(7, False, 1), ROW(15, True, 0)
163163
) AS fly_table (id, active, gender)
164-
) tmp ON account.id = tmp.id
165-
SET account.active = tmp.active, account.gender = tmp.gender
164+
) tmp ON account.id=tmp.id
165+
SET account.active=tmp.active, account.gender=tmp.gender
166166
```

examples/fastapi-efficient-sql.postman_collection.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@
155155
"method": "POST",
156156
"header": [],
157157
"url": {
158-
"raw": "{{local}}:8000/api/account/last_login/update?account_id=8",
158+
"raw": "{{local}}:8000/api/account/last_login/update?aid=8",
159159
"host": [
160160
"{{local}}"
161161
],
@@ -168,7 +168,7 @@
168168
],
169169
"query": [
170170
{
171-
"key": "account_id",
171+
"key": "aid",
172172
"value": "8"
173173
}
174174
]
@@ -203,7 +203,7 @@
203203
"header": [],
204204
"body": {
205205
"mode": "raw",
206-
"raw": "{\n \"account_ids\": [4, 5, 6]\n}",
206+
"raw": "{\n \"aids\": [4, 5, 6]\n}",
207207
"options": {
208208
"raw": {
209209
"language": "json"

examples/service/routers/account.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ async def query_group_by_locale_view(
5656
fields=[
5757
"locale", "gender", "COUNT(1) cnt"
5858
],
59-
wheres="id BETWEEN 1 AND 12",
59+
wheres=Q(id__range=[1, 12]),
6060
groups=["locale", "gender"],
6161
having="cnt > 0",
6262
orders=["locale", "-gender"],
@@ -104,7 +104,7 @@ async def query_last_login_view(
104104
"extend ->> '$.last_login.start_datetime' start_datetime",
105105
"CAST(extend ->> '$.last_login.online_sec' AS SIGNED) online_sec"
106106
],
107-
wheres=f"id IN ({', '.join(map(str, aids))}) AND gender = 1",
107+
wheres=f"id IN ({','.join(map(str, aids))}) AND gender=1",
108108
# wheres=Q(Q(id__in=aids), Q(gender=1), join_type="AND"),
109109
# wheres={"id__in": aids, "gender": 1},
110110
# wheres=[Q(id__in=aids), Q(gender=1)],
@@ -127,7 +127,7 @@ async def update_last_login_view(
127127
},
128128
"$.uuid": faker.uuid4(),
129129
},
130-
wheres=f"id = {aid}",
130+
wheres=Q(id=aid),
131131
)
132132
return {"row_cnt": row_cnt}
133133

@@ -158,7 +158,7 @@ async def bulk_clone_view(
158158
aids: List[int] = Body(..., embed=True),
159159
):
160160
ok = await AccountMgr.insert_into_select(
161-
wheres=f"id IN ({', '.join(map(str, aids))})",
161+
wheres=Q(id__in=aids),
162162
remain_fields=["gender", "locale"],
163163
assign_field_dict={
164164
"active": False,

fastapi_esql/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
"CursorHandler",
1818
"RawSQL",
1919
"SQLizer",
20-
"QsParsingError"
20+
"QsParsingError",
2121
"WrongParamsError",
2222
"timing",
2323
]

fastapi_esql/orm/base_app.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
from abc import ABCMeta
22

3-
from .base_model import BaseModel
4-
53

64
class AppMetaclass(ABCMeta):
75

@@ -25,6 +23,7 @@ def rw_conn(self):
2523

2624
@property
2725
def table(self):
28-
if self.model is BaseModel:
26+
db_table = self.model._meta.db_table
27+
if not db_table:
2928
raise NotImplementedError(f"Class attribute `model` was not defined by {self.__name__}!")
30-
return self.model._meta.db_table
29+
return db_table

fastapi_esql/orm/base_manager.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from tortoise.models import Model
77

88
from .base_app import AppMetaclass
9-
from .base_model import BaseModel
109
from ..utils.sqlizer import SQLizer
1110
from ..utils.cursor_handler import CursorHandler
1211

@@ -15,7 +14,7 @@
1514

1615
class BaseManager(metaclass=AppMetaclass):
1716

18-
model = BaseModel
17+
model = Model
1918

2019
@classmethod
2120
async def get_by_pk(
@@ -98,7 +97,7 @@ async def upsert_json_field(
9897
wheres,
9998
cls.model,
10099
)
101-
return await CursorHandler.calc_row_cnt(sql, cls.rw_conn, logger)
100+
return await CursorHandler.sum_row_cnt(sql, cls.rw_conn, logger)
102101

103102
@classmethod
104103
async def upsert_on_duplicated(
@@ -113,7 +112,7 @@ async def upsert_on_duplicated(
113112
insert_fields,
114113
upsert_fields,
115114
)
116-
return await CursorHandler.calc_row_cnt(sql, cls.rw_conn, logger)
115+
return await CursorHandler.sum_row_cnt(sql, cls.rw_conn, logger)
117116

118117
@classmethod
119118
async def insert_into_select(
@@ -144,4 +143,4 @@ async def bulk_update_with_fly_table(
144143
join_fields,
145144
update_fields,
146145
)
147-
return await CursorHandler.calc_row_cnt(sql, cls.rw_conn, logger)
146+
return await CursorHandler.sum_row_cnt(sql, cls.rw_conn, logger)

fastapi_esql/utils/cursor_handler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ async def fetch_dicts(
2020
return None
2121

2222
@classmethod
23-
async def calc_row_cnt(
23+
async def sum_row_cnt(
2424
cls,
2525
sql: str,
2626
conn: BaseDBAsyncClient,

fastapi_esql/utils/sqlizer.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,15 @@ def resolve_wheres(
5151
return modifier.where_criterion.get_sql(quote_char="`")
5252

5353
@classmethod
54-
def resolve_orders(cls, orderings: List[str]) -> str:
55-
orders = []
56-
for o in orderings:
54+
def resolve_orders(cls, orders: List[str]) -> str:
55+
orders_ = []
56+
for o in orders:
5757
if o.startswith("-"):
5858
order = "DESC"
5959
else:
6060
order = "ASC"
61-
orders.append(f"{o.strip('-')} {order}")
62-
return ", ".join(orders)
61+
orders_.append(f"{o.strip('-')} {order}")
62+
return ", ".join(orders_)
6363

6464
@classmethod
6565
def _sqlize_value(cls, value, to_json=False) -> str:
@@ -234,8 +234,8 @@ def bulk_update_with_fly_table(
234234
if not all([table, dicts, join_fields, update_fields]):
235235
raise WrongParamsError("Please check your params")
236236

237-
joins = [f"{table}.{jf} = tmp.{jf}" for jf in join_fields]
238-
updates = [f"{table}.{uf} = tmp.{uf}" for uf in update_fields]
237+
joins = [f"{table}.{jf}=tmp.{jf}" for jf in join_fields]
238+
updates = [f"{table}.{uf}=tmp.{uf}" for uf in update_fields]
239239

240240
sql = f"""
241241
UPDATE {table}

0 commit comments

Comments
 (0)