|
| 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