1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 15:18:01 +00:00

Add Execute A Raw SQL Query as a Prisma TIL

This commit is contained in:
jbranchaud
2022-05-27 11:01:48 -06:00
parent 20096fb81e
commit 62accfcd93
2 changed files with 47 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1206 TILs and counting..._
_1207 TILs and counting..._
---
@@ -682,6 +682,7 @@ _1206 TILs and counting..._
### Prisma
- [Execute A Raw SQL Query](prisma/execute-a-raw-sql-query.md)
- [Grab A Limited Set Of Records](prisma/grab-a-limited-set-of-records.md)
### Python

View File

@@ -0,0 +1,45 @@
# Execute A Raw SQL Query
[Prisma](https://www.prisma.io/) with TypeScript acts as a powerful
[ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) for
interacting with your database. However, not every kind of query that you may
need can be represented with the API generated from your schema. For instance,
certain tables might be ignored in your `prisma.schema` file. Or you may want
to hand-craft a query for performance or ergonomics reasons.
Like any good ORM, Prisma provides an escape hatch for this kind of situation
with the
[`$queryRaw`](https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access#queryraw)
tag function.
```typescript
function getExpiresIn({ email }) {
const prisma = new PrismaClient()
const result: Array<object> = await prisma.$queryRaw`
select
id,
code,
date_trunc('days', expires_at - now())::varchar as expires_in
from tickets
where email = ${email}
`
// result
// => [{ id: 123, code: 'abc123', expires_in: '3 days' }]
return result
}
```
This runs the raw SQL in the template literal against the database. The result
is returned as an array of objects with key-value pairs for each selected
value.
Writing the SQL query myself, in this case, means I can take advantage of
database (Postgres) specific features (e.g.
[`date_trunc`](https://www.postgresqltutorial.com/postgresql-date-functions/postgresql-date_trunc/)
and [interval
math](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-interval/)).
[source](https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access)