Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHESPTRUFRDEEN

Elysia Tools

导航

数据库

Prisma 示例

Prisma现代数据库工具包和ORM,包含模式定义、迁移、关系和类型安全的数据库访问

案例

这个案例集合中的条目

代码prisma简单

Prisma 模式定义

数据库模式定义,包含模型、关系和字段类型

prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

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

model User {
  id        Int      @id @default(autoincrement())
    email     String   @unique
    username  String?  @unique
    password  String
    firstName String?
    lastName  String?
    isActive  Boolean @default(true)
    role      Role     @default(USER)
    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt

    posts     Post[]
    comments  Comment[]
    profile   Profile?

    @@map("users")
}

model Profile {
    id        Int      @id @default(autoincrement())
    userId    Int      @unique
    bio       String?
    avatar    String?
    website   String?
    birthDate DateTime?

    user      User      @relation(fields: [userId], references: [id])

    @@map("profiles")
}

model Post {
    id          Int      @id @default(autoincrement())
    title       String
    slug        String   @unique
    content     String
    publishedAt DateTime?
    createdAt   DateTime @default(now())
    updatedAt   DateTime @updatedAt

    authorId    Int
    author      User      @relation(fields: [authorId], references: [id])
    comments    Comment[]

    @@map("posts")
}

model Comment {
    id        Int      @id @default(autoincrement())
    content   String
    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt

    postId   Int
    authorId Int

    post     Post     @relation(fields: [postId], references: [id])
    author   User     @relation(fields: [authorId], references: [id])

    @@map("comments")
}

enum Role {
  USER
  ADMIN
  MODERATOR
  AUTHOR
}
代码typescript简单

CRUD 操作

完整的CRUD操作,包含Prisma Client的创建、读取、更新和删除

typescript
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// CREATE Operations
async function createUser(userData: {
  email: string
  username?: string
  password: string
  firstName?: string
  lastName?: string
}) {
  try {
    const user = await prisma.user.create({
      data: userData,
      include: {
        profile: true
      }
    })
    return user
  } catch (error) {
    console.error('Error creating user:', error)
    throw error
  }
}

// Create user with profile
async function createUserWithProfile(userData: {
  email: string
  password: string
  profile: {
    bio?: string
    avatar?: string
    website?: string
  }
}) {
  const user = await prisma.user.create({
    data: {
      email: userData.email,
      password: userData.password,
      profile: {
        create: userData.profile
      }
    },
    include: {
      profile: true
    }
  })
  return user
}

// Create multiple users
async function createMultipleUsers(usersData: Array<{
  email: string
  password: string
}>) {
  const users = await prisma.user.createMany({
    data: usersData
  })
  return users
}

// READ Operations
async function getUserById(id: number) {
  const user = await prisma.user.findUnique({
    where: { id },
    include: {
      profile: true,
      posts: {
        include: {
          comments: true
        }
      }
    }
  })
  return user
}

async function getUserByEmail(email: string) {
  const user = await prisma.user.findUnique({
    where: { email },
    select: {
      id: true,
      email: true,
      username: true,
      firstName: true,
      lastName: true,
      role: true
    }
  })
  return user
}

async function getAllUsers(options: {
  page?: number
  limit?: number
  search?: string
  role?: string
}) {
  const { page = 1, limit = 10, search, role } = options
  const skip = (page - 1) * limit

  const where = {
    AND: [
      search ? {
        OR: [
          { username: { contains: search, mode: 'insensitive' as const } },
          { email: { contains: search, mode: 'insensitive' as const } },
          { firstName: { contains: search, mode: 'insensitive' as const } },
          { lastName: { contains: search, mode: 'insensitive' as const } }
        ]
      } : {},
      role ? { role: role as any } : {},
      { isActive: true }
    ]
  }

  const [users, total] = await Promise.all([
    prisma.user.findMany({
      where,
      skip,
      take: limit,
      include: {
        profile: true,
        _count: {
          select: {
            posts: true,
            comments: true
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    }),
    prisma.user.count({ where })
  ])

  return {
    users,
    pagination: {
      page,
      limit,
      total,
      pages: Math.ceil(total / limit)
    }
  }
}

// UPDATE Operations
async function updateUser(id: number, updateData: {
  email?: string
  username?: string
  firstName?: string
  lastName?: string
  role?: any
  isActive?: boolean
}) {
  const user = await prisma.user.update({
    where: { id },
    data: updateData,
    include: {
      profile: true
    }
  })
  return user
}

async function updateOrCreateProfile(userId: number, profileData: {
  bio?: string
  avatar?: string
  website?: string
  birthDate?: Date
}) {
  const profile = await prisma.profile.upsert({
    where: { userId },
    update: profileData,
    create: {
      userId,
      ...profileData
    }
  })
  return profile
}

// DELETE Operations
async function deleteUser(id: number) {
  // Soft delete
  const user = await prisma.user.update({
    where: { id },
    data: { isActive: false }
  })
  return user
}

async function hardDeleteUser(id: number) {
  const user = await prisma.user.delete({
    where: { id }
  })
  return user
}

// Transaction Operations
async function transferPostOwnership(postId: number, newAuthorId: number) {
  const result = await prisma.$transaction(async (tx) => {
    const post = await tx.post.findUnique({
      where: { id: postId },
      include: { author: true }
    })

    if (!post) {
      throw new Error('Post not found')
    }

    const updatedPost = await tx.post.update({
      where: { id: postId },
      data: { authorId: newAuthorId }
    })

    return {
      previousAuthor: post.author,
      updatedPost
    }
  })

  return result
}

// Advanced Queries
async function getUserWithPostStats(userId: number) {
  const userWithStats = await prisma.user.findUnique({
    where: { id: userId },
    include: {
      _count: {
        select: {
          posts: true,
          comments: true
        }
      },
      posts: {
        select: {
          id: true,
          title: true,
          publishedAt: true,
          _count: {
            select: {
              comments: true
            }
          }
        },
        orderBy: {
          publishedAt: 'desc'
        },
        take: 5
      }
    }
  })
  return userWithStats
}

export {
  createUser,
  createUserWithProfile,
  createMultipleUsers,
  getUserById,
  getUserByEmail,
  getAllUsers,
  updateUser,
  updateOrCreateProfile,
  deleteUser,
  hardDeleteUser,
  transferPostOwnership,
  getUserWithPostStats
}
代码bash中等

Prisma 迁移

数据库迁移脚本和模式变更的版本控制

bash
# Prisma Migrations Guide

# Create a new migration
npx prisma migrate dev --name add_user_bio

# View migration history
npx prisma migrate status

# Deploy migrations to production
npx prisma migrate deploy

# Reset database (development only)
npx prisma migrate reset

# Generate migration SQL without applying
npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script

# Example migration SQL:
-- AlterTable "users" ADD COLUMN "bio" TEXT;

-- CreateTable "profiles" (
--   "id" SERIAL NOT NULL,
--   "userId" INTEGER NOT NULL,
--   "bio" TEXT,
--   "avatar" TEXT,
--   "website" TEXT,
--   "birthDate" TIMESTAMP(3),
--   CONSTRAINT "profiles_pkey" PRIMARY KEY ("id")
-- );

-- CreateIndex
-- CreateIndex "posts_authorId_idx" ON "posts" ("authorId");

-- AlterTable
-- AlterTable "users" ALTER COLUMN "email" SET NOT NULL;

-- DropTable
-- DropTable "temp_table";

-- Raw SQL (use sparingly)
-- CREATE INDEX CONCURRENTLY IF NOT EXISTS "custom_index" ON "users" ("email");
代码typescript复杂

Prisma 高级功能

Prisma高级功能,包括事务、中间件、复杂查询和性能优化

typescript
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// 1. Advanced Query Operations
async function advancedQueries() {
  // Complex filtering with OR conditions
  const users = await prisma.user.findMany({
    where: {
      OR: [
        { email: { contains: '@gmail.com' } },
        { username: { startsWith: 'admin' } }
      ],
      isActive: true
    },
    include: {
      posts: {
        include: {
          author: {
            select: {
              id: true,
              firstName: true,
              lastName: true
            }
          }
        }
      }
    }
  })

  // Date range filtering with timezone
  const recentPosts = await prisma.post.findMany({
    where: {
      createdAt: {
        gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
      },
      publishedAt: {
        not: null
      }
    },
    orderBy: {
      createdAt: 'desc'
    },
    include: {
      author: true,
      _count: {
        select: {
          comments: true
        }
      }
    }
  })

  // Aggregation with grouping
  const postStats = await prisma.post.groupBy({
    by: ['authorId'],
    _count: {
      select: {
        id: true,
        title: true
      }
    },
    _sum: {
      id: true
    },
    _avg: {
      id: true
    }
  })

  return { users, recentPosts, postStats }
}

// 2. Transaction Management
async function transactionExample() {
  const result = await prisma.$transaction(async (tx) => {
    // Create user
    const user = await tx.user.create({
      data: {
        email: '[email protected]',
        username: 'newuser',
        password: 'hashedpassword'
      }
    })

    // Create profile
    const profile = await tx.profile.create({
      data: {
        userId: user.id,
        bio: 'User bio'
      }
    })

    // Create first post
    const post = await tx.post.create({
      data: {
        title: 'First Post',
        content: 'This is the content of the first post',
        authorId: user.id,
        slug: 'first-post',
        publishedAt: new Date()
      }
    })

    return { user, profile, post }
  })

  return result
}

// 3. Performance Optimization
async function optimizedQueries() {
  // Use select for better performance
  const users = await prisma.user.findMany({
    select: {
      id: true,
      email: true,
      username: true,
      isActive: true
    },
    where: {
      isActive: true
    },
    take: 100,
    skip: 0
  })

  // Batch operations
  const batchCreateUsers = await prisma.user.createMany({
    data: Array.from({ length: 10 }, (_, i) => ({
      email: `user${i}@example.com`,
      username: `user${i}`,
      password: 'hashedpassword',
      isActive: true
    }))
  })

  // Raw SQL for complex operations
  const customQuery = await prisma.$queryRaw`
    SELECT u.*, COUNT(p.id) as post_count
    FROM users u
    LEFT JOIN posts p ON u.id = p.authorId
    WHERE u.isActive = ${true}
    GROUP BY u.id
    HAVING COUNT(p.id) > 5
  `

  return { users, batchCreateUsers, customQuery }
}

// 4. Error Handling and Validation
async function errorHandling() {
  try {
    const user = await prisma.user.findUnique({
      where: { id: 1 }
    })

    if (!user) {
      throw new Error('User not found')
    }

    // Validation
    if (user.email && !user.email.includes('@')) {
      throw new Error('Invalid email format')
    }

    return user
  } catch (error) {
    console.error('Database error:', error)
    throw error
  }
}

// 5. Real-time Updates with Subscriptions
async function realTimeUpdates() {
  // Note: This requires PostgreSQL with logical replication
  // This is a conceptual example
  const stream = await prisma.$subscribe.user({
    where: {
      isActive: true
    },
    include: {
      posts: true,
      profile: true
    }
  })

  for await (const event of stream) {
    console.log('User event:', event)
    // Handle real-time updates
  }
}

// 6. Middleware Implementation
function setupMiddleware() {
  prisma.$use(async (params, next) => {
    // Log all queries
    console.log(`${params.model}.${params.action}`, params.args)

    // Add timestamps for create operations
    if (params.action === 'create') {
      params.args.data = {
        ...params.args.data,
        createdAt: new Date(),
        updatedAt: new Date()
      }
    }

    // Update timestamp for update operations
    if (params.action === 'update') {
      params.args.data = {
        ...params.args.data,
        updatedAt: new Date()
      }
    }

    return next(params)
  })

  // Soft delete middleware
  prisma.$use(async (params, next) => {
    if (params.action === 'delete') {
      // Convert delete to soft delete
      params.action = 'update'
      params.args.data = { isActive: false }
    }
    return next(params)
  })
}

// 7. Advanced Relationship Handling
async function complexRelationshipQueries() {
  // Nested creates and updates
  const userWithPosts = await prisma.user.create({
    data: {
      email: '[email protected]',
      password: 'password',
      username: 'author',
      posts: {
        create: [
          {
            title: 'First Post',
            content: 'Content 1',
            slug: 'first-post',
            publishedAt: new Date(),
            comments: {
              create: [
                {
                  content: 'Great post!',
                  authorId: 2 // Assuming user with ID 2 exists
                }
              ]
            }
          },
          {
            title: 'Second Post',
            content: 'Content 2',
            slug: 'second-post'
            // Not published yet
          }
        ]
      },
      profile: {
        create: {
          bio: 'Professional writer',
          website: 'https://example.com'
        }
      }
    },
    include: {
      posts: {
        include: {
          comments: {
            include: {
              author: {
                select: {
                  username: true,
                  firstName: true
                }
              }
            }
          }
        }
      },
      profile: true
    }
  })

  return userWithPosts
}

// 8. Pagination and Cursor-based Navigation
async function advancedPagination(options: {
  cursor?: string
  take?: number
  skip?: number
  direction?: 'forward' | 'backward'
}) {
  const { cursor, take = 10, skip, direction = 'forward' } = options

  const users = await prisma.user.findMany({
    take,
    skip,
    cursor: cursor ? { id: cursor } : undefined,
    orderBy: {
      id: direction === 'forward' ? 'asc' : 'desc'
    },
    select: {
      id: true,
      email: true,
      username: true,
      createdAt: true
    }
  })

  return {
    users,
    nextCursor: users.length > 0 ? users[users.length - 1].id : null,
    hasMore: users.length === take
  }
}

export {
  advancedQueries,
  transactionExample,
  optimizedQueries,
  errorHandling,
  realTimeUpdates,
  setupMiddleware,
  complexRelationshipQueries,
  advancedPagination
}

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

工具使用指南

帮助搜索与理解工作流的案例说明

标题

Prisma 示例

描述

Prisma现代数据库工具包和ORM,包含模式定义、迁移、关系和类型安全的数据库访问

概览

Prisma现代数据库工具包和ORM,包含模式定义、迁移、关系和类型安全的数据库访问

适用场景

  • Use this sample set when you want reference inputs for Prisma 示例.
  • Use it to preview output formats and compare related sample variants.

使用方式

  1. 1Open a sample entry to inspect the prepared example payload or asset.
  2. 2Compare it with related tools to understand how the workflow connects.

常见用途

  • Prisma 模式定义
  • CRUD 操作
  • Prisma 迁移
  • Prisma 高级功能

常见问题

What is included in Prisma 示例?

This page includes curated sample entries, related tools, and neighboring sample collections for Prisma 示例.

专题

药代动力学教学模型与结果核查

用于教学或 QA 的药代公式、模型假设和结果一致性核查,不提供用药剂量、诊断或临床建议。

专题

经典与现代密码工具

在安全的教学或 CTF 场景中比较可逆的经典变换与现代加密,并明确玩具密码不等于安全防护。

专题

文本前后缀与包裹符号批处理,整行整词一次到位

给文本行或词批量添加前后缀,为 SQL、配置和 Markdown 给每个值加引号或反引号包裹,并剥掉粘贴列表带来的编号、符号和装饰。

专题

数学与数字转换工作流

按清晰的精度检查流程转换计量单位、进制、分数、科学计数法、罗马数字以及字节/位数值。

首页
工具3201
案例593
可视化465
文件查看器103
专题233
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融644

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色297

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

FLAC/WAV 无损音源疑点筛查与证据交付
自托管抽奖组件配置复核、嵌入测试与上线交付
Stripe 优惠码候选批次审核与本地导入预检
批量照片技术初筛、近重复复核与修图候选交付
界面截图结构化、人工校对与开发交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Format Conversion

CSV 转多方言 SQL INSERT 生成器

解析 CSV/Excel-CSV/TSV(自动方言检测,RFC 4180),生成 MySQL/PostgreSQL/SQLite/SQL Server 的批量 INSERT,带类型推断和 ON CONFLICT/IGNORE 变体

Development

数据库备份生成器

为数据库表生成SQL备份脚本

Development

数据库迁移生成器

为数据库架构更改生成SQL迁移脚本

Development

数据库 Schema 对比

比较两个数据库 Schema 并生成迁移草案

Development

SQL 方言互译桥

在 MySQL / PostgreSQL / SQLite / BigQuery / Snowflake / Redshift 之间互译 DDL、DML、函数与类型,并标注不支持的写法

Development

SQL 执行计划可视化器

粘贴 EXPLAIN / EXPLAIN ANALYZE 输出(PostgreSQL/MySQL/SQLite),渲染为成本树,标注估算行数与实际行数的偏差热点,并给出具体的索引建议

Development

SQL 查询格式化器 & 压缩器

美化或压缩 SQL,完全可控 SQL 方言(PostgreSQL、MySQL、SQLite、SQL Server/T-SQL、BigQuery、Snowflake 等)、关键字/标识符/函数大小写、缩进风格(标准、左对齐表格、右对齐表格)以及语句间空行。输出带语法高亮、可直接复制的结果,并显示大小与语句数统计。

Development

表结构生成器

生成SQL表结构定义

数据库

MySQL 数据库示例

各种复杂度级别的MySQL数据库脚本示例,从简单表到企业ERP系统

数据库

Sequelize 示例

Sequelize Node.js ORM,包含模型定义、关联、迁移、查询和数据库操作

数据库

PostgreSQL 高级示例

高级 PostgreSQL 数据库示例,包括优化策略、复杂查询、索引和性能调优

数据库 ORM

Drizzle ORM 示例

Drizzle ORM轻量级TypeScript ORM示例,包括模式定义、查询、迁移、关系和数据库模式

数据格式

SQL 脚本示例

各种场景和用例的 SQL 查询示例和数据库脚本

数据库

SQLite 数据库示例

SQLite数据库示例,包括基本操作、高级查询、迁移和数据库管理