Database
Database setup with Prisma ORM and multiple provider options
Installation
Install the Package
Add Database to your project using the Codelesskit CLI:
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.
12345678# Database ConfigurationDATABASE_URL="postgresql://user:password@localhost:5432/dbname" # Database connection poolDATABASE_POOL_SIZE=10DATABASE_POOL_TIMEOUT=20 # Update DATABASE_URL with your actual database connection stringFile Tree
The following files are installed when you add Database:
123456789├─ lib/│ └─ db/│ ├─ index.ts│ ├─ utils.ts│ └─ config.ts├─ prisma/│ ├─ schema.prisma│ └─ seed.ts└─ prisma.config.tsUsage
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:
12345678model 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.
12345678# Format your Prisma schemanpx prisma format # Generate Prisma Clientnpx prisma generate # Push schema changes to your databasenpx prisma db pushQuerying Data
Use the Prisma client to query your database. Here's an example of querying books:
1234567891011121314151617181920212223242526272829import { db } from '@/lib/db' // Get all booksconst books = await db.book.findMany() // Get a book by IDconst book = await db.book.findUnique({ where: { id: 'book-id' }}) // Create a new bookconst newBook = await db.book.create({ data: { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', published: true }}) // Update a bookconst updatedBook = await db.book.update({ where: { id: 'book-id' }, data: { published: true }}) // Delete a bookawait db.book.delete({ where: { id: 'book-id' }})References
For more information about Database, check out these resources: