entc/gen: minor changes to annotation tests (#948)

This commit is contained in:
Ariel Mashraki
2020-11-13 22:41:45 +02:00
committed by GitHub
parent b71fc2714b
commit 45020a877b
12 changed files with 369 additions and 15 deletions

View File

@@ -43,7 +43,7 @@ type Annotation struct {
//
Options string `json:"options,omitempty"`
// Size define the column size in the generated schema. for example:
// Size defines the column size in the generated schema. For example:
//
// entsql.Annotation{
// Size: 128,

View File

@@ -418,13 +418,7 @@ func dumpFields(v interface{}) string {
}
fv := rv.Field(i)
if !fv.IsZero() {
var v interface{}
if fv.Kind() == reflect.Int64 {
v = fv.Int()
} else {
v = fv.String()
}
fields = append(fields, fmt.Sprintf("%s: %#v", f.Name, v))
fields = append(fields, fmt.Sprintf("%s: %#v", f.Name, fv.Interface()))
}
}
return strings.Join(fields, ", ")

View File

@@ -40,4 +40,8 @@ func TestSchemaConfig(t *testing.T) {
var n int
require.NoError(t, rows.Scan(&n), "scanning count")
require.Equalf(t, 1, n, "expecting table %q to be exist", table)
// Check that the table was created with the given custom name.
size := schema.User{}.Fields()[0].Descriptor().Annotations[0].(entsql.Annotation).Size
require.Equal(t, size, migrate.Tables[0].Columns[1].Size)
}

View File

@@ -16,6 +16,7 @@ var (
// UsersColumns holds the columns for the "Users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Nullable: true, Size: 128},
}
// UsersTable holds the schema information for the "Users" table.
UsersTable = &schema.Table{
@@ -23,7 +24,7 @@ var (
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
Annotation: &entsql.Annotation{Table: "Users", Charset: "utf8mb4", Size: 128},
Annotation: &entsql.Annotation{Table: "Users", Charset: "utf8mb4"},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{

View File

@@ -11,8 +11,10 @@ import (
"fmt"
"sync"
"github.com/facebook/ent"
"github.com/facebook/ent/entc/integration/config/ent/predicate"
"github.com/facebook/ent/entc/integration/config/ent/user"
"github.com/facebook/ent"
)
const (
@@ -34,6 +36,7 @@ type UserMutation struct {
op Op
typ string
id *int
name *string
clearedFields map[string]struct{}
done bool
oldValue func(context.Context) (*User, error)
@@ -119,6 +122,56 @@ func (m *UserMutation) ID() (id int, exists bool) {
return *m.id, true
}
// SetName sets the name field.
func (m *UserMutation) SetName(s string) {
m.name = &s
}
// Name returns the name value in the mutation.
func (m *UserMutation) Name() (r string, exists bool) {
v := m.name
if v == nil {
return
}
return *v, true
}
// OldName returns the old name value of the User.
// If the User 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 database query fails.
func (m *UserMutation) OldName(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, fmt.Errorf("OldName is allowed only on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, fmt.Errorf("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
}
// ClearName clears the value of name.
func (m *UserMutation) ClearName() {
m.name = nil
m.clearedFields[user.FieldName] = struct{}{}
}
// NameCleared returns if the field name was cleared in this mutation.
func (m *UserMutation) NameCleared() bool {
_, ok := m.clearedFields[user.FieldName]
return ok
}
// ResetName reset all changes of the "name" field.
func (m *UserMutation) ResetName() {
m.name = nil
delete(m.clearedFields, user.FieldName)
}
// Op returns the operation name.
func (m *UserMutation) Op() Op {
return m.op
@@ -133,7 +186,10 @@ func (m *UserMutation) Type() string {
// this mutation. Note that, in order to get all numeric
// fields that were in/decremented, call AddedFields().
func (m *UserMutation) Fields() []string {
fields := make([]string, 0, 0)
fields := make([]string, 0, 1)
if m.name != nil {
fields = append(fields, user.FieldName)
}
return fields
}
@@ -141,6 +197,10 @@ func (m *UserMutation) Fields() []string {
// The second boolean value indicates that this field was
// not set, or was not define in the schema.
func (m *UserMutation) Field(name string) (ent.Value, bool) {
switch name {
case user.FieldName:
return m.Name()
}
return nil, false
}
@@ -148,6 +208,10 @@ func (m *UserMutation) Field(name string) (ent.Value, bool) {
// An error is returned if the mutation operation is not UpdateOne,
// or the query to the database was failed.
func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case user.FieldName:
return m.OldName(ctx)
}
return nil, fmt.Errorf("unknown User field %s", name)
}
@@ -156,6 +220,13 @@ func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, er
// type mismatch the field type.
func (m *UserMutation) SetField(name string, value ent.Value) error {
switch name {
case user.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 User field %s", name)
}
@@ -177,13 +248,19 @@ func (m *UserMutation) AddedField(name string) (ent.Value, bool) {
// error if the field is not defined in the schema, or if the
// type mismatch the field type.
func (m *UserMutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown User numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared
// during this mutation.
func (m *UserMutation) ClearedFields() []string {
return nil
var fields []string
if m.FieldCleared(user.FieldName) {
fields = append(fields, user.FieldName)
}
return fields
}
// FieldCleared returns a boolean indicates if this field was
@@ -196,6 +273,11 @@ func (m *UserMutation) FieldCleared(name string) bool {
// ClearField clears the value for the given name. It returns an
// error if the field is not defined in the schema.
func (m *UserMutation) ClearField(name string) error {
switch name {
case user.FieldName:
m.ClearName()
return nil
}
return fmt.Errorf("unknown User nullable field %s", name)
}
@@ -203,6 +285,11 @@ func (m *UserMutation) ClearField(name string) error {
// given field name. It returns an error if the field is not
// defined in the schema.
func (m *UserMutation) ResetField(name string) error {
switch name {
case user.FieldName:
m.ResetName()
return nil
}
return fmt.Errorf("unknown User field %s", name)
}

View File

@@ -8,6 +8,7 @@ import (
"github.com/facebook/ent"
"github.com/facebook/ent/dialect/entsql"
"github.com/facebook/ent/schema"
"github.com/facebook/ent/schema/field"
"github.com/facebook/ent/schema/mixin"
)
@@ -27,6 +28,17 @@ type User struct {
ent.Schema
}
// Fields of the User schema.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("name").
Optional().
Annotations(entsql.Annotation{
Size: 128,
}),
}
}
// Mixin of the User schema.
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
@@ -39,7 +51,6 @@ func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{
Table: "Users",
Size: 128,
},
}
}

View File

@@ -16,15 +16,18 @@ import (
// User is the model entity for the User schema.
type User struct {
config
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*User) scanValues() []interface{} {
return []interface{}{
&sql.NullInt64{}, // id
&sql.NullInt64{}, // id
&sql.NullString{}, // name
}
}
@@ -40,6 +43,11 @@ func (u *User) assignValues(values ...interface{}) error {
}
u.ID = int(value.Int64)
values = values[1:]
if value, ok := values[0].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[0])
} else if value.Valid {
u.Name = value.String
}
return nil
}
@@ -66,6 +74,8 @@ func (u *User) String() string {
var builder strings.Builder
builder.WriteString("User(")
builder.WriteString(fmt.Sprintf("id=%v", u.ID))
builder.WriteString(", name=")
builder.WriteString(u.Name)
builder.WriteByte(')')
return builder.String()
}

View File

@@ -11,6 +11,8 @@ const (
Label = "user"
// 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 user in the database.
Table = "Users"
@@ -19,6 +21,7 @@ const (
// Columns holds all SQL columns for user fields.
var Columns = []string{
FieldID,
FieldName,
}
// ValidColumn reports if the column name is valid (part of the table columns).

View File

@@ -94,6 +94,138 @@ func IDLTE(id int) predicate.User {
})
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
})
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
})
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldName), v))
})
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.User {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.User(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldName), v...))
})
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.User {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.User(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldName), v...))
})
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldName), v))
})
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldName), v))
})
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldName), v))
})
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldName), v))
})
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldName), v))
})
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldName), v))
})
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldName), v))
})
}
// NameIsNil applies the IsNil predicate on the "name" field.
func NameIsNil() predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldName)))
})
}
// NameNotNil applies the NotNil predicate on the "name" field.
func NameNotNil() predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldName)))
})
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldName), v))
})
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldName), v))
})
}
// And groups list of predicates with the AND operator between them.
func And(predicates ...predicate.User) predicate.User {
return predicate.User(func(s *sql.Selector) {

View File

@@ -22,6 +22,20 @@ type UserCreate struct {
hooks []Hook
}
// SetName sets the name field.
func (uc *UserCreate) SetName(s string) *UserCreate {
uc.mutation.SetName(s)
return uc
}
// SetNillableName sets the name field if the given value is not nil.
func (uc *UserCreate) SetNillableName(s *string) *UserCreate {
if s != nil {
uc.SetName(*s)
}
return uc
}
// Mutation returns the UserMutation object of the builder.
func (uc *UserCreate) Mutation() *UserMutation {
return uc.mutation
@@ -100,6 +114,14 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
},
}
)
if value, ok := uc.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: user.FieldName,
})
_node.Name = value
}
return _node, _spec
}

View File

@@ -240,6 +240,19 @@ func (uq *UserQuery) Clone() *UserQuery {
// GroupBy 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.User.Query().
// GroupBy(user.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
//
func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy {
group := &UserGroupBy{config: uq.config}
group.fields = append([]string{field}, fields...)
@@ -253,6 +266,17 @@ func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy {
}
// Select one or more fields from the given query.
//
// Example:
//
// var v []struct {
// Name string `json:"name,omitempty"`
// }
//
// client.User.Query().
// Select(user.FieldName).
// Scan(ctx, &v)
//
func (uq *UserQuery) Select(field string, fields ...string) *UserSelect {
selector := &UserSelect{config: uq.config}
selector.fields = append([]string{field}, fields...)

View File

@@ -30,6 +30,26 @@ func (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate {
return uu
}
// SetName sets the name field.
func (uu *UserUpdate) SetName(s string) *UserUpdate {
uu.mutation.SetName(s)
return uu
}
// SetNillableName sets the name field if the given value is not nil.
func (uu *UserUpdate) SetNillableName(s *string) *UserUpdate {
if s != nil {
uu.SetName(*s)
}
return uu
}
// ClearName clears the value of name.
func (uu *UserUpdate) ClearName() *UserUpdate {
uu.mutation.ClearName()
return uu
}
// Mutation returns the UserMutation object of the builder.
func (uu *UserUpdate) Mutation() *UserMutation {
return uu.mutation
@@ -104,6 +124,19 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
}
}
}
if value, ok := uu.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: user.FieldName,
})
}
if uu.mutation.NameCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: user.FieldName,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{user.Label}
@@ -122,6 +155,26 @@ type UserUpdateOne struct {
mutation *UserMutation
}
// SetName sets the name field.
func (uuo *UserUpdateOne) SetName(s string) *UserUpdateOne {
uuo.mutation.SetName(s)
return uuo
}
// SetNillableName sets the name field if the given value is not nil.
func (uuo *UserUpdateOne) SetNillableName(s *string) *UserUpdateOne {
if s != nil {
uuo.SetName(*s)
}
return uuo
}
// ClearName clears the value of name.
func (uuo *UserUpdateOne) ClearName() *UserUpdateOne {
uuo.mutation.ClearName()
return uuo
}
// Mutation returns the UserMutation object of the builder.
func (uuo *UserUpdateOne) Mutation() *UserMutation {
return uuo.mutation
@@ -194,6 +247,19 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error)
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing User.ID for update")}
}
_spec.Node.ID.Value = id
if value, ok := uuo.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: user.FieldName,
})
}
if uuo.mutation.NameCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: user.FieldName,
})
}
_node = &User{config: uuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues()