Database Access
Runcobo's ORM is crsql, built for Runcobo. It's SQL-first: you write each query as a named SQL statement, and cobo generate turns it into a typed Crystal method you call from actions. It works with PostgreSQL, MySQL and SQLite.
How it fits together
db/migrations/*.sql · db/queries/*.sqlbin/cobo generatesrc/persistence/generated/queries.crstore.list_postsThe rest of this page builds that for a small blog with authors and posts, on PostgreSQL. You need a PostgreSQL server running locally and sqlc 1.31.1 on your PATH. Using MySQL or SQLite? The steps are the same — see what changes.
1. Configure the project
Add the PostgreSQL driver:
dependencies:
runcobo:
github: runcobo/runcobo
version: ~> 3.1
pg:
github: will/crystal-pg
version: ~> 0.31.0Tell cobo about your local database:
name: blog
database_prefix: blog # databases: blog_development, blog_testcobo connects to the PostgreSQL server at 127.0.0.1:5432 as postgres; set database_user and database_port here if yours differs.
Tell sqlc where the SQL lives and where to write the Crystal code:
version: "2"
plugins:
- name: crystal
process:
cmd: crsql
format: json
sql:
- engine: postgresql
schema: db/migrations # tables come from your migrations
queries: db/queries # your named queries
codegen:
- plugin: crystal
out: src/persistence/generated
options:
module: Blog::Store # the generated moduleThese are set up once per project. See runcobo.yml and Code Generation for every option.
2. Create the tables
Write a migration:
-- migrate:up
CREATE TABLE authors (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
bio text
);
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
author_id bigint NOT NULL REFERENCES authors(id),
title text NOT NULL,
status text NOT NULL DEFAULT 'draft'
);
-- migrate:down
DROP TABLE posts;
DROP TABLE authors;Create the development database and apply it:
bin/cobo db preparecobo creates blog_development on your PostgreSQL server and runs the migration. See Database & Migrations for the details.
3. Write queries and generate code
Each query starts with a comment naming it and saying what it returns — :one row, :many rows, or :exec for nothing:
-- name: CreatePost :one
INSERT INTO posts (author_id, title)
VALUES (sqlc.arg(author_id), sqlc.arg(title))
RETURNING id, author_id, title, status;
-- name: GetPost :one
SELECT id, author_id, title, status FROM posts WHERE id = sqlc.arg(id);
-- name: ListPosts :many
SELECT id, author_id, title, status FROM posts ORDER BY id DESC;sqlc.arg(name) declares a parameter. Generate:
bin/cobo generateThis writes src/persistence/generated/queries.cr. For each query you get a method on Blog::Store::Queries and a struct for its rows:
# Generated — do not edit. Shown simplified.
module Blog::Store
struct GetPostRow
getter id : Int64
getter author_id : Int64
getter title : String
getter status : String
end
class Queries
def create_post(*, author_id : Int64, title : String) : CreatePostRow
def get_post(*, id : Int64) : GetPostRow # raises if no row
def get_post?(*, id : Int64) : GetPostRow? # nil if no row
def list_posts : Array(ListPostsRow)
end
endThe types come from your schema: title is String because the column is NOT NULL. Commit the generated file, and run bin/cobo generate again whenever you change a migration or a query.
4. Give actions a store
The generated Blog::Store.open(url) opens a connection pool and yields a Blog::Store::Queries — the object you call queries on. Open it once when the app starts, then make it available to every request.
Dependencies travel on the request context. Declare a property for the store, and set it in a route handler — Runcobo::RouteHandler creates the action for each request, and build_action runs just before. Both belong to the request boundary, so they go in web/:
class HTTP::Server::Context
property! blog_store : Blog::Store::Queries
end
module Blog
class RouteHandler < Runcobo::RouteHandler
def initialize(@store : Store::Queries)
end
protected def build_action(action_class : Runcobo::Action.class, context : HTTP::Server::Context) : Runcobo::Action
context.blog_store = @store
super
end
end
endGive every action a short way to reach it, in the application's base action:
abstract class Blog::BaseAction < ::BaseAction
before read_input # reject oversized or mistyped bodies before any work
protected def store : Blog::Store::Queries
context.blog_store
end
endLoad everything in app.cr, and open the store in main.cr:
require "runcobo"
require "pg"
require "./persistence/generated/queries"
require "./actions/base_action"
require "./web/handlers"
require "./actions/**"require "./app"
Blog::Store.open(ENV["DATABASE_URL"]) do |store|
Runcobo.start(handlers: [
Runcobo::LogHandler.new,
Runcobo::ErrorHandler.new,
Blog::RouteHandler.new(store),
Runcobo::RouteNotFoundHandler.new,
] of HTTP::Handler)
endStart the app with bin/cobo dev. It prepares the database and runs src/main.cr with DATABASE_URL pointing at blog_development.
Why not a global?
Passing the store in keeps database access explicit and makes tests straightforward: specs build a Blog::RouteHandler with a store on the test database and dispatch requests through it.
5. Use it in actions
Each endpoint is three files in src/actions/posts/ — the action, its contract and its template (why). Creating a post:
class Posts::CreatePostContract < RequestValidation::Contract
schema do
required :author_id, Int64
required :title, String, filled: true, max_size: 200
end
endclass Posts::CreatePost < Blog::BaseAction
post "/posts"
call do
input = validate(CreatePostContract)
post = store.create_post(author_id: input.author_id, title: input.title)
render status_code: 201
end
endjson.partial! "posts/partials/post", post: postShowing one:
class Posts::ShowPostContract < RequestValidation::Contract
schema do
required :id, Int64
end
endclass Posts::ShowPost < Blog::BaseAction
get "/posts/:id"
call do
input = validate(ShowPostContract)
if post = store.get_post?(id: input.id)
render
else
render_json({error: "post_not_found"}, status_code: 404)
end
end
endjson.partial! "posts/partials/post", post: postBoth responses share one partial:
# locals: post
json.id post.id
json.title post.title
json.status post.statusThe contract hands you an Int64 and a String; the query method expects exactly those. The template lists the fields to return one by one — a row is a data-access result, not an API response, so adding a column never leaks it to clients.
That's the whole workflow. For filters, joins, partial updates and transactions, see Query Recipes. Coming from Rails or Lucky? The recipes page ends with how Active Record concepts map to crsql.
MySQL and SQLite
crsql generates the same kind of typed methods for MySQL and SQLite, and actions use them exactly as above. Two things change:
The driver in shard.yml, and DATABASE_URL:
pg:
github: will/crystal-pg
version: ~> 0.31.0
# DATABASE_URL=postgresql://postgres@127.0.0.1:5432/blog_developmentmysql:
github: crystal-lang/crystal-mysql
version: ~> 0.18.0
# DATABASE_URL=mysql://blog:secret@127.0.0.1:3306/blog_developmentsqlite3:
github: crystal-lang/crystal-sqlite3
version: ~> 0.24.0
# DATABASE_URL=sqlite3:./.local/sqlite/blog_development.sqlite3Require the matching driver in src/app.cr (require "mysql" or require "sqlite3" instead of require "pg").
The engine in sqlc.yaml: engine: mysql or engine: sqlite.
Nothing else. cobo db, cobo dev, cobo test and cobo generate read the engine from sqlc.yaml. For MySQL, cobo uses a server you already run; for SQLite, database files live in .local/sqlite/. See Database & Migrations for the defaults and what each engine needs.
Write queries in your engine's SQL dialect: the examples in this guide use PostgreSQL features such as RETURNING, which MySQL doesn't have. crsql's MySQL and SQLite guides cover types, connections and engine-specific details.