iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🧩

Is the Era of Hand-writing Types for Raw SQL Over? Prisma's New "TypedSQL"

に公開1件

Handling Raw SQL with $queryRaw

Prisma is an ORM library for TypeScript. Prisma provides an intuitive and type-safe API and is often the first library mentioned when discussing ORMs for TypeScript.

However, even with the popular Prisma, there are cases where the SQL generated under the hood is a bit peculiar or where the desired SQL cannot be achieved through Prisma's API.

For such cases, a method called $queryRaw is provided, allowing you to write raw SQL and receive the results. This is a common feature in other ORMs as well.

For example, it can be implemented as follows:

const users = await prisma.$queryRaw`
  SELECT id, name FROM "Users" WHERE id = ${userID}
`;
console.log(users) // [{ id: 1, name: "taro" }, { id: 2, name: "jiro" }]

However, there is a challenge when handling this in TypeScript: types.
Unfortunately, the type of users, where the result of $queryRaw is stored, becomes unknown.

Therefore, with $queryRaw, you need to specify the type of the returning records using Generics as shown below.

const users = await prisma.$queryRaw<{ id: number; name: string }[]>`
  SELECT id, name FROM "Users" WHERE id = ${userID}
`;

This adds a type to users.
However, writing types manually every time is tedious, and there is no guarantee that records will actually be returned with that type in the first place. It feels the same as using as.

In light of this, I'd like to introduce a wonderful new feature that Prisma released a few hours ago to solve this problem.

Prisma's New Feature: "TypedSQL"

Starting with Prisma 5.19, a feature called "TypedSQL" has been implemented as a Preview Feature. Roughly speaking, as the name suggests, it is a feature that automatically adds types to raw SQL.

https://www.prisma.io/blog/announcing-typedsql-make-your-raw-sql-queries-type-safe-with-prisma-orm

How It Works (Roughly)

Prisma provides a type-safe API, but this is achieved by pre-generating TypeScript type definitions from schema.prisma, written in a proprietary DSL, and referencing them. The command to generate these type definitions is prisma generate.

TypedSQL is realized through a similar mechanism. By writing the SQL you want to type in advance and running prisma generate --sql, TypeScript type definition files corresponding to the SQL are generated, and by using them during implementation, raw SQL also gets typed.

By the way, the process of extracting type information from this SQL seems to be implemented by a Rust-based component called prisma-engine.

Give it a try

1. Adding previewFeature

Since TypedSQL is currently a Preview Feature, add typedSql as a previewFeature in the generator client block of your schema.prisma.

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["typedSql"]
}

2. Placing arbitrary SQL files in sql/

Create a sql directory in the directory where schema.prisma is located, and create any .sql file under it. For example, if you place a file named sql/listPostsWithAuthor.sql, you can implement the following SQL:

Schema definition to be used

Assume the following is defined in schema.prisma.

schema.prisma
model User {
  id       Int     @id @default(autoincrement())
  name     String

  posts Post[]
}

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int
}
listPostsWithAuthor.sql
SELECT
    p.id,
    p.title,
    p.content,
    u.id as "authorId",
    u.name as "authorName"
FROM "Post" as p
    INNER JOIN "User" as u ON u.id = p."authorId"
WHERE u.id = $1;

3. Run generate

Execute the following:

prisma generate --sql

This generates code in node_modules/.prisma/client/sql.

4. Using $queryRawTyped

Call the code generated in step 3 using the newly implemented $queryRawTyped method.

import { listPostsWithAuthor } from "@prisma/client/sql"

const userId = 1;
const users = await prisma.$queryRawTyped(listPostsWithAuthor(userId));

As you can see, code corresponding to listPostsWithAuthor.sql has been generated as listPostsWithAuthor. Also, because this SQL includes a parameter u.id = $1, listPostsWithAuthor has a signature that takes a number as an argument.
And users is properly typed.

This shows that raw SQL can be handled in a type-safe manner.

By the way, prisma generate --sql generated a type definition file like the following:

listPostsWithAuthor.d.ts
import * as $runtime from "@prisma/client/runtime/library"

/**
 * @param int4
 */
export const listPostsWithAuthor: (int4: number) => $runtime.TypedSql<listPostsWithAuthor.Parameters, listPostsWithAuthor.Result>

export namespace listPostsWithAuthor {
  export type Parameters = [int4: number]
  export type Result = {
    id: number
    title: string
    content: string | null
    authorId: number
    authorName: string
  }
}

Supported Column Types

There is currently no documentation, but the following test code shows the supported types:
https://github.com/prisma/prisma/tree/main/packages/client/tests/functional/typed-sql

Looking at PostgreSQL, it seems the coverage is quite broad, including JSONB and XML types.

Final Thoughts

TypedSQL is extremely welcome. Recently, the frequency with which I write $queryRaw has been increasing, and this was exactly the feature I was looking for. I'm not sure how long this has been in development, but I can really feel Prisma's momentum. In particular, that massive PR for Prisma Client with around 4,000 lines was impressive (to put it simply).
https://github.com/prisma/prisma/pull/24907

Prisma's TypedSQL seems to have a similar concept to Go's sqlc. However, while sqlc calls an actual PostgreSQL parser to get type information, Prisma seems to differ in that it interacts with the actual database to retrieve type information.

Also, I personally feel that the world of TypeScript ORM libraries is in a "Warring States period." Prisma currently has a lead, but new ORMs and query builders with different concepts, like Drizzle and Kysely, are catching up quickly. Will Prisma's TypedSQL be the catalyst that solidifies its dominance? I have high expectations for future developments.

Discussion