oguimbal / pg-mem

An in memory postgres DB instance for your unit tests

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TypeORM VirtualColumn cause error in table creation and querying

XihuaYang opened this issue · comments

Describe the bug

Use VirtualColumn feature in TypeORM (https://orkhan.gitbook.io/typeorm/docs/decorator-reference#virtualcolumn) cause issues with table creation, table would either fail to create the table and later on run into relation "Foo" does not exist error, or the table could be mis-structured and run into column "Foo.bar" does not exist, even though bar is defined in the entity.
Removing the field annotated with @VirtualColumn would allow pg-mem to behave correctly.

To Reproduce

@Entity('test')
class TestEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  num: number;

  @VirtualColumn({
    query: (alias) => ` SELECT SUM(num) FROM ${alias}`,
  })
  test_sum: number;
}

The generated SQL from TypeORM by calling dataSource.getRepository(TestEntity).find() looks like below:

SELECT "TestEntity"."id" AS "TestEntity_id", "TestEntity"."num" AS "TestEntity_num", ( SELECT SUM(num) FROM "TestEntity") AS "TestEntity_test_sum" FROM "test" "TestEntity"

With the entity defined above, the SQL generated above would fail with error relation "TestEntity" does not exist. However, if simply remove the @VirtualColumn field test_sum, the .find() call would succeed without any problem. It also would not work if we copy the generated SQL and call dataSource.getRepository(TestEntity).query(sql), the failure is the same.
If we change the query in virtual column to use direct table name instead of alias: SELECT SUM(num) FROM "test", the query would run without error, but the returned result only contains result of the subquery for virtual column, the id and num fields are missing in the returned object.
We have verified the query can run successfully in an actual Postgres v16 DB.

pg-mem version

2.8.1

are you been able to fix this ?

are you been able to fix this ?

No I have not, I suspect this is related to the parser of pg-mem, and I've give up using virtual column, instead I'll just use a raw query and select whatever calculated column I need, then write code to fill the calculated result into a non-column field in the entity