# Go (go vet and golangci-lint)

> [!WARNING]
>
> **Preview**
>
> `go get github.com/jirikuncar/sqlty/go` gives `sqlty.SQL` and `pgxq`, which need no engine. The analyzer links the engine: `sqlty-vet` comes prebuilt for macOS and Linux with glibc 2.35 or newer (not Alpine), and the golangci-lint plugin builds from a checkout.

A query in Go is a string, and the struct you scan it into is a guess. pgx reports a wrong guess when the query runs, here on the row of a user without posts:

```go
type UserPosts struct {
    Email string
    Title string
}

rows, _ := conn.Query(ctx, `
    SELECT u.email, p.title
    FROM users u LEFT JOIN posts p ON p.user_id = u.id`)
_, err := pgx.CollectRows(rows, pgx.RowToStructByName[UserPosts])
// can't scan into dest[1] (col: title): cannot scan NULL into *string
```

`sqlty.SQL[R, P]` keeps your own structs and your own SQL, generates no code, and moves the check to `go vet`, before the code runs. Try it in the [playground](<https://sqlty.kuncar.dev/playground/index.md>): its "Go (go vet)" example runs the analyzer in your browser.

## The pattern

`R` is the row struct, `P` a func type naming the parameters. Both exist only for the compiler and the analyzer: at run time a `sqlty.SQL` is its string.

```go
package users

import (
    "time"

    "github.com/jirikuncar/sqlty/go"
)

type User struct {
    ID        int64
    Email     string
    Name      *string
    CreatedAt time.Time `db:"created_at"`
}

var GetUser = sqlty.SQL[User, func(email string)](`
    SELECT id, email, name, created_at FROM users WHERE email = $1`)

type UserPosts struct {
    Email string
    Title *string
    Posts int64
}

var ListUserPosts = sqlty.SQL[UserPosts, sqlty.NoParams](`
    SELECT u.email, p.title, COUNT(*) OVER (PARTITION BY u.id) AS posts
    FROM users u LEFT JOIN posts p ON p.user_id = u.id`)

var AddUser = sqlty.SQL[sqlty.NoRows, func(email string, name *string)](`
    INSERT INTO users (email, name) VALUES ($1, $2)`)
```

`pgxq` runs them with pgx v5, on a `pgx.Conn`, `pgxpool.Pool` or `pgx.Tx`:

```go
user, err := pgxq.One(ctx, conn, users.GetUser, "ada@example.com") // user is users.User
rows, err := pgxq.All(ctx, conn, users.ListUserPosts)               // rows is []users.UserPosts
_, err = pgxq.Exec(ctx, conn, users.AddUser, "bob@example.com", nil)
```

A query can also be a constant: `var GetUser sqlty.SQL[User, func(email string)] = "..."`. `R` may be one value, which `pgxq` scans from the only column: `int64` for `SELECT count(*)`, `time.Time`, or a `sql.Scanner` such as `pgtype.Numeric`.

`pgxq.Each` yields the rows one at a time, and `QueueAll`, `QueueOne` and `QueueExec` add a query to a `pgx.Batch`, scanning its rows when the batch's results are read:

```go
for post, err := range pgxq.Each(ctx, conn, users.ListUserPosts) {
    // post is a users.UserPosts
}

var b pgx.Batch
var posts []users.UserPosts
pgxq.QueueAll(&b, &posts, users.ListUserPosts)
err = conn.SendBatch(ctx, &b).Close()
```

pgx can run the query itself, as `string(q)`: the analyzer checks the arguments of `conn.Query(ctx, string(users.GetUser), email)`, `QueryRow`, `Exec` and `Batch.Queue` too.

The Go compiler checks what it can: `user` is a `User`, and a `sqlty.SQL` cannot be passed where pgx takes a plain `string`. The analyzer checks the rest against the schema.

Fields and parameters take the Go types pgx scans and encodes: an enum column a `string` or a type of string kind, `INTERVAL` a `time.Duration`, `INET` a `netip.Prefix`, and so on. A type of your own is accepted for any column when it is a `sql.Scanner`, and for any parameter when it is a `driver.Valuer`, as every `pgtype` type is.

## Configure the schema

The analyzer reads the same configuration as `sqlty check`: the nearest `sqlty.toml`, or `[tool.sqlty]` in a `pyproject.toml`, above each Go file.

`sqlty.toml`:

```toml
schema = "schema.sql"
```

`schema` takes `CREATE TABLE` files, directories and migrations, and `[rules]` sets the severity of the rules, as for Python: see [Configuration](<https://sqlty.kuncar.dev/reference/configuration/index.md>). A schema file that cannot be read is reported at the first query, as `sqlty: ...`.

## Run it in go vet

`brew install jirikuncar/sqlty/sqlty-vet` installs `sqlty-vet` on its own, without `sqlty`. From a checkout of the repository, `make go-vet` builds it into `rust/target/go/`. Then run it on your module:

```console
$ go vet -vettool=$(which sqlty-vet) ./...
broken/broken.go:19:60: [unknown-column] column `emial` does not exist in `users`; did you mean `email`?
broken/broken.go:19:48: [column-type-mismatch] column `id` is BIGINT, but broken.User.ID is int32: use int64 or int
broken/broken.go:19:48: [column-name-mismatch] broken.User.Email matches no column of the query (looked for `email`)
broken/broken.go:19:48: [nullable-mismatch] column `nick` can be NULL, but broken.User.Nick is string: use *string
broken/broken.go:19:48: [column-name-mismatch] column `emial` has no field in broken.User
broken/broken.go:19:48: [param-type-mismatch] parameter $1 is BIGINT, but `id` in P is string: use int64 or int
broken/broken.go:66:38: [param-type-mismatch] argument `id` is int, but func(id string) expects string
```

With Go 1.26 or newer, `-fix` applies what it can fix: a field of a column that can be NULL becomes a pointer (`nullable-mismatch`), a pointer of a column that is never NULL its value (`redundant-optional`), and a misspelled table or column the name it suggests.

A field changes type only where nothing else reads it: its struct is declared in the query's file, the package names the struct only as the row type of `sqlty.SQL` and never reads the field, every query scans it from columns of one nullability, and no exported name reaches the struct, such as an exported query variable (unless the package is `main`). The analyzer sees only the files of the current build, so a file behind other build tags, or a test when golangci-lint runs with `run.tests: false`, may still read the field; so may a conversion of the row to an unnamed struct. `go build` reports each. A name in the SQL is fixed when the query is one string literal without escapes. A fix can uncover another, such as a misspelled column of a misspelled table, which the next run fixes. `-diff` prints the patch instead of applying it (paths shortened):

```console
$ go vet -vettool=$(which sqlty-vet) -fix -diff ./...
--- contacts/contacts.go (old)
+++ contacts/contacts.go (new)
@@ -3,7 +3,7 @@
 import "github.com/jirikuncar/sqlty/go"

 type contact struct {
-   Name  string
+   Name  *string
    Email string
 }
```

`golangci-lint run --fix` and the playground's "Fix All in File" apply the same fixes.

In GitHub Actions, the action in the repository's `go` directory downloads the `sqlty-vet` of its release (the GitHub Release `go/vX.Y.Z`), checks it against the digest GitHub records for the asset, and runs it under `go vet`. Each finding fails the job and stays in the log; GitHub annotates the first ones on their lines:

```yaml
- uses: actions/setup-go@v7
  with:
    go-version-file: go.mod
- uses: jirikuncar/sqlty/go@v0.10.0
  # with:
  #   working-directory: .  # the directory of go.mod
  #   args: ./...           # the flags and packages of go vet
```

The release follows the action's commit, so pinning the action to a commit SHA pins `sqlty-vet` too; `version` picks another. With `install-only: true` it only installs `sqlty-vet` and puts it on `PATH`, for a `go vet` of your own, such as one per module:

```yaml
- uses: jirikuncar/sqlty/go@v0.10.0
  id: sqlty
  with:
    install-only: true
- run: for m in api worker; do (cd "$m" && go vet -vettool="$VETTOOL" ./...); done
  env:
    VETTOOL: ${{ steps.sqlty.outputs.path }}
```

It runs on Linux and macOS runners.

Each finding is reported at the query, or at the `pgxq` call for its arguments. `[rules]` sets the severity of every rule: `ignore` turns one off, and any other severity fails `go vet`, which has no warnings. What it reports:

| Rule | When |
| --- | --- |
| [`unknown-table`](<https://sqlty.kuncar.dev/reference/rules/unknown-table/index.md>), [`unknown-column`](<https://sqlty.kuncar.dev/reference/rules/unknown-column/index.md>), ... | The SQL rules of `sqlty check`, with the severities of `[rules]` |
| [`column-name-mismatch`](<https://sqlty.kuncar.dev/reference/rules/column-name-mismatch/index.md>) | A column has no field of `R`, a field matches no column, or a later field takes its column. Fields match columns as `pgx.RowToStructByName` matches them: the `db` tag, else the name ignoring case and underscores, with the fields of embedded structs |
| [`column-type-mismatch`](<https://sqlty.kuncar.dev/reference/rules/column-type-mismatch/index.md>) | A field cannot hold every value of the column's type: an `int32` for a `BIGINT`. Types the table does not know, interfaces and `pgtype` types are accepted |
| [`nullable-mismatch`](<https://sqlty.kuncar.dev/reference/rules/nullable-mismatch/index.md>) | A column can be NULL, and its field is not a pointer, `sql.Null*` or `pgtype` type. |
| [`redundant-optional`](<https://sqlty.kuncar.dev/reference/rules/redundant-optional/index.md>) | A column is never NULL, and its field is a pointer (off by default) |
| [`column-count-mismatch`](<https://sqlty.kuncar.dev/reference/rules/column-count-mismatch/index.md>) | `R` is `sqlty.NoRows` for a query with rows, or a row type for one without, or one value such as `int64` for a query of several columns |
| [`param-count-mismatch`](<https://sqlty.kuncar.dev/reference/rules/param-count-mismatch/index.md>) | `P` takes another number of parameters than the query, or a `pgxq` call passes another number of arguments than `P` |
| [`param-type-mismatch`](<https://sqlty.kuncar.dev/reference/rules/param-type-mismatch/index.md>) | A parameter of `P` cannot hold the placeholder's type, or an argument of a `pgxq` call is not of `P`'s kind: an `int` passes for an `int64`, a `string` does not |
| [`dynamic-query`](<https://sqlty.kuncar.dev/reference/rules/dynamic-query/index.md>) | The query is not a constant string, so it is not checked (off by default) |

## Run it in golangci-lint

The analyzer is a golangci-lint [module plugin](<https://golangci-lint.run/docs/plugins/module-plugins/>). `golangci-lint custom` builds a golangci-lint with it, from `.custom-gcl.yml`, with `path` at the `go` directory of a checkout whose engine `make go-lib` built:

```yaml
version: v2.12.2
name: golangci-sqlty
plugins:
  - module: github.com/jirikuncar/sqlty/go
    import: github.com/jirikuncar/sqlty/go/golangci
    path: /path/to/sqlty/go
```

and `.golangci.yml` enables it:

```yaml
version: "2"
linters:
  default: none
  enable:
    - sqlty
  settings:
    custom:
      sqlty:
        type: module
        description: Checks sqlty.SQL[R, P] queries against the schema.
```

```console
golangci-lint custom            # builds ./golangci-sqlty
./golangci-sqlty run ./...
```

In VS Code, the Go extension runs that binary on save: set `"go.lintTool": "golangci-lint-v2"` and point `"go.alternateTools": {"golangci-lint-v2": "/path/to/golangci-sqlty"}` at it. gopls cannot load an analyzer of its own, so the findings come on save, not as you type.

## The example

[`go/example`](<https://github.com/jirikuncar/sqlty/tree/main/go/example>) holds the queries above and a program that runs them. From a checkout:

```console
$ make go-vet          # build the engine and sqlty-vet, then go vet the example
$ make go-example      # the same, then build go/example/app
$ make go-lint         # golangci-lint with the plugin on the example
$ make go-test         # the analyzer's own tests
$ cd go/example && DATABASE_URL=postgres://localhost/app ./app
ada@example.com: Hello (1 posts)
bob@example.com: (none) (1 posts)
```
