iTranslated by AI

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

TypedSQL is useful, but the requirement for a DB connection at build time was a challenge

に公開
2026/02/09

Introduction

I've been using Prisma for quite a while now, but when it comes to things like aggregation screens, I inevitably need to send complex queries and often end up using $queryRaw with a heavy heart.

However, I recently came across the following article:
https://zenn.dev/tockn/articles/0e6eac6220e072

I started using it, thinking how convenient it was, but I got stuck during the build process and gave up on using it for a long time. However, I've managed to solve it this time, so I'm writing this article. It was a challenge involving a lot of trial and error, but in the end, the solution was quite simple.

Prerequisites

There was a project with the following structure:

  • Monorepo configuration (for simplicity, let's assume two: packages/cdk and packages/server)
    • packages/server was Next.js, but that's not very relevant to the main point
  • By deploying packages/cdk, packages/server is deployed as a container to AWS ECS
  • Therefore, packages/server is built using a Dockerfile
  • CDK uses DockerImageAsset

Code Example

First is the Dockerfile. It's quite simplified, but it runs prisma generate, builds Next.js, and starts it.
Since I want to use TypedSQL, I'm running yarn prisma generate --sql.

packages/server/Dockerfile
FROM public.ecr.aws/docker/library/node:lts-slim

# ...Omitted, but various apt-get installs and setting the working directory

# Prisma-related processing
RUN yarn prisma generate
# Generate TypedSQL
RUN yarn prisma generate --sql

# Build the application
RUN yarn build

# Port settings
EXPOSE 3000

# Startup
CMD ["yarn", "start"]

Next is the CDK. After building the container by pointing to the aforementioned Dockerfile path, it adds it to the task definition.

import { DockerImageAsset } from "aws-cdk-lib/aws-ecr-assets";

// ...omitted

const taskDef; // Task definition (creation part omitted)

// Build container image
const nextjsImage = new DockerImageAsset(this, "NextjsImage", {
  directory: "Path to the previous Dockerfile",
  buildArgs: {
    // Various environment variables needed during build
  },
});

// Add container to task definition
const container = taskDef.addContainer("NextjsContainer", {
  // Specify the image built above
  image: ContainerImage.fromDockerImageAsset(nextjsImage),
  logging: LogDrivers.awsLogs({ streamPrefix: "Nextjs" }),
  environment: {
    // DB connection is configured here because it happens after deployment to ECS, not during build
    DATABASE_URL: "Connection info for the RDS created with CDK",
  },
  command: [
    "sh",
    "-c",
    "yarn start",
  ],
});

What Happened

By adding yarn prisma generate --sql to the Dockerfile, the following error occurs during CDK deployment:

error: Environment variable not found: DATABASE_URL.
  -->  prisma/schema.prisma:16
| 
|   provider   = "postgresql"
|   url        = env("DATABASE_URL")

This happens because the DATABASE_URL specified in schema.prisma cannot be referenced.

Supplement: About DockerImageAsset

Regarding the DockerImageAsset used earlier, it deploys the container image before the CDK deployment (CloudFormation stack deployment). Therefore, the processing order is:

  1. Build the container image based on the Dockerfile on the process where cdk deploy was executed.
  2. Deploy according to the CDK descriptions.

Consequently, there is a painful constraint that you cannot include "values that aren't determined until CDK is deployed (e.g., resource ARNs)" in the buildArgs of DockerImageAsset.

Cause of the Error

Since DATABASE_URL is also connection information for the RDS created by CDK, it cannot be referenced during the build. However, this error does not occur when not using TypedSQL.

This is because prisma generate only references the schema rather than the actual DB, whereas prisma generate --sql requires a DB connection.
This is also mentioned in the official documentation:
https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/typedsql#active-database-connection-required

TypedSQL requires an active database connection to function properly.
This means you need to have a running database instance that Prisma can connect to when generating the client with the --sql flag.
If a directUrl is provided in your Prisma configuration, TypedSQL will use that for the connection.

In short, when using prisma generate --sql, a DB that can be referenced from that process must be available.
In this case, that would be the RDS, but since most RDS instances are placed within a private subnet in a VPC, they likely cannot be accessed from the build process.
Furthermore, in the case of the very first CDK deployment, the RDS probably hasn't even been created yet.

Solution: Create a dummy DB and have it referenced

In other words, "it's sufficient if a DB connection can be established only during the execution of prisma generate --sql. A dummy DB is also acceptable." So, I took that approach.

If you are performing the CDK deployment locally, starting a DB on localhost and referencing it is fine. If you are using GitHub Actions or similar, you can start a DB temporarily using services in the YAML file.

With that in mind, the previous Dockerfile and CDK have changed as follows:

packages/server/Dockerfile
FROM public.ecr.aws/docker/library/node:lts-slim

# ...Omitted, but various apt-get installs and setting the working directory

# Connection info for the dummy DB
ARG DATABASE_URL

# Prisma-related processing
RUN yarn prisma generate
# Since a temporary DB connection is required when using TypedSQL, run the migration on the dummy DB
RUN DATABASE_URL=$DATABASE_URL yarn prisma migrate deploy
# Generate TypedSQL
RUN DATABASE_URL=$DATABASE_URL yarn prisma generate --sql

# Build the application
RUN yarn build

# Port settings
EXPOSE 3000

# Startup
CMD ["yarn", "start"]
import { DockerImageAsset, NetworkMode } from "aws-cdk-lib/aws-ecr-assets";

// ...omitted

// Build container image
const nextjsImage = new DockerImageAsset(this, "NextjsImage", {
  directory: "Path to the previous Dockerfile",
  buildArgs: {
    // Temporarily pass dummy DB connection info
    DATABASE_URL: process.env.DATABASE_URL!,
  },
  // Use host networking to connect to the dummy DB on the host (build process) during build
  networkMode: NetworkMode.HOST,
});

// ...omitted

In the Dockerfile, environment variables are set within the RUN command to use those values temporarily.
In the CDK, the networkMode of DockerImageAsset is set to the host, allowing connection to the dummy DB residing on the host (the build process).
Then, you just need to either set the environment variable or specify it as a command-line argument during cdk deploy.

Summary

Prisma is one of my favorite ORMs for its ease of use, but when complex logic is involved, writing SQL is unavoidable.
In such cases, I previously had to use $queryRaw with a heavy heart and accept that the execution result would be any, but TypedSQL has greatly improved the situation.

However, the side effect appeared during the build and deployment phases, and since I couldn't find a specific solution even after searching online, I decided to write this article.

I hope this information is helpful.

Discussion