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.

String template not working in $queryRaw with postgres

See original GitHub issue

Bug description

String template variable triggers an error in my raw postgres query. When the I dont use a variable, but instead hardcode the value the query is completed sucessfully

How to reproduce

This is my query

const tableName = openaddressesma;
const radiusSearch = await prisma.$queryRaw`SELECT postcode FROM ${tableName} where ST_Distance(geolocation::geography, ST_SetSRID(ST_MakePoint(${parseFloat(
          long
        )},${parseFloat(lat)}),4326)::geography) < ${
          parseFloat(miles) * 1609.34
        };`; 

The above query fails and gives the error:

Invalid prisma.queryRaw() invocation: Raw query failed. Code: 42601. Message: db error: ERROR: syntax error at or near "$1"

But It succeeds when I remove ${tableName} from the query and replace it with a hard code value. eg

const radiusSearch = await prisma.$queryRaw`SELECT postcode FROM openaddressesma where ST_Distance(geolocation::geography, ST_SetSRID(ST_MakePoint(${parseFloat(
          long
        )},${parseFloat(lat)}),4326)::geography) < ${
          parseFloat(miles) * 1609.34
        };`;

Expected behavior

I expect The query to complete and return results from the database.

Prisma information

Environment & setup

  • OS: ubuntu 18.0.1
  • Database: PostgreSQL
  • Node.js version: v14.5.0
  • Prisma version: Prisma CLI version: prisma/1.34.10 (linux-x64) node-v14.5.0

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:9
  • Comments:13 (9 by maintainers)

github_iconTop GitHub Comments

9reactions
pantharshit00commented, Apr 16, 2021

@alexpmay you need to do the following:

const dbResult = await prisma.$queryRaw`select name from tenant where name=${name}`;

Since this will use a prepared statement it will translate the query to select name from tenant where name=$1 and send along $1 as a parameter so you don’t need wrap it around quotations.

8reactions
alexpmaycommented, Apr 14, 2021

I am having this issue as well. Here is a simple example:

async function testResolver() {
      // This will crash
      const name = "Tenant 1";
      const dbResult = await prisma.$queryRaw`select name from tenant where name='${name}'`;
      
      // This runs just fine
      //const dbResult = await prisma.$queryRaw`select name from tenant where name='Tenant 1'`;

      // As does this
      const name = "Tenant 1";
      const dbResult = await prisma.$queryRaw(`select name from tenant where name='${name}'`);

      console.log(dbResult[0]);
      return dbResult;
}

The error is:

Invalid prisma.queryRaw() invocation:\n\n\n Your raw query had an incorrect number of parameters. Expected: 0, actual: 1

If you turn on prisma logging, for the non string template you get

prisma:query select name from tenant where name=‘Tenant 1’

and for the string template you get:

prisma:query select name from tenant where name=‘$1’

and with the parens around the string template

prisma:query select name from tenant where name=‘Tenant 1’ { name: ‘Tenant 1’ }

Please fix. It is a very serious issue since it makes it very hard write safe SQL. Thank you.

Read more comments on GitHub >

github_iconTop Results From Across the Web

prisma $queryRaw doesn't work with single quotes in the string
Try to use: const interval = num + ' days'; ${interval}::TEXT::INTERVAL. instead of interval '${interval} day'. This is work for me!
Read more >
Prisma queryRaw throws error when using template string ...
Hi, @chenliu9. Unfortunately, that's not a valid “Tagged template” replacement - they work when replacing items like parameters in where clauses ...
Read more >
Raw database access (Reference) - Prisma
Considerations. Be aware that: Template variables cannot be used inside SQL string literals. For example, the following query would not work:.
Read more >
Building a SQL Query from Variables with prisma.$queryRaw
While writing the sorting query, I found another fun Prisma helper. Prisma.empty returns an empty templated string, a great way to provide no ......
Read more >
15: 9.4. String Functions and Operators - PostgreSQL
text IS [ NOT ] [ form ] NORMALIZED → boolean. Checks whether the string is in the specified Unicode normalization form. The...
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