Skip to content

Prisma SQLite

Directory Structure

.
├── package.json
├── prisma
│   ├── data.db
│   ├── migrations
│   │   ├── *_initial
│   │   │   └── migration.sql
│   │   └── migration_lock.toml
│   └── schema.prisma
├── src
│   └── index.ts
└── tsconfig.json

Environment Build

sh
pnpm add prisma -D
sh
pnpm add @prisma/client
sh
DATABASE_URL="file:./data.db"

schema.prisma作成

sh
pnpm prisma init --datasource-provider sqlite
prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String
}

migrate

sh
pnpm prisma migrate dev --name init

User Table

sql
-- CreateTable
CREATE TABLE "User" (
    "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    "email" TEXT NOT NULL,
    "name" TEXT NOT NULL
);

-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
ts
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

const deleteUsers = async () => {
  await prisma.user.deleteMany()
}

deleteUsers()

const createUsers = async () => {
  await prisma.user.createMany({
    data: [
      {
        id: 1,
        name: 'prisma',
        email: 'prisma@email.com',
      },
      {
        id: 2,
        name: 'drizzle',
        email: 'drizzle@email.com',
      },
      {
        id: 3,
        name: 'typeorm',
        email: 'typeorm@email.com',
      },
    ],
  })
}

const main = async () => {
  await createUsers()
  const users = await prisma.user.findMany()
  console.log(users)
}

main()
  .catch((e) => {
    console.error(e)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })

Execution

[
  { id: 1, email: 'prisma@email.com', name: 'prisma' },
  { id: 2, email: 'drizzle@email.com', name: 'drizzle' },
  { id: 3, email: 'typeorm@email.com', name: 'typeorm' }
]