Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add example showcasing Prisma ORM with Turso database #7497

Merged
merged 3 commits into from
Feb 7, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions databases/turso/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
# Keep environment variables out of version control
.env
76 changes: 76 additions & 0 deletions databases/turso/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Prisma with Turso Example

This example demonstrates how to use [Prisma ORM](https://www.prisma.io/) with [Turso](https://turso.tech/), a distributed database based on libSQL. The project showcases how to perform CRUD operations using [Prisma Client](https://www.prisma.io/docs/orm/prisma-client) in a **Node.js script**.

## How to use

### 1. Download example and navigate into the project directory

Download this example:

```
npx try-prisma@latest --template databases/turso-prisma-example
ankur-arch marked this conversation as resolved.
Show resolved Hide resolved
```

Then, navigate into the project directory:

```
cd turso-prisma-example
ankur-arch marked this conversation as resolved.
Show resolved Hide resolved
```

<details><summary><strong>Alternative:</strong> Clone the entire repo</summary>

Clone this repository:

```
git clone git@github.com:prisma/prisma-examples.git --depth=1
```

### 2. Install npm dependencies:

```
cd prisma-examples/databases/turso-prisma-example
ankur-arch marked this conversation as resolved.
Show resolved Hide resolved
npm install
```

</details>

### 3. Configure the database connection
Create a .env file in the root of the project and add your Turso credentials:
```sh
touch .env
```
If you don't have an existing database, you can provision a database by running the following command:
```sh
turso db create turso-prisma-db
```
The above command will create a database in the closest region to your location.

Run the following command to retrieve your database's connection string:
```sh
turso db show turso-prisma-db
```
Next, create an authentication token that will allow you to connect to the database:
```sh
turso db tokens create turso-prisma-db
```
Update your .env file with the authentication token and connection string:
```sh
TURSO_DATABASE_URL="your_turso_database_url"
TURSO_AUTH_TOKEN="your_turso_auth_token"
```
You can learn more from the [Prisma Turso documentation](https://www.prisma.io/docs/orm/overview/databases/turso#what-is-turso)

### 4. Generate Prisma Client
```sh
npx prisma generate
```
### 5. Run the script
Execute the script to create, retrieve, update, and delete data:
```sh
npm run dev
```
### 6. Understanding the project structure
- `prisma/schema.prisma`: Defines the database schema for Users and Posts.
- `src/script.ts`: A script demonstrating CRUD operations using Prisma Client.
- `.env`: Stores environment variables for database credentials.
24 changes: 24 additions & 0 deletions databases/turso/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "turso",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"dev": "ts-node src/script.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"@types/node": "^22.13.1",
"prisma": "^6.3.1",
"ts-node": "^10.9.2",
"typescript": "^5.7.3"
},
"dependencies": {
"@libsql/client": "^0.8.1",
"@prisma/adapter-libsql": "^6.3.1",
"@prisma/client": "^6.3.1",
"dotenv": "^16.4.7"
}
}
34 changes: 34 additions & 0 deletions databases/turso/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init

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

datasource db {
provider = "sqlite"
url = "file:./dev.db"
}

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}

model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
content String?
published Boolean @default(false)
viewCount Int @default(0)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}
95 changes: 95 additions & 0 deletions databases/turso/src/script.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
require('dotenv').config()
import { PrismaClient } from '@prisma/client'
import { PrismaLibSQL } from '@prisma/adapter-libsql'
import { createClient } from '@libsql/client'


const libsql = createClient({
url: `${process.env.TURSO_DATABASE_URL}`,
authToken: `${process.env.TURSO_AUTH_TOKEN}`,
})

const adapter = new PrismaLibSQL(libsql)
const prisma = new PrismaClient({ adapter })

async function main() {
// create user
const user = await prisma.user.create({
data: {
email: 'hana@hana.io',
name: 'Hana',
},
})

console.log(user)

// find user
const foundUser = await prisma.user.findUnique({
where: {
email: 'hana@hana.io'
}
})
console.log(foundUser)

// update user
const updatedUser = await prisma.user.update({
where: {
email: 'hana@hana.io',
},
data: {
name: 'Peters',
},
})
console.log(updatedUser)

// delete user
const deleteUser = await prisma.user.delete({
where: {
email: 'hana@hana.io',
}
})
console.log("User deleted", deleteUser)

// create user with posts
const userPosts = await prisma.user.create({
data: {
email: 'dave@prisma.io',
name: 'David',
posts: {
create: [
{ title: 'Hello world' },
{ title: 'Introduction to Prisma with Mongo' },
{ title: 'MongoDB and schemas' },
],
},
},
include: {
posts: true,
},
})

console.dir(userPosts, { depth: Infinity })

// find posts
const posts = await prisma.post.findMany({
include: {
author: true,
},
orderBy: {
createdAt: 'desc',
},
})

console.dir(posts, { depth: Infinity })
}




main()
.catch(e => {
throw e
})
.finally(async () => {
await prisma.$disconnect()
})
12 changes: 12 additions & 0 deletions databases/turso/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"sourceMap": true,
"outDir": "dist",
"strict": true,
"lib": [
"esnext",
"dom"
],
"esModuleInterop": true
}
}