Zapełnianie bazy danych i connection pooling
Zapełnij bazę danych wiarygodnymi danymi seed oraz skonfiguruj connection pooling w Prisma, aby aplikacja Next.js pozostała szybka i stabilna pod obciążeniem.
Zapełnianie bazy danych i connection pooling to bezpłatna lekcja Next.js 15 Fullstack (App Router + Server Actions) na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Next.js 15 Fullstack (App Router + Server Actions), a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Next.js 15 Fullstack (App Router + Server Actions) zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
Why Seed a Database?
Seeding fills your database with predictable starter data: admin users, demo records, lookup tables. It lets every developer and every CI run start from the same known state.
Without seeds, manual data entry makes tests flaky and onboarding slow.
The Prisma Seed Script
Prisma runs a seed file you point it at. Create prisma/seed.ts and register it in package.json under the prisma.seed key so prisma db seed knows what to execute.
{
"prisma": {
"seed": "ts-node prisma/seed.ts"
}
}Writing Seed Logic
Inside the seed file you instantiate the client and create records. Wrap it in an async function and disconnect when finished.
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function main() {
await prisma.user.create({
data: { email: 'admin@app.com', name: 'Admin' }
});
}
main().finally(() => prisma.$disconnect());Idempotent Seeds with upsert
Running a seed twice should not create duplicates. Use upsert so a record is created if missing and updated if it already exists.
await prisma.user.upsert({
where: { email: 'admin@app.com' },
update: {},
create: { email: 'admin@app.com', name: 'Admin' }
});Bulk Seeding
To insert many rows efficiently, use createMany. The skipDuplicates option avoids errors on unique conflicts.
await prisma.tag.createMany({
data: [
{ name: 'news' },
{ name: 'sports' },
{ name: 'tech' }
],
skipDuplicates: true
});Running the Seed
Trigger the script from the CLI. Prisma also runs it automatically after prisma migrate reset, giving you a clean reseeded database.
npx prisma db seedThe Connection Problem in Serverless
Next.js on Vercel runs serverless functions. Each invocation can open a fresh DB connection, and under load you quickly exhaust the database connection limit.
Connection pooling solves this by reusing a fixed set of connections.
Reusing the Prisma Client
In development, hot reload can spawn many clients. Store a single instance on globalThis so only one client exists per process.
import { PrismaClient } from '@prisma/client';
const g = globalThis as unknown as { prisma?: PrismaClient };
export const prisma = g.prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== 'production') g.prisma = prisma;Pooling with a Connection URL
Use a pooler such as PgBouncer or Prisma Accelerate. Point your DATABASE_URL at the pooled endpoint and add ?pgbouncer=true so Prisma disables prepared statements that PgBouncer cannot share.
DATABASE_URL="postgresql://user:pass@host:6543/db?pgbouncer=true&connection_limit=1"Direct URL for Migrations
Pooled connections cannot run migrations. Add a directUrl in your schema that bypasses the pooler so prisma migrate works.
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}Best Practices
Keep your data layer healthy:
- Make seeds idempotent with upsert
- Reuse a single client instance
- Use a pooler in serverless environments
- Keep a separate direct URL for migrations
Quick Check
Test what you learned about pooling.
Recap
You learned to seed and pool your database:
- Configure
prisma.seedand write idempotent seeds withupsert - Bulk insert with
createMany - Reuse a single Prisma client to avoid leaks
- Use a pooled
DATABASE_URLplus adirectUrlfor migrations
Now your database starts in a known state and scales safely.
Często zadawane pytania
Czy lekcja „Zapełnianie bazy danych i connection pooling” jest bezpłatna?
Tak — pełny tekst „Zapełnianie bazy danych i connection pooling” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Next.js 15 Fullstack (App Router + Server Actions), przejdź na CoddyKit PRO. Kurs Next.js 15 Fullstack (App Router + Server Actions) zawiera 4 lekcji w sumie.
Co nauczysz się w „Zapełnianie bazy danych i connection pooling”?
Zapełnij bazę danych wiarygodnymi danymi seed oraz skonfiguruj connection pooling w Prisma, aby aplikacja Next.js pozostała szybka i stabilna pod obciążeniem. Ćwiczysz Next.js 15 Fullstack (App Router + Server Actions) z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Next.js 15 Fullstack (App Router + Server Actions)?
Nie wymagamy żadnego doświadczenia. Next.js 15 Fullstack (App Router + Server Actions) w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.
Ile czasu zajmuje lekcja „Zapełnianie bazy danych i connection pooling”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Next.js 15 Fullstack (App Router + Server Actions)?
Tak. Każda lekcja Next.js 15 Fullstack (App Router + Server Actions) zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Konfiguracja Prisma ORM
- Operacje CRUD z Server Actions
- Migracje schematu bazy danych
- Zapełnianie bazy danych i connection pooling