LogoLogo
HomeAPIBlog
3.0.0-SNAPSHOT
3.0.0-SNAPSHOT
  • INTRODUCTION
    • Getting Started
      • Running Local Development Servers
      • Beginner Tutorial: Hello World
      • Beginner Tutorial: Hello Database
      • Tutorial: Wheels, AJAX, and You
    • Frameworks and Wheels
    • Requirements
    • Manual Installation
    • Upgrading
    • Screencasts
  • Command Line Tools
    • CLI Overview
    • Quick Start Guide
    • Command Reference
      • Core Commands
        • wheels init
        • wheels info
        • wheels reload
        • wheels deps
        • wheels destroy
        • wheels watch
      • Code Generation
        • wheels generate app
        • wheels generate app-wizard
        • wheels generate controller
        • wheels generate model
        • wheels generate view
        • wheels generate property
        • wheels generate route
        • wheels generate resource
        • wheels generate api-resource
        • wheels generate frontend
        • wheels generate test
        • wheels generate snippets
        • wheels scaffold
      • Database Commands
        • wheels dbmigrate info
        • wheels dbmigrate latest
        • wheels dbmigrate up
        • wheels dbmigrate down
        • wheels dbmigrate reset
        • wheels dbmigrate exec
        • wheels dbmigrate create blank
        • wheels dbmigrate create table
        • wheels dbmigrate create column
        • wheels dbmigrate remove table
        • wheels db schema
        • wheels db seed
      • Testing Commands
        • wheels test
        • wheels test run
        • wheels test coverage
        • wheels test debug
      • Configuration Commands
        • wheels config list
        • wheels config set
        • wheels config env
      • Environment Management
        • wheels env
        • wheels env setup
        • wheels env list
        • wheels env switch
      • Plugin Management
        • wheels plugins
        • wheels plugins list
        • wheels plugins install
        • wheels plugins remove
      • Code Analysis
        • wheels analyze
        • wheels analyze code
        • wheels analyze performance
        • wheels analyze security
      • Security Commands
        • wheels security
        • wheels security scan
      • Performance Commands
        • wheels optimize
        • wheels optimize performance
      • Documentation Commands
        • wheels docs
        • wheels docs generate
        • wheels docs serve
      • CI/CD Commands
        • wheels ci init
      • Docker Commands
        • wheels docker init
        • wheels docker deploy
      • Deployment Commands
        • wheels deploy
        • wheels deploy audit
        • wheels deploy exec
        • wheels deploy hooks
        • wheels deploy init
        • wheels deploy lock
        • wheels deploy logs
        • wheels deploy proxy
        • wheels deploy push
        • wheels deploy rollback
        • wheels deploy secrets
        • wheels deploy setup
        • wheels deploy status
        • wheels deploy stop
    • CLI Development Guides
      • Creating Commands
      • Service Architecture
      • Migrations Guide
      • Testing Guide
  • Working with Wheels
    • Conventions
    • Configuration and Defaults
    • Directory Structure
    • Switching Environments
    • Testing Your Application
    • Using the Test Environment
    • Contributing to Wheels
    • Submitting Pull Requests
    • Documenting your Code
  • Handling Requests with Controllers
    • Request Handling
    • Rendering Content
    • Redirecting Users
    • Sending Files
    • Sending Email
    • Responding with Multiple Formats
    • Using the Flash
    • Using Filters
    • Verification
    • Event Handlers
    • Routing
    • URL Rewriting
      • Apache
      • IIS
      • Tomcat
      • Nginx
    • Obfuscating URLs
    • Caching
    • Nesting Controllers
    • CORS Requests
  • Displaying Views to Users
    • Pages
    • Partials
    • Linking Pages
    • Layouts
    • Form Helpers and Showing Errors
    • Displaying Links for Pagination
    • Date, Media, and Text Helpers
    • Creating Custom View Helpers
    • Localization
  • Database Interaction Through Models
    • Object Relational Mapping
    • Creating Records
    • Reading Records
    • Updating Records
    • Deleting Records
    • Column Statistics
    • Dynamic Finders
    • Getting Paginated Data
    • Associations
    • Nested Properties
    • Object Validation
    • Object Callbacks
    • Calculated Properties
    • Transactions
    • Dirty Records
    • Soft Delete
    • Automatic Time Stamps
    • Database Migrations
      • Migrations in Production
    • Using Multiple Data Sources
  • Plugins
    • Installing and Using Plugins
    • Developing Plugins
    • Publishing Plugins
  • Project Documentation
    • Overview
  • External Links
    • Source Code
    • Issue Tracker
    • Sponsor Us
    • Community
Powered by GitBook
LogoLogo
On this page
  • Synopsis
  • Description
  • Options
  • --env
  • --file
  • --datasource
  • --clean
  • --only
  • --except
  • --verbose
  • --dry-run
  • Examples
  • Basic seeding
  • Clean and seed
  • Selective seeding
  • Custom seed files
  • Seed File Structure
  • Basic Seed File (db/seeds.cfm)
  • Modular Seed Files
  • Use Cases
  • Development Environment Setup
  • Testing Data
  • Demo Data
  • Performance Testing
  • Advanced Seeding Patterns
  • Faker Integration
  • Relationship Seeding
  • Conditional Seeding
  • Best Practices
  • 1. Idempotent Seeds
  • 2. Use Transactions
  • 3. Organize by Domain
  • 4. Document Seeds
  • Error Handling
  • Validation Errors
  • Dependency Handling
  • Notes
  • Related Commands

Was this helpful?

Edit on GitHub
Export as PDF
  1. Command Line Tools
  2. Command Reference
  3. Database Commands

wheels db seed

Populate the database with seed data for development and testing.

Synopsis

wheels db seed [options]

Description

The db seed command populates your database with predefined data sets. This is essential for development environments, testing scenarios, and demo installations. Seed data provides a consistent starting point for application development and testing.

Options

--env

  • Type: String

  • Default: development

  • Description: Environment to seed (development, testing, staging)

--file

  • Type: String

  • Default: db/seeds.cfm

  • Description: Path to seed file or directory

--datasource

  • Type: String

  • Default: Application default

  • Description: Specific datasource to seed

--clean

  • Type: Boolean

  • Default: false

  • Description: Clear existing data before seeding

--only

  • Type: String

  • Default: All seeds

  • Description: Run only specific seed files (comma-separated)

--except

  • Type: String

  • Default: None

  • Description: Skip specific seed files (comma-separated)

--verbose

  • Type: Boolean

  • Default: false

  • Description: Show detailed output during seeding

--dry-run

  • Type: Boolean

  • Default: false

  • Description: Preview seed operations without executing

Examples

Basic seeding

# Run default seeds
wheels db seed

# Seed specific environment
wheels db seed --env=testing

Clean and seed

# Clear data and reseed
wheels db seed --clean

# Clean seed with confirmation
wheels db seed --clean --verbose

Selective seeding

# Run specific seeds
wheels db seed --only=users,products

# Skip certain seeds
wheels db seed --except=large_dataset,temporary_data

Custom seed files

# Use custom seed file
wheels db seed --file=db/seeds/demo_data.cfm

# Use seed directory
wheels db seed --file=db/seeds/development/

Seed File Structure

Basic Seed File (db/seeds.cfm)

<cfscript>
// db/seeds.cfm
component extends="wheels.Seeder" {

    function run() {
        // Create admin user
        user = model("user").create(
            username = "admin",
            email = "admin@example.com",
            password = "password123",
            role = "admin"
        );

        // Create sample categories
        categories = [
            {name: "Electronics", slug: "electronics"},
            {name: "Books", slug: "books"},
            {name: "Clothing", slug: "clothing"}
        ];

        for (category in categories) {
            model("category").create(category);
        }

        // Create sample products
        electronicsCategory = model("category").findOne(where="slug='electronics'");
        
        products = [
            {
                name: "Laptop",
                price: 999.99,
                category_id: electronicsCategory.id,
                in_stock: true
            },
            {
                name: "Smartphone",
                price: 699.99,
                category_id: electronicsCategory.id,
                in_stock: true
            }
        ];

        for (product in products) {
            model("product").create(product);
        }

        announce("Seed data created successfully!");
    }

    function clean() {
        // Clean in reverse order of dependencies
        model("product").deleteAll();
        model("category").deleteAll();
        model("user").deleteAll();
        
        announce("Database cleaned!");
    }

}
</cfscript>

Modular Seed Files

// db/seeds/users.cfm
component extends="wheels.Seeder" {
    
    function run() {
        // Admin users
        createAdminUsers();
        
        // Regular users
        createSampleUsers(count=50);
        
        // Test users
        createTestUsers();
    }
    
    private function createAdminUsers() {
        admins = [
            {username: "admin", email: "admin@example.com", role: "admin"},
            {username: "moderator", email: "mod@example.com", role: "moderator"}
        ];
        
        for (admin in admins) {
            admin.password = hash("password123");
            model("user").create(admin);
        }
    }
    
    private function createSampleUsers(required numeric count) {
        for (i = 1; i <= arguments.count; i++) {
            model("user").create(
                username = "user#i#",
                email = "user#i#@example.com",
                password = hash("password123"),
                created_at = dateAdd("d", -randRange(1, 365), now())
            );
        }
    }
    
}

Use Cases

Development Environment Setup

Create consistent development data:

# Reset and seed development database
wheels dbmigrate reset --remigrate
wheels db seed --clean

Testing Data

Prepare test database:

# Seed test environment
wheels db seed --env=testing --clean

# Run tests
wheels test run

Demo Data

Create demonstration data:

# Load demo dataset
wheels db seed --file=db/seeds/demo.cfm --clean

Performance Testing

Generate large datasets:

# Create performance test data
wheels db seed --file=db/seeds/performance_test.cfm

Advanced Seeding Patterns

Faker Integration

component extends="wheels.Seeder" {
    
    function run() {
        faker = new lib.Faker();
        
        // Generate realistic data
        for (i = 1; i <= 100; i++) {
            model("customer").create(
                first_name = faker.firstName(),
                last_name = faker.lastName(),
                email = faker.email(),
                phone = faker.phoneNumber(),
                address = faker.streetAddress(),
                city = faker.city(),
                state = faker.state(),
                zip = faker.zipCode()
            );
        }
    }
    
}

Relationship Seeding

component extends="wheels.Seeder" {
    
    function run() {
        // Create users
        users = [];
        for (i = 1; i <= 10; i++) {
            users.append(model("user").create(
                username = "user#i#",
                email = "user#i#@example.com"
            ));
        }
        
        // Create posts for each user
        for (user in users) {
            postCount = randRange(5, 15);
            for (j = 1; j <= postCount; j++) {
                post = model("post").create(
                    user_id = user.id,
                    title = "Post #j# by #user.username#",
                    content = generateContent(),
                    published_at = dateAdd("d", -randRange(1, 30), now())
                );
                
                // Add comments
                addCommentsToPost(post, users);
            }
        }
    }
    
    private function addCommentsToPost(post, users) {
        commentCount = randRange(0, 10);
        for (i = 1; i <= commentCount; i++) {
            randomUser = users[randRange(1, arrayLen(users))];
            model("comment").create(
                post_id = post.id,
                user_id = randomUser.id,
                content = "Comment #i# on post",
                created_at = dateAdd("h", i, post.published_at)
            );
        }
    }
    
}

Conditional Seeding

component extends="wheels.Seeder" {
    
    function run() {
        // Only seed if empty
        if (model("user").count() == 0) {
            seedUsers();
        }
        
        // Environment-specific seeding
        if (application.environment == "development") {
            seedDevelopmentData();
        } else if (application.environment == "staging") {
            seedStagingData();
        }
    }
    
}

Best Practices

1. Idempotent Seeds

Make seeds safe to run multiple times:

function run() {
    // Check before creating
    if (!model("user").exists(username="admin")) {
        model("user").create(
            username = "admin",
            email = "admin@example.com"
        );
    }
}

2. Use Transactions

Wrap seeds in transactions:

function run() {
    transaction {
        try {
            seedUsers();
            seedProducts();
            seedOrders();
        } catch (any e) {
            transaction action="rollback";
            throw(e);
        }
    }
}

3. Organize by Domain

Structure seeds logically:

db/seeds/
  ├── 01_users.cfm
  ├── 02_products.cfm
  ├── 03_orders.cfm
  └── 04_analytics.cfm

4. Document Seeds

Add clear documentation:

/**
 * Seeds initial product catalog
 * Creates: 5 categories, 50 products
 * Dependencies: None
 * Runtime: ~2 seconds
 */
function run() {
    // Seed implementation
}

Error Handling

Validation Errors

function run() {
    try {
        user = model("user").create(data);
        if (user.hasErrors()) {
            announce("Failed to create user: #user.allErrors()#");
        }
    } catch (any e) {
        announce("Error: #e.message#", "error");
    }
}

Dependency Handling

function run() {
    // Check dependencies
    if (model("category").count() == 0) {
        throw("Categories must be seeded first!");
    }
    
    // Continue with seeding
}

Notes

  • Seed files are typically not run in production

  • Always use transactions for data integrity

  • Consider performance for large seed operations

  • Keep seed data realistic and useful

Related Commands

Previouswheels db schemaNextTesting Commands

Last updated 2 days ago

Was this helpful?

- Run migrations before seeding

- Export/import database structure

- Generate models for seeding

- Test with seeded data

wheels dbmigrate latest
wheels db schema
wheels generate model
wheels test run