Skip to content

find with multiple WHERE clauses where one is invalid generates invalid SQL #6465

@JaffParker

Description

@JaffParker

Issue type:

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

Database system/driver:

[ ] cordova
[ ] mongodb
[ ] mssql
[X] mysql / mariadb
[ ] oracle
[ ] postgres
[ ] cockroachdb
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo

TypeORM version:

[ ] latest
[ ] @next
[X] 0.2.22 (or put your version here)

Hiding first case as it's a duplicate of #2195

CASE 1:

Suppose you have an array of IDs and you want to fetch entries with those IDs. Array can be empty sometimes due to your app's logic. Code sample:

// it can contain IDs or be empty, need to be empty for this demo
const arr = []
const entries = await repo.find({ id: In(arr) })

With debug logging enabled this is the query you will see:

SELECT * FROM `table` WHERE `id` IN ();

... which will fail due to syntax error.

CASE 2:

You have a table for which users might submit a search string. That string needs to be matched against the fields amount: number and customerSummary: { name: string }. Because the Like filter is always considered a string, we start getting TS errors about wrong types, which forces us to add a bunch of //@ts-ignore like this:

const searchString = 'blah'
const entries = await repo.find({
  where: [
    {
      //@ts-ignore
      amount: Like(`%${searchString}%`),
    },
    {
      //@ts-ignore
      customerSummary: Like(`%name":"${searchString}%`),
    },
    {
      note: Like(`%${searchString}%`),
    }
  ]
})

This would produce a query:

SELECT * FROM `table` WHERE (`amount` LIKE '%searchString%') OR (`customerSummary` LIKE '%name":"searchString%') OR (`note` LIKE '%searchString%');

All good, But! If you make a typo in let's say, customerSumary, Typescript will not tell you since you had to tell it to ignore types on that line. In that case instead of TypeORM throwing an error (ideally) or at least ignoring the condition, you get a query like this:

SELECT * FROM `table` WHERE (`amount` LIKE '%searchString%') OR () OR (`note` LIKE '%searchString%');

So obviously this is a syntax error. Interstingly, it does obviously check for field validity, but doesn't bother letting me know instead just omitting it.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions