typeorm: QueryBuilder IN and ANY Fail with .where - Postgres

Issue type:

[ ] question [x ] bug report [ ] feature request [ ] documentation issue

Database system/driver:

[ ] cordova [ ] mongodb [ ] mssql [ ] mysql / mariadb [ ] oracle [ x] postgres [ ] sqlite [ ] sqljs [ ] react-native

TypeORM version:

[x ] latest [ ] @next [ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

This works:

    const sql = 'SELECT * FROM members WHERE '+ integerId + ' = ANY(skill_id_array)';
    const membersBySkill = await this.entityManager.query(sql);
    // This works: SELECT * FROM members WHERE 2 = ANY(skill_id_array)

Edit: Also this works, although not originally because I set it up like the ‘Any’ example in Find Options in the docs. This needs to be added to the QB doc for those of us who are new to the whole server stack and learning from the docs.

const membersBySkill = await getRepository(Members)
      .createQueryBuilder()
      .where(':id = ANY (skill_id_array)', {id: integerId})
      .getMany();

I’ve tried many setups but the two in the comments below have typical errors. The problem seems to be in the .where with both IN and ANY. Select statements are from my console.log on the server. The var integerId as a value of say 2, is an integer and skill_id_array is a column in the db with values such as {1,2,5}. There are no examples of my use in the docs or elsewhere and I suspect that this setup doesn’t work in TypeORM yet or is a bug.

   const membersBySkill = await getRepository(Members)
      .createQueryBuilder()
      // .select('*') Do not use here. QB needs the entire selection per @pleerock in comments below.
      .where(':id IN (skill_id_array)', {id: integerId})
      .getMany();
   console.log('membersBySkill: ', membersBySkill);
   return membersBySkill;

    //  {id: '{2}'}) -> SELECT * FROM "members" "Members" WHERE $1 IN (skill_id_array) -- PARAMETERS: ["{2}"]
    //  membersBySkill =  [] empty array and no error.
    //  {id: integerId} -> SELECT * FROM "members" "Members" WHERE $1 IN (skill_id_array) -- PARAMETERS: [2]
    //  errors: malformed array literal: "2"  &  Array value must start with "{" or dimension information.

The entity:

  @Column('int', { array: true, nullable: true})
  skill_id_array: number[];

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 20 (9 by maintainers)

Commits related to this issue

Most upvoted comments

SELECT * FROM Customers WHERE Country IN (‘Germany’, ‘France’, ‘UK’);

can be translated into:

createQueryBuilder(Customer, "customer")
   .where("customer.country IN (:countries)", { countries: countries.join(", ") })
   .getMany();

or

createQueryBuilder(Customer, "customer")
   .where("customer.country IN (:...countries)", { countries: countries })
   .getMany();