#TIL 10 - Add User Define Function to TypeORM entity

Feb 5, 2021 · Dung Huynh

What

Select from a user-defined function (UDF) in TypeORM QueryBuilder.

Why

TypeORM doesn't natively support database functions in selects. This workaround maps UDF results to entity fields.

How

1. Add virtual column to entity:

@Column('int', { insert: false, readonly: true })
public qty: number;

2. Select UDF in QueryBuilder:

repository
  .createQueryBuilder("user")
  .addSelect("dbo.udfFindTotalQty(user.id)", "user_qty")
  .getManyAndCount();

Note: Alias follows tableName_columnName convention (e.g., user_qty).