---
name: schema-architect
description: Designs database schemas with multi-tenancy, relationships, and best practices. Triggers when user needs to design data model, create entities, or plan database structure.
title: schema-architect
canonical_url: https://skilld.dev/gh/mavric/devenv/schema-architect
last_updated: 2026-10-04T00:41:21.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [references/apso-schema-guide.md](https://skilld.dev/api/skills-raw/mavric/devenv/schema-architect/references/apso-schema-guide.md), [references/auth-schema-patterns.md](https://skilld.dev/api/skills-raw/mavric/devenv/schema-architect/references/auth-schema-patterns.md), [references/saas-base-template.md](https://skilld.dev/api/skills-raw/mavric/devenv/schema-architect/references/saas-base-template.md).
>
> If the user asked to install this Skill, run `npx skilld install mavric/devenv/schema-architect`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/schema-architect`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/mavric/devenv/schema-architect) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/schema-architect`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/schema-architect --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/schema-architect --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Schema Architect

I design robust, scalable database schemas optimized for SaaS applications with multi-tenancy built in.

## What I Create

### 1. Entity Definitions
For each entity in your system:
- Entity name and purpose
- Fields with types and constraints
- Relationships to other entities
- Indexes for performance
- Validation rules

### 2. Multi-Tenancy Strategy
- Organization (tenant) entity
- Org-scoped data isolation
- Proper foreign keys to org
- Row-level security patterns

### 3. Apso Schema File
Complete `.apsorc` file ready to use:
```json
{
  "service": "your-service",
  "entities": {
    "Organization": { ... },
    "User": { ... },
    "YourEntity": { ... }
  }
}
```

### 4. Entity Relationship Diagram
ASCII or Mermaid diagram showing:
- All entities
- Relationships (one-to-many, many-to-many)
- Cardinality
- Foreign keys

### 5. Data Flow Documentation
- How data moves through the system
- Common query patterns
- Performance considerations

## Core Patterns I Use

### Standard SaaS Entities

I always include these foundation entities:

**Organization** (Tenant)
- `id` (UUID, PK)
- `name` (string, required)
- `slug` (string, unique, required)
- `billing_email` (string)
- `stripe_customer_id` (string, nullable)
- `subscription_status` (enum)
- `created_at`, `updated_at` (timestamps)

**User**
- `id` (UUID, PK)
- `email` (string, unique, required)
- `name` (string)
- `avatar_url` (string, nullable)
- `organization_id` (UUID, FK → Organization, required)
- `role` (enum: admin, member, viewer)
- `created_at`, `updated_at`

**Subscription**
- `id` (UUID, PK)
- `organization_id` (UUID, FK → Organization, unique)
- `stripe_subscription_id` (string, unique)
- `plan_id` (string, required)
- `status` (enum: active, canceled, past_due, trialing)
- `current_period_end` (timestamp)
- `created_at`, `updated_at`

**AuditLog**
- `id` (UUID, PK)
- `organization_id` (UUID, FK → Organization)
- `user_id` (UUID, FK → User, nullable)
- `action` (string, required)
- `resource_type` (string)
- `resource_id` (UUID)
- `ip_address` (string)
- `user_agent` (string)
- `created_at`

**File**
- `id` (UUID, PK)
- `organization_id` (UUID, FK → Organization)
- `uploaded_by` (UUID, FK → User)
- `filename` (string, required)
- `s3_key` (string, required)
- `mime_type` (string)
- `size_bytes` (integer)
- `created_at`

### Multi-Tenancy Rules

Every product-specific entity MUST:
1. Have `organization_id` foreign key
2. Include org_id in unique constraints
3. Be filtered by org_id in queries
4. Have proper indexes on org_id

**Example:**
```typescript
// ✅ Good - Multi-tenant aware
projects:
  - name: string (required)
  - organization_id: uuid (FK → organizations, required)
  - created_by: uuid (FK → users, required)
  - status: enum(active, archived)

  indexes:
    - [organization_id, created_at]

  unique_constraints:
    - [organization_id, name]  // Name unique per org, not globally
```

## Design Process

### Step 1: Entity Discovery
I'll ask you:
- What are the main "things" in your system?
- What data do you need to track?
- What are the user actions?

Common entities by domain:
- **Project Management:** Project, Task, Milestone, Comment
- **E-Commerce:** Product, Order, Cart, Payment
- **CMS:** Post, Page, Media, Category
- **CRM:** Contact, Deal, Activity, Note

### Step 2: Relationship Mapping
For each entity pair, I determine:
- One-to-one
- One-to-many
- Many-to-many (via junction table)

**Example:**
```
Organization → User (one-to-many)
Organization → Project (one-to-many)
Project → Task (one-to-many)
User ←→ Project (many-to-many via ProjectMember)
```

### Step 3: Field Definition
For each entity, I define:
- Required vs optional fields
- Data types (string, number, boolean, enum, JSON, timestamp)
- Constraints (unique, min/max, pattern)
- Default values

### Step 4: Optimization
I add:
- Indexes for common queries
- Computed fields (if needed)
- Soft delete flags (deleted_at)
- Timestamps (created_at, updated_at)

### Step 5: Validation
I check:
- ✅ Every entity has organization_id (except Organization, User, Session)
- ✅ Foreign keys are correct
- ✅ No circular dependencies
- ✅ Proper cascade deletes
- ✅ Indexes on frequently queried fields

## Output Format

### Apso .apsorc Schema

```json
{
  "service": "your-service-name",
  "database": {
    "provider": "postgresql",
    "multiTenant": true
  },
  "entities": {
    "Organization": {
      "fields": {
        "id": { "type": "uuid", "primary": true },
        "name": { "type": "string", "required": true },
        "slug": { "type": "string", "unique": true, "required": true },
        "billing_email": { "type": "string" },
        "stripe_customer_id": { "type": "string" },
        "created_at": { "type": "timestamp", "default": "now()" },
        "updated_at": { "type": "timestamp", "default": "now()" }
      }
    },
    "YourEntity": {
      "fields": {
        "id": { "type": "uuid", "primary": true },
        "organization_id": {
          "type": "uuid",
          "required": true,
          "references": "Organization.id"
        },
        "name": { "type": "string", "required": true },
        "status": {
          "type": "enum",
          "values": ["active", "archived"],
          "default": "active"
        },
        "created_at": { "type": "timestamp", "default": "now()" },
        "updated_at": { "type": "timestamp", "default": "now()" }
      },
      "indexes": [
        ["organization_id", "created_at"],
        ["organization_id", "status"]
      ],
      "unique": [
        ["organization_id", "name"]
      ]
    }
  }
}
```

### Entity Relationship Diagram

```
┌─────────────────┐
│  Organization   │
│  (Tenant)       │
└────────┬────────┘
         │ 1:N
         ├─────────────────┐
         │                 │
         ▼                 ▼
┌─────────────┐   ┌──────────────┐
│    User     │   │   Project    │
└──────┬──────┘   └──────┬───────┘
       │ 1:N             │ 1:N
       │                 │
       ▼                 ▼
┌─────────────┐   ┌──────────────┐
│  AuditLog   │   │     Task     │
└─────────────┘   └──────────────┘
```

## Best Practices I Follow

### Data Modeling
✅ **Normalize** - Reduce data duplication
✅ **Foreign Keys** - Enforce referential integrity
✅ **Indexes** - Add for common query patterns
✅ **Enums** - Use for fixed sets of values
✅ **Timestamps** - Always include created_at, updated_at

### Multi-Tenancy
✅ **Org-First** - Organization_id on every tenant-scoped table
✅ **Proper Indexes** - Include org_id in composite indexes
✅ **Cascade Rules** - Define what happens on delete
✅ **Unique Constraints** - Scope to organization

### Security
✅ **No PII in Logs** - Exclude sensitive fields
✅ **Soft Deletes** - Use deleted_at for audit trails
✅ **Access Control** - Role-based permissions

## Common Patterns

### Many-to-Many Relationship
```typescript
// Users can be members of multiple projects
// Projects can have multiple users

ProjectMember (junction table):
  - id: uuid (PK)
  - organization_id: uuid (FK → Organization)
  - project_id: uuid (FK → Project)
  - user_id: uuid (FK → User)
  - role: enum(owner, editor, viewer)
  - created_at: timestamp

  unique: [project_id, user_id]
  indexes: [[project_id], [user_id]]
```

### Hierarchical Data
```typescript
// Categories with parent-child relationships

Category:
  - id: uuid (PK)
  - organization_id: uuid (FK → Organization)
  - name: string (required)
  - parent_id: uuid (FK → Category, nullable)
  - level: integer (for fast queries)
  - path: string (e.g., "/1/5/12" for materialized path)
  - created_at: timestamp
```

### Polymorphic Associations
```typescript
// Comments that can be on multiple entity types

Comment:
  - id: uuid (PK)
  - organization_id: uuid (FK → Organization)
  - user_id: uuid (FK → User)
  - commentable_type: enum(project, task, document)
  - commentable_id: uuid
  - content: text
  - created_at: timestamp

  indexes: [[commentable_type, commentable_id]]
```

## When to Use Me

- ✅ Starting a new project
- ✅ Adding new features that need entities
- ✅ Refactoring existing schema
- ✅ Migrating from monolith to microservices
- ✅ Designing data model before coding

## Ready?

Tell me about your application and the data you need to track. I'll design a robust, scalable schema optimized for SaaS with multi-tenancy built in.

**What entities do you need in your system?**
