Skip to content

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 ​

Write migrations and queries
db/migrations/*.sql · db/queries/*.sql
Generate
bin/cobo generate
Checks each query against your migrations.
Get typed methods
src/persistence/generated/queries.cr
Blog::Store — one method per query.
Call them from actions
store.list_posts
main.cr opens the store and hands it to actions.

The 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:

shard.yml
yaml
dependencies:
  runcobo:
    github: runcobo/runcobo
    version: ~> 3.1
  pg:
    github: will/crystal-pg
    version: ~> 0.31.0

Tell cobo about your local database:

runcobo.yml
yaml
name: blog
database_prefix: blog      # databases: blog_development, blog_test

cobo 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:

sqlc.yaml
yaml
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 module

These are set up once per project. See runcobo.yml and Code Generation for every option.

2. Create the tables ​

Write a migration:

db/migrations/20261201000000_create_blog.sql
sql
-- 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:

sh
bin/cobo db prepare

cobo 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:

db/queries/posts.sql
sql
-- 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:

sh
bin/cobo generate

This writes src/persistence/generated/queries.cr. For each query you get a method on Blog::Store::Queries and a struct for its rows:

crystal
# 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
end

The 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/:

src/web/handlers.cr
crystal
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
end

Give every action a short way to reach it, in the application's base action:

src/actions/base_action.cr
crystal
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
end

Load everything in app.cr, and open the store in main.cr:

src/app.cr
crystal
require "runcobo"
require "pg"
require "./persistence/generated/queries"
require "./actions/base_action"
require "./web/handlers"
require "./actions/**"
src/main.cr
crystal
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)
end

Start 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:

src/actions/posts/create_post_contract.cr
crystal
class Posts::CreatePostContract < RequestValidation::Contract
  schema do
    required :author_id, Int64
    required :title, String, filled: true, max_size: 200
  end
end
src/actions/posts/create_post.cr
crystal
class 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
end
src/actions/posts/create_post.jbuilder
crystal
json.partial! "posts/partials/post", post: post

Showing one:

src/actions/posts/show_post_contract.cr
crystal
class Posts::ShowPostContract < RequestValidation::Contract
  schema do
    required :id, Int64
  end
end
src/actions/posts/show_post.cr
crystal
class 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
end
src/actions/posts/show_post.jbuilder
crystal
json.partial! "posts/partials/post", post: post

Both responses share one partial:

src/actions/posts/partials/post.jbuilder
crystal
# locals: post
json.id post.id
json.title post.title
json.status post.status

The 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:

yaml
pg:
  github: will/crystal-pg
  version: ~> 0.31.0
# DATABASE_URL=postgresql://postgres@127.0.0.1:5432/blog_development
yaml
mysql:
  github: crystal-lang/crystal-mysql
  version: ~> 0.18.0
# DATABASE_URL=mysql://blog:secret@127.0.0.1:3306/blog_development
yaml
sqlite3:
  github: crystal-lang/crystal-sqlite3
  version: ~> 0.24.0
# DATABASE_URL=sqlite3:./.local/sqlite/blog_development.sqlite3

Require 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.

Released under the MIT License.