Database

Database setup with Prisma ORM and multiple provider options

Installation

1

Install the Package

Add Database to your project using the Codelesskit CLI:

pnpm dlx codelesskit@latest add db
2

Set Environment Variables

Create a `.env` file in the root of your project and add the following environment variables. For detailed setup instructions, see how to create a database.

.env
1
2
3
4
5
6
7
8
# Database Configuration
DATABASE_URL="postgresql://user:password@localhost:5432/dbname"
 
# Database connection pool
DATABASE_POOL_SIZE=10
DATABASE_POOL_TIMEOUT=20
 
# Update DATABASE_URL with your actual database connection string

File Tree

The following files are installed when you add Database:

File Structure
1
2
3
4
5
6
7
8
9
├─ lib/
│ └─ db/
│ ├─ index.ts
│ ├─ utils.ts
│ └─ config.ts
├─ prisma/
│ ├─ schema.prisma
│ └─ seed.ts
└─ prisma.config.ts

Usage

Once you've installed Database, you can start using the following actions:

Adding a Model

Add a new model to your Prisma schema. Here's an example of adding a Book model:

prisma/schema.prisma
1
2
3
4
5
6
7
8
model Book {
id String @id @default(cuid())
title String
author String
published Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

Format, Generate, and Push Changes

After adding or modifying models in your schema, you need to format, generate the Prisma client, and push changes to your database. For more information, check out the Prisma documentation.

Terminal
1
2
3
4
5
6
7
8
# Format your Prisma schema
npx prisma format
 
# Generate Prisma Client
npx prisma generate
 
# Push schema changes to your database
npx prisma db push

Querying Data

Use the Prisma client to query your database. Here's an example of querying books:

lib/example.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { db } from '@/lib/db'
 
// Get all books
const books = await db.book.findMany()
 
// Get a book by ID
const book = await db.book.findUnique({
where: { id: 'book-id' }
})
 
// Create a new book
const newBook = await db.book.create({
data: {
title: 'The Great Gatsby',
author: 'F. Scott Fitzgerald',
published: true
}
})
 
// Update a book
const updatedBook = await db.book.update({
where: { id: 'book-id' },
data: { published: true }
})
 
// Delete a book
await db.book.delete({
where: { id: 'book-id' }
})

References

For more information about Database, check out these resources:

Create Database Guide
Step-by-step instructions for setting up PostgreSQL, MySQL, or MongoDB databases for your project.
Prisma Documentation
Complete documentation for Prisma ORM, including schema definition, queries, and migrations.
Database | Codelesskit