CQL
AzuAuthorityGithub
  • README
  • Introduction
  • Installation
  • Core Concepts
    • Schema Definition
    • Initializing Schema
    • Altering Schema
    • Migrations
    • CRUD Operations
      • Creating Records
      • Reading Records
      • Updating Records
      • Deleting Records
    • Patterns
      • Active Record
      • Entity Framework
      • Repository
  • Guides
    • Getting Started
    • Active Record with CQL
      • Defining Models
      • CRUD Operations
      • Querying
      • Complex Queries
      • Persistence Details
      • Validations
      • Callbacks
      • Transactions
      • Optimistic Locking
      • Relations
        • Belongs To
        • Has One
        • Has Many
        • Many To Many
      • Database Migrations
      • Scopes
      • Pagination
    • Transaction Management
    • Handling Migrations
  • Troubleshooting
  • FAQs
Powered by GitBook
On this page
  • Core Concepts & Guides
  • Prerequisites and Setup
  • Adding CQL to Your Project
  • Database Connection Setup
  • Quick Overview of Key Features
  • Defining Models
  • CRUD Operations
  • Querying
  • Transactions
  • Validations
  • Callbacks
  • Relations
  • Migrations
  • Scopes

Was this helpful?

Export as PDF
  1. Guides

Active Record with CQL

An overview of CQL's Active Record capabilities for defining models, interacting with your database, managing data integrity, and more.

PreviousGetting StartedNextDefining Models

Last updated 2 days ago

Was this helpful?

This guide provides a comprehensive overview of Crystal Query Language (CQL)'s Active Record implementation. Active Record is a design pattern that connects database tables to classes (or structs in Crystal), allowing you to interact with your data through objects and methods rather than raw SQL queries.

CQL's Active Record module offers a powerful and intuitive way to manage your database records, inspired by established ORMs while leveraging Crystal's type safety and performance.


Core Concepts & Guides

This central README provides a high-level introduction. For in-depth information on specific aspects of CQL Active Record, please refer to the following guides:

  • : Initial configuration for using CQL and Active Record. (Covered below)

  • : Learn how to define your Active Record models, map them to database tables, specify primary keys, and work with attributes.

  • : Detailed guide on creating, reading, updating, and deleting records using Active Record methods.

  • : Explore the powerful query interface, including direct finders, chainable queries, aggregations, and scopes.

  • : Ensure data integrity by using database transactions for multi-step operations.

  • : Understand how to check if a record is persisted and how to reload its data from the database.

  • : Ensure data integrity by defining and using model validations.

  • : Hook into the lifecycle of your models to trigger logic at specific events (e.g., before save, after create).

  • : Define and use associations between models:

    • (covers has_and_belongs_to_many)

  • : Manage your database schema changes over time.

  • : Define reusable query constraints for cleaner and more readable code.

  • : Easily paginate query results.


Prerequisites and Setup

Before getting started, ensure you have the following:

  • Crystal language installed (latest stable version recommended).

  • A supported relational database (e.g., PostgreSQL, MySQL) set up and accessible.

  • CQL added to your Crystal project.

Adding CQL to Your Project

Include CQL in your project's shard.yml:

dependencies:
  cql:
    github: azutoolkit/cql # Or the appropriate source for your CQL version
    version: "~> x.y.z" # Specify the version you are using

Then, run shards install to download and install the dependency.

Database Connection Setup

You need to configure CQL to connect to your database. This is typically done by setting a database URL and opening a connection. You might also define a database context for your application.

require "cql"

# Example: Define your database connection URL (replace with your actual credentials)
# For PostgreSQL:
ENV_DB_URL = ENV["DATABASE_URL"]? || "postgres://username:password@localhost:5432/myapp_development"

# Define a database context. This is often a class or module that your models will reference.
# The name `AcmeDB` is used as a placeholder in these guides.
module AcmeDB
  # Establishes and memoizes the database connection.
  def self.db
    @@db ||= DB.open(ENV_DB_URL)
  end

  # Optional: A method to close the connection if needed during shutdown or testing.
  def self.close_db
    @@db.try(&.close)
    @@db = nil
  end
end

# Ensure your models can reference this context, e.g.:
struct User
  include CQL::ActiveRecord::Model(Int64)
  db_context AcmeDB, :users
  # ...
end

Note: The exact mechanism for defining your database context (AcmeDB in the example) and making it accessible to your models should align with CQL's specific API and your application structure. Refer to CQL's core documentation for advanced database connection management, pooling, and context configuration.


Quick Overview of Key Features

Defining Models

Models are Crystal structs including CQL::ActiveRecord::Model(PkType) and use db_context to link to a table.

CRUD Operations

CQL provides intuitive methods for creating, reading, updating, and deleting records (e.g., save, create!, find?, find_by!, update!, delete!).

Querying

Fetch records using direct finders or build complex queries with a chainable interface (.where, .order, .limit, etc.).

Transactions

Maintain data integrity with ACID-compliant database transactions. CQL provides both model-level transaction support and a service objects pattern for complex operations.

# Basic transaction usage
BankAccount.transaction do |tx|
  account = BankAccount.find(1)
  account.balance -= 100
  account.save!

  Transaction.create!(
    amount: 100,
    transaction_type: "withdrawal",
    from_account_id: account.id,
    created_at: Time.utc
  )

  # All operations succeed or fail together
end

Validations

Ensure data integrity with built-in or custom validation rules triggered before saving records.

Callbacks

Execute custom logic at different points in a model's lifecycle (e.g., before_save, after_create).

Relations

Define associations like belongs_to, has_many, has_one, and many_to_many to manage relationships between models.

Migrations

Manage database schema changes systematically using Crystal-based migration files.

Scopes

Create reusable query shortcuts to keep your code clean and expressive.

See the full for details on attributes, primary keys, and more.

Explore the for comprehensive examples.

Dive into the for all query-building capabilities.

Learn more in the for maintaining data integrity across multiple operations.

Learn more in the .

Consult the for usage details.

See the for how to write and run migrations.

Read the for defining and using scopes.

Defining Models Guide
CRUD Operations Guide
Querying Guide
Transactions Guide
Validations Guide
Callbacks Guide
belongs_to
has_one
has_many
many_to_many
Database Migrations Guide
Scopes Guide
Defining Models
CRUD Operations
Querying
Transactions
Persistence Details
Validations
Callbacks
Relations
belongs_to
has_one
has_many
many_to_many
Database Migrations
Scopes
Pagination
Setup and Prerequisites