Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS Postgres Prisma - Error type 'string' is not assignable to parameter type 'TemplateStringsArray | Sql'

I'm trying to build a NestJS Monorepo service using Microservices architecture with PostgreSQL as a database, Prisma as ORM and TypeScript as primary language. But I keep getting the error below when I try executing a Postgres query.

src/infrastructure/persistence/work.repository.postgres.ts:188:7 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'TemplateStringsArray | Sql'.

I checked the data types and they seem to be compatible.

Please help me fix this.

Stack: TypeScript, PostgreSQL, Node.JS, Express and NestJS.

Thanks in advance!

  async findWriterNumber(writerAddress: string): Promise<number> {
    const maxNumber = await this.prismaService.$queryRaw<{
      max: number;
    }>(
      `SELECT coalesce(max('writerNumber') + 1, 0) as max
       FROM "Work"
                LEFT OUTER JOIN "WriterID"
                                ON "Work"."id" = "WorkID"."workId" AND "WorkID"."address" = '${writerAddress}'`,
    );
    return maxNumber[0].max;
  }
like image 584
Vakindu Avatar asked Jul 25 '26 02:07

Vakindu


2 Answers

Found a Simple Fix:

Remove ( ) around the sql statement.


async findWriterNumber(writerAddress: string): Promise<number> {
    const maxNumber = await this.prismaService.$queryRaw<{
      max: number;
    }>
      `SELECT coalesce(max('writerNumber') + 1, 0) as max
       FROM "Work"
                LEFT OUTER JOIN "WriterID"
                                ON "Work"."id" = "WorkID"."workId" AND "WorkID"."address" = '${writerAddress}'`;
    return maxNumber[0].max;
  }

A prepared statement will translate the query to "select coalesce ... from work where ... address=$1" and send along $1 as a parameter - so you don't need wrap it around quotations.

like image 161
Vakindu Avatar answered Jul 27 '26 11:07

Vakindu


Another solution is to use the Prisma.sql helper:

const maxNumber = await this.prismaService.$queryRaw<{ max: number; }>(
  Prisma.sql`SELECT coalesce(max('writerNumber') + 1, 0) as max
   FROM "Work"
   LEFT OUTER JOIN "WriterID"
   ON "Work"."id" = "WorkID"."workId"
   AND "WorkID"."address" = '${writerAddress}'`,
);
return maxNumber[0].max;
like image 22
Joulukuusi Avatar answered Jul 27 '26 09:07

Joulukuusi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!