Search code examples
gosqlc

How can I rename go model type names generated by sqlc so that they don't include the schema name?


Given this sqlc.yaml file:

version: "2"
sql:
  - engine: "postgresql"
    schema: "internal/db/schema.sql"
    queries: "internal/db/queries.sql"
    gen:
      go:
        package: "db"
        out: "internal/db"
        sql_package: "pgx/v5"

this internal/db/schema.sql:

CREATE SCHEMA go_htmx_todo;

CREATE TABLE go_htmx_todo.todos (
    id integer NOT NULL,
    task character varying(255) NOT NULL,
    done boolean DEFAULT false NOT NULL,
    created_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
    created_by integer NOT NULL,
    updated_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
    updated_by integer NOT NULL
);

and this internal/db/queries.sql:

-- name: GetTodo :one
SELECT * FROM go_htmx_todo.todos
WHERE id = $1 LIMIT 1;

when I run sqlc generate with sqlc version v1.26.0, the following internal/db/models.go file is generated:

package db

import (
    "github.com/jackc/pgx/v5/pgtype"
)

type GoHtmxTodoTodo struct {
    ID        int32
    Task      string
    Done      bool
    CreatedAt pgtype.Timestamp
    CreatedBy int32
    UpdatedAt pgtype.Timestamp
    UpdatedBy int32
}

The question is how can I configure sqlc to generate the model's struct name as Todo instead of GoHtmxTodoTodo i.e. to omit the schema name?

Update: I tried using the rename overrides with different patterns:

version: "2"
sql:
  - engine: "postgresql"
    schema: "internal/db/schema.sql"
    queries: "internal/db/queries.sql"
    database:
      uri: "postgres://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}"
    rules:
      - sqlc/db-prepare
    gen:
      go:
        package: "db"
        out: "internal/db"
        sql_package: "pgx/v5"
        emit_prepared_queries: true
        emit_interface: true
        emit_enum_valid_method: true
overrides:
  go:
    rename:
      go_htmx_todo_todos: Todo
      GoHtmxTodoTodo: Todo
      GoHtmxTodoTodos: Todo
      GoHtmxTodo_Todo: Todo
      GoHtmxTodo_Todos: Todo
      Go_Htmx_Todo_Todo: Todo
      Go_Htmx_Todo_Todos: Todo
      gohtmxtodotodo: Todo
      gohtmxtodotodos: Todo
      gohtmxtodo_todo: Todo
      gohtmxtodo_todos: Todo
      gohtmxtodo.todo: Todo
      gohtmxtodo.todos: Todo
      go_htmx_todo.todo: Todo
      go_htmx_todo.todos: Todo
      go.htmx.todo.todo: Todo
      go.htmx.todo.todos: Todo

Solution

  • https://docs.sqlc.dev/en/stable/howto/rename.html

    Add the overrides at the root level, at the bottom of your sqlc.yaml file. (There is a different overrides at the gen > go level.)

    The key needs to match what sqlc thinks it should be, which is a bit tricky. Seems you need to use an underscore where you have the .

    overrides:
      go:
        rename:
          go_htmx_todo_todo: Todo