sqlc-dev / sqlc

Generate type-safe code from SQL
https://sqlc.dev
MIT License
13.51k stars 810 forks source link

sqlc generates non idiomatic field names, when column names are in PascalCase or camelCase #3664

Open Crushless opened 1 month ago

Crushless commented 1 month ago

Version

1.27.0

What happened?

In our company there is a strict rule to never use snakecase in table column names. Table column names must always be in PascalCase (we are using "_" to separate column names when defining index names for example). When using sqlc to generate go code, sqlc looks for "_" in the column names to generate idiomatic go struct fields, but because there is no "_" in PascalCase, the generated field names are non idiomatic go code. Also the "initialisms" feature of sqlc does not work, because it always compares whole chunks (words between "\") in the column names.

Generated go code

models.go

type Bookmark struct {
    ID       int64   `db:"id" json:"id"`
    Scriptid int64   `db:"scriptid" json:"scriptid"`
    Lineno   int64   `db:"lineno" json:"lineno"`
    Label    *string `db:"label" json:"label"`
}

bookmarks.sql.go

const createBookmark = `-- name: CreateBookmark :exec
INSERT INTO Bookmarks(ScriptID, LineNo, Label)
VALUES ( ?, ?, ? )
`

type CreateBookmarkParams struct {
    Scriptid int64   `db:"scriptid" json:"scriptid"`
    Lineno   int64   `db:"lineno" json:"lineno"`
    Label    *string `db:"label" json:"label"`
}

func (q *Queries) CreateBookmark(ctx context.Context, arg CreateBookmarkParams) error {
    _, err := q.exec(ctx, q.createBookmarkStmt, createBookmark, arg.Scriptid, arg.Lineno, arg.Label)
    return err
}

Database schema

CREATE TABLE Bookmarks(
    ID          INTEGER PRIMARY KEY,
    ScriptID    INTEGER NOT NULL,
    LineNo      INTEGER NOT NULL,
    Label       TEXT,
    FOREIGN KEY (ScriptID) REFERENCES Scripts(ID) ON DELETE CASCADE
);

CREATE UNIQUE INDEX idxBookmarks_ScriptID_LineNo ON Bookmarks(ScriptID, LineNo);

SQL queries

-- name: ListBookmarks :many
SELECT ID, ScriptID, LineNo, Label FROM Bookmarks;

Configuration

version: '2'
sql:
  - engine: 'sqlite'
    queries: 'queries'
    schema: 'schema.sql'
    gen:
      go:
        emit_db_tags: true
        emit_json_tags: true
        emit_prepared_queries: true
        emit_empty_slices: true
        emit_pointers_for_null_types: true
        package: 'dto'
        out: '../dto'
    database:
      uri: 'file:../db.sqlite'
    rules:
      - sqlc/db-prepare

Playground URL

No response

What operating system are you using?

Linux

What database engines are you using?

SQLite

What type of code are you generating?

Go