Background
Our node app uses a postgres database and interacts with it via TypeORM.
I know how to create a table with a primary key generated by a postgres sequence as described here:
import {Entity, PrimaryGeneratedColumn} from "typeorm";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
}
Goal
I am trying to create a table for objects that are always created in pairs; let's call the objects "shoes" and say that the two members of the pair are the left shoe and right shoe. I would like the left and right shoes to be separate entries in my table, and I want to be able to easily query for both shoes in a pair.
One approach would be something like this, which gives me an index on pairId and enforces only one left shoe and one right shoe for each pair (TypeORM index docs)
enum Foot {
Left = "Left",
Right = "Right"
}
@Entity()
@Index(["foot", "pairId"], { unique: true })
export class Shoe {
@PrimaryGeneratedColumn()
id: number;
@Column({ type: "enum", enum: Foot })
foot: Foot;
@Column
pairId: number
}
However, this approach I am still responsible for generating the values in the pairId field.
Question
Is there a way I can get postgres to generate the values in pairId for me? Perhaps using the same kind of sequence that is automatically generated by the @PrimaryGeneratedColumn decorator?
Update
Response below proposes a possible solution in postgres, though I would still need to know how to do this in either by using TypeORM's API or getting TypeORM to run the relevant raw SQL commands at the right time.
I could write a TypeORM migration to run the raw SQL, but I'm not sure how to get it to run on table creation -- it seems like the documentation primarily anticipates running them from the command line.