Search code examples
node.jssql-servertypeorm

Set base / start value for Generated Column in TypeORM


I am in need of an auto incrementing order number in a system I'm building.

We are trying to use the following syntax:

@Column()
@Generated('increment')
private orderNumber: number;

The problem with this approach is that the starting value will be 1. We need to be able to set custom starting value, as we are replacing another order system with existing serial numbers.

We tried to use { default: 9000 } as column option, but this gives following error:

RequestError: Defaults cannot be created on columns with an IDENTITY attribute. Table 'order', column 'orderNumber'


Solution

  • Solved it the old school way

    async function createOrderNumber() {
        const startOrderNumber = 9000;
    
        const highestOrderNumber = await orderRepository
            .createQueryBuilder('order')
            .select('MAX(order.orderNumber)', 'order')
            .getRawOne();
    
        const newOrderNumber =
            highestOrderNumber.order < startOrderNumber ? startOrderNumber : highestOrderNumber.order + 1;
    
        return newOrderNumber;
    }