Search code examples
sqlnestjsquery-buildertypeorm

Typeorm getManager().query() works only if pass hardcoded SQL query string not variables


I try to make SQL requests from the server using Typeform and getManager().query(), passing to query string with SQL.

  1. Working example from MySqlWorkbench screenshot https://prnt.sc/uad3tu and code snippet. If I copy and paste it to the code, it works just fine
    SELECT `Event`.*, `Repeats`.`start_event_at`, `Repeats`.`end_event_at`
    FROM `events` `Event` 
    LEFT JOIN `event_repeats` `Repeats` on `Repeats`.`eventId` = `Event`.`id`
    WHERE `Event`.`category` = 'fitness' 
    AND `Repeats`.`end_event_at` >= '2020-09-02T14:59:00.000Z'
  1. But if I use variables in an interpolated string it throws an error, screenshot https://prnt.sc/uad5zy and
    SELECT `Event`.*, `Repeats`.`start_event_at`, `Repeats`.`end_event_at`
    FROM `events` `Event` 
    LEFT JOIN `event_repeats` `Repeats` on `Repeats`.`eventId` = `Event`.`id`
    WHERE `Event`.`category` = ${category} 
    AND `Repeats`.`end_event_at` >= '2020-09-02T14:59:00.000Z'

Thrown error: https://prnt.sc/uad6zs

What I do wrong and how to manage it?


Solution

  • When using query method use underlying driver escaping mechanism. For mysql:

    await getEntityManager().query('SELECT * FROM tbl_1 WHERE category = ?', [ 'fitness' ])