Skip to content

Code Generation ​

cobo generate runs crsql, Runcobo's ORM, to turn SQL queries into typed Crystal methods. crsql uses sqlc to analyze your migrations (the schema) and your named queries (the API).

Requirements ​

You don't add crsql to your shard.yml. On first use, cobo installs the version pinned by the framework into .local/runcobo/codegen/ and compiles bin/crsql. It's rebuilt automatically when you upgrade Runcobo to a version that pins a different generator.

Configure sqlc ​

sqlc.yaml
yaml
version: "2"
plugins:
  - name: crystal
    process:
      cmd: crsql
      format: json
sql:
  - engine: postgresql
    schema: db/migrations
    queries: db/queries
    codegen:
      - plugin: crystal
        out: src/persistence/generated
        options:
          module: Blog::Store
          emit_table_models: true

The schema is read straight from db/migrations — there's no separate schema file to keep in sync. Set engine to postgresql, mysql or sqlite.

Write queries ​

db/queries/authors.sql
sql
-- name: GetAuthor :one
SELECT id, name, bio FROM authors WHERE id = sqlc.arg(id);

-- name: ListAuthors :many
SELECT id, name, bio FROM authors ORDER BY id;

Use sqlc.arg(name) for parameters and sqlc.narg(name) for nullable ones. See Database Access for how the generated store is used in actions.

Generate ​

sh
bin/cobo generate

Writes the generated code to src/persistence/generated/. Commit it and never edit it by hand — change the SQL and regenerate.

Check in CI ​

sh
bin/cobo generate --check

Generates into a temporary directory and compares the result with your committed files, without rewriting anything. It fails with the list of differing files if someone changed SQL without regenerating.

Other commands ​

sh
bin/cobo crsql-build          # build bin/crsql without generating
bin/cobo crsql --help         # pass arguments straight to crsql

The generator is a development tool only. Your compiled application needs just the generated code and the pg driver.

Released under the MIT License.