Schema Alterations
Understanding Schema Changes: What, Why, and How
Schema alteration is the process of modifying your database structure after it's already been created and contains data. Think of it like renovating a house while people are still living in it - you need to be careful, methodical, and ensure everything continues to work.
Why Schema Changes Are Inevitable
When you first design a database, you make your best guess about what you'll need. But software evolves:
# Week 1: Simple user system
table :users do
primary :id, Int32
text :name
text :email
end
# Week 6: Need user preferences
table :users do
primary :id, Int32
text :name
text :email
text :preferences # ← New requirement!
bool :email_verified # ← Security requirement!
end
# Week 12: Need user roles and permissions
table :users do
primary :id, Int32
text :name
text :email
text :preferences
bool :email_verified
text :role # ← Admin vs regular users
timestamp :last_login # ← Analytics requirement
endThis is normal and expected! The key is handling these changes safely and systematically.
Two Approaches to Schema Changes in CQL
CQL gives you two ways to modify your database schema, each suited for different situations:
When to use which approach:
Migrations: Production apps, team projects, changes you want to track
Direct alterations: Quick experiments, one-off fixes, learning CQL
Core Concepts: Understanding Database Alterations
1. The AlterTable Operations - Your Schema Modification Toolkit
Think of AlterTable operations as your toolbox for database modifications. Each operation is designed for a specific type of change:
2. Schema Alteration Safety - Why Order Matters
Database alterations aren't just code changes - they affect live data. The order of operations matters:
3. The Connection to Migrations - Keeping Everything in Sync
When you alter schemas through migrations, CQL automatically updates your AppSchema.cr file:
This means your Crystal code always knows the current database structure, preventing runtime errors.
Learning Path: From Simple Changes to Complex Transformations
Level 1: Adding New Columns (The Safe Start)
Adding columns is usually the safest schema change because it doesn't affect existing data:
Key learning points:
New columns should usually be
null: trueto accommodate existing recordsProvide sensible defaults for non-nullable columns
Think about what happens to existing data
Always provide a rollback path
Level 2: Creating Indexes for Performance
As your app grows, you'll notice some queries getting slow. Indexes are your solution:
Why indexes matter:
Without index: Database scans every row to find matches (slow!)
With index: Database uses the index like a book's table of contents (fast!)
Unique indexes: Prevent duplicate data AND improve performance
Composite indexes: Optimize queries that filter on multiple columns
Level 3: Creating Relationships Between Tables
Real applications have related data. Foreign keys maintain data integrity:
Understanding foreign key options:
on_delete: "CASCADE": Delete related records when parent is deletedon_delete: "SET NULL": Set foreign key to NULL when parent is deletedon_delete: "RESTRICT": Prevent deletion of parent if children existon_update: "CASCADE": Update foreign keys when parent ID changes
Level 4: Complex Data Transformations
Sometimes you need to transform existing data, not just structure:
Data transformation best practices:
Plan carefully: Data transformations can be irreversible
Backup first: Always have a recovery plan
Test thoroughly: Use realistic test data
Consider performance: Large data migrations can be slow
Batch operations: Don't lock tables for too long
Working with Existing Databases: The Bootstrap Approach
When You Inherit a Database
Maybe you're joining a project with an existing database, or converting from another ORM. CQL's bootstrap feature creates a starting point:
What bootstrap gives you:
Complete
ExistingSchema.crfile matching your databaseBaseline for future migrations
Type safety for your Crystal code
No data loss or downtime
Adopting the Migration Workflow
After bootstrapping, future changes use migrations:
Environment-Specific Strategies
Development: Fast Iteration with Safety Nets
In development, you want speed but also safety:
Production: Safety First
Production requires careful, controlled changes:
Common Pitfalls and How to Avoid Them
Pitfall 1: Forgetting About Existing Data
Pitfall 2: Dropping Columns with Constraints
Pitfall 3: Not Testing Rollbacks
Performance Considerations: Making Changes Without Breaking Things
Index Creation on Large Tables
Batching Large Data Changes
Advanced Patterns: Real-World Scenarios
Pattern 1: Feature Flag Columns
Pattern 2: Data Archival Preparation
Pattern 3: Gradual Column Replacement
Debugging Schema Changes
Understanding What Went Wrong
Common Error Messages and Solutions
Complete Example: E-commerce Schema Evolution
Let's follow an e-commerce site's schema changes over time:
Related Documentation
Migrations - Complete migration workflow and team collaboration
Initializing the Database - Setting up new databases and bootstrap strategies
Schema Dump Guide - Working with existing databases
Migration Workflow Guide - Advanced patterns and real-world examples
Key Takeaways
Schema changes are inevitable - plan for them from the start
Use migrations for tracking - they provide version control for your database
Consider existing data - new columns should usually be nullable initially
Test rollbacks - ensure you can undo changes if something goes wrong
Performance matters - indexes can make queries thousands of times faster
Safety first in production - use manual verification and maintenance windows
Bootstrap existing databases - don't rewrite everything to adopt CQL
Schema alteration is both an art and a science. The technical operations are straightforward, but understanding when and how to use them safely requires experience. Start with simple changes, test thoroughly, and gradually work up to more complex transformations. CQL's integrated migration system makes this process as safe and straightforward as possible, but good practices and careful planning are still essential for success.
Last updated
Was this helpful?