tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

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

Open Hyney opened this issue 2 years ago • 2 comments

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

Hyney avatar Jul 11 '23 08:07 Hyney

same , how to resove

zenorochaV1 avatar Nov 08 '23 13:11 zenorochaV1

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`);

Dormitabnia avatar Feb 22 '24 06:02 Dormitabnia