Reputation: 457
some.entity.ts
amount:number
But when I store a very large data in my postgres it throws error '''integer out of range'''
My question is how can I store Big Int as type in psql using typeorm
Upvotes: 16
Views: 28097
Reputation: 574
For PostgreSQL connection type you can specify parseInt8: true
option in your Datasource definition (along with options like type
, host
, port
and so on).
Then change the type of column to bigint
in entity file:
@Column({type: 'bigint'})
columnName: bigint
Now after retrieving data from the table with columnName
you'll get columnName
as bigint
, not a string
.
P.S. Option bigNumberStrings
works just for MySQL/MariaDB.
Upvotes: 1
Reputation: 5084
I used column transformer:
export class ColumnNumberTransformer {
public to(data: number): number {
return data;
}
public from(data: string): number {
// output value, you can use Number, parseFloat variations
// also you can add nullable condition:
// if (!Boolean(data)) return 0;
return parseInt(data);
}
}
Then in entity:
@Entity('accounts')
export class AccountEntity extends BaseEntity {
@Column({
type: 'bigint',
nullable: false,
transformer: new ColumnNumberTransformer()
})
public balance: number;
}
Upvotes: 1
Reputation: 113
Great resonse from @Riajul Islam!
As an addition to his answer, if you want to store bigint
in PrimaryGeneratedColumn
, you should you the following:
@PrimaryGeneratedColumn( 'increment', {type: 'bigint'} )
id: number;
Upvotes: 7
Reputation: 1483
Define type bigint
in @Column decorator,
@Column({type: 'bigint'})
columnName: string;
Note: that based on TypeOrm documentation bigint
is mapped to string
.
Upvotes: 24
Reputation: 303
Just add { bigNumberStrings: false }
to TypeORM's configuration, such as:
TypeOrmModule.forRoot({
bigNumberStrings: false,
...config.database,
}),
Then the bigint will return number type.
Upvotes: 7