Adding CQL to Existing Project

This tutorial walks you through integrating CQL into an existing Crystal application. You'll learn how to add CQL alongside your current code, migrate existing data, and gradually adopt CQL patterns.

What You'll Learn

  • Adding CQL as a dependency

  • Configuring CQL alongside existing database code

  • Creating migrations for existing tables

  • Defining models for existing data

  • Gradually migrating to CQL patterns

Prerequisites

  • An existing Crystal project

  • Basic familiarity with CQL concepts

  • Access to your existing database

Step 1: Add Dependencies

Add CQL to your existing shard.yml:

dependencies:
  cql:
    github: azutoolkit/cql
    version: ~> 0.0.435

  # Keep your existing database driver or add one
  pg:
    github: will/crystal-pg
    version: "~> 0.26.0"

Install:

Step 2: Create Database Configuration

Create a separate file for CQL configuration:

Step 3: Define Existing Tables in Schema

If you have existing tables, define them in the schema so CQL knows about them:

Step 4: Create Models for Existing Tables

Create CQL models that map to your existing tables:

Step 5: Initialize CQL

Add CQL initialization to your application startup:

Step 6: Create New Migrations

For new features, create CQL migrations:

Step 7: Run New Migrations

Create a migration runner:

Run migrations:

Step 8: Gradual Migration Strategy

Adopt CQL incrementally:

Phase 1: Read Operations

Start by using CQL for read operations:

Phase 2: Simple Writes

Move simple create/update operations:

Phase 3: Complex Queries

Migrate complex queries:

Phase 4: Relationships

Add relationship navigation:

Handling Existing Migrations

If you have existing migrations (e.g., from another ORM), you have options:

Option A: Start Fresh

Create a baseline migration that represents your current schema:

Option B: Import Existing Schema

Mark existing migrations as applied:

Best Practices

  1. Don't modify existing tables with CQL initially - just read from them

  2. Test thoroughly before switching write operations

  3. Keep existing code working during transition

  4. Migrate one model at a time to limit risk

  5. Use transactions when doing bulk data updates

Common Issues

Column Name Mismatches

If your existing column names differ from CQL conventions:

Different Timestamp Format

If your timestamps use a different format:

Summary

You've learned how to:

  1. Add CQL to an existing Crystal project

  2. Define schemas for existing tables

  3. Create models for existing data

  4. Create new migrations for new features

  5. Gradually migrate from raw SQL to CQL patterns

Next Steps

Last updated

Was this helpful?