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.

Foreign column pointing to a table that has PK / FK column is not migrated

See original GitHub issue

Issue type:

[x] 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 [x] 0.2.25 (or put your version here)

Steps to reproduce or a small repository showing the problem:

I’m having problem when migrating columns from models files.

When I use a OneToOne relation to a table that have a primary key which is also a FK, the column is not generated.

I have the following models

@Entity({name: 'person'})
export class Person extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({type: 'varchar', nullable: true})
    fullname: string;

    @OneToOne(() => NaturalPerson, pf => pf.person, {eager: true})
    naturalPerson: NaturalPerson;

}

//Notice that primary column of this table it is a FK too. 
@Entity({name: 'natural_person'})
export class NaturalPerson extends BaseEntity {
    @OneToOne(() => Person, person => person.id, {primary: true})
    @JoinColumn()
    person: Person;

    @OneToOne(() => PEP, pep => pep.naturalPerson)
    pep: PEP;

    @OneToMany(() => NaturalPersonToLanguage, rl => rl.naturalPerson)
    languages: NaturalPersonToLanguage[];

}

//this table points to the last one...
@Entity({name: 'pep'})
export class PEP extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({type: 'varchar'})
    governmentJob: string;

    //This field do not get created on migrated table....
    @OneToOne(type => NaturalPerson, np => np.pep, {nullable: true})
    @JoinColumn()
    naturalPerson: NaturalPerson;
}

@Entity({name: 'Language'})
export class Language extends BaseEntity {
    @PrimaryGeneratedColumn()
    code: number;

    @Column({type: 'varchar', nullable: false})
    name: string

    @Column({type: 'varchar', nullable: false})
    shortName: string
}

//This table generate the FK column to NaturalPerson 
@Entity({name: 'natural_person_language'})
export class NaturalPersonToLanguage extends BaseEntity {
    @ManyToOne(type => NaturalPerson, np => np.languages, {primary: true})
    naturalPerson: NaturalPerson;

    @ManyToOne(type => Language, l => l.code, {primary: true})
    language: Language;

    @Column({type: 'boolean', nullable: false, default: false})
    main: boolean
}

Generated Migration:

 public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`CREATE TABLE "Language" ("code" SERIAL NOT NULL, "name" character varying NOT NULL, "shortName" character varying NOT NULL, CONSTRAINT "PK_5f94ac0a26192e198588241fa39" PRIMARY KEY ("code"))`);
        await queryRunner.query(`CREATE TABLE "person" ("id" SERIAL NOT NULL, "fullname" character varying, CONSTRAINT "PK_5fdaf670315c4b7e70cce85daa3" PRIMARY KEY ("id"))`);
        await queryRunner.query(`CREATE TABLE "pep" ("id" SERIAL NOT NULL, "governmentJob" character varying NOT NULL, CONSTRAINT "PK_4a13ca119b498fcf2fe38e8ba59" PRIMARY KEY ("id"))`);
        await queryRunner.query(`CREATE TABLE "natural_person" ("personId" integer NOT NULL, CONSTRAINT "REL_2218f10f17b2f92f1532e69072" UNIQUE ("personId"), CONSTRAINT "PK_2218f10f17b2f92f1532e690720" PRIMARY KEY ("personId"))`);
        await queryRunner.query(`CREATE TABLE "natural_person_language" ("main" boolean NOT NULL DEFAULT false, "naturalPersonPerson" integer NOT NULL, "languageCode" integer NOT NULL, CONSTRAINT "PK_5c7bd6b9a623ee8cef01041f270" PRIMARY KEY ("naturalPersonPerson", "languageCode"))`);
        await queryRunner.query(`ALTER TABLE "natural_person" ADD CONSTRAINT "FK_2218f10f17b2f92f1532e690720" FOREIGN KEY ("personId") REFERENCES "person"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`);
        await queryRunner.query(`ALTER TABLE "natural_person_language" ADD CONSTRAINT "FK_05c847be3309a36ca9ee33b2966" FOREIGN KEY ("naturalPersonPerson") REFERENCES "natural_person"("personId") ON DELETE NO ACTION ON UPDATE NO ACTION`);
        await queryRunner.query(`ALTER TABLE "natural_person_language" ADD CONSTRAINT "FK_792890985a41485df1d3edfd1d3" FOREIGN KEY ("languageCode") REFERENCES "Language"("code") ON DELETE NO ACTION ON UPDATE NO ACTION`);
    }

I tried with synchronize: true, and nothing change.

Also when I navigate through metadata of the affected Entity (PEP) It generate the FK to NaturalPerson Without problem…

Note: This is a simplified model of the real one, in the real one ManyToOne and OneToMany relations has the same problem.

Pic of the generated Table: image

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:2
  • Comments:8

github_iconTop GitHub Comments

5reactions
FrederickGR7commented, Sep 8, 2020

I have the same problem… helppp… My job depends on it…

3reactions
reynoldmorelcommented, Sep 8, 2020

I’m having the same issue. Please help!!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Creating a Relationship - how to migrate a PK Column as an ...
Select 'Replace', as the FK Column should have the same data type as in ... Migrating Foreign Key Unification' section of the user...
Read more >
3 common foreign key mistakes (and how to avoid them)
1. Mismatched data types ... When you're using a foreign key to reference a column in another table, the datatypes of both tables...
Read more >
Primary and Foreign Key Constraints - SQL Server
These are important database objects. Primary Key Constraints. A table typically has a column or combination of columns that contain values that ...
Read more >
laravel - Migration: Cannot add foreign key constraint
This error occurred for me because I created the migration table with the foreign key in it firstly before the key existed as...
Read more >
Migrate tables with a foreign key to memory-optimized tables ...
I have installed SQL Server 2019 and created a database named DemoDatabase on it. I have created two tables named tblOrder and tblProducts...
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