Using Prisma with Encore.ts
With Prisma you make your schema changes in a Prisma schema file schema.prisma
, and then use Prisma's CLI tools to generate SQL migrations and a TypeScript ORM client.
Here is an example of using Prisma with Encore.ts. We use DB.connectionString
to supply the connection string to Prisma:
database.tsprisma/schema.prismaimport { SQLDatabase } from "encore.dev/storage/sqldb";
import { PrismaClient } from "@prisma/client";
// Define a database named 'encore_prisma_test', using the database migrations
// in the "./prisma/migrations" folder (where prisma will generate their migrations).
// Set `source` to `prisma` to let Encore know that the migrations are generated by Prisma.
const DB = new SQLDatabase('encore_prisma_test', {
migrations: {
path: './prisma/migrations',
source: 'prisma',
},
});
// Setup prisma client with connection string
const prisma = new PrismaClient({
datasources: {
db: {
url: DB.connectionString,
},
},
});
// Select all users
const allUsers = prisma.user.findMany();
Related example
$ encore app create --example=ts/prisma
Configure Prisma
Prisma requires a "shadow database" for certain operations, essentially it's a second, temporary, database that is created and deleted automatically. Encore comes with built-in support for shadow databases, and by configuring Prisma to operate on Encore's shadow database, Encore.ts and Prisma won't interfere with each other. You can then use the Prisma CLI to generate migrations and the ORM client. Encore will take care of applying the migrations both in production and locally.
First add the prisma to your project by running:
npm install prisma --save-dev
To get the shadow db connection url to Encore.ts shadow database, run:
encore db conn-uri <database name> --shadow
To initialize Prisma, run the following command from within your service folder:
npx prisma init --url <shadow db connection url>
To be able to deploy your app via Encore Cloud, you also need to configure a postinstall hook in your package.json
that runs npx prisma generate
, e.g:
{
"scripts": {
"postinstall": "npx prisma generate --schema=users/prisma/schema.prisma"
}
}
You also need to configure binaryTargets
in schema.prisma
like this:
generator client {
provider = "prisma-client-js"
binaryTargets = ["native", "debian-openssl-3.0.x"]
}
Generate migrations
Run npx prisma migrate dev
in the same directory as you ran the init (where the prisma folder exist).
This will create new migrations if you have made any changes to the schema.prisma
file.
Migration
The migration files will be automatically applied by Encore, both locally (when you run encore run
) and in cloud environments.