question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

QueryBuilder IN and ANY Fail with .where - Postgres

See original GitHub issue

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[];

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:20 (9 by maintainers)

github_iconTop GitHub Comments

4reactions
pleerockcommented, Jun 8, 2018

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();
0reactions
jmprestoncommented, Jun 12, 2018

Thank you for your help! I think QB is more than a wrapper because I can’t use .select * with it in my query because somewhere in the black box of QB it does something different than SQL. This is the kind of mystery that newbies spot quickly and get confused. It eats a lot of time.

IN may work in QB but it is a lot of work. This from my SO post on this topic:

https://stackoverflow.com/questions/50705276/typeorm-postgres-where-any-or-in-with-querybuilder-or-find/50745182#50745182

The issue is you can't use a variable with IN like you can with ANY. It will never work. 
It requires a 'list of scalars' instead of an expression is how the docs put it. 
My var contained a list of scalars but the IN param must have a list, not a
 reference to a list.

IN (id1, id2, id5) should work and you need to populate those vars elsewhere with 
either integers or strings. For my app that means parsing my skill_id_array and 
assigning the individual integers to their own unique vars. 
This is a lot of work when ANY will easily accomplish the same result.
Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeORM Postgres WHERE ANY or IN With QueryBuilder Or ...
I'm new at all this but I believe I want an SQL statement that looks like this: SELECT * FROM members WHERE 2...
Read more >
Select using Query Builder - typeorm - GitBook
You can combine as many AND and OR expressions as you need. If you use .where more than once you'll override all previous...
Read more >
Knex Query Builder
The query builder starts off either by specifying a tableName you wish to query against, or by calling any method directly on the...
Read more >
TypeORM - Amazing ORM for TypeScript and JavaScript (ES7 ...
Select using Query Builder · Insert using Query Builder · Update using Query Builder · Delete using Query Builder · Working with Relations...
Read more >
Usage with MySQL, MariaDB, PostgreSQL or SQLite
When you need to execute some SQL query without all the ORM stuff ... leftJoin(field: string, alias?: string): QueryBuilder; QueryBuilder.where(cond: any, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found