Having trouble with this queryRaw <example from th...
# prisma-client
m
Having trouble with this queryRaw example from the docs. I had to edit it slightly to get it to type check properly
Copy code
interface TableNameQueryResult {
  tablename: string
}
export async function truncateAllTables() {
  const qres = await prisma.$queryRaw<
    TableNameQueryResult[]
  >`SELECT tablename FROM pg_tables WHERE schemaname='public'`
  for (const { tablename } of qres) {
    if (tablename !== "_prisma_migrations") {
      // try {
      await prisma.$queryRaw`TRUNCATE TABLE "public"."${tablename}" CASCADE;`
      // } catch (error) {
      // console.log({ error })
      // }
    }
  }
}
It gives me this error:
Copy code
Invalid `prisma.queryRaw()` invocation:


      Your raw query had an incorrect number of parameters. Expected: `0`, actual: `1`.

      81 |     if (tablename !== "_prisma_migrations") {
      82 |       // try {
    > 83 |       await prisma.$queryRaw`TRUNCATE TABLE "public"."${tablename}" CASCADE;`
         |       ^
t
Had the same issue, once upgrading to prisma 3 we had to change it to something like
Copy code
async truncate() {
    for (const { tablename } of await this.$queryRaw<
      { tablename: string }[]
    >`SELECT tablename FROM pg_tables WHERE schemaname='public'`) {
      if (tablename !== '_prisma_migrations') {
        // eslint-disable-next-line no-await-in-loop
        await this.$queryRawUnsafe<void>(
          `TRUNCATE TABLE "public"."${tablename}" CASCADE;`,
        );
      }
    }
  }
so using
$queryRawUnsafe
vs
$queryRaw
m
amazing thank you! @Joël you may want to update that doc as well
also how do you use query parameters in prisma 3?
r
@Mischa 👋 Updated the doc! You would need to use
$executeRawUnsafe
for truncating tables dynamically.
👍 1
m
trying to do this
okay thanks! but how do I use
$queryRaw
with query params in prisma 3?
r
You can use query params for values, not for identifiers like column or table names. For that,
$queryRawUnsafe
is the way to go.
m
if I switch that query (no templated identifiers) to
queryRaw
and use parentheses I get the error:
r
m
sorry I meant to say I removed the ()s
r
Yes, but if you’re referencing the table name dynamically, it won’t work. Tagged template literals only take values into account and not column names. What’s the query you’re performing?
i’d rather write it using prisma API if that’s possible
r
The last part i.e. querying by interval isn’t possible directly, so you would need to stick with a raw query for now.
m
ok thx
👍 1