question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to not insert duplicate row on save() with PrimaryGeneratedColumn()

See original GitHub issue

Issue 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:closed
  • Created 5 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

4reactions
liangchunncommented, Dec 29, 2018

My entity don’t need a PrimaryColumn but typeorm need it otherwise I get the error “MissingPrimaryColumnError”.

Every table needs at least one primary column.

Multiple rows can have the same special_ID (f.e. 1234) and multiple rows can have the same timestamp (f.e. 1546040428) but only one row can have that exact combination of special_ID 1234 and timestamp 1546040428, thats guaranteed.

In that case, a suggestion is to remove uuid and make special_id and timestamp the primary keys (which enforces unique (special_ID, timestamp) in the whole table):

@Entity('testtable')
export class TestTable {

  @PrimaryColumn()
  public special_id: string

  @PrimaryColumn()
  public timestamp: number

  @Column()
  public duration: number

}

And use it like this:

const repository = await connection.getRepository(TestTable)
const incomingTableData = [
  {
    special_id: '99:88:789',
    timestamp: 1546040428,
    duration: 120,
  },
  {
    special_id: '88:88:888',
    timestamp: 1546040459,
    duration: 70,
  },
]
await repository.save(incomingTableData)

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 and timestamp 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).

4reactions
liangchunncommented, Dec 28, 2018

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 same firstName and lastName, and because uuid is ultimately the identifier for the row.

Something like this would do it:

const userRepository = await connection.getRepository(User)
const user = await userRepository.findOne({ uuid })
user.firstName = 'new name'
await userRepository.save(user)
Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeORM many to many relationship give duplicate row when ...
Check your id-columns in data-tables and in join-table. They should have same type. I had such problem and this was the case.
Read more >
13.2.7.2 INSERT ... ON DUPLICATE KEY UPDATE Statement
Using the row alias new , the statement shown previously using VALUES() to access the new column values can be written in the...
Read more >
TypeORM - Amazing ORM for TypeScript and JavaScript (ES7 ...
save method returns an instance of the same object you pass to it. It's not a new copy of the object, it modifies...
Read more >
Entities - typeorm - GitBook
You can create an entity by defining a new class and mark it with @Entity() : import { Entity, PrimaryGeneratedColumn, Column } from...
Read more >
TypeORM unique indices with multiple fields
I recently run into an issue that I wanted to create a database ... @Entity() export class StudentEntity { @PrimaryGeneratedColumn() id: ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found