-
Notifications
You must be signed in to change notification settings - Fork 986
Description
Given a mixin like this:
type FooMixin struct {
mixin.Schema
}
func (FooMixin) Fields() []ent.Field {
return []ent.Field{
field.String("fooUrl").
StorageKey("foo_url").
SchemaType(/* ... */).
GoType(new(url.URL)).
ValueScanner(field.BinaryValueScanner[*url.URL]{}),
}
}The generated code does not compile. Digging in, the issue is that it doesn't generate a variable declaration due to this logic:
Line 469 in 5368e5c
| if f.Position != nil && f.Position.MixedIn && (f.Default || f.UpdateDefault || f.Validators > 0) { |
ValueScanner. This causes this template code to skip declaring the ...MixinFieldsN variable: ent/entc/gen/template/runtime.tmpl
Line 153 in 5368e5c
| {{ print $pkg "MixinFields" $i }} := {{ $pkg }}Mixin[{{ $i }}].Fields() |
HasValueScanner here: ent/entc/gen/template/runtime.tmpl
Line 192 in 5368e5c
| {{- with $f.HasValueScanner }} |
My guess at a solution:
- The
ent/entc/gen.Fieldtype needs a flag for whether it has a value scanner ~Line 94 in 5368e5c
Validators int - This needs to be copied over ~
Line 252 in 5368e5c
Validators: f.Validators, - The template needs to add this to the list of things that cause a field to be reported in
MixedInFields~Line 469 in 5368e5c
if f.Position != nil && f.Position.MixedIn && (f.Default || f.UpdateDefault || f.Validators > 0) {
- The issue is present in the latest release.
- I have searched the issues of this repository and believe that this is not a duplicate.
NOTE: This sounds similar to #3255, but on closer inspection they seem like independent issues AFAICT.
Current Behavior π―
Generated code fails to compile due to attempting to reference an undeclared local variable.
Expected Behavior π€
Generated code should declare the variable so it compiles.
Steps to Reproduce πΉ
Repro repo: https://github.com/mgabeler-lee-6rs/entbug-3785
Build output:
entbug-3785$ go build -v ./...
entgo.io/bug/ent
# entgo.io/bug/ent
ent/runtime.go:6:2: "net/url" imported and not used
ent/runtime.go:10:2: "entgo.io/ent/schema/field" imported and not used
ent/runtime.go:20:17: undefined: userMixinFields0(I think the unused import problem will go away with the fix, not sure, but I personally normally run a formatter over generated code anyways that cleans up such things for me)
Steps:
- Add a mixin like the above to a schema type
- Generate the code
- Try to compile it
Workaround
Add a no-op custom validator to the mixed in field so that the template declares the variable.
Your Environment π
| Tech | Version |
|---|---|
| Go | 1.21.1 |
| Ent | 0.12.4 |
| Database | PostgreSQL |
| Driver | github.com/jackc/pgx/v5 |