Get the FREE Ultimate OpenClaw Setup Guide →

database-patterns

npx machina-cli add skill shahtuyakov/claude-setup/database-patterns --openclaw
Files (1)
SKILL.md
4.6 KB

Database Patterns

Modern database design and implementation patterns.

Database Selection

DatabaseBest ForUse When
PostgreSQLRelational data, complex queriesStructured data, ACID needed, analytics
MongoDBDocument-oriented, flexible schemaRapid iteration, nested data, horizontal scale
SQLiteEmbedded, local-firstMobile apps, desktop apps, edge
RedisCaching, sessionsHigh-speed reads, ephemeral data

ORM Selection

ORMBest ForTrade-offs
DrizzlePerformance, serverlessSQL knowledge required
PrismaDeveloper experienceLarger bundle, slower edge
TypeORMNestJS, decoratorsLegacy patterns
KyselyType-safe SQL builderLower-level

Reference Files

TopicLoadUse When
Schema designreferences/schema-design.mdDesigning tables, relationships
PostgreSQLreferences/postgresql-patterns.mdPostgreSQL-specific patterns
MongoDBreferences/mongodb-patterns.mdMongoDB-specific patterns
ORM patternsreferences/orm-patterns.mdPrisma, Drizzle usage
Migrationsreferences/migrations.mdSchema versioning
Securityreferences/security.mdSQL injection, encryption

Quick Start Patterns

PostgreSQL Table

CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) NOT NULL UNIQUE,
    name VARCHAR(100) NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    email_verified_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMPTZ
);

CREATE INDEX users_email_idx ON users(email) WHERE deleted_at IS NULL;

Drizzle Schema

import { pgTable, uuid, varchar, timestamp } from 'drizzle-orm/pg-core';

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: varchar('email', { length: 255 }).notNull().unique(),
  name: varchar('name', { length: 100 }).notNull(),
  passwordHash: varchar('password_hash', { length: 255 }).notNull(),
  emailVerifiedAt: timestamp('email_verified_at', { withTimezone: true }),
  createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
  updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  deletedAt: timestamp('deleted_at', { withTimezone: true }),
});

Prisma Schema

model User {
  id              String    @id @default(uuid())
  email           String    @unique
  name            String
  passwordHash    String    @map("password_hash")
  emailVerifiedAt DateTime? @map("email_verified_at")
  createdAt       DateTime  @default(now()) @map("created_at")
  updatedAt       DateTime  @updatedAt @map("updated_at")
  deletedAt       DateTime? @map("deleted_at")

  posts           Post[]

  @@map("users")
}

MongoDB Document

interface User {
  _id: ObjectId;
  email: string;
  name: string;
  passwordHash: string;
  emailVerifiedAt?: Date;
  createdAt: Date;
  updatedAt: Date;
  deletedAt?: Date;
  // Embedded data
  profile?: {
    bio: string;
    avatarUrl: string;
  };
}

Schema Design Principles

  1. Normalize first - Start with 3NF, denormalize for performance
  2. UUID for IDs - Better for distributed systems
  3. Timestamps always - created_at, updated_at on every table
  4. Soft deletes - deleted_at over hard deletes
  5. Constraints - Use database constraints, not just app validation

Index Guidelines

Index TypeUse For
B-tree (default)Equality, range queries
HashEquality only (rare)
GINArrays, JSONB, full-text
GiSTGeometric, range types
BRINLarge sorted tables

Common Patterns

PatternDescription
Soft deletedeleted_at column instead of DELETE
Audit logSeparate table tracking all changes
Polymorphictype column + type-specific columns
EAVEntity-Attribute-Value (avoid if possible)
Materialized viewPre-computed query results

Security Checklist

  • Parameterized queries only
  • Passwords hashed with bcrypt/argon2
  • PII encrypted at rest
  • Database user has minimal privileges
  • SSL/TLS for connections
  • No sensitive data in logs

Source

git clone https://github.com/shahtuyakov/claude-setup/blob/main/skills/database-patterns/SKILL.mdView on GitHub

Overview

This skill covers database design and implementation patterns for PostgreSQL, MongoDB, and ORMs like Prisma and Drizzle. It helps when designing schemas, writing migrations, optimizing queries, and enforcing security best practices.

How This Skill Works

We map database choices to use cases, provide quick-start patterns, and supply example schemas and migrations. The guidance includes schema design principles, indexing guidelines, and ORM-specific snippets to help implement robust data models.

When to Use It

  • Designing normalized schemas for relational apps (PostgreSQL).
  • Iterating rapidly with document data in MongoDB.
  • Selecting and configuring an ORM (Drizzle, Prisma, etc.).
  • Planning migrations and schema versioning across environments.
  • Implementing indexing and security best practices.

Quick Start

  1. Step 1: Choose a database and ORM pattern (e.g., PostgreSQL + Drizzle or MongoDB + Mongoose/Prisma) based on your app needs.
  2. Step 2: Define a sample user schema that includes id, email, name, password, created_at, updated_at, and deleted_at.
  3. Step 3: Implement code samples from the Quick Start Patterns (PostgreSQL table, Drizzle schema, Prisma schema, MongoDB document) to bootstrap your project.

Best Practices

  • Normalize first (3NF) and denormalize selectively for performance.
  • Use UUIDs for IDs to support distributed systems.
  • Always include created_at and updated_at timestamps.
  • Implement soft deletes with deleted_at instead of hard deletes.
  • Enforce constraints at the database level, not only in app code.

Example Use Cases

  • PostgreSQL: users table with UUID id, unique email, and an index on email excluding soft-deleted rows.
  • Drizzle: define a users table with timestamps and soft-delete column in a serverless context.
  • Prisma: User model with mappings for created_at, updated_at, and passwordHash.
  • MongoDB: User document with embedded profile data and optional fields.
  • Migrations: using migrations.md references to version and apply schema changes.

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers