Getting Started

This tutorial walks you through building your first application with CQL from scratch. By the end, you'll have a working Crystal application that connects to a database, creates tables through migrations, and performs CRUD operations.

What You'll Learn

  • Installing CQL and database drivers

  • Configuring a database connection

  • Creating and running migrations

  • Defining Active Record models

  • Performing basic CRUD operations

  • Working with associations

  • Adding validations

  • Using transactions

Prerequisites

Before starting, ensure you have:

  • Crystal (latest stable version recommended)

  • A supported database: PostgreSQL, MySQL, or SQLite

  • Basic familiarity with Crystal syntax

Step 1: Create Your Project

Create a new Crystal project:

Step 2: Add Dependencies

Add CQL and your database driver to shard.yml:

Install the dependencies:

Step 3: Set Up Database Connection

Create a file to configure your database connection. The setup varies slightly by database.

PostgreSQL

SQLite

MySQL

Step 4: Create Your First Migration

Create a migrations directory and your first migration file:

Step 5: Define Your First Model

Create a model that maps to your users table:

Step 6: Initialize the Database and Run Migrations

Create a setup script to initialize everything:

Run the setup:

Step 7: Perform CRUD Operations

Now you can interact with your data. Create a main application file:

Run your application:

Let's add posts to demonstrate relationships. First, create the migration:

Create the Post model:

Update the User model to include the association:

Run migrations and test:

Step 9: Add Validations

Enhance your User model with validations:

Step 10: Use Transactions

Ensure data consistency with transactions:

Project Structure

Your completed project should look like this:

Troubleshooting

Database Connection Issues

Migration Issues

Next Steps

Congratulations! You've built your first CQL application. Continue learning with:

Last updated

Was this helpful?