I want to use an ORM so that it can handle optimization and provide nice abstractions
So I started learning Prisma, but every time I want to do something just little involved I end up needing to write a raw query for it.
for example, how can I write this without using the raw query:
const rawResults = await db.$queryRaw`
select
age,
round(avg(todep), 2) as avg_phq9,
round(avg(tosc), 2) as avg_scs,
round(avg(toas), 2) as avg_asiss,
round(avg(todep + tosc + toas), 2) as total_score
from students
where inter_dom = 'Inter'
group by age
order by total_score desc
`;I don't want to waste time learning other stuff, I just wanna know is that normal for you guys to use raw queries so often with Prisma.
does Drizzle solve this problem?
I'm aware of the extends and query extensions... if $extends is capable of doing aggregate and all that could be nice.
Raw query in Prisma Query Console - Stack Overflow
Queryraw condition joining
Type error in `IN` clause in postgreSQL using `$queryRaw` when upgrading to v4
postgresql - Prisma $queryRaw with variable length parameter list - Stack Overflow
RTFM: https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access#tagged-template-helpers
import { Prisma } from "@prisma/client";
const ids = [1, 3, 5, 10, 20];
const result = await prisma.$queryRaw`SELECT * FROM User WHERE id IN (${Prisma.join(
ids
)})`;
As @MichaelDausmann has mentioned above, there is a Prisma function that joins array items and formats the SQL by the types of parameters. But when you use uuid type, Prisma's join function formats the parameters adding double apostrophe. So you can take error like 'type mismatch' in PostreSQL. Alternatively, you can use native Array.join function to build a sql string and send it to Prisma raw query function using Prisma.raw function.
const sql = `select * from table where id in (${idArray.map(v => `'${v}'::uuid`).join(",")})`
result = await prisma.$queryRaw(Prisma.raw(sql))