sequelize / sequelize-typescript

Decorators and some other features for sequelize

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support Sequelize.literal on VIRTUAL data type

eduwr opened this issue · comments

Issue

It would be nice to support Sequelize.literal on virtual subqueries, because it's a really common use-case.

Versions

  • sequelize: 6.5.1
  • sequelize-typescript: 2.1.0
  • typescript: 4.7.2

Issue type

  • bug report
  • feature request

Actual behavior

I'm trying to perform a subquery on a virtual field similar to the one in the following comment:

sequelize/sequelize#4942 (comment)

it happens that sequelize-typescript doesn't expect a Sequelize literal on virtual constructor and when I implemented the code I found this error:

Type '[Literal, string]' is not assignable to type 'string'

Expected behavior

No Typescript error

Steps to reproduce

Implement a model with 1-to-N relation and include a virtual field with a subquery using a Sequelize.literal like this:

@Column({
    type: DataType.VIRTUAL(DataType.INTEGER, [
      [
        Sequelize.literal(
          '(SELECT COUNT("Subthings"."id") FROM "Subthings" WHERE "Subthings"."parentId" = "Thing"."id")'
        ),
        'thingCount'
      ]
    ])
  })
  thingCount: number

Related code

@Column({
    type: DataType.VIRTUAL(DataType.INTEGER, [
      //@ts-expect-error - sequelize-typescript doesn't support Sequelize.literal type
      [
        Sequelize.literal(
          '(SELECT COUNT("Subthings"."id") FROM "Subthings" WHERE "Subthings"."parentId" = "Thing"."id")'
        ),
        'thingCount'
      ]
    ])
  })
  thingCount: number