diff --git a/README.md b/README.md index 1f7a531..576a8ae 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/prisma/execute-a-raw-sql-query.md b/prisma/execute-a-raw-sql-query.md new file mode 100644 index 0000000..fa75fca --- /dev/null +++ b/prisma/execute-a-raw-sql-query.md @@ -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 = 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)