Getting Started Guide

Welcome to CQL (Crystal Query Language). This guide will walk you through setting up CQL in your Crystal project, connecting to a database, defining your first model, and performing basic operations.

CQL is a powerful Object-Relational Mapping (ORM) library that provides type-safe database interactions, migrations, and Active Record patterns for Crystal applications.


Prerequisites

Before getting started, ensure you have:

  • Crystal (latest stable version recommended)

  • A supported database: PostgreSQL, MySQL, or SQLite

  • Database driver shards: Depending on your database choice


1. Installation

Add CQL and your database driver to your shard.yml:

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

  # Choose your database driver:
  pg: # For PostgreSQL
    github: will/crystal-pg
    version: "~> 0.26.0"

  # OR
  mysql: # For MySQL
    github: crystal-lang/crystal-mysql
    version: "~> 0.14.0"

  # OR
  sqlite3: # For SQLite
    github: crystal-lang/crystal-sqlite3
    version: "~> 0.18.0"

Then install dependencies:


2. Database Setup

PostgreSQL Example

SQLite Example

MySQL Example


3. Creating Your First Migration

Create a migration to set up your database schema:


4. Defining Your First Model

Create a model that represents your users table:


5. Initialize Database and Run Migrations

Set up automatic schema synchronization and run your migrations:


6. Basic CRUD Operations

Now you can start working with your data:

Create Records

Read Records

Update Records

Delete Records


7. Working with Associations

Let's add posts to demonstrate relationships:

Create Posts Migration

Define Post Model

Update User Model with Association

Work with Associations


8. Using Validations

Add validations to ensure data integrity:


9. Using Transactions

Ensure data consistency with transactions:


10. Next Steps

Congratulations! You now have a working CQL application. Here's what to explore next:

Essential Guides

Advanced Topics

Patterns and Best Practices


Common Issues and Solutions

Database Connection Issues

Migration Issues

Schema Synchronization Issues


Example Application Structure


Welcome to CQL! You're now ready to build powerful, type-safe database applications with Crystal. 🎉

Last updated

Was this helpful?