Schema Definition

CQL schemas define your database structure declaratively with type-safe column definitions.

Defining a Schema

require "cql"

AppDB = CQL::Schema.define(
  :app_database,
  adapter: CQL::Adapter::Postgres,
  uri: ENV["DATABASE_URL"]
) do
  table :users do
    primary :id, Int64
    text :name
    text :email
    integer :age, null: true
    boolean :active, default: "true"
    timestamps
  end
end

Adapters

Configure the database adapter based on your database:

Connection URI

Use environment variables for database connections:

Column Types

Method
Crystal Type
SQL Type

primary :id, Int64

Int64

BIGSERIAL PRIMARY KEY

primary :id, UUID

UUID

UUID PRIMARY KEY

text :name

String

TEXT / VARCHAR

integer :count

Int32

INTEGER

bigint :amount

Int64

BIGINT

boolean :active

Bool

BOOLEAN

float :price

Float64

DOUBLE PRECISION

timestamp :published_at

Time

TIMESTAMP

date :birth_date

Time

DATE

Column Options

Indexes

Foreign Keys

Complete Example

Next Steps

  • Models - Define model structs that map to tables

  • Migrations - Manage schema changes over time

Last updated

Was this helpful?