---
url: /runcobo/cli/codegen.md
description: >-
  Generate typed Crystal query methods from SQL with cobo generate, sqlc and
  crsql.
---

# Code Generation

`cobo generate` runs [crsql](https://github.com/shootingfly/sqlc-gen-crystal), Runcobo's ORM, to turn SQL queries into typed Crystal methods. crsql uses [sqlc](https://sqlc.dev) to analyze your migrations (the schema) and your named queries (the API).

## Requirements

* Crystal and Shards
* [sqlc](https://docs.sqlc.dev/en/latest/overview/install.html) `1.31.1` on your `PATH`
* A [`runcobo.yml`](/cli/configuration)

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

```yaml [sqlc.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

```sql [db/queries/authors.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](/guide/database) 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.
