Elysia Tools

Durchsuche Tools, Beispiele, visuelle Erklärungen und Themenguides an einem klaren Ort.

Beliebte Kategorien

Themen

Sprache
ZHESPTRUFRDEEN

Elysia Tools

Mobile Navigation

Datenbanken

Prisma Beispiele

Prisma moderne Datenbank-Toolkit und ORM mit Schema-Definitionen, Migrationen, Beziehungen und typsicherem Datenbankzugriff

Beispiele

Einträge in dieser Sammlung

QuellcodeprismaEinfach

Prisma Schema-Definition

Datenbank-Schema-Definition mit Modellen, Beziehungen und Feldtypen

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
}
QuellcodetypescriptEinfach

CRUD-Operationen

Vollständige CRUD-Operationen mit Prisma Client einschließlich Erstellen, Lesen, Aktualisieren und Löschen

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
}
QuellcodebashMittel

Prisma Migrationen

Datenbank-Migrationsskripte und Versionskontrolle für Schema-Änderungen

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");
QuellcodetypescriptKomplex

Prisma Erweiterte Funktionen

Erweiterte Prisma-Funktionen einschließlich Transaktionen, Middleware, komplexe Abfragen und Performance-Optimierung

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
}

Werkzeuge

Tools, die oft mit diesem Beispiel genutzt werden

Verwandt

Verwandte Beispielsammlungen

Verwandt

Verwandte Themen

Leitfaden zur Tool-Nutzung

Kontext zum Verständnis dieser Beispielsammlung

Titel

Prisma Beispiele

Beschreibung

Prisma moderne Datenbank-Toolkit und ORM mit Schema-Definitionen, Migrationen, Beziehungen und typsicherem Datenbankzugriff

Überblick

Prisma moderne Datenbank-Toolkit und ORM mit Schema-Definitionen, Migrationen, Beziehungen und typsicherem Datenbankzugriff

Wann verwenden

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

So funktioniert es

  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.

Anwendungsfälle

  • Prisma Schema-Definition
  • CRUD-Operationen
  • Prisma Migrationen
  • Prisma Erweiterte Funktionen

FAQ

What is included in Prisma Beispiele?

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

Thema

JSON Schema aus Beispielen und Tabellen ableiten

Leiten Sie aus repräsentativen JSON-Beispielen oder XLSX-Zeilen einen prüfbaren JSON-Schema-Entwurf ab und kontrollieren Sie Typen, Pflichtfelder, Nullwerte und Ausreißer, bevor er als Vertrag dient.

Thema

Selbst gehostetes Gewinnspiel-Widget prüfen und zur Einbettung übergeben

Konfiguration, API-Beispiele, Lesbarkeit und responsive Ansichten prüfen und die Widget-Dateien mit nachvollziehbaren Browser-Abnahmetests übergeben.

Thema

Standardisierung und Komprimierung von Bildern im Batch

Bereiten Sie einen einheitlichen Bildbestand vor: Ausrichtung korrigieren, unerwünschte Ränder entfernen, eine Größenregel anwenden, Dateien komprimieren und repräsentative Ausgaben vor der Übergabe prüfen.

Thema

Klassische und moderne Verschlüsselungswerkzeuge

Üben Sie sichere Lern- und CTF-Abläufe, indem Sie reversible klassische Verfahren mit moderner Verschlüsselung und ihren Grenzen vergleichen.

Start
Werkzeuge3201
Beispiele593
Visualisierungen465
Dateibetrachter103
Themen233
Schlagwörter333
Bilder, Audio & Video657

Werkzeuge für Bild-, Audio- und Videobearbeitung, Konvertierung und Optimierung

Mathe, Datum & Finanzen644

Rechner, Zahlenwerkzeuge, Datumslogik, Statistik und Finanztools

Design & Farbe297

Werkzeuge für Farben, Layouts, Grafiken, visuelle Gestaltung und Designhilfen

Text & Schreiben209

Werkzeuge für Schreiben, Bereinigung, Formatierung, Extraktion und Textanalyse

Entwicklung & Web193

Entwicklerwerkzeuge, Netzwerk-Utilities, Web-Debugging und Automatisierungshelfer

Konvertierung & Kodierung175

Werkzeuge für Format-, Datei-, Archiv-, Einheiten- und Kodierungskonvertierung

FLAC/WAV-Quellen prüfen und Nachweise übergeben
Selbst gehostetes Gewinnspiel-Widget prüfen und zur Einbettung übergeben
Stripe-Codepaket prüfen und lokalen Import vorbereiten
Technische Fotoauswahl prüfen und Kandidaten zur Bearbeitung übergeben
UI-Screenshot strukturieren, prüfen und an die Entwicklung übergeben

© 2026 Elysia Tools. Alle Rechte vorbehalten.

DokumentationTarifeÜber unsNutzungsbedingungenDatenschutzerklärungCookiesKontakt

Format Conversion

CSV-zu-SQL-INSERT-Generator

Parst CSV/Excel-CSV/TSV (Auto-Erkennung, RFC 4180) und erzeugt INSERT-Stapel für MySQL/PostgreSQL/SQLite/SQL Server mit Typinferenz und ON CONFLICT/IGNORE

Development

Datenbank-Backup-Generator

SQL-Backup-Skripte für Datenbanktabellen generieren

Development

Datenbank-Migrations-Generator

SQL-Migrationsskripte für Schemaänderungen generieren

Development

Datenbank Schema Diff

Vergleicht zwei Datenbankschemas und erstellt einen Migrationsentwurf

Development

SQL-Dialekt-Brücke

Übersetzt DDL, DML, Funktionen und Typen zwischen MySQL / PostgreSQL / SQLite / BigQuery / Snowflake / Redshift und markiert Nicht-Unterstütztes

Development

SQL Ausführungsplan-Visualisierer

Füge EXPLAIN-/EXPLAIN-ANALYZE-Ausgaben (PostgreSQL/MySQL/SQLite) ein, um einen Kostenbaum zu erhalten, Abweichungen zwischen geschätzten und tatsächlichen Zeilen zu markieren und Indexvorschläge zu erhalten

Development

SQL-Formatierer & Minifier

Verschönert oder minifiziert SQL mit voller Kontrolle über den Dialekt (PostgreSQL, MySQL, SQLite, SQL Server/T-SQL, BigQuery, Snowflake u.a.), Groß-/Kleinschreibung von Schlüsselwörtern/Bezeichnern/Funktionen, Einzugsstil (Standard, tabellarisch links/rechts) und Leerzeilen zwischen Anweisungen. Liefert ein farbig hervorgehobenes, kopierfertiges Ergebnis mit Größen- und Anweisungsstatistik.

Development

Tabellen-Schema-Generator

SQL-Tabellenschema-Definitionen generieren

Datenbanken

MySQL Database Beispiele

MySQL-Datenbankskripte verschiedener Komplexitätsstufen, von einfachen Tabellen bis zu Unternehmens-ERP-Systemen

Datenbanken

Sequelize Beispiele

Sequelize Node.js ORM mit Modell-Definitionen, Assoziationen, Migrationen, Abfragen und Datenbank-Operationen

Datenbanken

Erweiterte PostgreSQL Beispiele

Erweiterte PostgreSQL Datenbankbeispiele einschließlich Optimierungsstrategien, komplexe Abfragen, Indizierung und Performance-Tuning

Datenbank-ORMs

Drizzle ORM Beispiele

Drizzle ORM leichtgewichtiges TypeScript ORM Beispiele einschließlich Schema-Definition, Queries, Migrationen, Beziehungen und Datenbank-Mustern

Datenformate

SQL-Skript-Beispiele

SQL-Abfragebeispiele und Datenbankskripte für verschiedene Szenarien und Anwendungsfälle

Datenbanken

SQLite Datenbank-Beispiele

SQLite Datenbank-Beispiele einschließlich grundlegender Operationen, fortgeschrittener Abfragen, Migrationen und Datenbank-Management