Database Patterns logo

Database Patterns

Community
yonatangross
database-patterns

Database design and migration patterns for Alembic migrations, schema design (SQL/NoSQL), and database versioning. Use when creating migrations, designing schemas, normalizing data, managing database versions, or handling schema drift.

Overview

Publisheryonatangross
Repositoryorchestkit
Skill namedatabase-patterns
Stars
298
Forks
35
Bundled files
23
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 23 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by yonatangross on GitHub. Read the source before you install it.

Installation

Install the Database Patterns AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/yonatangross/orchestkit/tree/main/plugins/ork/skills/database-patterns
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/yonatangross/orchestkit.git /tmp/orchestkit
mkdir -p .claude/skills
cp -r /tmp/orchestkit/plugins/ork/skills/database-patterns .claude/skills/database-patterns
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Database Patterns in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Database Patterns on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Database Patterns is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Database Patterns

Comprehensive patterns for database migrations, schema design, and version management. Each category has individual rule files in rules/ loaded on-demand.

Quick Reference

CategoryRulesImpactWhen to Use
Alembic Migrations2CRITICALData migrations, branch management
Schema Design3HIGHNormalization, indexing strategies, NoSQL patterns
Versioning2HIGHChangelogs, schema drift detection
Zero-Downtime Migration2CRITICALExpand-contract, pgroll, rollback monitoring

| Database Selection | 1 | HIGH | Choosing the right database, PostgreSQL vs MongoDB, cost analysis |

Total: 10 rules across 5 categories

This skill is a wrap around Alembic and PostgreSQL, not a replacement for their docs. Read references/ork-delta.md first: it holds the version floors, corrections and house conventions that upstream does not carry. Everything in the table below was removed on purpose.

Upstream coverage (do not restate)

These topics are vendor documentation. Fetch them from the source instead of re-teaching them here.

TopicFirst-party source
Alembic autogenerate, async env.py template, revision/upgrade/downgrade/history CLIhttps://alembic.sqlalchemy.org/en/latest/autogenerate.html (our one correction to the async template is in references/ork-delta.md)
Migration branches, merge revisions, tuple down_revision, branch labelshttps://alembic.sqlalchemy.org/en/latest/branches.html
Multi-database env.py, batched backfill recipes, migration hooks, environment-conditional migrationshttps://alembic.sqlalchemy.org/en/latest/cookbook.html
Rollback and data-integrity test harnessesreferences/migration-testing.md
JSONB operators, indexing and storage tradeoffshttps://www.postgresql.org/docs/current/datatype-json.html (normal forms and the house denormalization call stay in rules/schema-normalization.md)
Full index-type reference and syntax (B-tree, GIN, partial, covering, CREATE INDEX CONCURRENTLY, REINDEX)https://www.postgresql.org/docs/current/sql-createindex.html (the house subset we actually apply stays in rules/schema-indexing.md)
lock_timeout, statement_timeout, advisory locks during migrationhttps://www.postgresql.org/docs/current/runtime-config-client.html and rules/versioning-drift.md
Enum type changeshttps://www.postgresql.org/docs/current/datatype-enum.html
Table partitioninghttps://www.postgresql.org/docs/current/ddl-partitioning.html
Trigger functionshttps://www.postgresql.org/docs/current/plpgsql-trigger.html
Foreign-key cascade semanticshttps://www.postgresql.org/docs/current/ddl-constraints.html
Temporal and audit-trail tables, CDC change logs, stored-procedure and view versioninghttps://www.postgresql.org/docs/18/sql-createtable.html (read references/ork-delta.md before assuming these give row history)
HNSW and vector index tuning (m, ef_construction, hnsw.ef_search)https://github.com/pgvector/pgvector
Generic pre-deployment, backup and schema-review checklistshttps://alembic.sqlalchemy.org/en/latest/tutorial.html
Async SQLAlchemy sessions, FastAPI wiring, connection pool tuningork:python-backend skill

Quick Start

python
# Alembic: Auto-generate migration from model changes
# alembic revision --autogenerate -m "add user preferences"

def upgrade() -> None:
    op.add_column('users', sa.Column('org_id', UUID(as_uuid=True), nullable=True))
    op.execute("UPDATE users SET org_id = 'default-org-uuid' WHERE org_id IS NULL")

def downgrade() -> None:
    op.drop_column('users', 'org_id')
sql
-- Schema: Normalization to 3NF with proper indexing
-- PG18: prefer uuidv7() (time-ordered, better B-tree locality) over gen_random_uuid() (random v4)
CREATE TABLE orders (
    id UUID PRIMARY KEY DEFAULT uuidv7(),
    customer_id UUID NOT NULL REFERENCES customers(id),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_orders_customer_id ON orders(customer_id);

Alembic Migrations

Migration management with Alembic for SQLAlchemy 2.0 async applications.

RuleFileKey Pattern
Data Migrationrules/alembic-data-migration.mdBatch backfill, two-phase NOT NULL, zero-downtime
Branchingrules/alembic-branching.mdFeature branches, merge migrations, conflict resolution

Autogenerate setup is upstream. Our one deviation from Alembic's async env.py template (the in_greenlet() guard) is in references/ork-delta.md.

Schema Design

SQL and NoSQL schema design with normalization, indexing, and constraint patterns.

RuleFileKey Pattern
Normalizationrules/schema-normalization.md1NF-3NF, when to denormalize, JSON vs normalized
Indexingrules/schema-indexing.mdB-tree, GIN, HNSW, partial/covering indexes
NoSQL Patternsrules/schema-nosql.mdEmbed vs reference, document design, sharding

Versioning

Database version control and change management across environments.

RuleFileKey Pattern
Changelogrules/versioning-changelog.mdSchema version table, semantic versioning, audit trails
Drift Detectionrules/versioning-drift.mdEnvironment sync, checksum verification, migration locks

Rollback testing lives in references/migration-testing.md; the docstring convention for lossy downgrades is in references/ork-delta.md.

Database Selection

Decision frameworks for choosing the right database. Default: PostgreSQL.

RuleFileKey Pattern
Selection Guiderules/db-selection.mdPostgreSQL-first, tier-based matrix, anti-patterns

Key Decisions

DecisionRecommendationRationale
Async dialectpostgresql+asyncpgNative async support for SQLAlchemy 2.0
NOT NULL columnTwo-phase: nullable first, then alterAvoids locking, backward compatible
Large table indexCREATE INDEX CONCURRENTLYZero-downtime, no table locks
Normalization target3NF for OLTPReduces redundancy while maintaining query performance
Primary key strategyUUID for distributed, INT for single-DBContext-appropriate key generation
Soft deletesdeleted_at timestamp columnPreserves audit trail, enables recovery
Migration granularityOne logical change per fileEasier rollback and debugging
Production deploymentGenerate SQL, review, then applyNever auto-run in production

Anti-Patterns (FORBIDDEN)

python
# NEVER: Add NOT NULL without default or two-phase approach
op.add_column('users', sa.Column('org_id', UUID, nullable=False))  # LOCKS TABLE!

# NEVER: Use blocking index creation on large tables
op.create_index('idx_large', 'big_table', ['col'])  # Use CONCURRENTLY

# NEVER: Skip downgrade implementation
def downgrade():
    pass  # WRONG - implement proper rollback

# NEVER: Modify migration after deployment - create new migration instead

# NEVER: Run migrations automatically in production
# Use: alembic upgrade head --sql > review.sql

# NEVER: Run CONCURRENTLY inside transaction
op.execute("BEGIN; CREATE INDEX CONCURRENTLY ...; COMMIT;")  # FAILS

# NEVER: Delete migration history
command.stamp(alembic_config, "head")  # Loses history

# NEVER: Skip environments (Always: local -> CI -> staging -> production)

Detailed Documentation

ResourceDescription
references/ork-delta.mdOur corrections and house conventions. Read this first
references/migration-testing.mdUpgrade/downgrade cycle and data-integrity test harnesses
references/postgres-vs-mongodb.mdHead-to-head comparison behind the PostgreSQL-first default
references/db-migration-paths.mdCross-engine migration risk matrix
references/cost-comparison.mdManaged database cost analysis
references/storage-and-cms.mdObject storage and CMS selection
scripts/Migration template, model change detector

Zero-Downtime Migration

Safe database schema changes without downtime using expand-contract pattern and online schema changes.

RuleFileKey Pattern
Expand-Contractrules/migration-zero-downtime.mdExpand phase, backfill, contract phase, pgroll automation
Rollback & Monitoringrules/migration-rollback.mdpgroll rollback, lock monitoring, replication lag, backfill progress

Related Skills

  • sqlalchemy-2-async - Async SQLAlchemy session patterns
  • ork:testing-integration - Integration testing patterns including migration testing
  • caching - Cache layer design to complement database performance
  • ork:performance - Performance optimization patterns

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Database Patterns AI skill do?

Database design and migration patterns for Alembic migrations, schema design (SQL/NoSQL), and database versioning. Use when creating migrations, designing schemas, normalizing data, managing database versions, or handling schema drift.

Why use Database Patterns on TypingMind?

Because you install it once and use it with any model. Database Patterns is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Database Patterns in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/yonatangross/orchestkit/tree/main/plugins/ork/skills/database-patterns. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Database Patterns?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Database Patterns?

As many as you like. As long as a model supports skills, you can use Database Patterns with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Database Patterns AI skill free?

Yes. It is published on GitHub by yonatangross under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇