tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.67k stars 390 forks source link

v0.19: bulk_create doesn't work correctly with on_conflict #1422

Open Hyney opened 1 year ago

Hyney commented 1 year ago

Describe the bug bulk_create works not correctly with on_conflicts. raise tortoise.exceptions.OperationalError: (1064, "You have an error in your SQL syntax")

To Reproduce

The SQL syntax seems to be error on Mysql-5.7.28

cls.MODEL.bulk_create(results, update_fields=['update_time'], on_conflict=['domain_name']).sql()

INSERT INTO `domain` (`create_time`,`update_time`,`domain_name`,`describe`,`data_type`,`rule`,`is_standard`,`is_union`,`relate_domain`,`encrypt_key`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) AS `new_domain` ON DUPLICATE KEY UPDATE `update_time`=`new_domain`.`update_time`;

Exception

check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS `new_domain` ON DUPLICATE KEY UPDATE `update_time`=`new_domain' at line 1
zenorochaV1 commented 1 year ago

same , how to resove

Dormitabnia commented 8 months ago

Same problem, here is my solution. MySQL's INSERT ... ON DUPLICATE KEY UPDATE syntax does not support the alias syntax AS new_domain to refer to the newly inserted values. To refer to the newly inserted values, should use the VALUES(column_name) function directly.

INSERT INTO `domain` (`domain_name`,`describe`) VALUES (%s,%s) ON DUPLICATE KEY UPDATE 
`domain_name` = VALUES(`domain_name`),
`describe` = VALUES(`describe`);