Skip to content

Commit 62accfc

Browse files
committed
Add Execute A Raw SQL Query as a Prisma TIL
1 parent 20096fb commit 62accfc

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1206 TILs and counting..._
13+
_1207 TILs and counting..._
1414

1515
---
1616

@@ -682,6 +682,7 @@ _1206 TILs and counting..._
682682

683683
### Prisma
684684

685+
- [Execute A Raw SQL Query](prisma/execute-a-raw-sql-query.md)
685686
- [Grab A Limited Set Of Records](prisma/grab-a-limited-set-of-records.md)
686687

687688
### Python

prisma/execute-a-raw-sql-query.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Execute A Raw SQL Query
2+
3+
[Prisma](https://www.prisma.io/) with TypeScript acts as a powerful
4+
[ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) for
5+
interacting with your database. However, not every kind of query that you may
6+
need can be represented with the API generated from your schema. For instance,
7+
certain tables might be ignored in your `prisma.schema` file. Or you may want
8+
to hand-craft a query for performance or ergonomics reasons.
9+
10+
Like any good ORM, Prisma provides an escape hatch for this kind of situation
11+
with the
12+
[`$queryRaw`](https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access#queryraw)
13+
tag function.
14+
15+
```typescript
16+
function getExpiresIn({ email }) {
17+
const prisma = new PrismaClient()
18+
19+
const result: Array<object> = await prisma.$queryRaw`
20+
select
21+
id,
22+
code,
23+
date_trunc('days', expires_at - now())::varchar as expires_in
24+
from tickets
25+
where email = ${email}
26+
`
27+
28+
// result
29+
// => [{ id: 123, code: 'abc123', expires_in: '3 days' }]
30+
31+
return result
32+
}
33+
```
34+
35+
This runs the raw SQL in the template literal against the database. The result
36+
is returned as an array of objects with key-value pairs for each selected
37+
value.
38+
39+
Writing the SQL query myself, in this case, means I can take advantage of
40+
database (Postgres) specific features (e.g.
41+
[`date_trunc`](https://www.postgresqltutorial.com/postgresql-date-functions/postgresql-date_trunc/)
42+
and [interval
43+
math](https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-interval/)).
44+
45+
[source](https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access)

0 commit comments

Comments
 (0)