Skip to content

Improve sqlc.embed Go field naming #2687

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion docs/howto/embedding.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,24 @@ type ScoreAndTestsRow struct {
Student Student
TestScore TestScore
}
```
```

sqlc can generate structs with fields based on the alias inside the macro `sqlc.embed()` by adding the `emit_embed_alias` key to the configuration file as it shows on [configuration reference](../reference/config.md).

```sql
-- name: ListUserLink :many
SELECT
sqlc.embed(owner),
sqlc.embed(consumer)
FROM
user_links
INNER JOIN users AS owner ON owner.id = user_links.owner_id
INNER JOIN users AS consumer ON consumer.id = user_links.consumer_id;
```

```
type ListUserLinkRow struct {
Owner User
Consumer User
}
```
5 changes: 5 additions & 0 deletions docs/reference/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ The `gen` mapping supports the following keys:
- `emit_all_enum_values`:
- If true, emit a function per enum type
that returns all valid enum values.
- `emit_embed_alias`:
- If true, use alias name inside `sqlc.embed()` macro instead of table name for field name. Defaults to `false`.
- `emit_sql_as_comment`:
- If true, emits the SQL statement as a code-block comment above the generated function, appending to any existing comments. Defaults to `false`.
- `build_tags`:
Expand Down Expand Up @@ -412,6 +414,7 @@ packages:
emit_pointers_for_null_types: false
emit_enum_valid_method: false
emit_all_enum_values: false
emit_embed_alias: false
build_tags: "some_tag"
json_tags_case_style: "camel"
omit_unused_structs: false
Expand Down Expand Up @@ -467,6 +470,8 @@ Each mapping in the `packages` collection has the following keys:
- `emit_all_enum_values`:
- If true, emit a function per enum type
that returns all valid enum values.
- `emit_embed_alias`:
- If true, use alias name inside `sqlc.embed()` macro instead of table name for field name. Defaults to `false`.
- `build_tags`:
- If set, add a `//go:build <build_tags>` directive at the beginning of each generated Go file.
- `json_tags_case_style`:
Expand Down
2 changes: 2 additions & 0 deletions internal/codegen/golang/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ type tmplCtx struct {
EmitMethodsWithDBArgument bool
EmitEnumValidMethod bool
EmitAllEnumValues bool
EmitEmbedAlias bool
UsesCopyFrom bool
UsesBatch bool
OmitSqlcVersion bool
Expand Down Expand Up @@ -177,6 +178,7 @@ func generate(req *plugin.GenerateRequest, options *opts.Options, enums []Enum,
EmitMethodsWithDBArgument: options.EmitMethodsWithDbArgument,
EmitEnumValidMethod: options.EmitEnumValidMethod,
EmitAllEnumValues: options.EmitAllEnumValues,
EmitEmbedAlias: options.EmitEmbedAlias,
UsesCopyFrom: usesCopyFrom(queries),
UsesBatch: usesBatch(queries),
SQLDriver: parseDriver(options.SqlPackage),
Expand Down
1 change: 1 addition & 0 deletions internal/codegen/golang/opts/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type Options struct {
EmitPointersForNullTypes bool `json:"emit_pointers_for_null_types" yaml:"emit_pointers_for_null_types"`
EmitEnumValidMethod bool `json:"emit_enum_valid_method,omitempty" yaml:"emit_enum_valid_method"`
EmitAllEnumValues bool `json:"emit_all_enum_values,omitempty" yaml:"emit_all_enum_values"`
EmitEmbedAlias bool `json:"emit_embed_alias,omitempty" yaml:"emit_embed_alias"`
EmitSqlAsComment bool `json:"emit_sql_as_comment,omitempty" yaml:"emit_sql_as_comment"`
JsonTagsCaseStyle string `json:"json_tags_case_style,omitempty" yaml:"json_tags_case_style"`
Package string `json:"package" yaml:"package"`
Expand Down
13 changes: 8 additions & 5 deletions internal/codegen/golang/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ type goEmbed struct {

// look through all the structs and attempt to find a matching one to embed
// We need the name of the struct and its field names.
func newGoEmbed(embed *plugin.Identifier, structs []Struct, defaultSchema string) *goEmbed {
func newGoEmbed(options *opts.Options, columnName string, embed *plugin.Identifier, structs []Struct, defaultSchema string) *goEmbed {
if embed == nil {
return nil
}
Expand All @@ -141,13 +141,16 @@ func newGoEmbed(embed *plugin.Identifier, structs []Struct, defaultSchema string
}

fields := make([]Field, len(s.Fields))
for i, f := range s.Fields {
fields[i] = f
copy(fields, s.Fields)

structName := s.Name
if options.EmitEmbedAlias && s.Table.Name != columnName {
structName = columnName
}

return &goEmbed{
modelType: s.Name,
modelName: s.Name,
modelName: structName,
fields: fields,
}
}
Expand Down Expand Up @@ -306,7 +309,7 @@ func buildQueries(req *plugin.GenerateRequest, options *opts.Options, structs []
columns = append(columns, goColumn{
id: i,
Column: c,
embed: newGoEmbed(c.EmbedTable, structs, req.Catalog.DefaultSchema),
embed: newGoEmbed(options, c.Name, c.EmbedTable, structs, req.Catalog.DefaultSchema),
})
}
var err error
Expand Down
2 changes: 1 addition & 1 deletion internal/compiler/output_columns.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ func (c *Compiler) outputColumns(qc *QueryCatalog, node ast.Node) ([]*Column, er
// add a column with a reference to an embedded table
if embed, ok := qc.embeds.Find(n); ok {
cols = append(cols, &Column{
Name: embed.Table.Name,
Name: embed.Name(),
EmbedTable: embed.Table,
})
continue
Expand Down
2 changes: 2 additions & 0 deletions internal/config/v_one.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ type v1PackageSettings struct {
EmitPointersForNullTypes bool `json:"emit_pointers_for_null_types" yaml:"emit_pointers_for_null_types"`
EmitEnumValidMethod bool `json:"emit_enum_valid_method,omitempty" yaml:"emit_enum_valid_method"`
EmitAllEnumValues bool `json:"emit_all_enum_values,omitempty" yaml:"emit_all_enum_values"`
EmitEmbedAlias bool `json:"emit_embed_alias,omitempty" yaml:"emit_embed_alias"`
EmitSqlAsComment bool `json:"emit_sql_as_comment,omitempty" yaml:"emit_sql_as_comment"`
JSONTagsCaseStyle string `json:"json_tags_case_style,omitempty" yaml:"json_tags_case_style"`
SQLPackage string `json:"sql_package" yaml:"sql_package"`
Expand Down Expand Up @@ -151,6 +152,7 @@ func (c *V1GenerateSettings) Translate() Config {
EmitPointersForNullTypes: pkg.EmitPointersForNullTypes,
EmitEnumValidMethod: pkg.EmitEnumValidMethod,
EmitAllEnumValues: pkg.EmitAllEnumValues,
EmitEmbedAlias: pkg.EmitEmbedAlias,
EmitSqlAsComment: pkg.EmitSqlAsComment,
Package: pkg.Name,
Out: pkg.Path,
Expand Down
5 changes: 5 additions & 0 deletions internal/endtoend/testdata/sqlc_embed/mysql/go/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

45 changes: 45 additions & 0 deletions internal/endtoend/testdata/sqlc_embed/mysql/go/query.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 10 additions & 1 deletion internal/endtoend/testdata/sqlc_embed/mysql/query.sql
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,13 @@ SELECT sqlc.embed(bu) FROM baz.users bu;

-- name: WithCrossSchema :many
SELECT sqlc.embed(users), sqlc.embed(bu) FROM users
INNER JOIN baz.users bu ON users.id = bu.id;
INNER JOIN baz.users bu ON users.id = bu.id;

-- name: ListUserLink :many
SELECT
sqlc.embed(owner),
sqlc.embed(consumers)
FROM
user_links
INNER JOIN users AS owner ON owner.id = user_links.owner_id
INNER JOIN users AS consumers ON consumers.id = user_links.consumer_id;
6 changes: 5 additions & 1 deletion internal/endtoend/testdata/sqlc_embed/mysql/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,8 @@ CREATE TABLE baz.users (
name varchar(255) NOT NULL
);


CREATE TABLE user_links (
owner_id integer NOT NULL,
consumer_id integer NOT NULL,
PRIMARY KEY (owner_id, consumer_id)
);

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 10 additions & 1 deletion internal/endtoend/testdata/sqlc_embed/postgresql/pgx/query.sql
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,13 @@ SELECT sqlc.embed(bu) FROM baz.users bu;

-- name: WithCrossSchema :many
SELECT sqlc.embed(users), sqlc.embed(bu) FROM users
INNER JOIN baz.users bu ON users.id = bu.id;
INNER JOIN baz.users bu ON users.id = bu.id;

-- name: ListUserLink :many
SELECT
sqlc.embed(owner),
sqlc.embed(consumer)
FROM
user_links
INNER JOIN users AS owner ON owner.id = user_links.owner_id
INNER JOIN users AS consumer ON consumer.id = user_links.consumer_id;
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,8 @@ CREATE TABLE baz.users (
name varchar(255) NOT NULL
);


CREATE TABLE user_links (
owner_id integer NOT NULL,
consumer_id integer NOT NULL,
PRIMARY KEY (owner_id, consumer_id)
);

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,13 @@ SELECT sqlc.embed(bu) FROM baz.users bu;

-- name: WithCrossSchema :many
SELECT sqlc.embed(users), sqlc.embed(bu) FROM users
INNER JOIN baz.users bu ON users.id = bu.id;
INNER JOIN baz.users bu ON users.id = bu.id;

-- name: ListUserLink :many
SELECT
sqlc.embed(owner),
sqlc.embed(consumer)
FROM
user_links
INNER JOIN users AS owner ON owner.id = user_links.owner_id
INNER JOIN users AS consumer ON consumer.id = user_links.consumer_id;
Loading
Loading