Skip to main content
ClaudeWave
Skill237 repo starsupdated 1mo ago

Backend Models Standards

Backend Models Standards defines database model structure, naming conventions, field requirements, data integrity constraints, and relationship definitions for backend applications. Use this skill when creating or modifying ORM classes, schema files, or database model definitions to ensure proper data representation, enforce constraints at the database level, establish clear relationships between entities, and implement consistent naming conventions across model files.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/Microck/ordinary-claude-skills /tmp/backend-models-standards && cp -r /tmp/backend-models-standards/skills_all/backend-models-standards ~/.claude/skills/backend-models-standards
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# Backend Models Standards

**Core Rule:** Models define data structure and integrity. Keep them focused on data representation, not business logic.

## When to use this skill

- When creating or modifying database model files (models.py, models/, schema.prisma, etc.)
- When defining ORM classes or ActiveRecord models for database tables
- When establishing table relationships (one-to-many, many-to-many, has-many, belongs-to)
- When configuring foreign keys, indexes, and cascade behaviors
- When implementing model-level validation rules
- When adding timestamp fields (created_at, updated_at) for auditing
- When setting database constraints (NOT NULL, UNIQUE, CHECK constraints)
- When choosing appropriate data types for model fields
- When balancing normalization with query performance needs
- When defining model methods or scopes for common queries

This Skill provides Claude Code with specific guidance on how to adhere to coding standards as they relate to how it should handle backend models.

## Naming Conventions

**Models:** Singular, PascalCase (`User`, `OrderItem`, `PaymentMethod`)

**Tables:** Plural, snake_case (`users`, `order_items`, `payment_methods`)

**Relationships:** Descriptive and clear
- `user.orders` (one-to-many)
- `order.items` (one-to-many)
- `product.categories` (many-to-many)

**Avoid generic names:** `data`, `info`, `record`, `entity`

## Required Fields

**Timestamps on every model:**
```python
created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
updated_at = Column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
```

**Primary keys:** Always explicit, prefer UUIDs for distributed systems or auto-incrementing integers for simplicity

**Why:** Auditing, debugging, data lineage tracking, soft deletes

## Data Integrity - Database Level

**Use constraints, not just application validation:**

```python
# NOT NULL for required fields
email = Column(String(255), nullable=False)

# UNIQUE constraints
email = Column(String(255), unique=True, nullable=False)

# CHECK constraints for business rules
age = Column(Integer, CheckConstraint('age >= 18'))

# Foreign keys with explicit cascade behavior
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'))
```

**Why:** Database enforces rules even if application code bypassed. Defense in depth.

## Data Types - Choose Appropriately

| Data       | Type               | Avoid       |
| ---------- | ------------------ | ----------- |
| Email, URL | VARCHAR(255)       | TEXT        |
| Short text | VARCHAR(n)         | TEXT        |
| Long text  | TEXT               | VARCHAR     |
| Money      | DECIMAL(10,2)      | FLOAT       |
| Boolean    | BOOLEAN            | TINYINT     |
| Timestamps | TIMESTAMP/DATETIME | VARCHAR     |
| JSON data  | JSON/JSONB         | TEXT        |
| UUIDs      | UUID               | VARCHAR(36) |

**Why:** Correct types enable database optimizations, constraints, and prevent data corruption.

## Indexes - Performance Critical

**Always index:**
- Primary keys (automatic)
- Foreign keys (manual in most ORMs)
- Columns in WHERE clauses
- Columns in JOIN conditions
- Columns in ORDER BY clauses

**Example:**
```python
class Order(Base):
    __tablename__ = 'orders'
    
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'), index=True)
    status = Column(String(50), index=True)  # Frequently filtered
    created_at = Column(DateTime, index=True)  # Frequently sorted
```

**Don't over-index:** Each index slows writes. Index only queried columns.

## Relationships - Explicit Configuration

**Define both sides of relationships:**

```python
# One-to-many
class User(Base):
    orders = relationship('Order', back_populates='user', cascade='all, delete-orphan')

class Order(Base):
    user_id = Column(Integer, ForeignKey('users.id'))
    user = relationship('User', back_populates='orders')
```

**Cascade behaviors:**
- `CASCADE`: Delete related records (user deleted → orders deleted)
- `SET NULL`: Nullify foreign key (category deleted → product.category_id = NULL)
- `RESTRICT`: Prevent deletion if related records exist
- `NO ACTION`: Database default, usually same as RESTRICT

**Choose based on business logic, not convenience.**

## Validation - Two Layers

**Model-level validation (application):**
```python
@validates('email')
def validate_email(self, key, email):
    if not re.match(r'^[^@]+@[^@]+\.[^@]+$', email):
        raise ValueError('Invalid email format')
    return email
```

**Database-level constraints (see Data Integrity section)**

**Why both:** Model validation provides clear error messages. Database constraints prevent data corruption if application bypassed.

## What Belongs in Models

**YES:**
- Field definitions and types
- Relationships to other models
- Simple property methods (`@property def full_name`)
- Data validation rules
- Database constraints

**NO:**
- Business logic (move to service layer)
- External API calls
- Complex calculations (move to service methods)
- Email sending, file uploads, etc.

**Models represent data structure, not behavior.**

## Normalization vs Performance

**Normalize when:**
- Data has clear entity boundaries
- Updates need to propagate (user email changes once)
- Avoiding data duplication is critical

**Denormalize when:**
- Read performance critical (analytics, reporting)
- Data rarely changes (historical snapshots)
- Joins become too expensive

**Default to normalized. Denormalize only with evidence of performance issues.**

## Common Patterns

**Soft deletes:**
```python
deleted_at = Column(DateTime, nullable=True, index=True)

# Query only active records
query = session.query(User).filter(User.deleted_at.is_(None))
```

**Polymorphic associations:**
```python
# Avoid if possible - complex and hard to maintain
# Prefer separate relationship fields or inheritance
```

**Enums for fixed values:**
```python
from enum import Enum

class OrderStatus(str
activitypub-testingSkill

Testing patterns for PHPUnit and Playwright E2E tests. Use when writing tests, debugging test failures, setting up test coverage, or implementing test patterns for ActivityPub features.

adaptyvSkill

Cloud laboratory platform for automated protein testing and validation. Use when designing proteins and needing experimental validation including binding assays, expression testing, thermostability measurements, enzyme activity assays, or protein sequence optimization. Also use for submitting experiments via API, tracking experiment status, downloading results, optimizing protein sequences for better expression using computational tools (NetSolP, SoluProt, SolubleMPNN, ESM), or managing protein design workflows with wet-lab validation.

add-uint-supportSkill

Add unsigned integer (uint) type support to PyTorch operators by updating AT_DISPATCH macros. Use when adding support for uint16, uint32, uint64 types to operators, kernels, or when user mentions enabling unsigned types, barebones unsigned types, or uint support.

Agent DevelopmentSkill

This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.

AgentDB Advanced FeaturesSkill

Master advanced AgentDB features including QUIC synchronization, multi-database management, custom distance metrics, hybrid search, and distributed systems integration. Use when building distributed AI systems, multi-agent coordination, or advanced vector search applications.

AgentDB Learning PluginsSkill

Create and train AI learning plugins with AgentDB's 9 reinforcement learning algorithms. Includes Decision Transformer, Q-Learning, SARSA, Actor-Critic, and more. Use when building self-learning agents, implementing RL, or optimizing agent behavior through experience.

AgentDB Memory PatternsSkill

Implement persistent memory patterns for AI agents using AgentDB. Includes session memory, long-term storage, pattern learning, and context management. Use when building stateful agents, chat systems, or intelligent assistants.

AgentDB Performance OptimizationSkill

Optimize AgentDB performance with quantization (4-32x memory reduction), HNSW indexing (150x faster search), caching, and batch operations. Use when optimizing memory usage, improving search speed, or scaling to millions of vectors.