-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
.save() is throwing duplicate key value violates unique constraint #4122
Comments
I have exactly the same problem with sqlite. |
Same kind of issue on postgres for me. I have a composite unique key (foreign key + a date column) throw error "QueryFailedError: duplicate key value violates unique constraint " when ever I use save method on this particular table. |
Still no patch concerning this duplication problem when backing up data? |
I ran into the same issue in #3238. Using |
As a workaround I added a PrimaryColumn id that is the concatenation of all the originally as primary keys intended fields. Also ugly, but can be easily removed once this is fixed. |
Which was great aside from:
Here's my final workaround.
|
I can confirm that this problem still exists. I'm using |
Same here |
same here |
Had a similar issue Resolved it by converting all UUID's on save to lowercase. An external source was giving me UUID's in uppercase. Saving them to Postgres worked the first time since Postgres simply converts the UUID to lowercase. |
Simple entity that this causing this problem with
This was working for a while but suddenly started throwing |
Same problem with oracle. Using following entity and getting export class DayData {
@Column({name: 'DAY', type: 'date', primary: true})
day: Date;
@Column({name: 'ID1', type: 'number', primary: true})
id1: number;
@Column({name: 'ID2', type: 'number', primary: true})
id2: number;
@Column({name: 'QUANTITY'})
quantity: number;
} The problem is, that TypeORM is using a wrong date format during the select: SELECT
"DayData"."DAY" AS "DayData_DAY",
"DayData"."QUANTITY" AS "DayData_QUANTITY",
"DayData"."ID1" AS "DayData_ID1",
"DayData"."ID2" AS "DayData_ID2"
FROM "DAY_DATA" "DayData"
WHERE "DayData"."DAY" = :id_0_0
AND "DayData"."ID1" = :id_0_1
AND "DayData"."ID2" = :id_0_2
;
-- PARAMETERS: ["2017-12-31T23:00:00.000Z",17,100] And for the insert this one: INSERT INTO "DAY_DATA"
("DAY", "QUANTITY", "ID1", "ID2")
VALUES
(TO_DATE('2018-01-01', 'YYYY-MM-DD'), :i0_QUANTITY, :i0_ID1, :i0_ID2)
;
-- PARAMETERS: [18025,17,100] It's a bit strange, that TypeORM itself casting the date param, but i think it's ok, because it uses the to_date function. But don't know if it's possible to get attacked by sql injection, there - need to test. |
Having spent the last week building a platform on top of typeorm and then to discover there is no way to save an entity due to this bug is an extremely frustrating situation. I've tried working around this in various ways, without success. Does anybody know of ANY solution to get Typeorm working with Postgres (using dual-foreign keys, not the single primary key uuid pattern)? |
You find any solution for this? I am also stuck same problem. |
Using the upsert technique I mentioned above, I wanted to know whether a conflict occurred or not. I had to replace this:
With this:
But this will probably only correctly differentiate when the entity model does not have a @dulkith I think the only way to solve it is to manually craft a raw query or use a query builder. You might be able to adapt the snippet I adapted. |
This issue occurs when you are trying to save() an object with its relations. Example with 2 tables: Photo and Category photo = { id: 1, category: { id: 1, name: "holidays" } }
// first save works
this.save(photo) // works
// second save does not work
this.save(photo) It does not work the second time because save() tries to recreate the relation between Photo(1) <=> Category(1). You should do: photo = { id: 1, category: { id: 1, name: "holidays" } }
// first save works
this.save(photo)
delete photo.category
// second save works!
this.save(photo) |
I just got this problem, but I am not sure why it only happens if the entity has relationships in my case. In the meanwhile, try this after inserting the data in your database (in the end of your migration/seed, for example) (PostgreSQL only): SELECT setval(
pg_get_serial_sequence('"your_table_name"', 'your_primary_key_name'),
(SELECT MAX("id") FROM "your_table_name") + 1
) Source: https://stackoverflow.com/a/21639138/2957291 It should solve the problem for now. If I find more information before somebody else here I will paste updates. @ubershmekel @dulkith @n8sabes @bohendo @oscar-corredor @dekdekbaloo @vogler @aosifre @vamseekm @DrakkenSaer, can you confirm if this solves your problem? |
@saulotoledo Nope, it doesn't. Still having troubles with this. Any updates on this? This seems like an important bug to fix. |
@lapwat Are you saying that we cannot use .save to cascade updates down related entities, but we can use it to update just the primary entity (and no related entities)? I agree, .save works fine for individual entities, it just fails when you have related entities. |
This worked for me. Thanks. |
any updates on this? Still failling for me using postgres with dual keys (2 columns) as primary key. |
I just removed all objects from table, and then i saved my model without error. |
Any solution on this one? I have 1 PK and 1 UNIQUE and since I'm not passing the PK it will always attempt to insert, which is not desirable since it will raise |
Hi guys. I was getting the same problem a few hours ago. I have discovered that if you don't tell entity id explicitly, typeorm is gonna try to create a new one. I have just initialized id (when it exists) and it solved problem. This aproach was generating the issued error:
PD:
|
@JarLowrey seems unrelated to what's described in this thread. Most of the examples here seem to be with multiple primary columns. Is that the case? If so, anyone want to confirm that #6417 fixes / doesn't fix the issue? |
Is there any workaround while a patch is being released? @imnotjames |
This issue still persists. When I manually altered the row of records by exporting the whole table and import a new set of data into the table, this error occurs. It seems to me that TypeORM does not recognize the last inserted ID of the table? I have to run the script by @goktugyil in order to solve the issue. |
Same here, issue still persists when saving nested object with multiple keys in unique constraint - I use POSTGRES |
Also here, when saving twice an entity that have |
This happens for MongoDB nested objects too. Is there any workaround? |
This is my workaround. Hope this helps someone. Basically I just created a repository wrapper and use import {DeepPartial, EntityRepository, Repository, SaveOptions, ObjectID} from 'typeorm';
import {IdEntity} from './id-entity';
@EntityRepository()
export class SaveSafeRepository<T> extends Repository<T> {
save<T extends DeepPartial<T>>(
entity: T & {_id?: ObjectID},
options?: SaveOptions
): Promise<T> {
// @ts-ignore
if (!entity._id) return this.create(entity);
// @ts-ignore
else return this.update(entity._id, entity);
}
} Note that you possibly need to change the |
In case this helps at all. I had a situation where updating a one-to-one foreign key on a table would cause this error. What fixed it for me was simply creating a new entity rather than updating the existing one in order to get a new ID, then saving that new ID as the foreign key on the other table. |
I'm facing the same issue here. Any update about fixing this wrong behavior ? |
check for existing record with findOne and save in case records does not exist, also this will prevent increasing autoincrement in case of you use maria|mysql, and InnoDB |
This is still not working appropriately in Postgres. |
Is anyone from TypeOrm looking into this? This seems to be a huge issue. |
I'm using a number as a primary key. |
You could potentially just remove the |
Struggled with this for the last 5 hours, finally made it. So first add a name to constraint in your entity,
Then, you can use onConflict with ON CONSTRAINT
|
@imnotjames, thank you for your fix #6417. Just in case you missed it (because this topic is now set at "closed"), this is still not working appropriately in Postgres. |
@emagnier fyi this is working for me in postgres right now - I initially thought it wasn't but that was due to some bad data in my dev env |
I'm still facing the same issue in Postgres.
I now use
It is not a fix but the odds of not having a matching Id helps |
This happened to me because I inserted records using literal, numeric values (instead of DEFAULT or undefined) as arguments for the auto-incremented column. Doing so circumvents the column's underlying sequence object's increment call, hence making the sequence's value out of sync with the values in the column in the table. |
still bug not fixed.. |
@Form1ca can you provide a minimal reproduction? ideally in a repo |
Excuse me, in this case, "your_table_name" is the name of the main table in both cases? The related table isn't meant to be included anywhere in the query? |
The original issue has been corrected. If you believe there's still a problem please open a new issue with a way to reproduce the problem. |
Issue type:
[x] question
[ ] bug report
[ ] feature request
[ ] documentation issue
Database system/driver:
[ ]
cordova
[ ]
mongodb
[ ]
mssql
[ ]
mysql
/mariadb
[ ]
oracle
[x]
postgres
[ ]
cockroachdb
[ ]
sqlite
[ ]
sqljs
[ ]
react-native
[ ]
expo
TypeORM version:
[x]
latest
[ ]
@next
[ ]
0.x.x
(or put your version here)This was working for me earlier but now it is not. I am using a composite key of three different properties. Every time I try to update and existing row, I get the error
QueryFailedError: duplicate key value violates unique constraint "PK_8b1375852f33d30b328388e5a5c"
.This is my entity:
The text was updated successfully, but these errors were encountered: