Your first query
On this page
On MariaDB:
- ? placeholders
- INSERT ... RETURNING, which MySQL lacks, so CreateTask is a one query rather than execresult
- BIGINT AUTO_INCREMENT maps to int64; INT maps to int32
- DATETIME maps to time.Time, which needs parseTime=true in the DSN
- migrate_backend_mysql.New is the migration backend, as MariaDB speaks MySQL's protocol; WithDriverMultiStatements passes on the DSN's multiStatements setting
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 BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(200) NOT NULL,
completed INT NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
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 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 (?) 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 = 1 WHERE id = ?;
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 int32 `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/mariadb/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.
//
// MariaDB, unlike MySQL, has INSERT ... RETURNING, so CreateTask is a one query that
// hands back the new row, the AUTO_INCREMENT id and the column defaults included.
//
// 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, "%d\t%-18s completed=%d\n", task.ID, task.Title, task.Completed)
}
return nil
}
What it prints
completed 1 task
1 Feed the seagulls completed=1
2 Count the chips completed=0
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.
| MariaDB | SQLite | PostgreSQL | CockroachDB | MySQL | DuckDB | ClickHouse | |
|---|---|---|---|---|---|---|---|
id column | int64 | int64 | int64 | int64 | · | int64 | · |
title column | string | string | string | string | · | string | · |
completed column | int32 | int64 | bool | bool | · | bool | · |
created_at column | time.Time | string | time.Time | time.Time | · | time.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, CockroachDB, MySQL, DuckDB and ClickHouse.
Run it locally
From the directory you cloned the Seagull repository into:
cd seagull/examples/mariadb && go run ./001_first_query
Its test runs it too, and checks what it prints against output.txt:
cd seagull/examples/mariadb && SGL_EXAMPLE_DSN="$DATABASE_URL" go test ./001_first_query
Needs a running MariaDB 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: mariadb
migrations: db/migrations
queries: db/queries
go:
package: store
out: internal/store
db/migrations/0001_init.up.sql
CREATE TABLE tasks (
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(200) NOT NULL,
completed INT NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
db/migrations/0001_init.down.sql
DROP TABLE tasks;
db/queries/tasks.sql
-- sgl.query(CreateTask, one)
INSERT INTO tasks (title) VALUES (?) RETURNING id, title, completed, created_at;
-- sgl.query(ListTasks, many)
SELECT id, title, completed, created_at FROM tasks ORDER BY id;
-- sgl.query(CompleteTask, execrows)
UPDATE tasks SET completed = 1 WHERE id = ?;
example.go
package main
import (
"context"
"database/sql"
"fmt"
"io"
"seagull.sh/seagull/examples/mariadb/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.
//
// MariaDB, unlike MySQL, has INSERT ... RETURNING, so CreateTask is a one query that
// hands back the new row, the AUTO_INCREMENT id and the column defaults included.
//
// 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, "%d\t%-18s completed=%d\n", task.ID, task.Title, task.Completed)
}
return nil
}
main.go
// Command 001_first_query applies its migrations to a MariaDB database, then runs the
// example in example.go: two tasks are added, one is completed, and both are listed.
//
// Run it with `go run . -dsn 'user:password@tcp(localhost:3306)/tasks'`, or set
// DATABASE_URL instead of passing -dsn. Give it an empty database of its own, as the
// migrations create its tables and the example adds rows each time it runs.
package main
import (
"context"
"database/sql"
"embed"
"errors"
"flag"
"fmt"
"log"
"os"
"github.com/go-sql-driver/mysql"
"seagull.sh/seagull/sdk/migrate"
"seagull.sh/seagull/sdk/migrate/migrate_backend_mysql"
)
// migrations holds the migration files, compiled into the binary.
//
//go:embed db/migrations
var migrations embed.FS
func main() {
dsn := flag.String("dsn", os.Getenv("DATABASE_URL"), "MariaDB data source name; defaults to $DATABASE_URL")
flag.Parse()
if err := execute(context.Background(), *dsn); err != nil {
log.Fatal(err)
}
}
// execute opens and migrates the database dsn names, and runs the example against it.
//
// Takes dsn (string) which is the database's data source name.
//
// Returns error when the database cannot be prepared or the example fails.
func execute(ctx context.Context, dsn string) error {
if dsn == "" {
return errors.New("set -dsn or DATABASE_URL to a MariaDB data source name")
}
config, err := mysql.ParseDSN(dsn)
if err != nil {
return err
}
// Seagull maps DATETIME and TIMESTAMP columns to time.Time, which the driver returns
// only when parseTime is set.
config.ParseTime = true
dsn = config.FormatDSN()
database, err := sql.Open("mysql", dsn)
if err != nil {
return err
}
defer func() { _ = database.Close() }()
migrator, err := migrate.NewMigrator(database, migrate_backend_mysql.New(migrate.WithDriverMultiStatements(config.MultiStatements)), 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 int32 `json:"completed"`
CreatedAt time.Time `json:"created_at"`
}
internal/store/querier.go
// Code generated by sgl. DO NOT EDIT.
// Package store reads DATETIME, DATE and TIMESTAMP columns into time.Time, so the DSN it connects with must set parseTime=true.
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 = 1 WHERE id = ?;`
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 (?) RETURNING id, title, completed, created_at;`
type CreateTaskRow struct {
ID int64 `json:"id"`
Title string `json:"title"`
Completed int32 `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 id;`
type ListTasksRow struct {
ID int64 `json:"id"`
Title string `json:"title"`
Completed int32 `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
1 Feed the seagulls completed=1
2 Count the chips completed=0