diff --git a/entc/gen/template/builder/query.tmpl b/entc/gen/template/builder/query.tmpl index 780422f33..a262b0910 100644 --- a/entc/gen/template/builder/query.tmpl +++ b/entc/gen/template/builder/query.tmpl @@ -221,9 +221,20 @@ func ({{ $receiver }} *{{ $builder }}) AllX(ctx context.Context) []*{{ $.Name }} {{ $receiver }}.Unique(true) } ctx = setContextOp(ctx, {{ $receiver }}.ctx, ent.OpQueryIDs) - if err = {{ $receiver }}.Select({{ $.Package }}.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } + {{- if and $.ID.HasValueScanner (eq $.Storage.Name "sql") }} + var nodes []*{{ $.Name }} + if nodes, err = {{ $receiver }}.Select({{ $.Package }}.FieldID).All(ctx); err != nil { + return nil, err + } + ids = make([]{{ $.ID.Type }}, len(nodes)) + for i := range nodes { + ids[i] = nodes[i].ID + } + {{- else }} + if err = {{ $receiver }}.Select({{ $.Package }}.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + {{- end }} return ids, nil } diff --git a/entc/gen/template/dialect/sql/create.tmpl b/entc/gen/template/dialect/sql/create.tmpl index 3f871e44a..32b037994 100644 --- a/entc/gen/template/dialect/sql/create.tmpl +++ b/entc/gen/template/dialect/sql/create.tmpl @@ -28,24 +28,39 @@ func ({{ $receiver }} *{{ $builder }}) sqlSave(ctx context.Context) (*{{ $.Name return nil, err } {{- if $.HasCompositeID }} - {{- else if or $.ID.Type.ValueScanner (not $.ID.Type.Numeric) }} + {{- else if or $.ID.HasValueScanner $.ID.Type.ValueScanner (not $.ID.Type.Numeric) }} if _spec.ID.Value != nil { - {{- /* If the ID type is not a pointer, but implements the ValueScanner interface (e.g. UUID fields). */}} - {{- if and $.ID.Type.ValueScanner (not $.ID.Type.RType.IsPtr) }} - if id, ok := _spec.ID.Value.(*{{ $.ID.Type }}); ok { - _node.ID = *id - {{- else }} - if id, ok := _spec.ID.Value.({{ $.ID.Type }}); ok { - _node.ID = id - {{- end }} - {{- if $.ID.Type.ValueScanner }} - } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { - return nil, err - {{- else }} - } else { - return nil, fmt.Errorf("unexpected {{ $.Name }}.ID type: %T", _spec.ID.Value) - {{- end }} + {{- if $.ID.HasValueScanner }} + sv, ok := _spec.ID.Value.(field.ValueScanner) + if !ok { + sv = {{ $.ID.ScanValueFunc }}() + if err := sv.Scan(_spec.ID.Value); err != nil { + return nil, err + } } + if value, err := {{ $.ID.FromValueFunc }}(sv); err != nil { + return nil, err + } else { + _node.ID = value + } + {{- else }} + {{- /* If the ID type is not a pointer, but implements the ValueScanner interface (e.g. UUID fields). */}} + {{- if and $.ID.Type.ValueScanner (not $.ID.Type.RType.IsPtr) }} + if id, ok := _spec.ID.Value.(*{{ $.ID.Type }}); ok { + _node.ID = *id + {{- else }} + if id, ok := _spec.ID.Value.({{ $.ID.Type }}); ok { + _node.ID = id + {{- end }} + {{- if $.ID.Type.ValueScanner }} + } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { + return nil, err + {{- else }} + } else { + return nil, fmt.Errorf("unexpected {{ $.Name }}.ID type: %T", _spec.ID.Value) + {{- end }} + } + {{- end }} } {{- else }} {{- if $.ID.UserDefined }} @@ -78,7 +93,15 @@ func ({{ $receiver }} *{{ $builder }}) createSpec() (*{{ $.Name }}, *sqlgraph.Cr {{- if and (not $.HasCompositeID) $.ID.UserDefined }} if id, ok := {{ $mutation }}.{{ $.ID.MutationGet }}(); ok { _node.ID = id - _spec.ID.Value = {{ if and $.ID.Type.ValueScanner (not $.ID.Type.RType.IsPtr) }}&{{ end }}id + {{- if $.ID.HasValueScanner }} + vv, err := {{ $.ID.ValueFunc }}(id) + if err != nil { + return nil, nil, err + } + _spec.ID.Value = vv + {{- else }} + _spec.ID.Value = {{ if and $.ID.Type.ValueScanner (not $.ID.Type.RType.IsPtr) }}&{{ end }}id + {{- end }} } {{- end }} {{- range $f := $.MutationFields }} @@ -194,8 +217,23 @@ func ({{ $receiver }} *{{ $builder }}) Save(ctx context.Context) ([]*{{ $.Name } } {{- if $.HasOneFieldID }} mutation.{{ $.ID.BuilderField }} = &nodes[i].{{ $.ID.StructField }} - {{- if or $.ID.IsString $.ID.IsUUID $.ID.IsBytes $.ID.IsOther }} + {{- if and (or $.ID.IsString $.ID.IsUUID $.ID.IsBytes $.ID.IsOther) (not $.ID.HasValueScanner) }} {{- /* Do nothing, because these 4 types must be supplied by the user. */ -}} + {{- else if $.ID.HasValueScanner }} + if specs[i].ID.Value != nil { + sv, ok := specs[i].ID.Value.(field.ValueScanner) + if !ok { + sv = {{ $.ID.ScanValueFunc }}() + if err := sv.Scan(specs[i].ID.Value); err != nil { + return nil, err + } + } + if id, err := {{ $.ID.FromValueFunc }}(sv); err != nil { + return nil, err + } else { + nodes[i].ID = id + } + } {{- else if or $.ID.Type.ValueScanner }} if specs[i].ID.Value != nil { if err := nodes[i].ID.Scan(specs[i].ID.Value); err != nil { diff --git a/entc/gen/template/dialect/sql/decode.tmpl b/entc/gen/template/dialect/sql/decode.tmpl index 27690c4ca..f64e9054f 100644 --- a/entc/gen/template/dialect/sql/decode.tmpl +++ b/entc/gen/template/dialect/sql/decode.tmpl @@ -11,8 +11,10 @@ in the LICENSE file in the root directory of this source tree. {{ $ctypes := dict }} {{ if $.HasOneFieldID }} - {{ $idscantype := $.ID.NewScanType }} - {{ $ctypes = set $ctypes $idscantype (list $.ID.Constant) }} + {{- if not $.ID.HasValueScanner }} + {{ $idscantype := $.ID.NewScanType }} + {{ $ctypes = set $ctypes $idscantype (list $.ID.Constant) }} + {{- end }} {{ end }} {{ range $f := $.Fields }} {{- if $f.HasValueScanner }} @@ -31,6 +33,10 @@ func (*{{ $.Name }}) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { + {{- if and $.HasOneFieldID $.ID.HasValueScanner }} + case {{ $.Package }}.{{ $.ID.Constant }}: + values[i] = {{ $.ID.ScanValueFunc }}() + {{- end }} {{- range $type, $columns := $ctypes }} case {{ range $i, $c := $columns }}{{ if ne $i 0 }},{{ end }}{{ $.Package }}.{{ $c }}{{ end }}: values[i] = {{ $type }} @@ -64,7 +70,7 @@ func ({{ $receiver }} *{{ $.Name }}) assignValues(columns []string, values []any switch columns[i] { {{- if $.HasOneFieldID }} case {{ $.Package }}.{{ $.ID.Constant }}: - {{- if or $.ID.IsString $.ID.IsBytes $.ID.HasGoType }} + {{- if or $.ID.IsString $.ID.IsBytes $.ID.HasGoType $.ID.HasValueScanner }} {{- with extend $ "Idx" "i" "Field" $.ID "Rec" $receiver }} {{ template "dialect/sql/decode/field" . }} {{- end }} diff --git a/entc/gen/template/dialect/sql/predicate.tmpl b/entc/gen/template/dialect/sql/predicate.tmpl index 820be16b8..66d950d24 100644 --- a/entc/gen/template/dialect/sql/predicate.tmpl +++ b/entc/gen/template/dialect/sql/predicate.tmpl @@ -7,13 +7,22 @@ in the LICENSE file in the root directory of this source tree. {{/* gotype: entgo.io/ent/entc/gen.typeScope */}} {{ define "dialect/sql/predicate/id" -}} - sql.FieldEQ({{ $.ID.Constant }}, id) + {{- $arg := "id" }} + {{- with $.Scope.Arg }} + {{- $arg = . }} + {{- end -}} + sql.FieldEQ({{ $.ID.Constant }}, {{ $arg }}) {{- end }} {{ define "dialect/sql/predicate/id/ops" -}} {{- $op := $.Scope.Op -}} {{- $storage := $.Scope.Storage -}} - sql.Field{{ call $storage.OpCode $op }}({{ $.ID.Constant }}{{ if not $op.Niladic }},{{ if $op.Variadic }}ids...{{ else }}id{{ end }}{{ end }}) + {{- $arg := "id" -}} + {{- if $op.Variadic }}{{ $arg = "ids" }}{{ end -}} + {{- with $.Scope.Arg -}} + {{- $arg = . -}} + {{- end -}} + sql.Field{{ call $storage.OpCode $op }}({{ $.ID.Constant }}{{ if not $op.Niladic }}, {{ $arg }}{{ if $op.Variadic }}...{{ end }}{{ end }}) {{- end }} {{ define "dialect/sql/predicate/field" -}} diff --git a/entc/gen/template/dialect/sql/query.tmpl b/entc/gen/template/dialect/sql/query.tmpl index 70f01e4bc..b5dc722e0 100644 --- a/entc/gen/template/dialect/sql/query.tmpl +++ b/entc/gen/template/dialect/sql/query.tmpl @@ -116,7 +116,15 @@ func ({{ $receiver }} *{{ $builder }}) sqlAll(ctx context.Context, hooks ...quer byID := make(map[{{ $.ID.Type }}]*{{ $.Name }}) nids := make(map[{{ $e.Type.ID.Type }}]map[*{{ $.Name }}]struct{}) for i, node := range nodes { - edgeIDs[i] = node.ID + {{- if $.ID.HasValueScanner }} + vv, err := {{ $.ID.ValueFunc }}(node.ID) + if err != nil { + return err + } + edgeIDs[i] = vv + {{- else }} + edgeIDs[i] = node.ID + {{- end }} byID[node.ID] = node if init != nil { init(node) @@ -154,11 +162,29 @@ func ({{ $receiver }} *{{ $builder }}) sqlAll(ctx context.Context, hooks ...quer if err != nil { return nil, err } - return append([]any{new({{ $out }})}, values...), nil + {{- if $.ID.HasValueScanner }} + return append([]any{ {{ $.ID.ScanValueFunc }}() }, values...), nil + {{- else }} + return append([]any{new({{ $out }})}, values...), nil + {{- end }} } spec.Assign = func(columns []string, values []any) error { - outValue := {{ with extend $ "Arg" "values[0]" "Field" $.ID "ScanType" $out }}{{ template "dialect/sql/query/eagerloading/m2massign" . }}{{ end }} - inValue := {{ with extend $ "Arg" "values[1]" "Field" $e.Type.ID "ScanType" $in }}{{ template "dialect/sql/query/eagerloading/m2massign" . }}{{ end }} + {{- if $.ID.HasValueScanner }} + var outValue {{ $.ID.Type }} + {{- with extend $ "Arg" "values[0]" "Field" $.ID "ScanType" $out "Ident" "outValue" }} + {{ template "dialect/sql/query/eagerloading/m2massign" . }} + {{- end }} + {{- else }} + outValue := {{- with extend $ "Arg" "values[0]" "Field" $.ID "ScanType" $out }}{{ template "dialect/sql/query/eagerloading/m2massignexpr" . }}{{- end }} + {{- end }} + {{- if $e.Type.ID.HasValueScanner }} + var inValue {{ $e.Type.ID.Type }} + {{- with extend $ "Arg" "values[1]" "Field" $e.Type.ID "ScanType" $in "Ident" "inValue" }} + {{ template "dialect/sql/query/eagerloading/m2massign" . }} + {{- end }} + {{- else }} + inValue := {{- with extend $ "Arg" "values[1]" "Field" $e.Type.ID "ScanType" $in }}{{ template "dialect/sql/query/eagerloading/m2massignexpr" . }}{{- end }} + {{- end }} if nids[inValue] == nil { nids[inValue] = map[*{{ $.Name }}]struct{}{byID[outValue]: {}} return assign(columns[1:], values[1:]) @@ -218,7 +244,15 @@ func ({{ $receiver }} *{{ $builder }}) sqlAll(ctx context.Context, hooks ...quer fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[{{ $.ID.Type }}]*{{ $.Name }}) for i := range nodes { - fks = append(fks, nodes[i].ID) + {{- if $.ID.HasValueScanner }} + vv, err := {{ $.ID.ValueFunc }}(nodes[i].ID) + if err != nil { + return err + } + fks = append(fks, vv) + {{- else }} + fks = append(fks, nodes[i].ID) + {{- end }} nodeids[nodes[i].ID] = nodes[i] {{- if $e.O2M }} if init != nil { @@ -431,7 +465,16 @@ func ({{ $receiver }} *{{ $builder }}) sqlQuery(ctx context.Context) *sql.Select {{- $e := $.Scope.Edge }} {{/* the edge we need to genegrate the path to. */}} {{- $ident := $.Scope.Ident -}} {{- $receiver := $.Scope.Receiver -}} - id := {{ $receiver }}.ID + {{- if $n.ID.HasValueScanner -}} + id := any({{ $receiver }}.ID) + vv, err := {{ $n.ID.ValueFunc }}({{ $receiver }}.ID) + if err != nil { + return nil, err + } + id = vv + {{- else -}} + id := {{ $receiver }}.ID + {{- end }} step := sqlgraph.NewStep( sqlgraph.From({{ $n.Package }}.Table, {{ $n.Package }}.{{ $n.ID.Constant }}, id), sqlgraph.To({{ $e.Type.Package }}.Table, {{ $e.Type.Package }}.{{ if $e.Type.HasCompositeID }}{{ $e.Ref.ColumnConstant }}{{ else }}{{ $e.Type.ID.Constant }}{{ end }}), @@ -452,10 +495,28 @@ func ({{ $receiver }} *{{ $builder }}) sqlQuery(ctx context.Context) *sql.Select {{ $ident }} = sqlgraph.Neighbors({{ $receiver }}.driver.Dialect(), step) {{ end }} -{{ define "dialect/sql/query/eagerloading/m2massign" }} - {{- $arg := $.Scope.Arg }} - {{- $field := $.Scope.Field }} - {{- $scantype := $.Scope.ScanType }} +{{ define "dialect/sql/query/eagerloading/m2massign" -}} + {{- $arg := $.Scope.Arg -}} + {{- $field := $.Scope.Field -}} + {{- $scantype := $.Scope.ScanType -}} + {{- $ident := $.Scope.Ident -}} + {{- if $field.HasValueScanner }} + if value, err := {{ $field.FromValueFunc }}({{ $arg }}); err != nil { + return err + } else { + {{ $ident }} = value + } + {{- else if hasPrefix $scantype "sql" -}} + {{ $ident }} = {{ printf "%s.(*%s)" $arg $scantype | $field.ScanTypeField }} + {{- else -}} + {{ $ident }} = {{ if not $field.Nillable }}*{{ end }}{{ printf "%s.(*%s)" $arg $scantype }} + {{- end }} +{{- end }} + +{{ define "dialect/sql/query/eagerloading/m2massignexpr" -}} + {{- $arg := $.Scope.Arg -}} + {{- $field := $.Scope.Field -}} + {{- $scantype := $.Scope.ScanType -}} {{- if hasPrefix $scantype "sql" -}} {{ printf "%s.(*%s)" $arg $scantype | $field.ScanTypeField -}} {{- else -}} diff --git a/entc/gen/template/dialect/sql/update.tmpl b/entc/gen/template/dialect/sql/update.tmpl index 55bbdd9f8..93f034ea9 100644 --- a/entc/gen/template/dialect/sql/update.tmpl +++ b/entc/gen/template/dialect/sql/update.tmpl @@ -50,7 +50,15 @@ func ({{ $receiver }} *{{ $builder }}) sqlSave(ctx context.Context) (_node {{ if if !ok { return {{ $zero }}, &ValidationError{Name: "{{ $.ID.Name }}", err: errors.New(`{{ $pkg }}: missing "{{ $.Name }}.{{ $.ID.Name }}" for update`)} } - _spec.Node.ID.Value = id + {{- if $.ID.HasValueScanner }} + vv, err := {{ $.ID.ValueFunc }}(id) + if err != nil { + return {{ $zero }}, err + } + _spec.Node.ID.Value = vv + {{- else }} + _spec.Node.ID.Value = id + {{- end }} if fields := {{ $receiver }}.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, {{ $.Package }}.{{ $.ID.Constant }}) diff --git a/entc/gen/template/meta.tmpl b/entc/gen/template/meta.tmpl index 8a6d8f2da..aa8fef887 100644 --- a/entc/gen/template/meta.tmpl +++ b/entc/gen/template/meta.tmpl @@ -98,8 +98,10 @@ const ( {{- if $.HasValueScanner }} // ValueScanner of all {{ $.Name }} fields. ValueScanner struct { - {{- range $f := $.Fields }} - {{- if $f.HasValueScanner }} + {{- $fields := $.Fields }}{{ if $.HasOneFieldID }}{{ if $.ID.UserDefined }}{{ $fields = append $fields $.ID }}{{ end }}{{ end }} + {{- range $f := $fields }} + {{- $idscan := and $.HasOneFieldID (eq $f.Name $.ID.Name) }} + {{- if and $f.HasValueScanner (or (not $idscan) (eq $.Storage.Name "sql")) }} {{ $f.StructField }} field.TypeValueScanner[{{ $f.Type }}] {{- end }} {{- end }} diff --git a/entc/gen/template/runtime.tmpl b/entc/gen/template/runtime.tmpl index 415cb6ddd..da84b3ac7 100644 --- a/entc/gen/template/runtime.tmpl +++ b/entc/gen/template/runtime.tmpl @@ -165,8 +165,9 @@ func init() { {{- end }} {{- range $i, $f := $fields }} {{- $desc := print $pkg "Desc" $f.StructField }} + {{- $idscan := and $n.HasOneFieldID (eq $f.Name $n.ID.Name) }} {{- /* enum default values handled near their declarations (in type package). */}} - {{- if or (and $f.Default (not $f.IsEnum)) $f.UpdateDefault $f.Validators $f.HasValueScanner }} + {{- if or (and $f.Default (not $f.IsEnum)) $f.UpdateDefault $f.Validators (and $f.HasValueScanner (or (not $idscan) (eq $n.Storage.Name "sql"))) }} // {{ $desc }} is the schema descriptor for {{ $f.Name }} field. {{- if $f.Position.MixedIn }} {{ $desc }} := {{ print $pkg "MixinFields" $f.Position.MixinIndex }}[{{ $f.Position.Index }}].Descriptor() @@ -193,7 +194,7 @@ func init() { // {{ $default }} holds the default value on update for the {{ $f.Name }} field. {{ $default }} = {{ $desc }}.UpdateDefault.(func() {{ $f.Type }}) {{- end }} - {{- with $f.HasValueScanner }} + {{- if and $f.HasValueScanner (or (not $idscan) (eq $n.Storage.Name "sql")) }} {{- $valuescan := print $pkg ".ValueScanner." $f.StructField }} {{ $valuescan }} = {{ $desc }}.ValueScanner.(field.TypeValueScanner[{{ $f.Type }}]) {{- end }} diff --git a/entc/gen/template/where.tmpl b/entc/gen/template/where.tmpl index 57280a8e3..866b60303 100644 --- a/entc/gen/template/where.tmpl +++ b/entc/gen/template/where.tmpl @@ -17,23 +17,65 @@ in the LICENSE file in the root directory of this source tree. {{ if .HasOneFieldID }} // ID filters vertices based on their ID field. func ID(id {{ $.ID.Type }}) predicate.{{ $.Name }} { - return predicate.{{ $.Name }}( - {{- $tmpl := printf "dialect/%s/predicate/id" $.Storage }} - {{- xtemplate $tmpl $ -}} - ) + {{- if and $.ID.HasValueScanner (eq $.Storage.Name "sql") }} + vc, err := ValueScanner.{{ $.ID.StructField }}.Value(id) + return predicate.{{ $.Name }}OrErr( + {{- with extend $ "Arg" "vc" -}} + {{- $tmpl := printf "dialect/%s/predicate/id" $.Storage }} + {{- xtemplate $tmpl . -}} + {{- end -}}, err) + {{- else }} + return predicate.{{ $.Name }}( + {{- with extend $ "Arg" "id" -}} + {{- $tmpl := printf "dialect/%s/predicate/id" $.Storage }} + {{- xtemplate $tmpl . -}} + {{- end -}} + ) + {{- end }} } {{ range $op := $.ID.Ops }} {{ $arg := "id" }}{{ if $op.Variadic }}{{ $arg = "ids" }}{{ end }} + {{ $stringOp := eq $op.Name "EqualFold" "Contains" "ContainsFold" "HasPrefix" "HasSuffix" }} {{ $func := printf "ID%s" $op.Name }} // {{ $func }} applies the {{ $op.Name }} predicate on the ID field. func {{ $func }}({{ $arg }} {{ if $op.Variadic }}...{{ end }}{{ $.ID.Type }}) predicate.{{ $.Name }} { - return predicate.{{ $.Name }}( - {{- with extend $ "Arg" $arg "Op" $op "Storage" $.Storage -}} - {{ $tmpl := printf "dialect/%s/predicate/id/ops" $.Storage }} - {{- xtemplate $tmpl . }} - {{- end -}} - ) + {{- if and (eq $.Storage.Name "sql") $.ID.HasValueScanner (or $op.Variadic (not $op.Niladic)) }} + {{- if $op.Variadic }} + var ( + err error + vcs = make([]any, len({{ $arg }})) + ) + for i := range vcs { + if vcs[i], err = ValueScanner.{{ $.ID.StructField }}.Value({{ print $arg "[i]" }}); err != nil { + break + } + } + {{- $arg = "vcs" }} + {{- else }} + vc, err := ValueScanner.{{ $.ID.StructField }}.Value({{ $arg }}) + {{- $arg = "vc" }} + {{- if $stringOp }} + {{- $arg = "vcs" }} + vcs, ok := vc.(string) + if err == nil && !ok { + err = fmt.Errorf("{{ $.ID.Name }} value is not a string: %T", vc) + } + {{- end }} + {{- end }} + return predicate.{{ $.Name }}OrErr( + {{- with extend $ "Arg" $arg "Op" $op "Storage" $.Storage -}} + {{ $tmpl := printf "dialect/%s/predicate/id/ops" $.Storage }} + {{- xtemplate $tmpl . }} + {{- end }}, err) + {{- else }} + return predicate.{{ $.Name }}( + {{- with extend $ "Arg" $arg "Op" $op "Storage" $.Storage -}} + {{ $tmpl := printf "dialect/%s/predicate/id/ops" $.Storage }} + {{- xtemplate $tmpl . }} + {{- end -}} + ) + {{- end }} } {{ end }} {{ end }} @@ -84,7 +126,7 @@ in the LICENSE file in the root directory of this source tree. {{- if $op.Variadic }} var ( err error - v = make([]any, len({{ $arg }})) + v = make([]any, len({{ $arg }})) ) for i := range v { if v[i], err = ValueScanner.{{ $f.StructField }}.Value({{ print $arg "[i]" }}); err != nil { diff --git a/entc/gen/type.go b/entc/gen/type.go index 252f0a629..62d8c877c 100644 --- a/entc/gen/type.go +++ b/entc/gen/type.go @@ -260,11 +260,8 @@ func NewType(c *Config, schema *load.Schema) (*Type, error) { } // User defined id field. if typ.ID != nil && tf.Name == typ.ID.Name { - switch { - case tf.Optional: + if tf.Optional { return nil, errors.New("id field cannot be optional") - case f.ValueScanner: - return nil, errors.New("id field cannot have an external ValueScanner") } typ.ID = tf } else { @@ -1427,6 +1424,10 @@ func (f Field) ScanType() string { // HasValueScanner reports if any of the fields has (an external) ValueScanner. func (t Type) HasValueScanner() bool { + sqlStorage := t.Config == nil || t.Storage == nil || t.Storage.Name == "sql" + if sqlStorage && t.ID != nil && t.ID.HasValueScanner() { + return true + } for _, f := range t.Fields { if f.HasValueScanner() { return true diff --git a/entc/gen/type_test.go b/entc/gen/type_test.go index 64f716e27..86aad6b70 100644 --- a/entc/gen/type_test.go +++ b/entc/gen/type_test.go @@ -90,6 +90,15 @@ func TestType(t *testing.T) { }) require.EqualError(err, "id field cannot be optional", "id field cannot be optional") + typ, err = NewType(&Config{Package: "entc/gen"}, &load.Schema{ + Name: "T", + Fields: []*load.Field{ + {Name: "id", Info: &field.TypeInfo{Type: field.TypeString}, ValueScanner: true}, + }, + }) + require.NoError(err) + require.True(typ.HasValueScanner()) + _, err = NewType(&Config{Package: "entc/gen"}, &load.Schema{Name: "Type"}) require.EqualError(err, "schema lowercase name conflicts with Go keyword \"type\"") _, err = NewType(&Config{Package: "entc/gen"}, &load.Schema{Name: "Int"}) diff --git a/entc/integration/customid/customid_test.go b/entc/integration/customid/customid_test.go index 87948b57d..dc54f07df 100644 --- a/entc/integration/customid/customid_test.go +++ b/entc/integration/customid/customid_test.go @@ -20,8 +20,10 @@ import ( "entgo.io/ent/entc/integration/customid/ent/doc" "entgo.io/ent/entc/integration/customid/ent/intsid" "entgo.io/ent/entc/integration/customid/ent/pet" + entschema "entgo.io/ent/entc/integration/customid/ent/schema" "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" + "entgo.io/ent/entc/integration/customid/ent/valuescan" "entgo.io/ent/entc/integration/customid/sid" "entgo.io/ent/schema/field" @@ -178,6 +180,39 @@ func CustomID(t *testing.T, client *ent.Client) { child := client.Note.Create().SetText("child").SetParent(parent).SaveX(ctx) require.NotEmpty(t, child.QueryParent().OnlyIDX(ctx)) + t.Run("ValueScanner ID", func(t *testing.T) { + id1 := entschema.ValueScanID{V: 10} + id2 := entschema.ValueScanID{V: 20} + id3 := entschema.ValueScanID{V: 30} + id4 := entschema.ValueScanID{V: 40} + + client.ValueScan.Create().SetID(id1).SetName("first").SaveX(ctx) + client.ValueScan.Create().SetID(id2).SetName("second").SaveX(ctx) + require.Equal(t, id1, client.ValueScan.GetX(ctx, id1).ID) + require.Equal(t, id2, client.ValueScan.Query().Where(valuescan.ID(id2)).OnlyX(ctx).ID) + require.True(t, client.ValueScan.Query().Where(valuescan.ID(id1)).ExistX(ctx)) + require.False(t, client.ValueScan.Query().Where(valuescan.ID(entschema.ValueScanID{V: 999})).ExistX(ctx)) + + client.ValueScan.CreateBulk( + client.ValueScan.Create().SetID(id3).SetName("third"), + client.ValueScan.Create().SetID(id4).SetName("fourth"), + ).SaveX(ctx) + require.ElementsMatch(t, []entschema.ValueScanID{id1, id2, id3, id4}, client.ValueScan.Query().IDsX(ctx)) + + client.ValueScan.UpdateOneID(id2).SetName("updated").ExecX(ctx) + require.Equal(t, "updated", client.ValueScan.GetX(ctx, id2).Name) + + var raw []struct { + ID int + } + client.ValueScan.Query(). + Where(valuescan.Name("updated")). + Select(valuescan.FieldID). + ScanX(ctx, &raw) + require.Len(t, raw, 1) + require.Equal(t, 20, raw[0].ID) + }) + pdoc := client.Doc.Create().SetText("parent").SaveX(ctx) require.NotEmpty(t, pdoc.ID) require.NotEmpty(t, pdoc.Text) diff --git a/entc/integration/customid/ent/client.go b/entc/integration/customid/ent/client.go index af08dc974..8e9a20b87 100644 --- a/entc/integration/customid/ent/client.go +++ b/entc/integration/customid/ent/client.go @@ -40,6 +40,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/session" "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" + "entgo.io/ent/entc/integration/customid/ent/valuescan" ) // Client is the client that holds all ent builders. @@ -81,6 +82,8 @@ type Client struct { Token *TokenClient // User is the client for interacting with the User builders. User *UserClient + // ValueScan is the client for interacting with the ValueScan builders. + ValueScan *ValueScanClient } // NewClient creates a new client configured with the given options. @@ -109,6 +112,7 @@ func (c *Client) init() { c.Session = NewSessionClient(c.config) c.Token = NewTokenClient(c.config) c.User = NewUserClient(c.config) + c.ValueScan = NewValueScanClient(c.config) } type ( @@ -199,25 +203,26 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { cfg := c.config cfg.driver = tx return &Tx{ - ctx: ctx, - config: cfg, - Account: NewAccountClient(cfg), - Blob: NewBlobClient(cfg), - BlobLink: NewBlobLinkClient(cfg), - Car: NewCarClient(cfg), - Device: NewDeviceClient(cfg), - Doc: NewDocClient(cfg), - Group: NewGroupClient(cfg), - IntSID: NewIntSIDClient(cfg), - Link: NewLinkClient(cfg), - MixinID: NewMixinIDClient(cfg), - Note: NewNoteClient(cfg), - Other: NewOtherClient(cfg), - Pet: NewPetClient(cfg), - Revision: NewRevisionClient(cfg), - Session: NewSessionClient(cfg), - Token: NewTokenClient(cfg), - User: NewUserClient(cfg), + ctx: ctx, + config: cfg, + Account: NewAccountClient(cfg), + Blob: NewBlobClient(cfg), + BlobLink: NewBlobLinkClient(cfg), + Car: NewCarClient(cfg), + Device: NewDeviceClient(cfg), + Doc: NewDocClient(cfg), + Group: NewGroupClient(cfg), + IntSID: NewIntSIDClient(cfg), + Link: NewLinkClient(cfg), + MixinID: NewMixinIDClient(cfg), + Note: NewNoteClient(cfg), + Other: NewOtherClient(cfg), + Pet: NewPetClient(cfg), + Revision: NewRevisionClient(cfg), + Session: NewSessionClient(cfg), + Token: NewTokenClient(cfg), + User: NewUserClient(cfg), + ValueScan: NewValueScanClient(cfg), }, nil } @@ -235,25 +240,26 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) cfg := c.config cfg.driver = &txDriver{tx: tx, drv: c.driver} return &Tx{ - ctx: ctx, - config: cfg, - Account: NewAccountClient(cfg), - Blob: NewBlobClient(cfg), - BlobLink: NewBlobLinkClient(cfg), - Car: NewCarClient(cfg), - Device: NewDeviceClient(cfg), - Doc: NewDocClient(cfg), - Group: NewGroupClient(cfg), - IntSID: NewIntSIDClient(cfg), - Link: NewLinkClient(cfg), - MixinID: NewMixinIDClient(cfg), - Note: NewNoteClient(cfg), - Other: NewOtherClient(cfg), - Pet: NewPetClient(cfg), - Revision: NewRevisionClient(cfg), - Session: NewSessionClient(cfg), - Token: NewTokenClient(cfg), - User: NewUserClient(cfg), + ctx: ctx, + config: cfg, + Account: NewAccountClient(cfg), + Blob: NewBlobClient(cfg), + BlobLink: NewBlobLinkClient(cfg), + Car: NewCarClient(cfg), + Device: NewDeviceClient(cfg), + Doc: NewDocClient(cfg), + Group: NewGroupClient(cfg), + IntSID: NewIntSIDClient(cfg), + Link: NewLinkClient(cfg), + MixinID: NewMixinIDClient(cfg), + Note: NewNoteClient(cfg), + Other: NewOtherClient(cfg), + Pet: NewPetClient(cfg), + Revision: NewRevisionClient(cfg), + Session: NewSessionClient(cfg), + Token: NewTokenClient(cfg), + User: NewUserClient(cfg), + ValueScan: NewValueScanClient(cfg), }, nil } @@ -285,7 +291,7 @@ func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ c.Account, c.Blob, c.BlobLink, c.Car, c.Device, c.Doc, c.Group, c.IntSID, c.Link, c.MixinID, c.Note, c.Other, c.Pet, c.Revision, c.Session, c.Token, - c.User, + c.User, c.ValueScan, } { n.Use(hooks...) } @@ -297,7 +303,7 @@ func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ c.Account, c.Blob, c.BlobLink, c.Car, c.Device, c.Doc, c.Group, c.IntSID, c.Link, c.MixinID, c.Note, c.Other, c.Pet, c.Revision, c.Session, c.Token, - c.User, + c.User, c.ValueScan, } { n.Intercept(interceptors...) } @@ -340,6 +346,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.Token.mutate(ctx, m) case *UserMutation: return c.User.mutate(ctx, m) + case *ValueScanMutation: + return c.ValueScan.mutate(ctx, m) default: return nil, fmt.Errorf("ent: unknown mutation type %T", m) } @@ -2989,14 +2997,147 @@ func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) } } +// ValueScanClient is a client for the ValueScan schema. +type ValueScanClient struct { + config +} + +// NewValueScanClient returns a client for the ValueScan from the given config. +func NewValueScanClient(c config) *ValueScanClient { + return &ValueScanClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `valuescan.Hooks(f(g(h())))`. +func (c *ValueScanClient) Use(hooks ...Hook) { + c.hooks.ValueScan = append(c.hooks.ValueScan, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `valuescan.Intercept(f(g(h())))`. +func (c *ValueScanClient) Intercept(interceptors ...Interceptor) { + c.inters.ValueScan = append(c.inters.ValueScan, interceptors...) +} + +// Create returns a builder for creating a ValueScan entity. +func (c *ValueScanClient) Create() *ValueScanCreate { + mutation := newValueScanMutation(c.config, OpCreate) + return &ValueScanCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ValueScan entities. +func (c *ValueScanClient) CreateBulk(builders ...*ValueScanCreate) *ValueScanCreateBulk { + return &ValueScanCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *ValueScanClient) MapCreateBulk(slice any, setFunc func(*ValueScanCreate, int)) *ValueScanCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ValueScanCreateBulk{err: fmt.Errorf("calling to ValueScanClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ValueScanCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ValueScanCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ValueScan. +func (c *ValueScanClient) Update() *ValueScanUpdate { + mutation := newValueScanMutation(c.config, OpUpdate) + return &ValueScanUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ValueScanClient) UpdateOne(_m *ValueScan) *ValueScanUpdateOne { + mutation := newValueScanMutation(c.config, OpUpdateOne, withValueScan(_m)) + return &ValueScanUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ValueScanClient) UpdateOneID(id schema.ValueScanID) *ValueScanUpdateOne { + mutation := newValueScanMutation(c.config, OpUpdateOne, withValueScanID(id)) + return &ValueScanUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ValueScan. +func (c *ValueScanClient) Delete() *ValueScanDelete { + mutation := newValueScanMutation(c.config, OpDelete) + return &ValueScanDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ValueScanClient) DeleteOne(_m *ValueScan) *ValueScanDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ValueScanClient) DeleteOneID(id schema.ValueScanID) *ValueScanDeleteOne { + builder := c.Delete().Where(valuescan.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ValueScanDeleteOne{builder} +} + +// Query returns a query builder for ValueScan. +func (c *ValueScanClient) Query() *ValueScanQuery { + return &ValueScanQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeValueScan}, + inters: c.Interceptors(), + } +} + +// Get returns a ValueScan entity by its id. +func (c *ValueScanClient) Get(ctx context.Context, id schema.ValueScanID) (*ValueScan, error) { + return c.Query().Where(valuescan.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ValueScanClient) GetX(ctx context.Context, id schema.ValueScanID) *ValueScan { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *ValueScanClient) Hooks() []Hook { + return c.hooks.ValueScan +} + +// Interceptors returns the client interceptors. +func (c *ValueScanClient) Interceptors() []Interceptor { + return c.inters.ValueScan +} + +func (c *ValueScanClient) mutate(ctx context.Context, m *ValueScanMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ValueScanCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ValueScanUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ValueScanUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ValueScanDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown ValueScan mutation op: %q", m.Op()) + } +} + // hooks and interceptors per client, for fast access. type ( hooks struct { Account, Blob, BlobLink, Car, Device, Doc, Group, IntSID, Link, MixinID, Note, - Other, Pet, Revision, Session, Token, User []ent.Hook + Other, Pet, Revision, Session, Token, User, ValueScan []ent.Hook } inters struct { Account, Blob, BlobLink, Car, Device, Doc, Group, IntSID, Link, MixinID, Note, - Other, Pet, Revision, Session, Token, User []ent.Interceptor + Other, Pet, Revision, Session, Token, User, ValueScan []ent.Interceptor } ) diff --git a/entc/integration/customid/ent/ent.go b/entc/integration/customid/ent/ent.go index 5b78de3e8..ef3e7d806 100644 --- a/entc/integration/customid/ent/ent.go +++ b/entc/integration/customid/ent/ent.go @@ -33,6 +33,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/session" "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" + "entgo.io/ent/entc/integration/customid/ent/valuescan" ) // ent aliases to avoid import conflicts in user's code. @@ -93,23 +94,24 @@ var ( func checkColumn(t, c string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ - account.Table: account.ValidColumn, - blob.Table: blob.ValidColumn, - bloblink.Table: bloblink.ValidColumn, - car.Table: car.ValidColumn, - device.Table: device.ValidColumn, - doc.Table: doc.ValidColumn, - group.Table: group.ValidColumn, - intsid.Table: intsid.ValidColumn, - link.Table: link.ValidColumn, - mixinid.Table: mixinid.ValidColumn, - note.Table: note.ValidColumn, - other.Table: other.ValidColumn, - pet.Table: pet.ValidColumn, - revision.Table: revision.ValidColumn, - session.Table: session.ValidColumn, - token.Table: token.ValidColumn, - user.Table: user.ValidColumn, + account.Table: account.ValidColumn, + blob.Table: blob.ValidColumn, + bloblink.Table: bloblink.ValidColumn, + car.Table: car.ValidColumn, + device.Table: device.ValidColumn, + doc.Table: doc.ValidColumn, + group.Table: group.ValidColumn, + intsid.Table: intsid.ValidColumn, + link.Table: link.ValidColumn, + mixinid.Table: mixinid.ValidColumn, + note.Table: note.ValidColumn, + other.Table: other.ValidColumn, + pet.Table: pet.ValidColumn, + revision.Table: revision.ValidColumn, + session.Table: session.ValidColumn, + token.Table: token.ValidColumn, + user.Table: user.ValidColumn, + valuescan.Table: valuescan.ValidColumn, }) }) return columnCheck(t, c) diff --git a/entc/integration/customid/ent/entql.go b/entc/integration/customid/ent/entql.go index 24a5e431d..7cd406c45 100644 --- a/entc/integration/customid/ent/entql.go +++ b/entc/integration/customid/ent/entql.go @@ -25,6 +25,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/session" "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" + "entgo.io/ent/entc/integration/customid/ent/valuescan" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" @@ -34,7 +35,7 @@ import ( // schemaGraph holds a representation of ent/schema at runtime. var schemaGraph = func() *sqlgraph.Schema { - graph := &sqlgraph.Schema{Nodes: make([]*sqlgraph.Node, 17)} + graph := &sqlgraph.Schema{Nodes: make([]*sqlgraph.Node, 18)} graph.Nodes[0] = &sqlgraph.Node{ NodeSpec: sqlgraph.NodeSpec{ Table: account.Table, @@ -269,6 +270,20 @@ var schemaGraph = func() *sqlgraph.Schema { Type: "User", Fields: map[string]*sqlgraph.FieldSpec{}, } + graph.Nodes[17] = &sqlgraph.Node{ + NodeSpec: sqlgraph.NodeSpec{ + Table: valuescan.Table, + Columns: valuescan.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: valuescan.FieldID, + }, + }, + Type: "ValueScan", + Fields: map[string]*sqlgraph.FieldSpec{ + valuescan.FieldName: {Type: field.TypeString, Column: valuescan.FieldName}, + }, + } graph.MustAddE( "token", &sqlgraph.EdgeSpec{ @@ -1729,3 +1744,48 @@ func (f *UserFilter) WhereHasPetsWith(preds ...predicate.Pet) { } }))) } + +// addPredicate implements the predicateAdder interface. +func (_q *ValueScanQuery) addPredicate(pred func(s *sql.Selector)) { + _q.predicates = append(_q.predicates, pred) +} + +// Filter returns a Filter implementation to apply filters on the ValueScanQuery builder. +func (_q *ValueScanQuery) Filter() *ValueScanFilter { + return &ValueScanFilter{config: _q.config, predicateAdder: _q} +} + +// addPredicate implements the predicateAdder interface. +func (m *ValueScanMutation) addPredicate(pred func(s *sql.Selector)) { + m.predicates = append(m.predicates, pred) +} + +// Filter returns an entql.Where implementation to apply filters on the ValueScanMutation builder. +func (m *ValueScanMutation) Filter() *ValueScanFilter { + return &ValueScanFilter{config: m.config, predicateAdder: m} +} + +// ValueScanFilter provides a generic filtering capability at runtime for ValueScanQuery. +type ValueScanFilter struct { + predicateAdder + config +} + +// Where applies the entql predicate on the query filter. +func (f *ValueScanFilter) Where(p entql.P) { + f.addPredicate(func(s *sql.Selector) { + if err := schemaGraph.EvalP(schemaGraph.Nodes[17].Type, p, s); err != nil { + s.AddError(err) + } + }) +} + +// WhereID applies the entql int predicate on the id field. +func (f *ValueScanFilter) WhereID(p entql.IntP) { + f.Where(p.Field(valuescan.FieldID)) +} + +// WhereName applies the entql string predicate on the name field. +func (f *ValueScanFilter) WhereName(p entql.StringP) { + f.Where(p.Field(valuescan.FieldName)) +} diff --git a/entc/integration/customid/ent/hook/hook.go b/entc/integration/customid/ent/hook/hook.go index 82deb730c..e2f2d38d8 100644 --- a/entc/integration/customid/ent/hook/hook.go +++ b/entc/integration/customid/ent/hook/hook.go @@ -217,6 +217,18 @@ func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m) } +// The ValueScanFunc type is an adapter to allow the use of ordinary +// function as ValueScan mutator. +type ValueScanFunc func(context.Context, *ent.ValueScanMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f ValueScanFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.ValueScanMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ValueScanMutation", m) +} + // Condition is a hook condition function. type Condition func(context.Context, ent.Mutation) bool diff --git a/entc/integration/customid/ent/migrate/schema.go b/entc/integration/customid/ent/migrate/schema.go index b57433148..4ba438387 100644 --- a/entc/integration/customid/ent/migrate/schema.go +++ b/entc/integration/customid/ent/migrate/schema.go @@ -329,6 +329,17 @@ var ( }, }, } + // ValueScansColumns holds the columns for the "value_scans" table. + ValueScansColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString}, + } + // ValueScansTable holds the schema information for the "value_scans" table. + ValueScansTable = &schema.Table{ + Name: "value_scans", + Columns: ValueScansColumns, + PrimaryKey: []*schema.Column{ValueScansColumns[0]}, + } // DocRelatedColumns holds the columns for the "doc_related" table. DocRelatedColumns = []*schema.Column{ {Name: "doc_id", Type: field.TypeString, Size: 36, SchemaType: map[string]string{"postgres": "uuid"}}, @@ -423,6 +434,7 @@ var ( SessionsTable, TokensTable, UsersTable, + ValueScansTable, DocRelatedTable, GroupUsersTable, PetFriendsTable, diff --git a/entc/integration/customid/ent/mutation.go b/entc/integration/customid/ent/mutation.go index c7c89b649..be2d7c995 100644 --- a/entc/integration/customid/ent/mutation.go +++ b/entc/integration/customid/ent/mutation.go @@ -32,6 +32,7 @@ import ( "entgo.io/ent/entc/integration/customid/ent/session" "entgo.io/ent/entc/integration/customid/ent/token" "entgo.io/ent/entc/integration/customid/ent/user" + "entgo.io/ent/entc/integration/customid/ent/valuescan" "entgo.io/ent/entc/integration/customid/sid" uuidc "entgo.io/ent/entc/integration/customid/uuidcompatible" "github.com/google/uuid" @@ -46,23 +47,24 @@ const ( OpUpdateOne = ent.OpUpdateOne // Node types. - TypeAccount = "Account" - TypeBlob = "Blob" - TypeBlobLink = "BlobLink" - TypeCar = "Car" - TypeDevice = "Device" - TypeDoc = "Doc" - TypeGroup = "Group" - TypeIntSID = "IntSID" - TypeLink = "Link" - TypeMixinID = "MixinID" - TypeNote = "Note" - TypeOther = "Other" - TypePet = "Pet" - TypeRevision = "Revision" - TypeSession = "Session" - TypeToken = "Token" - TypeUser = "User" + TypeAccount = "Account" + TypeBlob = "Blob" + TypeBlobLink = "BlobLink" + TypeCar = "Car" + TypeDevice = "Device" + TypeDoc = "Doc" + TypeGroup = "Group" + TypeIntSID = "IntSID" + TypeLink = "Link" + TypeMixinID = "MixinID" + TypeNote = "Note" + TypeOther = "Other" + TypePet = "Pet" + TypeRevision = "Revision" + TypeSession = "Session" + TypeToken = "Token" + TypeUser = "User" + TypeValueScan = "ValueScan" ) // AccountMutation represents an operation that mutates the Account nodes in the graph. @@ -7544,3 +7546,335 @@ func (m *UserMutation) ResetEdge(name string) error { } return fmt.Errorf("unknown User edge %s", name) } + +// ValueScanMutation represents an operation that mutates the ValueScan nodes in the graph. +type ValueScanMutation struct { + config + op Op + typ string + id *schema.ValueScanID + name *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*ValueScan, error) + predicates []predicate.ValueScan +} + +var _ ent.Mutation = (*ValueScanMutation)(nil) + +// valuescanOption allows management of the mutation configuration using functional options. +type valuescanOption func(*ValueScanMutation) + +// newValueScanMutation creates new mutation for the ValueScan entity. +func newValueScanMutation(c config, op Op, opts ...valuescanOption) *ValueScanMutation { + m := &ValueScanMutation{ + config: c, + op: op, + typ: TypeValueScan, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withValueScanID sets the ID field of the mutation. +func withValueScanID(id schema.ValueScanID) valuescanOption { + return func(m *ValueScanMutation) { + var ( + err error + once sync.Once + value *ValueScan + ) + m.oldValue = func(ctx context.Context) (*ValueScan, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().ValueScan.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withValueScan sets the old ValueScan of the mutation. +func withValueScan(node *ValueScan) valuescanOption { + return func(m *ValueScanMutation) { + m.oldValue = func(context.Context) (*ValueScan, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m ValueScanMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m ValueScanMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of ValueScan entities. +func (m *ValueScanMutation) SetID(id schema.ValueScanID) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *ValueScanMutation) ID() (id schema.ValueScanID, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *ValueScanMutation) IDs(ctx context.Context) ([]schema.ValueScanID, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []schema.ValueScanID{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().ValueScan.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *ValueScanMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *ValueScanMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the ValueScan entity. +// If the ValueScan object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ValueScanMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *ValueScanMutation) ResetName() { + m.name = nil +} + +// Where appends a list predicates to the ValueScanMutation builder. +func (m *ValueScanMutation) Where(ps ...predicate.ValueScan) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ValueScanMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ValueScanMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ValueScan, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ValueScanMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ValueScanMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ValueScan). +func (m *ValueScanMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *ValueScanMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.name != nil { + fields = append(fields, valuescan.FieldName) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *ValueScanMutation) Field(name string) (ent.Value, bool) { + switch name { + case valuescan.FieldName: + return m.Name() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *ValueScanMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case valuescan.FieldName: + return m.OldName(ctx) + } + return nil, fmt.Errorf("unknown ValueScan field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ValueScanMutation) SetField(name string, value ent.Value) error { + switch name { + case valuescan.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + } + return fmt.Errorf("unknown ValueScan field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ValueScanMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *ValueScanMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ValueScanMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ValueScan numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ValueScanMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ValueScanMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *ValueScanMutation) ClearField(name string) error { + return fmt.Errorf("unknown ValueScan nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *ValueScanMutation) ResetField(name string) error { + switch name { + case valuescan.FieldName: + m.ResetName() + return nil + } + return fmt.Errorf("unknown ValueScan field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ValueScanMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ValueScanMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ValueScanMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ValueScanMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ValueScanMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ValueScanMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *ValueScanMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown ValueScan unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *ValueScanMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown ValueScan edge %s", name) +} diff --git a/entc/integration/customid/ent/predicate/predicate.go b/entc/integration/customid/ent/predicate/predicate.go index f9838988f..eaa4a8b68 100644 --- a/entc/integration/customid/ent/predicate/predicate.go +++ b/entc/integration/customid/ent/predicate/predicate.go @@ -60,3 +60,17 @@ type Token func(*sql.Selector) // User is the predicate function for user builders. type User func(*sql.Selector) + +// ValueScan is the predicate function for valuescan builders. +type ValueScan func(*sql.Selector) + +// ValueScanOrErr calls the predicate only if the error is not nit. +func ValueScanOrErr(p ValueScan, err error) ValueScan { + return func(s *sql.Selector) { + if err != nil { + s.AddError(err) + return + } + p(s) + } +} diff --git a/entc/integration/customid/ent/privacy/privacy.go b/entc/integration/customid/ent/privacy/privacy.go index 36fb86743..0d026e1b9 100644 --- a/entc/integration/customid/ent/privacy/privacy.go +++ b/entc/integration/customid/ent/privacy/privacy.go @@ -523,6 +523,30 @@ func (f UserMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.UserMutation", m) } +// The ValueScanQueryRuleFunc type is an adapter to allow the use of ordinary +// functions as a query rule. +type ValueScanQueryRuleFunc func(context.Context, *ent.ValueScanQuery) error + +// EvalQuery return f(ctx, q). +func (f ValueScanQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.ValueScanQuery); ok { + return f(ctx, q) + } + return Denyf("ent/privacy: unexpected query type %T, expect *ent.ValueScanQuery", q) +} + +// The ValueScanMutationRuleFunc type is an adapter to allow the use of ordinary +// functions as a mutation rule. +type ValueScanMutationRuleFunc func(context.Context, *ent.ValueScanMutation) error + +// EvalMutation calls f(ctx, m). +func (f ValueScanMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { + if m, ok := m.(*ent.ValueScanMutation); ok { + return f(ctx, m) + } + return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.ValueScanMutation", m) +} + type ( // Filter is the interface that wraps the Where function // for filtering nodes in queries and mutations. @@ -592,6 +616,8 @@ func queryFilter(q ent.Query) (Filter, error) { return q.Filter(), nil case *ent.UserQuery: return q.Filter(), nil + case *ent.ValueScanQuery: + return q.Filter(), nil default: return nil, Denyf("ent/privacy: unexpected query type %T for query filter", q) } @@ -633,6 +659,8 @@ func mutationFilter(m ent.Mutation) (Filter, error) { return m.Filter(), nil case *ent.UserMutation: return m.Filter(), nil + case *ent.ValueScanMutation: + return m.Filter(), nil default: return nil, Denyf("ent/privacy: unexpected mutation type %T for mutation filter", m) } diff --git a/entc/integration/customid/ent/runtime.go b/entc/integration/customid/ent/runtime.go index 7fa4a3427..23e7118c6 100644 --- a/entc/integration/customid/ent/runtime.go +++ b/entc/integration/customid/ent/runtime.go @@ -23,9 +23,12 @@ import ( "entgo.io/ent/entc/integration/customid/ent/schema" "entgo.io/ent/entc/integration/customid/ent/session" "entgo.io/ent/entc/integration/customid/ent/token" + "entgo.io/ent/entc/integration/customid/ent/valuescan" "entgo.io/ent/entc/integration/customid/sid" uuidc "entgo.io/ent/entc/integration/customid/uuidcompatible" "github.com/google/uuid" + + "entgo.io/ent/schema/field" ) // The init function reads all schema descriptors with runtime code @@ -196,4 +199,9 @@ func init() { tokenDescID := tokenFields[0].Descriptor() // token.DefaultID holds the default value on creation for the id field. token.DefaultID = tokenDescID.Default.(func() sid.ID) + valuescanFields := schema.ValueScan{}.Fields() + _ = valuescanFields + // valuescanDescID is the schema descriptor for id field. + valuescanDescID := valuescanFields[0].Descriptor() + valuescan.ValueScanner.ID = valuescanDescID.ValueScanner.(field.TypeValueScanner[schema.ValueScanID]) } diff --git a/entc/integration/customid/ent/schema/valuescan.go b/entc/integration/customid/ent/schema/valuescan.go new file mode 100644 index 000000000..53881c161 --- /dev/null +++ b/entc/integration/customid/ent/schema/valuescan.go @@ -0,0 +1,43 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +package schema + +import ( + "database/sql" + "database/sql/driver" + + "entgo.io/ent" + "entgo.io/ent/schema/field" +) + +// ValueScan holds the schema definition for the ValueScan entity. +type ValueScan struct { + ent.Schema +} + +// ValueScanID is a custom ID type that relies on an external ValueScanner. +type ValueScanID struct { + V int +} + +// Fields of the ValueScan. +func (ValueScan) Fields() []ent.Field { + return []ent.Field{ + field.Int("id"). + GoType(ValueScanID{}). + ValueScanner(field.ValueScannerFunc[ValueScanID, *sql.NullInt64]{ + V: func(id ValueScanID) (driver.Value, error) { + return int64(id.V), nil + }, + S: func(id *sql.NullInt64) (ValueScanID, error) { + if !id.Valid { + return ValueScanID{}, nil + } + return ValueScanID{V: int(id.Int64)}, nil + }, + }), + field.String("name"), + } +} diff --git a/entc/integration/customid/ent/tx.go b/entc/integration/customid/ent/tx.go index 35ad15cc2..026a096d7 100644 --- a/entc/integration/customid/ent/tx.go +++ b/entc/integration/customid/ent/tx.go @@ -50,6 +50,8 @@ type Tx struct { Token *TokenClient // User is the client for interacting with the User builders. User *UserClient + // ValueScan is the client for interacting with the ValueScan builders. + ValueScan *ValueScanClient // lazily loaded. client *Client @@ -198,6 +200,7 @@ func (tx *Tx) init() { tx.Session = NewSessionClient(tx.config) tx.Token = NewTokenClient(tx.config) tx.User = NewUserClient(tx.config) + tx.ValueScan = NewValueScanClient(tx.config) } // txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. diff --git a/entc/integration/customid/ent/valuescan.go b/entc/integration/customid/ent/valuescan.go new file mode 100644 index 000000000..0bf8e741e --- /dev/null +++ b/entc/integration/customid/ent/valuescan.go @@ -0,0 +1,108 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/customid/ent/schema" + "entgo.io/ent/entc/integration/customid/ent/valuescan" +) + +// ValueScan is the model entity for the ValueScan schema. +type ValueScan struct { + config `json:"-"` + // ID of the ent. + ID schema.ValueScanID `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ValueScan) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case valuescan.FieldID: + values[i] = valuescan.ValueScanner.ID.ScanValue() + case valuescan.FieldName: + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the ValueScan fields. +func (_m *ValueScan) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case valuescan.FieldID: + if value, err := valuescan.ValueScanner.ID.FromValue(values[i]); err != nil { + return err + } else { + _m.ID = value + } + case valuescan.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ValueScan. +// This includes values selected through modifiers, order, etc. +func (_m *ValueScan) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this ValueScan. +// Note that you need to call ValueScan.Unwrap() before calling this method if this ValueScan +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ValueScan) Update() *ValueScanUpdateOne { + return NewValueScanClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ValueScan entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *ValueScan) Unwrap() *ValueScan { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: ValueScan is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ValueScan) String() string { + var builder strings.Builder + builder.WriteString("ValueScan(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteByte(')') + return builder.String() +} + +// ValueScans is a parsable slice of ValueScan. +type ValueScans []*ValueScan diff --git a/entc/integration/customid/ent/valuescan/valuescan.go b/entc/integration/customid/ent/valuescan/valuescan.go new file mode 100644 index 000000000..353c88196 --- /dev/null +++ b/entc/integration/customid/ent/valuescan/valuescan.go @@ -0,0 +1,60 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package valuescan + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/customid/ent/schema" + "entgo.io/ent/schema/field" +) + +const ( + // Label holds the string label denoting the valuescan type in the database. + Label = "value_scan" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // Table holds the table name of the valuescan in the database. + Table = "value_scans" +) + +// Columns holds all SQL columns for valuescan fields. +var Columns = []string{ + FieldID, + FieldName, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // ValueScanner of all ValueScan fields. + ValueScanner struct { + ID field.TypeValueScanner[schema.ValueScanID] + } +) + +// OrderOption defines the ordering options for the ValueScan queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} diff --git a/entc/integration/customid/ent/valuescan/where.go b/entc/integration/customid/ent/valuescan/where.go new file mode 100644 index 000000000..31508a216 --- /dev/null +++ b/entc/integration/customid/ent/valuescan/where.go @@ -0,0 +1,104 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package valuescan + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/ent/schema" +) + +// ID filters vertices based on their ID field. +func ID(id schema.ValueScanID) predicate.ValueScan { + vc, err := ValueScanner.ID.Value(id) + return predicate.ValueScanOrErr(sql.FieldEQ(FieldID, vc), err) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldEQ(FieldName, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.ValueScan { + return predicate.ValueScan(sql.FieldContainsFold(FieldName, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.ValueScan) predicate.ValueScan { + return predicate.ValueScan(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ValueScan) predicate.ValueScan { + return predicate.ValueScan(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ValueScan) predicate.ValueScan { + return predicate.ValueScan(sql.NotPredicates(p)) +} diff --git a/entc/integration/customid/ent/valuescan_create.go b/entc/integration/customid/ent/valuescan_create.go new file mode 100644 index 000000000..f1509cdb2 --- /dev/null +++ b/entc/integration/customid/ent/valuescan_create.go @@ -0,0 +1,519 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/schema" + "entgo.io/ent/entc/integration/customid/ent/valuescan" + "entgo.io/ent/schema/field" +) + +// ValueScanCreate is the builder for creating a ValueScan entity. +type ValueScanCreate struct { + config + mutation *ValueScanMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetName sets the "name" field. +func (_c *ValueScanCreate) SetName(v string) *ValueScanCreate { + _c.mutation.SetName(v) + return _c +} + +// SetID sets the "id" field. +func (_c *ValueScanCreate) SetID(v schema.ValueScanID) *ValueScanCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the ValueScanMutation object of the builder. +func (_c *ValueScanCreate) Mutation() *ValueScanMutation { + return _c.mutation +} + +// Save creates the ValueScan in the database. +func (_c *ValueScanCreate) Save(ctx context.Context) (*ValueScan, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ValueScanCreate) SaveX(ctx context.Context) *ValueScan { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ValueScanCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ValueScanCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ValueScanCreate) check() error { + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "ValueScan.name"`)} + } + return nil +} + +func (_c *ValueScanCreate) sqlSave(ctx context.Context) (*ValueScan, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec, err := _c.createSpec() + if err != nil { + return nil, err + } + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + sv, ok := _spec.ID.Value.(field.ValueScanner) + if !ok { + sv = valuescan.ValueScanner.ID.ScanValue() + if err := sv.Scan(_spec.ID.Value); err != nil { + return nil, err + } + } + if value, err := valuescan.ValueScanner.ID.FromValue(sv); err != nil { + return nil, err + } else { + _node.ID = value + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *ValueScanCreate) createSpec() (*ValueScan, *sqlgraph.CreateSpec, error) { + var ( + _node = &ValueScan{config: _c.config} + _spec = sqlgraph.NewCreateSpec(valuescan.Table, sqlgraph.NewFieldSpec(valuescan.FieldID, field.TypeInt)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + vv, err := valuescan.ValueScanner.ID.Value(id) + if err != nil { + return nil, nil, err + } + _spec.ID.Value = vv + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(valuescan.FieldName, field.TypeString, value) + _node.Name = value + } + return _node, _spec, nil +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ValueScan.Create(). +// SetName(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ValueScanUpsert) { +// SetName(v+v). +// }). +// Exec(ctx) +func (_c *ValueScanCreate) OnConflict(opts ...sql.ConflictOption) *ValueScanUpsertOne { + _c.conflict = opts + return &ValueScanUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ValueScan.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ValueScanCreate) OnConflictColumns(columns ...string) *ValueScanUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ValueScanUpsertOne{ + create: _c, + } +} + +type ( + // ValueScanUpsertOne is the builder for "upsert"-ing + // one ValueScan node. + ValueScanUpsertOne struct { + create *ValueScanCreate + } + + // ValueScanUpsert is the "OnConflict" setter. + ValueScanUpsert struct { + *sql.UpdateSet + } +) + +// SetName sets the "name" field. +func (u *ValueScanUpsert) SetName(v string) *ValueScanUpsert { + u.Set(valuescan.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ValueScanUpsert) UpdateName() *ValueScanUpsert { + u.SetExcluded(valuescan.FieldName) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.ValueScan.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(valuescan.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ValueScanUpsertOne) UpdateNewValues() *ValueScanUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(valuescan.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ValueScan.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ValueScanUpsertOne) Ignore() *ValueScanUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ValueScanUpsertOne) DoNothing() *ValueScanUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ValueScanCreate.OnConflict +// documentation for more info. +func (u *ValueScanUpsertOne) Update(set func(*ValueScanUpsert)) *ValueScanUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ValueScanUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *ValueScanUpsertOne) SetName(v string) *ValueScanUpsertOne { + return u.Update(func(s *ValueScanUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ValueScanUpsertOne) UpdateName() *ValueScanUpsertOne { + return u.Update(func(s *ValueScanUpsert) { + s.UpdateName() + }) +} + +// Exec executes the query. +func (u *ValueScanUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for ValueScanCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ValueScanUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *ValueScanUpsertOne) ID(ctx context.Context) (id schema.ValueScanID, err error) { + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *ValueScanUpsertOne) IDX(ctx context.Context) schema.ValueScanID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// ValueScanCreateBulk is the builder for creating many ValueScan entities in bulk. +type ValueScanCreateBulk struct { + config + err error + builders []*ValueScanCreate + conflict []sql.ConflictOption +} + +// Save creates the ValueScan entities in the database. +func (_c *ValueScanCreateBulk) Save(ctx context.Context) ([]*ValueScan, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ValueScan, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ValueScanMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i], err = builder.createSpec() + if err != nil { + return nil, err + } + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + sv, ok := specs[i].ID.Value.(field.ValueScanner) + if !ok { + sv = valuescan.ValueScanner.ID.ScanValue() + if err := sv.Scan(specs[i].ID.Value); err != nil { + return nil, err + } + } + if id, err := valuescan.ValueScanner.ID.FromValue(sv); err != nil { + return nil, err + } else { + nodes[i].ID = id + } + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *ValueScanCreateBulk) SaveX(ctx context.Context) []*ValueScan { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ValueScanCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ValueScanCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ValueScan.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.ValueScanUpsert) { +// SetName(v+v). +// }). +// Exec(ctx) +func (_c *ValueScanCreateBulk) OnConflict(opts ...sql.ConflictOption) *ValueScanUpsertBulk { + _c.conflict = opts + return &ValueScanUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ValueScan.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ValueScanCreateBulk) OnConflictColumns(columns ...string) *ValueScanUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ValueScanUpsertBulk{ + create: _c, + } +} + +// ValueScanUpsertBulk is the builder for "upsert"-ing +// a bulk of ValueScan nodes. +type ValueScanUpsertBulk struct { + create *ValueScanCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ValueScan.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(valuescan.FieldID) +// }), +// ). +// Exec(ctx) +func (u *ValueScanUpsertBulk) UpdateNewValues() *ValueScanUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(valuescan.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ValueScan.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ValueScanUpsertBulk) Ignore() *ValueScanUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *ValueScanUpsertBulk) DoNothing() *ValueScanUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ValueScanCreateBulk.OnConflict +// documentation for more info. +func (u *ValueScanUpsertBulk) Update(set func(*ValueScanUpsert)) *ValueScanUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ValueScanUpsert{UpdateSet: update}) + })) + return u +} + +// SetName sets the "name" field. +func (u *ValueScanUpsertBulk) SetName(v string) *ValueScanUpsertBulk { + return u.Update(func(s *ValueScanUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *ValueScanUpsertBulk) UpdateName() *ValueScanUpsertBulk { + return u.Update(func(s *ValueScanUpsert) { + s.UpdateName() + }) +} + +// Exec executes the query. +func (u *ValueScanUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the ValueScanCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for ValueScanCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ValueScanUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/customid/ent/valuescan_delete.go b/entc/integration/customid/ent/valuescan_delete.go new file mode 100644 index 000000000..d908558a6 --- /dev/null +++ b/entc/integration/customid/ent/valuescan_delete.go @@ -0,0 +1,92 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/ent/valuescan" + "entgo.io/ent/schema/field" +) + +// ValueScanDelete is the builder for deleting a ValueScan entity. +type ValueScanDelete struct { + config + hooks []Hook + mutation *ValueScanMutation +} + +// Where appends a list predicates to the ValueScanDelete builder. +func (_d *ValueScanDelete) Where(ps ...predicate.ValueScan) *ValueScanDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ValueScanDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ValueScanDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ValueScanDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(valuescan.Table, sqlgraph.NewFieldSpec(valuescan.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// ValueScanDeleteOne is the builder for deleting a single ValueScan entity. +type ValueScanDeleteOne struct { + _d *ValueScanDelete +} + +// Where appends a list predicates to the ValueScanDelete builder. +func (_d *ValueScanDeleteOne) Where(ps ...predicate.ValueScan) *ValueScanDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ValueScanDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{valuescan.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ValueScanDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entc/integration/customid/ent/valuescan_query.go b/entc/integration/customid/ent/valuescan_query.go new file mode 100644 index 000000000..819011934 --- /dev/null +++ b/entc/integration/customid/ent/valuescan_query.go @@ -0,0 +1,537 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/ent/schema" + "entgo.io/ent/entc/integration/customid/ent/valuescan" + "entgo.io/ent/schema/field" +) + +// ValueScanQuery is the builder for querying ValueScan entities. +type ValueScanQuery struct { + config + ctx *QueryContext + order []valuescan.OrderOption + inters []Interceptor + predicates []predicate.ValueScan + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ValueScanQuery builder. +func (_q *ValueScanQuery) Where(ps ...predicate.ValueScan) *ValueScanQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ValueScanQuery) Limit(limit int) *ValueScanQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ValueScanQuery) Offset(offset int) *ValueScanQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *ValueScanQuery) Unique(unique bool) *ValueScanQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ValueScanQuery) Order(o ...valuescan.OrderOption) *ValueScanQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first ValueScan entity from the query. +// Returns a *NotFoundError when no ValueScan was found. +func (_q *ValueScanQuery) First(ctx context.Context) (*ValueScan, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{valuescan.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ValueScanQuery) FirstX(ctx context.Context) *ValueScan { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first ValueScan ID from the query. +// Returns a *NotFoundError when no ValueScan ID was found. +func (_q *ValueScanQuery) FirstID(ctx context.Context) (id schema.ValueScanID, err error) { + var ids []schema.ValueScanID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{valuescan.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *ValueScanQuery) FirstIDX(ctx context.Context) schema.ValueScanID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single ValueScan entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ValueScan entity is found. +// Returns a *NotFoundError when no ValueScan entities are found. +func (_q *ValueScanQuery) Only(ctx context.Context) (*ValueScan, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{valuescan.Label} + default: + return nil, &NotSingularError{valuescan.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ValueScanQuery) OnlyX(ctx context.Context) *ValueScan { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only ValueScan ID in the query. +// Returns a *NotSingularError when more than one ValueScan ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *ValueScanQuery) OnlyID(ctx context.Context) (id schema.ValueScanID, err error) { + var ids []schema.ValueScanID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{valuescan.Label} + default: + err = &NotSingularError{valuescan.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *ValueScanQuery) OnlyIDX(ctx context.Context) schema.ValueScanID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of ValueScans. +func (_q *ValueScanQuery) All(ctx context.Context) ([]*ValueScan, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ValueScan, *ValueScanQuery]() + return withInterceptors[[]*ValueScan](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ValueScanQuery) AllX(ctx context.Context) []*ValueScan { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of ValueScan IDs. +func (_q *ValueScanQuery) IDs(ctx context.Context) (ids []schema.ValueScanID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + var nodes []*ValueScan + if nodes, err = _q.Select(valuescan.FieldID).All(ctx); err != nil { + return nil, err + } + ids = make([]schema.ValueScanID, len(nodes)) + for i := range nodes { + ids[i] = nodes[i].ID + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *ValueScanQuery) IDsX(ctx context.Context) []schema.ValueScanID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *ValueScanQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*ValueScanQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ValueScanQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *ValueScanQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *ValueScanQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ValueScanQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *ValueScanQuery) Clone() *ValueScanQuery { + if _q == nil { + return nil + } + return &ValueScanQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]valuescan.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ValueScan{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ValueScan.Query(). +// GroupBy(valuescan.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *ValueScanQuery) GroupBy(field string, fields ...string) *ValueScanGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ValueScanGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = valuescan.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.ValueScan.Query(). +// Select(valuescan.FieldName). +// Scan(ctx, &v) +func (_q *ValueScanQuery) Select(fields ...string) *ValueScanSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ValueScanSelect{ValueScanQuery: _q} + sbuild.label = valuescan.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ValueScanSelect configured with the given aggregations. +func (_q *ValueScanQuery) Aggregate(fns ...AggregateFunc) *ValueScanSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ValueScanQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !valuescan.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *ValueScanQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ValueScan, error) { + var ( + nodes = []*ValueScan{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ValueScan).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ValueScan{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *ValueScanQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *ValueScanQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(valuescan.Table, valuescan.Columns, sqlgraph.NewFieldSpec(valuescan.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, valuescan.FieldID) + for i := range fields { + if fields[i] != valuescan.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *ValueScanQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(valuescan.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = valuescan.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ValueScanGroupBy is the group-by builder for ValueScan entities. +type ValueScanGroupBy struct { + selector + build *ValueScanQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ValueScanGroupBy) Aggregate(fns ...AggregateFunc) *ValueScanGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ValueScanGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ValueScanQuery, *ValueScanGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ValueScanGroupBy) sqlScan(ctx context.Context, root *ValueScanQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ValueScanSelect is the builder for selecting fields of ValueScan entities. +type ValueScanSelect struct { + *ValueScanQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ValueScanSelect) Aggregate(fns ...AggregateFunc) *ValueScanSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ValueScanSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ValueScanQuery, *ValueScanSelect](ctx, _s.ValueScanQuery, _s, _s.inters, v) +} + +func (_s *ValueScanSelect) sqlScan(ctx context.Context, root *ValueScanQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/entc/integration/customid/ent/valuescan_update.go b/entc/integration/customid/ent/valuescan_update.go new file mode 100644 index 000000000..ddf1b3932 --- /dev/null +++ b/entc/integration/customid/ent/valuescan_update.go @@ -0,0 +1,217 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/entc/integration/customid/ent/predicate" + "entgo.io/ent/entc/integration/customid/ent/valuescan" + "entgo.io/ent/schema/field" +) + +// ValueScanUpdate is the builder for updating ValueScan entities. +type ValueScanUpdate struct { + config + hooks []Hook + mutation *ValueScanMutation +} + +// Where appends a list predicates to the ValueScanUpdate builder. +func (_u *ValueScanUpdate) Where(ps ...predicate.ValueScan) *ValueScanUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetName sets the "name" field. +func (_u *ValueScanUpdate) SetName(v string) *ValueScanUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ValueScanUpdate) SetNillableName(v *string) *ValueScanUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// Mutation returns the ValueScanMutation object of the builder. +func (_u *ValueScanUpdate) Mutation() *ValueScanMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ValueScanUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ValueScanUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ValueScanUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ValueScanUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *ValueScanUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(valuescan.Table, valuescan.Columns, sqlgraph.NewFieldSpec(valuescan.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(valuescan.FieldName, field.TypeString, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{valuescan.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ValueScanUpdateOne is the builder for updating a single ValueScan entity. +type ValueScanUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ValueScanMutation +} + +// SetName sets the "name" field. +func (_u *ValueScanUpdateOne) SetName(v string) *ValueScanUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *ValueScanUpdateOne) SetNillableName(v *string) *ValueScanUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// Mutation returns the ValueScanMutation object of the builder. +func (_u *ValueScanUpdateOne) Mutation() *ValueScanMutation { + return _u.mutation +} + +// Where appends a list predicates to the ValueScanUpdate builder. +func (_u *ValueScanUpdateOne) Where(ps ...predicate.ValueScan) *ValueScanUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *ValueScanUpdateOne) Select(field string, fields ...string) *ValueScanUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ValueScan entity. +func (_u *ValueScanUpdateOne) Save(ctx context.Context) (*ValueScan, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ValueScanUpdateOne) SaveX(ctx context.Context) *ValueScan { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ValueScanUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ValueScanUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *ValueScanUpdateOne) sqlSave(ctx context.Context) (_node *ValueScan, err error) { + _spec := sqlgraph.NewUpdateSpec(valuescan.Table, valuescan.Columns, sqlgraph.NewFieldSpec(valuescan.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "ValueScan.id" for update`)} + } + vv, err := valuescan.ValueScanner.ID.Value(id) + if err != nil { + return nil, err + } + _spec.Node.ID.Value = vv + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, valuescan.FieldID) + for _, f := range fields { + if !valuescan.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != valuescan.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(valuescan.FieldName, field.TypeString, value) + } + _node = &ValueScan{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{valuescan.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +}