1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Prisma v7 + PostgreSQL(Docker)で ローカルDB構築からSeedデータ挿入までの手順

1
Posted at

AIコーディングツールに慣れてきたけど、データベース周りの基礎がまだ曖昧な方や、Prisma v7 でのセットアップ方法がわからない方に向けて、ローカル環境でのDB起動からシードデータ挿入までの流れをまとめました。

🧩 前提環境

この記事は以下の環境で動作確認しています。

  • Node.js 24
  • Next.js プロジェクト(※Next.jsである必要はありません)
  • Docker(今回は OrbStack を使用)
  • PostgreSQL 16(Docker上)
  • Prisma v7
  • DB確認ツール:TablePlus
  • TypeScript で seed を実装

🎯 ゴール

以下の状態を作ることが目的です。

  • Docker上のPostgreSQLに接続できる
  • Prisma v7 + adapter-pg 構成で動作する
  • npx prisma db seed が成功する
  • TablePlusでデータ挿入を確認できる

1. Next.js プロジェクト作成

npx create-next-app@latest test-app
cd test-app

2. PostgreSQL を Docker(OrbStack)で起動

docker-compose.yml

services:
  db:
    image: postgres:16
    container_name: test-app
    environment:
      POSTGRES_USER: testuser
      POSTGRES_PASSWORD: test1234
      POSTGRES_DB: testdb
    ports:
      - "5432:5432"
    volumes:
      - testapp_db:/var/lib/postgresql/data

volumes:
  testapp_db:

起動

docker compose up -d
docker compose ps

3. Prisma v7 セットアップ

npm install -D prisma
npm install @prisma/client
npx prisma init

自動生成されるもの:

  • prisma/
  • schema.prisma
  • .env
  • prisma.config.ts

Prisma v7 では prisma.config.ts が追加されている点もポイントです。

4. .env を設定

DATABASE_URL="postgresql://testuser:test1234@localhost:5432/testdb"

※ docker-compose.yml の設定と合わせてください

5. adapter-pg 構成に必要なパッケージ追加

npm i pg
npm i @prisma/adapter-pg
npm i -D @types/pg

6. schema.prisma に User モデルを追加

prisma/schema.prisma を以下のように編集します。

model User {
  id        String @id @default(cuid())
  name      String
  email     String @unique
  gender    String
  createdAt DateTime @default(now())
}

※ 今回はシンプルな User モデルを例に使用します。

7. Prisma Client 生成

npx prisma generate

8. マイグレーション実行(テーブル作成)

npx prisma migrate dev --name init

9. prisma.config.ts に seed 設定を追加

変更前

import "dotenv/config";
import { defineConfig } from "prisma/config";

export default defineConfig({
  schema: "prisma/schema.prisma",
  migrations: {
    path: "prisma/migrations",
  },
  datasource: {
    url: process.env["DATABASE_URL"],
  },
});

変更後

import "dotenv/config";
import { defineConfig } from "prisma/config";

export default defineConfig({
  schema: "prisma/schema.prisma",
  migrations: {
    path: "prisma/migrations",
    seed: "tsx prisma/seed/seed.ts", //追加
  },
  datasource: {
    url: process.env["DATABASE_URL"],
  },
});

10. tsx を追加(重要)

npm i -D tsx

入れないと:

spawn tsx ENOENT

エラーになります。

11. seed フォルダを作成

prisma/
  schema.prisma
  migrations/
  seed/
    seed.ts
    seed-data.ts

※ フォルダ分けは必須ではありませんが、今回は整理のために分けています。

12. seed-data.ts

export const SEED_USERS = [
  { name: "田中太郎", email: "tanaka@example.com", gender: "男性" },
  { name: "佐藤花子", email: "sato@example.com", gender: "女性" },
  { name: "鈴木一郎", email: "suzuki@example.com", gender: "男性" },
];

※ダミーデータを少し増やしておくと、挿入確認がしやすくなります。

13. seed.ts

import { PrismaClient } from "@/generated/prisma/client";
import { Pool } from "pg";
import { PrismaPg } from "@prisma/adapter-pg";
import { SEED_USERS } from "./seed-data";

// PostgreSQLへ接続するためのコネクションプールを作成
const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

// Prisma v7 用の PostgreSQL アダプターを作成
const adapter = new PrismaPg(pool);

// PrismaClient に adapter を設定
const prisma = new PrismaClient({ adapter });

// seed処理
async function main() {
  await prisma.user.createMany({
    data: SEED_USERS,
    skipDuplicates: true,
  });

  console.log(`Seeded ${SEED_USERS.length} users`);
}

main()
  .catch((e) => {
    console.error("Seed failed:", e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
    await pool.end();
  });

PrismaClient の import は、generator output のパスに合わせて調整してください。

14. Seed 実行

npx prisma db seed

よくあるエラー

エラー 原因 解決
spawn tsx ENOENT tsx未インストール npm i -D tsx
DATABASE_URL undefined .env未読込 prisma.config.tsのdotenv確認
unique制約エラー seed重複 skipDuplicates追加

まとめ

Prisma v7 + adapter-pg 構成では、

  • pg

  • @prisma/adapter-pg

  • tsx(TypeScript seedの場合)

この3つが揃って初めて npx prisma db seed が成功します。

Prisma v6 以前の情報とは手順が異なるため、
v7 では必ず adapter-pg 構成でセットアップする点に注意してください。

この記事がローカル環境でのDB構築の参考になれば幸いです!

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?