This example shows how to use the TypedSQL feature of Prisma ORM in a TypeScript project. TypedSQL allows you to write fully type-safe SQL queries and then run them via Prisma Client.
Download this example:
npx try-prisma@latest --template orm/typedsql --install npm --name typedsql
Then, navigate into the project directory:
cd typedsql
Alternative: Clone the entire repo
Clone this repository:
git clone git@github.com:prisma/prisma-examples.git --depth=1
Install npm dependencies:
cd prisma-examples/orm/typedsql
npm install
Run the following command to create your SQLite database file. This also creates the User
and Post
tables that are defined in prisma/schema.prisma
:
npx prisma migrate dev --name init
When npx prisma migrate dev
is executed against a newly created database, seeding is also triggered. The seed file in prisma/seed.ts
will be executed and your database will be populated with the sample data.
npx prisma generate --sql
This command runs prisma generate --sql
, which will generate the Prisma Client and also check any SQL files in the prisma/sql
directory. After type-checking the SQL files, they are compiled into JavaScript and added to the Prisma Client.
Tip
This also works with the --watch
flag! If you want to automatically generate and watch for changes, you can use npx prisma generate --sql --watch
.
npm run dev
This command will run index.ts
, which will execute the SQL query defined in prisma/sql/conversionByVariant.sql
and print the results to the console.
This example project is structured similarly to the starter example with a key difference:
prisma/sql/
: Contains SQL query files that are type-checked by Prisma and then included in the generated Prisma Client.prisma/sql/conversionByVariant.sql
: Example SQL query used in the project.
Key areas to look at:
- Database schema:
prisma/schema.prisma
- Example SQL query:
prisma/sql/conversionByVariant.sql
- Query execution:
src/index.ts
- Data seeding:
prisma/seed.ts
- Build and run scripts:
package.json
- Check out the Prisma docs
- Join our community on Discord to share feedback and interact with other users.
- Subscribe to our YouTube channel for live demos and video tutorials.
- Follow us on X for the latest updates.
- Report issues or ask questions on GitHub.