# Models and migrations

Source: https://bogie-go.com/docs/models.html

A model here is a few files, each with one job: the type and its rules, the SQL, and the store that joins them, plus the migration, two specs and a factory. One command writes all seven:

```
bogie g model post title body:text
```

A field with no `:type` is a `string`, so `title` is `title:string`.

```
      create  db/migrate/20261028094447_create_posts.sql
      create  db/queries/posts.sql
      create  app/models/post.go
      create  app/models/post_test.go
      create  db/adapter/posts.go
      create  db/adapter/posts_test.go
      create  test/factories/posts.go
         run  sqlc generate
```

Running the same command again is safe. It reports each file as `identical` and writes nothing new:

```
   identical  db/migrate/20261105015802_create_posts.sql
   identical  db/queries/posts.sql
   identical  app/models/post.go
   identical  app/models/post_test.go
   identical  db/adapter/posts.go
   identical  db/adapter/posts_test.go
   identical  test/factories/posts.go
         run  sqlc generate
```

Leave the name off and it stops with **bogie: generate model: NAME is required**, after printing the generator usage. Give it a name: `bogie g model post`.

## The migration

goose SQL, stamped with the UTC time it was generated (`20261028094447` is 28 Oct 2026, 09:44:47 UTC), embedded in the binary:

```
-- +goose Up
CREATE TABLE posts (
    id         bigserial   PRIMARY KEY,
    title      varchar     NOT NULL DEFAULT '',
    body       text        NOT NULL DEFAULT '',
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz NOT NULL DEFAULT now()
);

-- +goose Down
DROP TABLE posts;
```

Every generated column is `NOT NULL`, so sqlc emits plain Go types rather than pointers. Strings, numbers, booleans and `jsonb` also get a default; `datetime`, `uuid` and `references` columns have none, so every insert must supply them. A column that needs null takes `:null` (`archived_at:datetime:null`) in `g model` or `g migration`, and the model field is a pointer (`*string`, `*time.Time`).

## The queries

`db/queries/posts.sql`, named statements that sqlc compiles:

```
-- Written by `bogie g model`: overwritten whole on the next run. A
-- hand-written query goes in posts_extra.sql, not here.

-- name: GetPost :one
SELECT * FROM posts WHERE id = $1;

-- name: ListPosts :many
SELECT * FROM posts ORDER BY created_at DESC, id DESC LIMIT $1;

-- name: CreatePost :one
INSERT INTO posts (title, body) VALUES ($1, $2) RETURNING *;

-- name: UpdatePost :one
UPDATE posts SET title = $2, body = $3, updated_at = now() WHERE id = $1 RETURNING *;

-- name: DeletePost :execrows
DELETE FROM posts WHERE id = $1;
```

sqlc compiles these into `db/sqlc/posts.sql.go`. A query that names a column which does not exist fails at `make sqlc`, not in production.

## The model

`app/models/post.go` imports nothing third-party (rule 3). In the default `bigint` scheme an id is an `int64`; in an `--id=uuid` app it is a `string`, which the store turns into a uuid:

```
// Post is a post. Imports nothing third-party: ids are int64s here and
// become bigint at the store boundary.
type Post struct {
	ID        int64
	Title     string
	Body      string
	CreatedAt time.Time
	UpdatedAt time.Time
}

// Validate is the model's validations. Wrap every
// failure in ErrInvalid so a controller can answer 422 without knowing the
// rule:
//
//	return fmt.Errorf("%w: title is required", ErrInvalid)
func (p Post) Validate() error {
	return nil
}
```

`Validate` starts empty; fill it in with the rules the model must keep. It runs on both create and update, inside the store, so every caller gets it and none can forget it. The same file's neighbour, `app/models/post_test.go`, is the model's own spec: it starts from the factory's defaults, which are valid by construction, so a rule you add to `Validate` that the defaults break fails there, and it shows where the next rule's `Context` goes.

## The store

`db/adapter/posts.go` (package `adapter`) converts between the model and sqlc's row type from `db/sqlc`, maps "no rows" to `models.ErrNotFound`, and runs `Validate` before writing:

```
func (s *Store) CreatePost(ctx context.Context, p models.Post) (models.Post, error) {
	if err := p.Validate(); err != nil {
		return models.Post{}, err
	}
	row, err := s.q.CreatePost(ctx, sqlc.CreatePostParams{Title: p.Title, Body: p.Body})
	if err != nil {
		return models.Post{}, fmt.Errorf("store: create post: %w", err)
	}
	return postFromRow(row), nil
}
```

`GetPost`, `ListPosts`, `UpdatePost` and `DeletePost` follow the same shape. The `Store` itself, its connection pool and its unexported `withTx` live in `db/adapter/store.go`, written once by `bogie new`. `db/adapter/posts_test.go` is a Ginkgo spec on the real test database, with a `Describe` per store method: an id that is not a number, is empty, or matches no post is `ErrNotFound` for both `GetPost` and `DeletePost`, an update to a missing post is `ErrNotFound`, and a saved post reads back, lists, updates and deletes. `test/factories/posts.go` builds valid posts for it and for every other spec (`factories.Post(GinkgoT(), store)`). It's yours to edit once written, and `model:sync` merges a new column's default into it. Store specs need the database up: `make up` first. See [Testing and CI](https://bogie-go.com/docs/testing.html).

## Attribute types

`string text integer bigint boolean datetime uuid jsonb references`, each optionally followed by `:index` or `:uniq`:

```
bogie g model comment body:text post:references score:integer
```

A misspelled type is refused before anything is written. For `bogie g model tag name:strng`:

```
bogie: generate model: "name:strng": unknown type "strng"; one of bigint, boolean, datetime, integer, jsonb, references, string, text, uuid
```

**unknown type "strng"** means the word after the colon is not one of the listed types. Fix the spelling and run it again.

`string` is Postgres `varchar` (unlimited) and `text` is `text`: the distinction is kept, not collapsed. Columns written by v0.2.3 and earlier keep whatever their migration already says.

`post:references` writes the column `post_id` as `bigint NOT NULL REFERENCES posts (id)`, with its own index (`uuid` in an `--id=uuid` app: a foreign key is always made of whatever its target's id is). `slug:string:uniq` adds a unique constraint.

A `references` column whose foreign key names nothing is `ErrInvalid` on `Create` and `Update` (`invalid: post_id does not exist`), the way a duplicate value in a `:uniq` column is, so a controller answers 422 and not 500 (before v0.6.4 it was a 500). `g model` writes a `CreateComment` spec for it when a model has a reference.

A `uuid` column works in a bigint app too. Its two conversions, `parseUUID` and `uuidString`, live in `db/adapter/uuid.go`, which a `--id=uuid` app has from `bogie new` and a bigint app gets, once, with the first model that has a `uuid` attribute (`model:sync` writes it too, when a new column is a uuid). Before v0.6.3 the store of such a model did not compile.

## Id schemes

Since v0.2.9 every `id` is a `bigserial`, an auto-incrementing `bigint`. `bogie new NAME --id=uuid` makes them `uuid PRIMARY KEY DEFAULT gen_random_uuid()` instead. Pick uuid when an API should not reveal how many records exist (`/orders/41` next to `/orders/42` does); pick bigint when people read the ids.

```
bogie new blog              # id bigserial, model ID int64
bogie new blog --id=uuid    # id uuid, model ID string
```

The choice is made once, for the whole app, and written to `bogie.toml` as `id = "bigint"` or `id = "uuid"`. Every later `g model`, `g scaffold` and `g authentication` reads it, and so does `app:update`. It cannot be mixed per model, because a `references` column has to match the id it points to. Store methods still take the id as the string from the URL; the store parses it for its scheme, and an id that does not parse is `ErrNotFound`.

An app made before v0.2.9 has no `id` line in `bogie.toml`. That reads as `uuid`, what it was always generated with, so its new models keep matching its old tables. Do not add `id = "bigint"` to such an app: new tables would get bigint ids and the new `references` columns would no longer match the uuid ids already there.

## Changing a table

```
bogie g migration add_slug_to_posts slug:string:uniq
bogie g migration remove_draft_from_posts draft:boolean
```

Three migration name shapes get their SQL written automatically; any other name gets an empty Up and Down to fill in by hand:

- `create_<table>`: the table and its columns.
- `add_<x>_to_<table>`: `ALTER TABLE ... ADD COLUMN` for each attribute, reversed on the way down.
- `remove_<x>_from_<table>`: `ALTER TABLE ... DROP COLUMN`, with the Down able to re-add it.

```
-- +goose Up
ALTER TABLE posts ADD COLUMN slug varchar NOT NULL DEFAULT '' UNIQUE;

-- +goose Down
ALTER TABLE posts DROP COLUMN slug;
```

`bogie g migration add_slug_to_posts slug:string:uniq` prints:

```
      create  db/migrate/20261105015804_add_slug_to_posts.sql
         run  sqlc generate
```

A name that fits none of the three shapes, like `bogie g migration add_slug`, prints the same two lines for its own file. Nothing warns you, and `bogie db:migrate:status` lists it as `pending` (see below) until you have filled it in and applied it.

The migration generator runs sqlc immediately too, so `db/sqlc/*.sql.go` changes before the migration is ever applied, and a renamed column shows up as a compile error right away.

## Carrying a column into the model: model:sync

A migration changes the table and nothing else. To bring the model, its queries, its store and its factory along, commit, then run `model:sync`:

```
bogie g migration add_stock_to_products stock:integer
git commit -am "Add stock to products"
bogie model:sync products
go build ./... && bogie test
```

It reads the columns from sqlc's compile of `db/migrate/*.sql`, so a migration written by hand counts too. It adds a field for each new column and removes the field for each column a migration dropped or renamed away; a field you added that never had a column stays. The queries, the store and the factory are regenerated and merged into your copies the way `app:update` merges, so an edit of yours on the same lines gets conflict markers. `Validate`, the views, the controllers and the specs are left alone, and it says so: add the field to the views if the API should carry it. It refuses on a dirty git tree, so the result is one diff to review or undo; `bogie new` does not run `git init`, and outside a git repository the sync runs without that check, so start one first. Without a table name it syncs every model.

With uncommitted changes, `bogie model:sync posts` stops with:

```
bogie: model:sync: the git tree has uncommitted changes; commit or stash them first, so the sync can be undone with git
```

**the git tree has uncommitted changes**: `git commit` or `git stash`, then run it again.

Add `:null` to an attribute for a column that may be NULL (`archived_at:datetime:null`): the field is a pointer, and a nullable datetime is `*time.Time`. `g scaffold` does not take `:null` yet.

## Running them

```
bogie db:migrate
bogie db:rollback
bogie db:migrate:status
bogie db:reset
bogie db:seed
bogie db:version
```

All through the app's own binary, never the goose CLI directly, so development runs exactly what a deployed container runs. `db:reset` drops the database and rebuilds it from the migrations; there is no schema dump to load instead. Seeds are not migrations: they are plain Go, written with `bogie g seed` and run, every one of them, by `bogie db:seed`. See [Seeds](https://bogie-go.com/docs/seeds.html).

Since v0.7.0, `bogie db:status` (and `bogie db status`) is the one database task the tool runs itself. It only reads: it resolves the database the way `config.Load` does (`<NAME>_ENV`, the credentials file, `DATABASE_URL` over the file, and test from `<NAME>_TEST_DATABASE_URL` only), opens a read-only pgx session, and prints host, port, database, Postgres version, the latest applied goose migration and how many files are still pending, and how many tables. A generated app gains no command and no import. This is not `db:migrate:status`, which still lists every migration file through the app's binary.

### Looking at the database the server would use

On a connection failure the driver's error is kept, one hint line is added, and the process exits non-zero. With Postgres stopped:

```
bogie: failed to connect to `user=postgres database=blog_development`:
	127.0.0.1:5440 (localhost): dial error: dial tcp 127.0.0.1:5440: connect: connection refused
	[::1]:5440 (localhost): dial error: dial tcp [::1]:5440: connect: connection refused
Postgres isn't running (try `docker compose up -d`)
```

A bad password is hinted with `check credentials`; a missing database with `` run `bogie db:prepare` ``. A successful run prints one fact per line, in this shape (the Postgres version string is whatever the server reports):

```
host:      localhost
port:      5440
database:  blog_development
postgres:  16.15 (Ubuntu 16.15-0ubuntu0.24.04.1)
migration: 0 (0 pending)
tables:    0
```

After a migration has been applied and another file is only on disk, `migration:` shows the latest applied stamp and how many files are still pending, for example `20261105000000 (1 pending)`, and `tables:` counts the tables that are there.

Each command logs what it did. `bogie db:migrate`, then `bogie db:rollback` (one migration at a time):

```
time=2026-11-05T08:58:04.706+07:00 level=INFO msg="schema applied" service=blog from=20261105015750 to=20261105015805
time=2026-11-05T08:58:05.147+07:00 level=INFO msg="schema rolled back" service=blog from=20261105015805 to=20261105015804
```

`bogie db:migrate:status` lists every migration file and whether it has run:

```
state       applied at              migration
applied     2026-11-05 08:57:52     20261105015750_create_products.sql
applied     2026-11-05 08:58:04     20261105015802_create_posts.sql
applied     2026-11-05 08:58:04     20261105015803_create_comments.sql
applied     2026-11-05 08:58:04     20261105015804_add_slug_to_posts.sql
pending     pending                 20261105015805_add_slug.sql
```

### A migration that is older than one already applied

goose applies migrations in the order of their timestamps and refuses one whose file is older than the newest already applied, which happens when a branch brings a migration stamped before one you have run. Since v0.6.8 the error says what to do:

```
blog: migrate: up: detected 1 missing (out-of-order) migration lower than database version (20261031071415): version 20200101000000: a migration file is older than the newest one already applied; rename the new file with a timestamp after it (only if no other database has applied it yet)
```

Rename the file with a later timestamp (`20261101000000_add_note.sql`) and run `bogie db:migrate` again. Do not rename one another database has already applied: it would run a second time there.

## Hand-written code beside generated code

`g model` writes two files whole every time it runs: `db/queries/<table>.sql` and `db/adapter/<table>.go`. Run it again and each file is reported `identical` when nothing changed, or `conflict` when it differs from what the generator would write, as it does after a query or method written straight into it. A conflict leaves the differing file as it is (a file that does not exist yet is still created) and the command exits with an error; only `--force` overwrites. Both files open with a comment that says so. Put your own code in a sibling `_extra` file instead:

- **`db/queries/posts_extra.sql`** for a hand-written query. sqlc compiles every `*.sql` file in `db/queries/`, so `make sqlc` picks it up like the generated ones.
- **`db/adapter/posts_extra.go`** for a hand-written store method. Go merges every file in a package, so the store gains the method and the generator never sees it.

```
-- db/queries/posts_extra.sql
-- name: ListPostsByTitle :many
SELECT * FROM posts WHERE title = $1 ORDER BY created_at DESC;
```

```
// db/adapter/posts_extra.go
package adapter

func (s *Store) PostsByTitle(ctx context.Context, title string) ([]models.Post, error) {
	// call s.q.ListPostsByTitle (written by make sqlc) and convert
	// each row with postFromRow, as the generated methods do
}
```

## Taking it out

```
bogie d model post
```

Removes everything `bogie g model` wrote for it: the migration, the queries, the model and its spec, the store and its spec, the factory, and sqlc's output for the table. A migration that was already applied somewhere stays applied there; `bogie db:reset` rebuilds the development database from the files that remain.
