How to not insert duplicate row on save() with PrimaryGeneratedColumn()
See original GitHub issueIssue type:
[x ] question [ ] bug report [ ] feature request [ ] documentation issue
Database system/driver:
[ ] cordova
[ ] mongodb
[ ] mssql
[x ] mysql
/ mariadb
[ ] oracle
[ ] postgres
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo
TypeORM version:
[ x] latest
[ ] @next
[ ] 0.x.x
(or put your version here)
Steps to reproduce or a small repository showing the problem:
Hi, I run in this problem:
My entity don’t need a PrimaryColumn but typeorm need it otherwise I get the error “MissingPrimaryColumnError”. So I added a PrimaryGeneratedColumn with a UUID like this:
@PrimaryColumn() @PrimaryGeneratedColumn('uuid') uuid: string;
This works fine. But now I run into a other problem. When I want to save a second dataset to my db like repository.save(data)
the .save() method don’t see the duplication with already added rows because of the UUID every row have. Is there a way to specify a auto generated uuid field so that .save would not insert duplications?
Or a other option which would also work is checking on save if two column values are the same. Like:
got a entity with objects like this:
{ firstName: Peter, lastName: Parker, city: Fakecity, phone: 555-666, }
Now if there is already a object in the database with the same firstName and lastName then update that object otherwise insert
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (1 by maintainers)
Every table needs at least one primary column.
In that case, a suggestion is to remove
uuid
and makespecial_id
andtimestamp
the primary keys (which enforces unique (special_ID, timestamp) in the whole table):And use it like this:
I’ve tested this out and it seems to work fine with this approach, and replicates your desired results.
The reason yours didn’t work is because the uniqueness of the rows are determined by the primary keys, and by making
special_id
andtimestamp
the PKs, you can ensure that there will never be duplicate pairs existing in your table (and also update the existing ones if they happen to exist).If you really want to handle unique columns, you would use the
@Unique
on the class, something like@Unique(['firstName', 'lastName'])
, but this doesn’t really solve your problem.I would suggest passing the primary
uuid
every single time you want to ‘update’ something, because it can happen that two people can have the samefirstName
andlastName
, and becauseuuid
is ultimately the identifier for the row.Something like this would do it: