Skip to content

Commit ff2e35a

Browse files
committed
fix: deprecation warning of VALUES function
1 parent 379aaa6 commit ff2e35a

File tree

4 files changed

+23
-10
lines changed

4 files changed

+23
-10
lines changed

README.md

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ class AccountMgr(BaseManager, metaclass=DemoMetaclass):
2828

2929
## Some supported efficient sql
3030
### **select_custom_fields**
31+
**without `groupbys`**
3132
```python
3233
await AccountMgr.select_custom_fields(
3334
fields=[
@@ -46,6 +47,7 @@ Generate sql and execute
4647
WHERE id IN (1, 2, 3)
4748
```
4849

50+
**with `groupbys`**
4951
```python
5052
await AccountMgr.select_custom_fields(
5153
fields=[
@@ -90,9 +92,9 @@ Generate sql and execute
9092
```python
9193
await AccountMgr.upsert_on_duplicated(
9294
[
93-
{'id': 7, 'gender': 1, 'name': '松田 陽一', 'locale': 'ja_JP', 'extend': {}},
94-
{'id': 8, 'gender': 2, 'name': 'Zeeshan Kadakia', 'locale': 'en_IN', 'extend': {}},
95-
{'id': 9, 'gender': 0, 'name': '姜淑珍', 'locale': 'zh_CN', 'extend': {}}
95+
{'id': 7, 'gender': 1, 'name': '斉藤 修平', 'locale': 'ja_JP', 'extend': {}},
96+
{'id': 8, 'gender': 1, 'name': 'Ojas Salvi', 'locale': 'en_IN', 'extend': {}},
97+
{'id': 9, 'gender': 1, 'name': '羊淑兰', 'locale': 'zh_CN', 'extend': {}}
9698
],
9799
insert_fields=["id", "gender", "name", "locale", "extend"],
98100
upsert_fields=["name", "locale"],
@@ -103,8 +105,9 @@ Generate sql and execute
103105
INSERT INTO account
104106
(id, gender, name, locale, extend)
105107
VALUES
106-
(7, 1, '松田 陽一', 'ja_JP', '{}'), (8, 2, 'Zeeshan Kadakia', 'en_IN', '{}'), (9, 0, '姜淑珍', 'zh_CN', '{}')
107-
ON DUPLICATE KEY UPDATE name=VALUES(name), locale=VALUES(locale)
108+
(7, 1, '斉藤 修平', 'ja_JP', '{}'), (8, 1, 'Ojas Salvi', 'en_IN', '{}'), (9, 1, '羊淑兰', 'zh_CN', '{}')
109+
AS `new_account`
110+
ON DUPLICATE KEY UPDATE name=`new_account`.name, locale=`new_account`.locale
108111
```
109112

110113
### **insert_into_select**

examples/service/routers/account.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,14 @@ async def bulk_init_view():
7878
}
7979
}
8080
})
81-
logger.debug(dicts)
82-
ok = await AccountMgr.bulk_create_from_dicts(dicts)
81+
# logger.debug(dicts)
82+
ok = await AccountMgr.bulk_create_from_dicts(
83+
dicts,
84+
batch_size=5,
85+
# ignore_conflicts=True,
86+
update_fields=["gender", "name", "locale"],
87+
on_conflict=["id"],
88+
)
8389
return {"ok": ok}
8490

8591

fastapi_esql/orm/base_manager.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,12 @@ async def update_from_dict(cls, obj: Model, params: Dict[str, Any]) -> bool:
4646
return False
4747

4848
@classmethod
49-
async def bulk_create_from_dicts(cls, dicts: List[Dict[str, Any]]) -> bool:
49+
async def bulk_create_from_dicts(cls, dicts: List[Dict[str, Any]], **kwargs) -> bool:
5050
try:
51+
# NOTE Here is a bug in bulk_create. https://github.com/tortoise/tortoise-orm/issues/1281
5152
await cls.model.bulk_create(
5253
objects=[cls.model(**d) for d in dicts],
54+
**kwargs,
5355
using_db=cls.rw_conn,
5456
)
5557
return True

fastapi_esql/utils/sqlizer.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def _sqlize_value(cls, value, to_json=False) -> str:
2929
return value.sql
3030
elif isinstance(value, (int, float, bool)):
3131
return f"{value}"
32-
elif isinstance(value, (dict, list)):
32+
elif isinstance(value, (dict, list, tuple)):
3333
dumped = dumps(value, ensure_ascii=False)
3434
if to_json:
3535
return f"CAST('{dumped}' AS JSON)"
@@ -98,15 +98,17 @@ def upsert_on_duplicated(
9898
for d in dicts:
9999
values.append(f"({', '.join(cls._sqlize_value(d.get(f)) for f in insert_fields)})")
100100
# logger.debug(values)
101+
new_table = f"`new_{table}`"
101102
upserts = []
102103
for field in upsert_fields:
103-
upserts.append(f"{field}=VALUES({field})")
104+
upserts.append(f"{field}={new_table}.{field}")
104105

105106
sql = f"""
106107
INSERT INTO {table}
107108
({", ".join(insert_fields)})
108109
VALUES
109110
{", ".join(values)}
111+
AS {new_table}
110112
ON DUPLICATE KEY UPDATE {", ".join(upserts)}"""
111113
logger.debug(sql)
112114
return sql

0 commit comments

Comments
 (0)