Your first query

On this page

On CockroachDB:

  • $1 placeholders
  • INT8 DEFAULT unique_rowid() keys are large, time-ordered int64 values, not 1, 2, 3, so the output prints titles rather than IDs
  • STRING maps to string, BOOL to bool and TIMESTAMPTZ to time.Time
  • the list orders by created_at, id, since unique_rowid() values are only roughly in insertion order across nodes
  • migrations run through migrate_backend_cockroachdb.New(), which locks with a table because CockroachDB has no advisory locks
  • transactions use SERIALIZABLE isolation by default and may fail with SQLSTATE 40001; the generated RunInTx does not retry them

Seagull reads two things: the migrations that build your schema, and the queries you write against it. From them it generates a Go package with a method for every query, typed from the schema. This first example is a tasks list: one table, and three queries to add a task, complete it and list them all.

The schema

Migrations are plain SQL files, applied in order. Seagull replays them to learn every table and column, including which columns can be NULL.

db/migrations/0001_init.up.sql

CREATE TABLE tasks (
    id         INT8        NOT NULL DEFAULT unique_rowid() PRIMARY KEY,
    title      STRING      NOT NULL,
    completed  BOOL        NOT NULL DEFAULT false,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

The queries

Each query starts with an sgl.query header giving the method's name and its command: what the method returns. ListTasks returns every row, so it is many.

db/queries/tasks.sql

-- sgl.query(ListTasks, many)
SELECT id, title, completed, created_at FROM tasks ORDER BY created_at, id;

Adding a task uses RETURNING, so the new row comes straight back and the command is one:

db/queries/tasks.sql

-- sgl.query(CreateTask, one)
INSERT INTO tasks (title) VALUES ($1) RETURNING id, title, completed, created_at;

Completing a task is execrows, which returns how many rows changed, so the program can tell whether the task existed:

db/queries/tasks.sql

-- sgl.query(CompleteTask, execrows)
UPDATE tasks SET completed = true WHERE id = $1;

What sgl generates

sgl generate writes the package named in sgl.yaml. Every column of the query becomes a field of a row struct, typed from the schema: a column that can be NULL would be a pointer, and these cannot be, so none are.

internal/store

type ListTasksRow struct {
	ID        int64     `json:"id"`
	Title     string    `json:"title"`
	Completed bool      `json:"completed"`
	CreatedAt time.Time `json:"created_at"`
}

func (queries *Queries) ListTasks(ctx context.Context) ([]ListTasksRow, error) {
	rows, err := queries.reader.QueryContext(ctx, listTasksSQL)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var results []ListTasksRow
	if rows.Next() {
		var row ListTasksRow
		scanArgs := []any{&row.ID, &row.Title, &row.Completed, &row.CreatedAt}
		for more := true; more; more = rows.Next() {
			row = ListTasksRow{}
			if err := rows.Scan(scanArgs...); err != nil {
				return nil, err
			}
			results = append(results, row)
		}
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return results, nil
}

Using it

The program opens the database, runs the migrations and calls the generated methods. There is no SQL in it and nothing to scan by hand: the methods take and return Go values.

example.go

package main

import (
	"context"
	"database/sql"
	"fmt"
	"io"

	"seagull.sh/seagull/examples/cockroachdb/001_first_query/internal/store"
)

// run adds two tasks, completes the first and lists them all, through the methods sgl
// generated from db/queries/tasks.sql.
//
// The code is what it would be on PostgreSQL; the differences are in the database.
// CockroachDB fills id with unique_rowid(), a large int64 built from the time and the
// node, so IDs are neither 1 and 2 nor the same from one run to the next, and the list
// prints titles instead. CockroachDB uses SERIALIZABLE isolation by default and may abort
// one with SQLSTATE 40001 when it conflicts with another. The generated RunInTx does not
// retry, so code that uses it on CockroachDB retries the whole function itself.
//
// Takes database (*sql.DB) which is a migrated database.
// Takes output (io.Writer) which receives the task list.
//
// Returns error when a query fails.
func run(ctx context.Context, database *sql.DB, output io.Writer) error {
	queries := store.New(database)

	feed, err := queries.CreateTask(ctx, "Feed the seagulls")
	if err != nil {
		return fmt.Errorf("creating a task: %w", err)
	}
	if _, err := queries.CreateTask(ctx, "Count the chips"); err != nil {
		return fmt.Errorf("creating a task: %w", err)
	}

	completed, err := queries.CompleteTask(ctx, feed.ID)
	if err != nil {
		return fmt.Errorf("completing task %d: %w", feed.ID, err)
	}
	fmt.Fprintf(output, "completed %d task\n", completed)

	tasks, err := queries.ListTasks(ctx)
	if err != nil {
		return fmt.Errorf("listing tasks: %w", err)
	}
	for _, task := range tasks {
		fmt.Fprintf(output, "%-18s completed=%t\n", task.Title, task.Completed)
	}
	return nil
}

What it prints

completed 1 task
Feed the seagulls  completed=true
Count the chips    completed=false

Try it

Change a column's type in the migration, or ask for a column that does not exist, and run sgl generate again: the Go changes with it, or sgl vet says what is wrong, with a code you can look up in the diagnostics.

Across engines

Only these Go types of CreateTask differ between engines; the rest are the same everywhere.

CockroachDBSQLitePostgreSQLMySQLMariaDBDuckDBClickHouse
id columnint64int64int64·int64int64·
title columnstringstringstring·stringstring·
completed columnboolint64bool·int32bool·
created_at columntime.Timestringtime.Time·time.Timetime.Time·
id parameter······uint64

A · marks a parameter or column that version of the example does not have.

TimescaleDB runs the PostgreSQL version unchanged.

Compare the whole example side by side with SQLite, PostgreSQL, MySQL, MariaDB, DuckDB and ClickHouse.

Run it locally

From the directory you cloned the Seagull repository into:

cd seagull/examples/cockroachdb && go run ./001_first_query

Its test runs it too, and checks what it prints against output.txt:

cd seagull/examples/cockroachdb && SGL_EXAMPLE_DSN="$DATABASE_URL" go test ./001_first_query

Needs a running CockroachDB server: set DATABASE_URL, or pass -dsn, to the address of an empty database.

The files

Every file of the example, as it is in the Seagull repository.

sgl.yaml

# Copyright 2026 PolitePixels Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This project stands against fascism, authoritarianism, and all forms of
# oppression. We built this to empower people, not to enable those who would
# strip others of their rights and dignity.

version: 1

databases:
  - name: tasks
    dialect: cockroachdb
    migrations: db/migrations
    queries: db/queries
    go:
      package: store
      out: internal/store

db/migrations/0001_init.up.sql

CREATE TABLE tasks (
    id         INT8        NOT NULL DEFAULT unique_rowid() PRIMARY KEY,
    title      STRING      NOT NULL,
    completed  BOOL        NOT NULL DEFAULT false,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

db/migrations/0001_init.down.sql

DROP TABLE tasks;

db/queries/tasks.sql

-- sgl.query(CreateTask, one)
INSERT INTO tasks (title) VALUES ($1) RETURNING id, title, completed, created_at;

-- sgl.query(ListTasks, many)
SELECT id, title, completed, created_at FROM tasks ORDER BY created_at, id;

-- sgl.query(CompleteTask, execrows)
UPDATE tasks SET completed = true WHERE id = $1;

example.go

package main

import (
	"context"
	"database/sql"
	"fmt"
	"io"

	"seagull.sh/seagull/examples/cockroachdb/001_first_query/internal/store"
)

// run adds two tasks, completes the first and lists them all, through the methods sgl
// generated from db/queries/tasks.sql.
//
// The code is what it would be on PostgreSQL; the differences are in the database.
// CockroachDB fills id with unique_rowid(), a large int64 built from the time and the
// node, so IDs are neither 1 and 2 nor the same from one run to the next, and the list
// prints titles instead. CockroachDB uses SERIALIZABLE isolation by default and may abort
// one with SQLSTATE 40001 when it conflicts with another. The generated RunInTx does not
// retry, so code that uses it on CockroachDB retries the whole function itself.
//
// Takes database (*sql.DB) which is a migrated database.
// Takes output (io.Writer) which receives the task list.
//
// Returns error when a query fails.
func run(ctx context.Context, database *sql.DB, output io.Writer) error {
	queries := store.New(database)

	feed, err := queries.CreateTask(ctx, "Feed the seagulls")
	if err != nil {
		return fmt.Errorf("creating a task: %w", err)
	}
	if _, err := queries.CreateTask(ctx, "Count the chips"); err != nil {
		return fmt.Errorf("creating a task: %w", err)
	}

	completed, err := queries.CompleteTask(ctx, feed.ID)
	if err != nil {
		return fmt.Errorf("completing task %d: %w", feed.ID, err)
	}
	fmt.Fprintf(output, "completed %d task\n", completed)

	tasks, err := queries.ListTasks(ctx)
	if err != nil {
		return fmt.Errorf("listing tasks: %w", err)
	}
	for _, task := range tasks {
		fmt.Fprintf(output, "%-18s completed=%t\n", task.Title, task.Completed)
	}
	return nil
}

main.go

// Command 001_first_query applies its migrations to a CockroachDB database, then runs the
// example in example.go: two tasks are added, one is completed, and both are listed.
//
// Run it with `go run .` against a local insecure node, which `docker run -d -p
// 26257:26257 cockroachdb/cockroach:latest-v25.1 start-single-node --insecure` starts, or
// point it elsewhere with `go run . -dsn <connection string>` or DATABASE_URL.
package main

import (
	"cmp"
	"context"
	"database/sql"
	"embed"
	"flag"
	"fmt"
	"log"
	"os"

	_ "github.com/jackc/pgx/v5/stdlib"

	"seagull.sh/seagull/sdk/migrate"
	"seagull.sh/seagull/sdk/migrate/migrate_backend_cockroachdb"
)

// localDSN reaches an insecure single node on this machine.
const localDSN = "postgresql://root@localhost:26257/defaultdb?sslmode=disable"

// migrations holds the migration files, compiled into the binary.
//
//go:embed db/migrations
var migrations embed.FS

func main() {
	dsn := flag.String("dsn", cmp.Or(os.Getenv("DATABASE_URL"), localDSN), "CockroachDB connection string")
	flag.Parse()
	if err := execute(context.Background(), *dsn); err != nil {
		log.Fatal(err)
	}
}

// execute connects to the database at dsn, migrates it with the CockroachDB backend and
// runs the example against it.
//
// Takes dsn (string) which is the connection string.
//
// Returns error when the database cannot be prepared or the example fails.
func execute(ctx context.Context, dsn string) error {
	database, err := sql.Open("pgx", dsn)
	if err != nil {
		return err
	}
	defer func() { _ = database.Close() }()

	migrator, err := migrate.NewMigrator(database, migrate_backend_cockroachdb.New(), migrations, "db/migrations")
	if err != nil {
		return err
	}
	if _, err := migrator.Up(ctx); err != nil {
		return fmt.Errorf("migrating: %w", err)
	}
	return run(ctx, database, os.Stdout)
}

internal/store/models.go

// Code generated by sgl. DO NOT EDIT.

package store

import "time"

type Tasks struct {
	ID        int64     `json:"id"`
	Title     string    `json:"title"`
	Completed bool      `json:"completed"`
	CreatedAt time.Time `json:"created_at"`
}

internal/store/querier.go

// Code generated by sgl. DO NOT EDIT.

package store

import (
	"context"
	"database/sql"
)

type DBTX interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

type dbtxWrapper interface {
	WrapDBTX(inner any) any
}

type Queries struct {
	reader  DBTX
	writer  DBTX
	wrapper dbtxWrapper
}

func New(db DBTX) *Queries {
	wrapper, _ := db.(dbtxWrapper)
	return &Queries{reader: db, writer: db, wrapper: wrapper}
}

func NewWithReplica(writer DBTX, reader DBTX) *Queries {
	wrapper, _ := writer.(dbtxWrapper)
	return &Queries{reader: reader, writer: writer, wrapper: wrapper}
}

func (queries *Queries) WithTx(transaction *sql.Tx) *Queries {
	if queries == nil {
		return &Queries{reader: transaction, writer: transaction, wrapper: nil}
	}
	db := queries.wrapDBTX(transaction)
	return &Queries{reader: db, writer: db, wrapper: queries.wrapper}
}

func (queries *Queries) wrapDBTX(db DBTX) DBTX {
	if queries.wrapper == nil {
		return db
	}
	wrapped, ok := queries.wrapper.WrapDBTX(db).(DBTX)
	if !ok {
		return db
	}
	return wrapped
}

func (queries *Queries) RunInTx(ctx context.Context, db *sql.DB, fn func(*Queries) error) error {
	transaction, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer transaction.Rollback()
	if err = fn(queries.WithTx(transaction)); err != nil {
		return err
	}
	return transaction.Commit()
}

internal/store/tasks.sql.go

// Code generated by sgl. DO NOT EDIT.

package store

import (
	"context"
	"time"
)

const completeTaskSQL = `UPDATE tasks SET completed = true WHERE id = $1;`

func (queries *Queries) CompleteTask(ctx context.Context, id int64) (int64, error) {
	results, err := queries.writer.ExecContext(ctx, completeTaskSQL, id)
	if err != nil {
		return 0, err
	}
	return results.RowsAffected()
}

const createTaskSQL = `INSERT INTO tasks (title) VALUES ($1) RETURNING id, title, completed, created_at;`

type CreateTaskRow struct {
	ID        int64     `json:"id"`
	Title     string    `json:"title"`
	Completed bool      `json:"completed"`
	CreatedAt time.Time `json:"created_at"`
}

func (queries *Queries) CreateTask(ctx context.Context, title string) (CreateTaskRow, error) {
	var row CreateTaskRow
	err := queries.writer.QueryRowContext(ctx, createTaskSQL, title).Scan(&row.ID, &row.Title, &row.Completed, &row.CreatedAt)
	if err != nil {
		return CreateTaskRow{}, err
	}
	return row, nil
}

const listTasksSQL = `SELECT id, title, completed, created_at FROM tasks ORDER BY created_at, id;`

type ListTasksRow struct {
	ID        int64     `json:"id"`
	Title     string    `json:"title"`
	Completed bool      `json:"completed"`
	CreatedAt time.Time `json:"created_at"`
}

func (queries *Queries) ListTasks(ctx context.Context) ([]ListTasksRow, error) {
	rows, err := queries.reader.QueryContext(ctx, listTasksSQL)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var results []ListTasksRow
	if rows.Next() {
		var row ListTasksRow
		scanArgs := []any{&row.ID, &row.Title, &row.Completed, &row.CreatedAt}
		for more := true; more; more = rows.Next() {
			row = ListTasksRow{}
			if err := rows.Scan(scanArgs...); err != nil {
				return nil, err
			}
			results = append(results, row)
		}
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return results, nil
}

output.txt

completed 1 task
Feed the seagulls  completed=true
Count the chips    completed=false

Also on other engines