Record Models

The Cql::Record module in the CQL toolkit is a crucial part of the Object-Relational Mapping (ORM) system in Crystal. It allows you to define models that map to tables in your database and provides a wide array of functionalities for querying, inserting, updating, and deleting records. In this guide, we'll explore how the Cql::Record module works and how to use it effectively.

Example: Building a Simple Blog System

Let's combine everything we've learned to build a simple blog system where posts can have many comments.

Defining the Schema:

AcmeDB = Cql::Schema.define(
  :acme_db,
  adapter: Cql::Adapter::Postgres,
  uri: "postgresql://example:example@localhost:5432/example"
) do
  table :posts do
    primary
    text :title
    text :body
    timestamp :published_at
  end

  table :comments do
    primary
    bigint :post_id
    text :body
  end
end

Defining the Models:

struct Post < Cql::Record(Int64)
  db_context AcmeDB, :posts

  getter id : Int64?
  getter title : String
  getter body : String
  getter published_at : Time

  has_many :comments, Comment

  def initialize(@title : String, @body : String, @published_at : Time = Time.utc)
  end
end

struct Comment < Cql::Record(Int64)
  db_context AcmeDB, :comments

  getter id : Int64?
  getter post_id : Int64
  getter body : String

  belongs_to :post, Post

  def initialize(@post_id : Int64, @body : String)
  end
end

Using the Models:

  • Creating a Post:

post = Post.new("My First Blog Post", "This is the content of my first blog post.")
post.save
  • Adding Comments to the Post:

comment = Comment.new(post.id.not_nil!, "This is a comment.")
comment.save
  • Fetching Comments for a Post:

post = Post.find(1)
comments = post.comments

Conclusion

The Cql::Record module provides powerful tools for working with database records in a Crystal application. It simplifies the process of defining models, querying records, and managing associations. By leveraging the capabilities of CQL's Active Record-style ORM, you can build complex applications with ease.

With Cql::Record, you have access to:

  • Easy schema and model definition.

  • A rich set of query and manipulation methods.

  • Powerful association handling (belongs_to, has_many,

Last updated