generate database schemas

This commit is contained in:
Hayden 2022-08-30 10:04:50 -08:00
parent 4c76f6b367
commit 63cfeffc4d
70 changed files with 26933 additions and 1398 deletions

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
@ -17,13 +17,15 @@ import (
type AuthTokens struct { type AuthTokens struct {
config `json:"-"` config `json:"-"`
// ID of the ent. // ID of the ent.
ID int `json:"id,omitempty"` ID uuid.UUID `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Token holds the value of the "token" field. // Token holds the value of the "token" field.
Token []byte `json:"token,omitempty"` Token []byte `json:"token,omitempty"`
// ExpiresAt holds the value of the "expires_at" field. // ExpiresAt holds the value of the "expires_at" field.
ExpiresAt time.Time `json:"expires_at,omitempty"` ExpiresAt time.Time `json:"expires_at,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// Edges holds the relations/edges for other nodes in the graph. // Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the AuthTokensQuery when eager-loading is set. // The values are being populated by the AuthTokensQuery when eager-loading is set.
Edges AuthTokensEdges `json:"edges"` Edges AuthTokensEdges `json:"edges"`
@ -44,8 +46,7 @@ type AuthTokensEdges struct {
func (e AuthTokensEdges) UserOrErr() (*User, error) { func (e AuthTokensEdges) UserOrErr() (*User, error) {
if e.loadedTypes[0] { if e.loadedTypes[0] {
if e.User == nil { if e.User == nil {
// The edge user was loaded in eager-loading, // Edge was loaded but was not found.
// but was not found.
return nil, &NotFoundError{label: user.Label} return nil, &NotFoundError{label: user.Label}
} }
return e.User, nil return e.User, nil
@ -60,10 +61,10 @@ func (*AuthTokens) scanValues(columns []string) ([]interface{}, error) {
switch columns[i] { switch columns[i] {
case authtokens.FieldToken: case authtokens.FieldToken:
values[i] = new([]byte) values[i] = new([]byte)
case authtokens.FieldID: case authtokens.FieldCreatedAt, authtokens.FieldUpdatedAt, authtokens.FieldExpiresAt:
values[i] = new(sql.NullInt64)
case authtokens.FieldExpiresAt, authtokens.FieldCreatedAt:
values[i] = new(sql.NullTime) values[i] = new(sql.NullTime)
case authtokens.FieldID:
values[i] = new(uuid.UUID)
case authtokens.ForeignKeys[0]: // user_auth_tokens case authtokens.ForeignKeys[0]: // user_auth_tokens
values[i] = &sql.NullScanner{S: new(uuid.UUID)} values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default: default:
@ -82,11 +83,23 @@ func (at *AuthTokens) assignValues(columns []string, values []interface{}) error
for i := range columns { for i := range columns {
switch columns[i] { switch columns[i] {
case authtokens.FieldID: case authtokens.FieldID:
value, ok := values[i].(*sql.NullInt64) if value, ok := values[i].(*uuid.UUID); !ok {
if !ok { return fmt.Errorf("unexpected type %T for field id", values[i])
return fmt.Errorf("unexpected type %T for field id", value) } else if value != nil {
at.ID = *value
}
case authtokens.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
at.CreatedAt = value.Time
}
case authtokens.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
at.UpdatedAt = value.Time
} }
at.ID = int(value.Int64)
case authtokens.FieldToken: case authtokens.FieldToken:
if value, ok := values[i].(*[]byte); !ok { if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field token", values[i]) return fmt.Errorf("unexpected type %T for field token", values[i])
@ -99,12 +112,6 @@ func (at *AuthTokens) assignValues(columns []string, values []interface{}) error
} else if value.Valid { } else if value.Valid {
at.ExpiresAt = value.Time at.ExpiresAt = value.Time
} }
case authtokens.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
at.CreatedAt = value.Time
}
case authtokens.ForeignKeys[0]: case authtokens.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok { if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field user_auth_tokens", values[i]) return fmt.Errorf("unexpected type %T for field user_auth_tokens", values[i])
@ -132,11 +139,11 @@ func (at *AuthTokens) Update() *AuthTokensUpdateOne {
// Unwrap unwraps the AuthTokens entity that was returned from a transaction after it was closed, // Unwrap unwraps the AuthTokens 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. // so that all future queries will be executed through the driver which created the transaction.
func (at *AuthTokens) Unwrap() *AuthTokens { func (at *AuthTokens) Unwrap() *AuthTokens {
tx, ok := at.config.driver.(*txDriver) _tx, ok := at.config.driver.(*txDriver)
if !ok { if !ok {
panic("ent: AuthTokens is not a transactional entity") panic("ent: AuthTokens is not a transactional entity")
} }
at.config.driver = tx.drv at.config.driver = _tx.drv
return at return at
} }
@ -144,13 +151,18 @@ func (at *AuthTokens) Unwrap() *AuthTokens {
func (at *AuthTokens) String() string { func (at *AuthTokens) String() string {
var builder strings.Builder var builder strings.Builder
builder.WriteString("AuthTokens(") builder.WriteString("AuthTokens(")
builder.WriteString(fmt.Sprintf("id=%v", at.ID)) builder.WriteString(fmt.Sprintf("id=%v, ", at.ID))
builder.WriteString(", token=") builder.WriteString("created_at=")
builder.WriteString(fmt.Sprintf("%v", at.Token))
builder.WriteString(", expires_at=")
builder.WriteString(at.ExpiresAt.Format(time.ANSIC))
builder.WriteString(", created_at=")
builder.WriteString(at.CreatedAt.Format(time.ANSIC)) builder.WriteString(at.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(at.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("token=")
builder.WriteString(fmt.Sprintf("%v", at.Token))
builder.WriteString(", ")
builder.WriteString("expires_at=")
builder.WriteString(at.ExpiresAt.Format(time.ANSIC))
builder.WriteByte(')') builder.WriteByte(')')
return builder.String() return builder.String()
} }

View file

@ -1,9 +1,11 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package authtokens package authtokens
import ( import (
"time" "time"
"github.com/google/uuid"
) )
const ( const (
@ -11,12 +13,14 @@ const (
Label = "auth_tokens" Label = "auth_tokens"
// FieldID holds the string denoting the id field in the database. // FieldID holds the string denoting the id field in the database.
FieldID = "id" FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldToken holds the string denoting the token field in the database. // FieldToken holds the string denoting the token field in the database.
FieldToken = "token" FieldToken = "token"
// FieldExpiresAt holds the string denoting the expires_at field in the database. // FieldExpiresAt holds the string denoting the expires_at field in the database.
FieldExpiresAt = "expires_at" FieldExpiresAt = "expires_at"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// EdgeUser holds the string denoting the user edge name in mutations. // EdgeUser holds the string denoting the user edge name in mutations.
EdgeUser = "user" EdgeUser = "user"
// Table holds the table name of the authtokens in the database. // Table holds the table name of the authtokens in the database.
@ -33,9 +37,10 @@ const (
// Columns holds all SQL columns for authtokens fields. // Columns holds all SQL columns for authtokens fields.
var Columns = []string{ var Columns = []string{
FieldID, FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldToken, FieldToken,
FieldExpiresAt, FieldExpiresAt,
FieldCreatedAt,
} }
// ForeignKeys holds the SQL foreign-keys that are owned by the "auth_tokens" // ForeignKeys holds the SQL foreign-keys that are owned by the "auth_tokens"
@ -60,8 +65,14 @@ func ValidColumn(column string) bool {
} }
var ( var (
// DefaultExpiresAt holds the default value on creation for the "expires_at" field.
DefaultExpiresAt func() time.Time
// DefaultCreatedAt holds the default value on creation for the "created_at" field. // DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// DefaultExpiresAt holds the default value on creation for the "expires_at" field.
DefaultExpiresAt func() time.Time
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
) )

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package authtokens package authtokens
@ -7,39 +7,34 @@ import (
"entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/dialect/sql/sqlgraph"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/predicate" "github.com/hay-kot/content/backend/ent/predicate"
) )
// ID filters vertices based on their ID field. // ID filters vertices based on their ID field.
func ID(id int) predicate.AuthTokens { func ID(id uuid.UUID) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id)) s.Where(sql.EQ(s.C(FieldID), id))
}) })
} }
// IDEQ applies the EQ predicate on the ID field. // IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.AuthTokens { func IDEQ(id uuid.UUID) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id)) s.Where(sql.EQ(s.C(FieldID), id))
}) })
} }
// IDNEQ applies the NEQ predicate on the ID field. // IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.AuthTokens { func IDNEQ(id uuid.UUID) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id)) s.Where(sql.NEQ(s.C(FieldID), id))
}) })
} }
// IDIn applies the In predicate on the ID field. // IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.AuthTokens { func IDIn(ids ...uuid.UUID) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(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(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids)) v := make([]interface{}, len(ids))
for i := range v { for i := range v {
v[i] = ids[i] v[i] = ids[i]
@ -49,14 +44,8 @@ func IDIn(ids ...int) predicate.AuthTokens {
} }
// IDNotIn applies the NotIn predicate on the ID field. // IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.AuthTokens { func IDNotIn(ids ...uuid.UUID) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(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(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids)) v := make([]interface{}, len(ids))
for i := range v { for i := range v {
v[i] = ids[i] v[i] = ids[i]
@ -66,33 +55,47 @@ func IDNotIn(ids ...int) predicate.AuthTokens {
} }
// IDGT applies the GT predicate on the ID field. // IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.AuthTokens { func IDGT(id uuid.UUID) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id)) s.Where(sql.GT(s.C(FieldID), id))
}) })
} }
// IDGTE applies the GTE predicate on the ID field. // IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.AuthTokens { func IDGTE(id uuid.UUID) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id)) s.Where(sql.GTE(s.C(FieldID), id))
}) })
} }
// IDLT applies the LT predicate on the ID field. // IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.AuthTokens { func IDLT(id uuid.UUID) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id)) s.Where(sql.LT(s.C(FieldID), id))
}) })
} }
// IDLTE applies the LTE predicate on the ID field. // IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.AuthTokens { func IDLTE(id uuid.UUID) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id)) s.Where(sql.LTE(s.C(FieldID), id))
}) })
} }
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
})
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Token applies equality check predicate on the "token" field. It's identical to TokenEQ. // Token applies equality check predicate on the "token" field. It's identical to TokenEQ.
func Token(v []byte) predicate.AuthTokens { func Token(v []byte) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(func(s *sql.Selector) {
@ -107,13 +110,134 @@ func ExpiresAt(v time.Time) predicate.AuthTokens {
}) })
} }
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. // CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAt(v time.Time) predicate.AuthTokens { func CreatedAtEQ(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreatedAt), v)) s.Where(sql.EQ(s.C(FieldCreatedAt), v))
}) })
} }
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldCreatedAt), v))
})
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.AuthTokens {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldCreatedAt), v...))
})
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.AuthTokens {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldCreatedAt), v...))
})
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldCreatedAt), v))
})
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.AuthTokens {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldUpdatedAt), v...))
})
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.AuthTokens {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...))
})
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// TokenEQ applies the EQ predicate on the "token" field. // TokenEQ applies the EQ predicate on the "token" field.
func TokenEQ(v []byte) predicate.AuthTokens { func TokenEQ(v []byte) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(func(s *sql.Selector) {
@ -135,12 +259,6 @@ func TokenIn(vs ...[]byte) predicate.AuthTokens {
v[i] = vs[i] v[i] = vs[i]
} }
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(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(FieldToken), v...)) s.Where(sql.In(s.C(FieldToken), v...))
}) })
} }
@ -152,12 +270,6 @@ func TokenNotIn(vs ...[]byte) predicate.AuthTokens {
v[i] = vs[i] v[i] = vs[i]
} }
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(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(FieldToken), v...)) s.Where(sql.NotIn(s.C(FieldToken), v...))
}) })
} }
@ -211,12 +323,6 @@ func ExpiresAtIn(vs ...time.Time) predicate.AuthTokens {
v[i] = vs[i] v[i] = vs[i]
} }
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(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(FieldExpiresAt), v...)) s.Where(sql.In(s.C(FieldExpiresAt), v...))
}) })
} }
@ -228,12 +334,6 @@ func ExpiresAtNotIn(vs ...time.Time) predicate.AuthTokens {
v[i] = vs[i] v[i] = vs[i]
} }
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(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(FieldExpiresAt), v...)) s.Where(sql.NotIn(s.C(FieldExpiresAt), v...))
}) })
} }
@ -266,82 +366,6 @@ func ExpiresAtLTE(v time.Time) predicate.AuthTokens {
}) })
} }
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
})
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldCreatedAt), v))
})
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.AuthTokens {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(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(FieldCreatedAt), v...))
})
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.AuthTokens {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(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(FieldCreatedAt), v...))
})
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldCreatedAt), v))
})
}
// HasUser applies the HasEdge predicate on the "user" edge. // HasUser applies the HasEdge predicate on the "user" edge.
func HasUser() predicate.AuthTokens { func HasUser() predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) { return predicate.AuthTokens(func(s *sql.Selector) {

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
@ -22,6 +22,34 @@ type AuthTokensCreate struct {
hooks []Hook hooks []Hook
} }
// SetCreatedAt sets the "created_at" field.
func (atc *AuthTokensCreate) SetCreatedAt(t time.Time) *AuthTokensCreate {
atc.mutation.SetCreatedAt(t)
return atc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (atc *AuthTokensCreate) SetNillableCreatedAt(t *time.Time) *AuthTokensCreate {
if t != nil {
atc.SetCreatedAt(*t)
}
return atc
}
// SetUpdatedAt sets the "updated_at" field.
func (atc *AuthTokensCreate) SetUpdatedAt(t time.Time) *AuthTokensCreate {
atc.mutation.SetUpdatedAt(t)
return atc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (atc *AuthTokensCreate) SetNillableUpdatedAt(t *time.Time) *AuthTokensCreate {
if t != nil {
atc.SetUpdatedAt(*t)
}
return atc
}
// SetToken sets the "token" field. // SetToken sets the "token" field.
func (atc *AuthTokensCreate) SetToken(b []byte) *AuthTokensCreate { func (atc *AuthTokensCreate) SetToken(b []byte) *AuthTokensCreate {
atc.mutation.SetToken(b) atc.mutation.SetToken(b)
@ -42,16 +70,16 @@ func (atc *AuthTokensCreate) SetNillableExpiresAt(t *time.Time) *AuthTokensCreat
return atc return atc
} }
// SetCreatedAt sets the "created_at" field. // SetID sets the "id" field.
func (atc *AuthTokensCreate) SetCreatedAt(t time.Time) *AuthTokensCreate { func (atc *AuthTokensCreate) SetID(u uuid.UUID) *AuthTokensCreate {
atc.mutation.SetCreatedAt(t) atc.mutation.SetID(u)
return atc return atc
} }
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. // SetNillableID sets the "id" field if the given value is not nil.
func (atc *AuthTokensCreate) SetNillableCreatedAt(t *time.Time) *AuthTokensCreate { func (atc *AuthTokensCreate) SetNillableID(u *uuid.UUID) *AuthTokensCreate {
if t != nil { if u != nil {
atc.SetCreatedAt(*t) atc.SetID(*u)
} }
return atc return atc
} }
@ -115,9 +143,15 @@ func (atc *AuthTokensCreate) Save(ctx context.Context) (*AuthTokens, error) {
} }
mut = atc.hooks[i](mut) mut = atc.hooks[i](mut)
} }
if _, err := mut.Mutate(ctx, atc.mutation); err != nil { v, err := mut.Mutate(ctx, atc.mutation)
if err != nil {
return nil, err return nil, err
} }
nv, ok := v.(*AuthTokens)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from AuthTokensMutation", v)
}
node = nv
} }
return node, err return node, err
} }
@ -146,27 +180,38 @@ func (atc *AuthTokensCreate) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save. // defaults sets the default values of the builder before save.
func (atc *AuthTokensCreate) defaults() { func (atc *AuthTokensCreate) defaults() {
if _, ok := atc.mutation.CreatedAt(); !ok {
v := authtokens.DefaultCreatedAt()
atc.mutation.SetCreatedAt(v)
}
if _, ok := atc.mutation.UpdatedAt(); !ok {
v := authtokens.DefaultUpdatedAt()
atc.mutation.SetUpdatedAt(v)
}
if _, ok := atc.mutation.ExpiresAt(); !ok { if _, ok := atc.mutation.ExpiresAt(); !ok {
v := authtokens.DefaultExpiresAt() v := authtokens.DefaultExpiresAt()
atc.mutation.SetExpiresAt(v) atc.mutation.SetExpiresAt(v)
} }
if _, ok := atc.mutation.CreatedAt(); !ok { if _, ok := atc.mutation.ID(); !ok {
v := authtokens.DefaultCreatedAt() v := authtokens.DefaultID()
atc.mutation.SetCreatedAt(v) atc.mutation.SetID(v)
} }
} }
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (atc *AuthTokensCreate) check() error { func (atc *AuthTokensCreate) check() error {
if _, ok := atc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "AuthTokens.created_at"`)}
}
if _, ok := atc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "AuthTokens.updated_at"`)}
}
if _, ok := atc.mutation.Token(); !ok { if _, ok := atc.mutation.Token(); !ok {
return &ValidationError{Name: "token", err: errors.New(`ent: missing required field "AuthTokens.token"`)} return &ValidationError{Name: "token", err: errors.New(`ent: missing required field "AuthTokens.token"`)}
} }
if _, ok := atc.mutation.ExpiresAt(); !ok { if _, ok := atc.mutation.ExpiresAt(); !ok {
return &ValidationError{Name: "expires_at", err: errors.New(`ent: missing required field "AuthTokens.expires_at"`)} return &ValidationError{Name: "expires_at", err: errors.New(`ent: missing required field "AuthTokens.expires_at"`)}
} }
if _, ok := atc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "AuthTokens.created_at"`)}
}
return nil return nil
} }
@ -174,12 +219,17 @@ func (atc *AuthTokensCreate) sqlSave(ctx context.Context) (*AuthTokens, error) {
_node, _spec := atc.createSpec() _node, _spec := atc.createSpec()
if err := sqlgraph.CreateNode(ctx, atc.driver, _spec); err != nil { if err := sqlgraph.CreateNode(ctx, atc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) { if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err} err = &ConstraintError{msg: err.Error(), wrap: err}
} }
return nil, err return nil, err
} }
id := _spec.ID.Value.(int64) if _spec.ID.Value != nil {
_node.ID = int(id) if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
_node.ID = *id
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
return nil, err
}
}
return _node, nil return _node, nil
} }
@ -189,11 +239,31 @@ func (atc *AuthTokensCreate) createSpec() (*AuthTokens, *sqlgraph.CreateSpec) {
_spec = &sqlgraph.CreateSpec{ _spec = &sqlgraph.CreateSpec{
Table: authtokens.Table, Table: authtokens.Table,
ID: &sqlgraph.FieldSpec{ ID: &sqlgraph.FieldSpec{
Type: field.TypeInt, Type: field.TypeUUID,
Column: authtokens.FieldID, Column: authtokens.FieldID,
}, },
} }
) )
if id, ok := atc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := atc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := atc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := atc.mutation.Token(); ok { if value, ok := atc.mutation.Token(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBytes, Type: field.TypeBytes,
@ -210,14 +280,6 @@ func (atc *AuthTokensCreate) createSpec() (*AuthTokens, *sqlgraph.CreateSpec) {
}) })
_node.ExpiresAt = value _node.ExpiresAt = value
} }
if value, ok := atc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldCreatedAt,
})
_node.CreatedAt = value
}
if nodes := atc.mutation.UserIDs(); len(nodes) > 0 { if nodes := atc.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{ edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O, Rel: sqlgraph.M2O,
@ -274,7 +336,7 @@ func (atcb *AuthTokensCreateBulk) Save(ctx context.Context) ([]*AuthTokens, erro
// Invoke the actual operation on the latest mutation in the chain. // Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, atcb.driver, spec); err != nil { if err = sqlgraph.BatchCreate(ctx, atcb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) { if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err} err = &ConstraintError{msg: err.Error(), wrap: err}
} }
} }
} }
@ -283,10 +345,6 @@ func (atcb *AuthTokensCreateBulk) Save(ctx context.Context) ([]*AuthTokens, erro
} }
mutation.id = &nodes[i].ID mutation.id = &nodes[i].ID
mutation.done = true mutation.done = true
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
return nodes[i], nil return nodes[i], nil
}) })
for i := len(builder.hooks) - 1; i >= 0; i-- { for i := len(builder.hooks) - 1; i >= 0; i-- {

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
@ -72,7 +72,7 @@ func (atd *AuthTokensDelete) sqlExec(ctx context.Context) (int, error) {
Node: &sqlgraph.NodeSpec{ Node: &sqlgraph.NodeSpec{
Table: authtokens.Table, Table: authtokens.Table,
ID: &sqlgraph.FieldSpec{ ID: &sqlgraph.FieldSpec{
Type: field.TypeInt, Type: field.TypeUUID,
Column: authtokens.FieldID, Column: authtokens.FieldID,
}, },
}, },
@ -84,7 +84,11 @@ func (atd *AuthTokensDelete) sqlExec(ctx context.Context) (int, error) {
} }
} }
} }
return sqlgraph.DeleteNodes(ctx, atd.driver, _spec) affected, err := sqlgraph.DeleteNodes(ctx, atd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
} }
// AuthTokensDeleteOne is the builder for deleting a single AuthTokens entity. // AuthTokensDeleteOne is the builder for deleting a single AuthTokens entity.

View file

@ -1,10 +1,9 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"math" "math"
@ -26,7 +25,6 @@ type AuthTokensQuery struct {
order []OrderFunc order []OrderFunc
fields []string fields []string
predicates []predicate.AuthTokens predicates []predicate.AuthTokens
// eager-loading edges.
withUser *UserQuery withUser *UserQuery
withFKs bool withFKs bool
// intermediate query (i.e. traversal path). // intermediate query (i.e. traversal path).
@ -111,8 +109,8 @@ func (atq *AuthTokensQuery) FirstX(ctx context.Context) *AuthTokens {
// FirstID returns the first AuthTokens ID from the query. // FirstID returns the first AuthTokens ID from the query.
// Returns a *NotFoundError when no AuthTokens ID was found. // Returns a *NotFoundError when no AuthTokens ID was found.
func (atq *AuthTokensQuery) FirstID(ctx context.Context) (id int, err error) { func (atq *AuthTokensQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []int var ids []uuid.UUID
if ids, err = atq.Limit(1).IDs(ctx); err != nil { if ids, err = atq.Limit(1).IDs(ctx); err != nil {
return return
} }
@ -124,7 +122,7 @@ func (atq *AuthTokensQuery) FirstID(ctx context.Context) (id int, err error) {
} }
// FirstIDX is like FirstID, but panics if an error occurs. // FirstIDX is like FirstID, but panics if an error occurs.
func (atq *AuthTokensQuery) FirstIDX(ctx context.Context) int { func (atq *AuthTokensQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := atq.FirstID(ctx) id, err := atq.FirstID(ctx)
if err != nil && !IsNotFound(err) { if err != nil && !IsNotFound(err) {
panic(err) panic(err)
@ -133,7 +131,7 @@ func (atq *AuthTokensQuery) FirstIDX(ctx context.Context) int {
} }
// Only returns a single AuthTokens entity found by the query, ensuring it only returns one. // Only returns a single AuthTokens entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when exactly one AuthTokens entity is not found. // Returns a *NotSingularError when more than one AuthTokens entity is found.
// Returns a *NotFoundError when no AuthTokens entities are found. // Returns a *NotFoundError when no AuthTokens entities are found.
func (atq *AuthTokensQuery) Only(ctx context.Context) (*AuthTokens, error) { func (atq *AuthTokensQuery) Only(ctx context.Context) (*AuthTokens, error) {
nodes, err := atq.Limit(2).All(ctx) nodes, err := atq.Limit(2).All(ctx)
@ -160,10 +158,10 @@ func (atq *AuthTokensQuery) OnlyX(ctx context.Context) *AuthTokens {
} }
// OnlyID is like Only, but returns the only AuthTokens ID in the query. // OnlyID is like Only, but returns the only AuthTokens ID in the query.
// Returns a *NotSingularError when exactly one AuthTokens ID is not found. // Returns a *NotSingularError when more than one AuthTokens ID is found.
// Returns a *NotFoundError when no entities are found. // Returns a *NotFoundError when no entities are found.
func (atq *AuthTokensQuery) OnlyID(ctx context.Context) (id int, err error) { func (atq *AuthTokensQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []int var ids []uuid.UUID
if ids, err = atq.Limit(2).IDs(ctx); err != nil { if ids, err = atq.Limit(2).IDs(ctx); err != nil {
return return
} }
@ -179,7 +177,7 @@ func (atq *AuthTokensQuery) OnlyID(ctx context.Context) (id int, err error) {
} }
// OnlyIDX is like OnlyID, but panics if an error occurs. // OnlyIDX is like OnlyID, but panics if an error occurs.
func (atq *AuthTokensQuery) OnlyIDX(ctx context.Context) int { func (atq *AuthTokensQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := atq.OnlyID(ctx) id, err := atq.OnlyID(ctx)
if err != nil { if err != nil {
panic(err) panic(err)
@ -205,8 +203,8 @@ func (atq *AuthTokensQuery) AllX(ctx context.Context) []*AuthTokens {
} }
// IDs executes the query and returns a list of AuthTokens IDs. // IDs executes the query and returns a list of AuthTokens IDs.
func (atq *AuthTokensQuery) IDs(ctx context.Context) ([]int, error) { func (atq *AuthTokensQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []int var ids []uuid.UUID
if err := atq.Select(authtokens.FieldID).Scan(ctx, &ids); err != nil { if err := atq.Select(authtokens.FieldID).Scan(ctx, &ids); err != nil {
return nil, err return nil, err
} }
@ -214,7 +212,7 @@ func (atq *AuthTokensQuery) IDs(ctx context.Context) ([]int, error) {
} }
// IDsX is like IDs, but panics if an error occurs. // IDsX is like IDs, but panics if an error occurs.
func (atq *AuthTokensQuery) IDsX(ctx context.Context) []int { func (atq *AuthTokensQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := atq.IDs(ctx) ids, err := atq.IDs(ctx)
if err != nil { if err != nil {
panic(err) panic(err)
@ -272,6 +270,7 @@ func (atq *AuthTokensQuery) Clone() *AuthTokensQuery {
// clone intermediate query. // clone intermediate query.
sql: atq.sql.Clone(), sql: atq.sql.Clone(),
path: atq.path, path: atq.path,
unique: atq.unique,
} }
} }
@ -292,25 +291,26 @@ func (atq *AuthTokensQuery) WithUser(opts ...func(*UserQuery)) *AuthTokensQuery
// Example: // Example:
// //
// var v []struct { // var v []struct {
// Token []byte `json:"token,omitempty"` // CreatedAt time.Time `json:"created_at,omitempty"`
// Count int `json:"count,omitempty"` // Count int `json:"count,omitempty"`
// } // }
// //
// client.AuthTokens.Query(). // client.AuthTokens.Query().
// GroupBy(authtokens.FieldToken). // GroupBy(authtokens.FieldCreatedAt).
// Aggregate(ent.Count()). // Aggregate(ent.Count()).
// Scan(ctx, &v) // Scan(ctx, &v)
//
func (atq *AuthTokensQuery) GroupBy(field string, fields ...string) *AuthTokensGroupBy { func (atq *AuthTokensQuery) GroupBy(field string, fields ...string) *AuthTokensGroupBy {
group := &AuthTokensGroupBy{config: atq.config} grbuild := &AuthTokensGroupBy{config: atq.config}
group.fields = append([]string{field}, fields...) grbuild.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) { grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := atq.prepareQuery(ctx); err != nil { if err := atq.prepareQuery(ctx); err != nil {
return nil, err return nil, err
} }
return atq.sqlQuery(ctx), nil return atq.sqlQuery(ctx), nil
} }
return group grbuild.label = authtokens.Label
grbuild.flds, grbuild.scan = &grbuild.fields, grbuild.Scan
return grbuild
} }
// Select allows the selection one or more fields/columns for the given query, // Select allows the selection one or more fields/columns for the given query,
@ -319,16 +319,18 @@ func (atq *AuthTokensQuery) GroupBy(field string, fields ...string) *AuthTokensG
// Example: // Example:
// //
// var v []struct { // var v []struct {
// Token []byte `json:"token,omitempty"` // CreatedAt time.Time `json:"created_at,omitempty"`
// } // }
// //
// client.AuthTokens.Query(). // client.AuthTokens.Query().
// Select(authtokens.FieldToken). // Select(authtokens.FieldCreatedAt).
// Scan(ctx, &v) // Scan(ctx, &v)
//
func (atq *AuthTokensQuery) Select(fields ...string) *AuthTokensSelect { func (atq *AuthTokensQuery) Select(fields ...string) *AuthTokensSelect {
atq.fields = append(atq.fields, fields...) atq.fields = append(atq.fields, fields...)
return &AuthTokensSelect{AuthTokensQuery: atq} selbuild := &AuthTokensSelect{AuthTokensQuery: atq}
selbuild.label = authtokens.Label
selbuild.flds, selbuild.scan = &atq.fields, selbuild.Scan
return selbuild
} }
func (atq *AuthTokensQuery) prepareQuery(ctx context.Context) error { func (atq *AuthTokensQuery) prepareQuery(ctx context.Context) error {
@ -347,7 +349,7 @@ func (atq *AuthTokensQuery) prepareQuery(ctx context.Context) error {
return nil return nil
} }
func (atq *AuthTokensQuery) sqlAll(ctx context.Context) ([]*AuthTokens, error) { func (atq *AuthTokensQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AuthTokens, error) {
var ( var (
nodes = []*AuthTokens{} nodes = []*AuthTokens{}
withFKs = atq.withFKs withFKs = atq.withFKs
@ -363,26 +365,33 @@ func (atq *AuthTokensQuery) sqlAll(ctx context.Context) ([]*AuthTokens, error) {
_spec.Node.Columns = append(_spec.Node.Columns, authtokens.ForeignKeys...) _spec.Node.Columns = append(_spec.Node.Columns, authtokens.ForeignKeys...)
} }
_spec.ScanValues = func(columns []string) ([]interface{}, error) { _spec.ScanValues = func(columns []string) ([]interface{}, error) {
node := &AuthTokens{config: atq.config} return (*AuthTokens).scanValues(nil, columns)
nodes = append(nodes, node)
return node.scanValues(columns)
} }
_spec.Assign = func(columns []string, values []interface{}) error { _spec.Assign = func(columns []string, values []interface{}) error {
if len(nodes) == 0 { node := &AuthTokens{config: atq.config}
return fmt.Errorf("ent: Assign called without calling ScanValues") nodes = append(nodes, node)
}
node := nodes[len(nodes)-1]
node.Edges.loadedTypes = loadedTypes node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values) return node.assignValues(columns, values)
} }
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, atq.driver, _spec); err != nil { if err := sqlgraph.QueryNodes(ctx, atq.driver, _spec); err != nil {
return nil, err return nil, err
} }
if len(nodes) == 0 { if len(nodes) == 0 {
return nodes, nil return nodes, nil
} }
if query := atq.withUser; query != nil { if query := atq.withUser; query != nil {
if err := atq.loadUser(ctx, query, nodes, nil,
func(n *AuthTokens, e *User) { n.Edges.User = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (atq *AuthTokensQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*AuthTokens, init func(*AuthTokens), assign func(*AuthTokens, *User)) error {
ids := make([]uuid.UUID, 0, len(nodes)) ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*AuthTokens) nodeids := make(map[uuid.UUID][]*AuthTokens)
for i := range nodes { for i := range nodes {
@ -398,20 +407,18 @@ func (atq *AuthTokensQuery) sqlAll(ctx context.Context) ([]*AuthTokens, error) {
query.Where(user.IDIn(ids...)) query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx) neighbors, err := query.All(ctx)
if err != nil { if err != nil {
return nil, err return err
} }
for _, n := range neighbors { for _, n := range neighbors {
nodes, ok := nodeids[n.ID] nodes, ok := nodeids[n.ID]
if !ok { if !ok {
return nil, fmt.Errorf(`unexpected foreign-key "user_auth_tokens" returned %v`, n.ID) return fmt.Errorf(`unexpected foreign-key "user_auth_tokens" returned %v`, n.ID)
} }
for i := range nodes { for i := range nodes {
nodes[i].Edges.User = n assign(nodes[i], n)
} }
} }
} return nil
return nodes, nil
} }
func (atq *AuthTokensQuery) sqlCount(ctx context.Context) (int, error) { func (atq *AuthTokensQuery) sqlCount(ctx context.Context) (int, error) {
@ -437,7 +444,7 @@ func (atq *AuthTokensQuery) querySpec() *sqlgraph.QuerySpec {
Table: authtokens.Table, Table: authtokens.Table,
Columns: authtokens.Columns, Columns: authtokens.Columns,
ID: &sqlgraph.FieldSpec{ ID: &sqlgraph.FieldSpec{
Type: field.TypeInt, Type: field.TypeUUID,
Column: authtokens.FieldID, Column: authtokens.FieldID,
}, },
}, },
@ -514,6 +521,7 @@ func (atq *AuthTokensQuery) sqlQuery(ctx context.Context) *sql.Selector {
// AuthTokensGroupBy is the group-by builder for AuthTokens entities. // AuthTokensGroupBy is the group-by builder for AuthTokens entities.
type AuthTokensGroupBy struct { type AuthTokensGroupBy struct {
config config
selector
fields []string fields []string
fns []AggregateFunc fns []AggregateFunc
// intermediate query (i.e. traversal path). // intermediate query (i.e. traversal path).
@ -537,209 +545,6 @@ func (atgb *AuthTokensGroupBy) Scan(ctx context.Context, v interface{}) error {
return atgb.sqlScan(ctx, v) return atgb.sqlScan(ctx, v)
} }
// ScanX is like Scan, but panics if an error occurs.
func (atgb *AuthTokensGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := atgb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by.
// It is only allowed when executing a group-by query with one field.
func (atgb *AuthTokensGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(atgb.fields) > 1 {
return nil, errors.New("ent: AuthTokensGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := atgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (atgb *AuthTokensGroupBy) StringsX(ctx context.Context) []string {
v, err := atgb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (atgb *AuthTokensGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = atgb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authtokens.Label}
default:
err = fmt.Errorf("ent: AuthTokensGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (atgb *AuthTokensGroupBy) StringX(ctx context.Context) string {
v, err := atgb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by.
// It is only allowed when executing a group-by query with one field.
func (atgb *AuthTokensGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(atgb.fields) > 1 {
return nil, errors.New("ent: AuthTokensGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := atgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (atgb *AuthTokensGroupBy) IntsX(ctx context.Context) []int {
v, err := atgb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (atgb *AuthTokensGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = atgb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authtokens.Label}
default:
err = fmt.Errorf("ent: AuthTokensGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (atgb *AuthTokensGroupBy) IntX(ctx context.Context) int {
v, err := atgb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by.
// It is only allowed when executing a group-by query with one field.
func (atgb *AuthTokensGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(atgb.fields) > 1 {
return nil, errors.New("ent: AuthTokensGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := atgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (atgb *AuthTokensGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := atgb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (atgb *AuthTokensGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = atgb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authtokens.Label}
default:
err = fmt.Errorf("ent: AuthTokensGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (atgb *AuthTokensGroupBy) Float64X(ctx context.Context) float64 {
v, err := atgb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by.
// It is only allowed when executing a group-by query with one field.
func (atgb *AuthTokensGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(atgb.fields) > 1 {
return nil, errors.New("ent: AuthTokensGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := atgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (atgb *AuthTokensGroupBy) BoolsX(ctx context.Context) []bool {
v, err := atgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (atgb *AuthTokensGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = atgb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authtokens.Label}
default:
err = fmt.Errorf("ent: AuthTokensGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (atgb *AuthTokensGroupBy) BoolX(ctx context.Context) bool {
v, err := atgb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (atgb *AuthTokensGroupBy) sqlScan(ctx context.Context, v interface{}) error { func (atgb *AuthTokensGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range atgb.fields { for _, f := range atgb.fields {
if !authtokens.ValidColumn(f) { if !authtokens.ValidColumn(f) {
@ -781,6 +586,7 @@ func (atgb *AuthTokensGroupBy) sqlQuery() *sql.Selector {
// AuthTokensSelect is the builder for selecting fields of AuthTokens entities. // AuthTokensSelect is the builder for selecting fields of AuthTokens entities.
type AuthTokensSelect struct { type AuthTokensSelect struct {
*AuthTokensQuery *AuthTokensQuery
selector
// intermediate query (i.e. traversal path). // intermediate query (i.e. traversal path).
sql *sql.Selector sql *sql.Selector
} }
@ -794,201 +600,6 @@ func (ats *AuthTokensSelect) Scan(ctx context.Context, v interface{}) error {
return ats.sqlScan(ctx, v) return ats.sqlScan(ctx, v)
} }
// ScanX is like Scan, but panics if an error occurs.
func (ats *AuthTokensSelect) ScanX(ctx context.Context, v interface{}) {
if err := ats.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (ats *AuthTokensSelect) Strings(ctx context.Context) ([]string, error) {
if len(ats.fields) > 1 {
return nil, errors.New("ent: AuthTokensSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := ats.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (ats *AuthTokensSelect) StringsX(ctx context.Context) []string {
v, err := ats.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (ats *AuthTokensSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = ats.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authtokens.Label}
default:
err = fmt.Errorf("ent: AuthTokensSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (ats *AuthTokensSelect) StringX(ctx context.Context) string {
v, err := ats.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (ats *AuthTokensSelect) Ints(ctx context.Context) ([]int, error) {
if len(ats.fields) > 1 {
return nil, errors.New("ent: AuthTokensSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := ats.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (ats *AuthTokensSelect) IntsX(ctx context.Context) []int {
v, err := ats.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (ats *AuthTokensSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = ats.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authtokens.Label}
default:
err = fmt.Errorf("ent: AuthTokensSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (ats *AuthTokensSelect) IntX(ctx context.Context) int {
v, err := ats.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (ats *AuthTokensSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(ats.fields) > 1 {
return nil, errors.New("ent: AuthTokensSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := ats.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (ats *AuthTokensSelect) Float64sX(ctx context.Context) []float64 {
v, err := ats.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (ats *AuthTokensSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = ats.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authtokens.Label}
default:
err = fmt.Errorf("ent: AuthTokensSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (ats *AuthTokensSelect) Float64X(ctx context.Context) float64 {
v, err := ats.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (ats *AuthTokensSelect) Bools(ctx context.Context) ([]bool, error) {
if len(ats.fields) > 1 {
return nil, errors.New("ent: AuthTokensSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := ats.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (ats *AuthTokensSelect) BoolsX(ctx context.Context) []bool {
v, err := ats.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (ats *AuthTokensSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = ats.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authtokens.Label}
default:
err = fmt.Errorf("ent: AuthTokensSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (ats *AuthTokensSelect) BoolX(ctx context.Context) bool {
v, err := ats.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (ats *AuthTokensSelect) sqlScan(ctx context.Context, v interface{}) error { func (ats *AuthTokensSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{} rows := &sql.Rows{}
query, args := ats.sql.Query() query, args := ats.sql.Query()

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
@ -30,6 +30,12 @@ func (atu *AuthTokensUpdate) Where(ps ...predicate.AuthTokens) *AuthTokensUpdate
return atu return atu
} }
// SetUpdatedAt sets the "updated_at" field.
func (atu *AuthTokensUpdate) SetUpdatedAt(t time.Time) *AuthTokensUpdate {
atu.mutation.SetUpdatedAt(t)
return atu
}
// SetToken sets the "token" field. // SetToken sets the "token" field.
func (atu *AuthTokensUpdate) SetToken(b []byte) *AuthTokensUpdate { func (atu *AuthTokensUpdate) SetToken(b []byte) *AuthTokensUpdate {
atu.mutation.SetToken(b) atu.mutation.SetToken(b)
@ -50,20 +56,6 @@ func (atu *AuthTokensUpdate) SetNillableExpiresAt(t *time.Time) *AuthTokensUpdat
return atu return atu
} }
// SetCreatedAt sets the "created_at" field.
func (atu *AuthTokensUpdate) SetCreatedAt(t time.Time) *AuthTokensUpdate {
atu.mutation.SetCreatedAt(t)
return atu
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (atu *AuthTokensUpdate) SetNillableCreatedAt(t *time.Time) *AuthTokensUpdate {
if t != nil {
atu.SetCreatedAt(*t)
}
return atu
}
// SetUserID sets the "user" edge to the User entity by ID. // SetUserID sets the "user" edge to the User entity by ID.
func (atu *AuthTokensUpdate) SetUserID(id uuid.UUID) *AuthTokensUpdate { func (atu *AuthTokensUpdate) SetUserID(id uuid.UUID) *AuthTokensUpdate {
atu.mutation.SetUserID(id) atu.mutation.SetUserID(id)
@ -100,6 +92,7 @@ func (atu *AuthTokensUpdate) Save(ctx context.Context) (int, error) {
err error err error
affected int affected int
) )
atu.defaults()
if len(atu.hooks) == 0 { if len(atu.hooks) == 0 {
affected, err = atu.sqlSave(ctx) affected, err = atu.sqlSave(ctx)
} else { } else {
@ -148,13 +141,21 @@ func (atu *AuthTokensUpdate) ExecX(ctx context.Context) {
} }
} }
// defaults sets the default values of the builder before save.
func (atu *AuthTokensUpdate) defaults() {
if _, ok := atu.mutation.UpdatedAt(); !ok {
v := authtokens.UpdateDefaultUpdatedAt()
atu.mutation.SetUpdatedAt(v)
}
}
func (atu *AuthTokensUpdate) sqlSave(ctx context.Context) (n int, err error) { func (atu *AuthTokensUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{ _spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{ Node: &sqlgraph.NodeSpec{
Table: authtokens.Table, Table: authtokens.Table,
Columns: authtokens.Columns, Columns: authtokens.Columns,
ID: &sqlgraph.FieldSpec{ ID: &sqlgraph.FieldSpec{
Type: field.TypeInt, Type: field.TypeUUID,
Column: authtokens.FieldID, Column: authtokens.FieldID,
}, },
}, },
@ -166,6 +167,13 @@ func (atu *AuthTokensUpdate) sqlSave(ctx context.Context) (n int, err error) {
} }
} }
} }
if value, ok := atu.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldUpdatedAt,
})
}
if value, ok := atu.mutation.Token(); ok { if value, ok := atu.mutation.Token(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes, Type: field.TypeBytes,
@ -180,13 +188,6 @@ func (atu *AuthTokensUpdate) sqlSave(ctx context.Context) (n int, err error) {
Column: authtokens.FieldExpiresAt, Column: authtokens.FieldExpiresAt,
}) })
} }
if value, ok := atu.mutation.CreatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldCreatedAt,
})
}
if atu.mutation.UserCleared() { if atu.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{ edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O, Rel: sqlgraph.M2O,
@ -226,7 +227,7 @@ func (atu *AuthTokensUpdate) sqlSave(ctx context.Context) (n int, err error) {
if _, ok := err.(*sqlgraph.NotFoundError); ok { if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{authtokens.Label} err = &NotFoundError{authtokens.Label}
} else if sqlgraph.IsConstraintError(err) { } else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err} err = &ConstraintError{msg: err.Error(), wrap: err}
} }
return 0, err return 0, err
} }
@ -241,6 +242,12 @@ type AuthTokensUpdateOne struct {
mutation *AuthTokensMutation mutation *AuthTokensMutation
} }
// SetUpdatedAt sets the "updated_at" field.
func (atuo *AuthTokensUpdateOne) SetUpdatedAt(t time.Time) *AuthTokensUpdateOne {
atuo.mutation.SetUpdatedAt(t)
return atuo
}
// SetToken sets the "token" field. // SetToken sets the "token" field.
func (atuo *AuthTokensUpdateOne) SetToken(b []byte) *AuthTokensUpdateOne { func (atuo *AuthTokensUpdateOne) SetToken(b []byte) *AuthTokensUpdateOne {
atuo.mutation.SetToken(b) atuo.mutation.SetToken(b)
@ -261,20 +268,6 @@ func (atuo *AuthTokensUpdateOne) SetNillableExpiresAt(t *time.Time) *AuthTokensU
return atuo return atuo
} }
// SetCreatedAt sets the "created_at" field.
func (atuo *AuthTokensUpdateOne) SetCreatedAt(t time.Time) *AuthTokensUpdateOne {
atuo.mutation.SetCreatedAt(t)
return atuo
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (atuo *AuthTokensUpdateOne) SetNillableCreatedAt(t *time.Time) *AuthTokensUpdateOne {
if t != nil {
atuo.SetCreatedAt(*t)
}
return atuo
}
// SetUserID sets the "user" edge to the User entity by ID. // SetUserID sets the "user" edge to the User entity by ID.
func (atuo *AuthTokensUpdateOne) SetUserID(id uuid.UUID) *AuthTokensUpdateOne { func (atuo *AuthTokensUpdateOne) SetUserID(id uuid.UUID) *AuthTokensUpdateOne {
atuo.mutation.SetUserID(id) atuo.mutation.SetUserID(id)
@ -318,6 +311,7 @@ func (atuo *AuthTokensUpdateOne) Save(ctx context.Context) (*AuthTokens, error)
err error err error
node *AuthTokens node *AuthTokens
) )
atuo.defaults()
if len(atuo.hooks) == 0 { if len(atuo.hooks) == 0 {
node, err = atuo.sqlSave(ctx) node, err = atuo.sqlSave(ctx)
} else { } else {
@ -337,9 +331,15 @@ func (atuo *AuthTokensUpdateOne) Save(ctx context.Context) (*AuthTokens, error)
} }
mut = atuo.hooks[i](mut) mut = atuo.hooks[i](mut)
} }
if _, err := mut.Mutate(ctx, atuo.mutation); err != nil { v, err := mut.Mutate(ctx, atuo.mutation)
if err != nil {
return nil, err return nil, err
} }
nv, ok := v.(*AuthTokens)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from AuthTokensMutation", v)
}
node = nv
} }
return node, err return node, err
} }
@ -366,13 +366,21 @@ func (atuo *AuthTokensUpdateOne) ExecX(ctx context.Context) {
} }
} }
// defaults sets the default values of the builder before save.
func (atuo *AuthTokensUpdateOne) defaults() {
if _, ok := atuo.mutation.UpdatedAt(); !ok {
v := authtokens.UpdateDefaultUpdatedAt()
atuo.mutation.SetUpdatedAt(v)
}
}
func (atuo *AuthTokensUpdateOne) sqlSave(ctx context.Context) (_node *AuthTokens, err error) { func (atuo *AuthTokensUpdateOne) sqlSave(ctx context.Context) (_node *AuthTokens, err error) {
_spec := &sqlgraph.UpdateSpec{ _spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{ Node: &sqlgraph.NodeSpec{
Table: authtokens.Table, Table: authtokens.Table,
Columns: authtokens.Columns, Columns: authtokens.Columns,
ID: &sqlgraph.FieldSpec{ ID: &sqlgraph.FieldSpec{
Type: field.TypeInt, Type: field.TypeUUID,
Column: authtokens.FieldID, Column: authtokens.FieldID,
}, },
}, },
@ -401,6 +409,13 @@ func (atuo *AuthTokensUpdateOne) sqlSave(ctx context.Context) (_node *AuthTokens
} }
} }
} }
if value, ok := atuo.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldUpdatedAt,
})
}
if value, ok := atuo.mutation.Token(); ok { if value, ok := atuo.mutation.Token(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes, Type: field.TypeBytes,
@ -415,13 +430,6 @@ func (atuo *AuthTokensUpdateOne) sqlSave(ctx context.Context) (_node *AuthTokens
Column: authtokens.FieldExpiresAt, Column: authtokens.FieldExpiresAt,
}) })
} }
if value, ok := atuo.mutation.CreatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldCreatedAt,
})
}
if atuo.mutation.UserCleared() { if atuo.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{ edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O, Rel: sqlgraph.M2O,
@ -464,7 +472,7 @@ func (atuo *AuthTokensUpdateOne) sqlSave(ctx context.Context) (_node *AuthTokens
if _, ok := err.(*sqlgraph.NotFoundError); ok { if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{authtokens.Label} err = &NotFoundError{authtokens.Label}
} else if sqlgraph.IsConstraintError(err) { } else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err} err = &ConstraintError{msg: err.Error(), wrap: err}
} }
return nil, err return nil, err
} }

View file

@ -1,9 +1,10 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"log" "log"
@ -11,6 +12,11 @@ import (
"github.com/hay-kot/content/backend/ent/migrate" "github.com/hay-kot/content/backend/ent/migrate"
"github.com/hay-kot/content/backend/ent/authtokens" "github.com/hay-kot/content/backend/ent/authtokens"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/itemfield"
"github.com/hay-kot/content/backend/ent/label"
"github.com/hay-kot/content/backend/ent/location"
"github.com/hay-kot/content/backend/ent/user" "github.com/hay-kot/content/backend/ent/user"
"entgo.io/ent/dialect" "entgo.io/ent/dialect"
@ -25,6 +31,16 @@ type Client struct {
Schema *migrate.Schema Schema *migrate.Schema
// AuthTokens is the client for interacting with the AuthTokens builders. // AuthTokens is the client for interacting with the AuthTokens builders.
AuthTokens *AuthTokensClient AuthTokens *AuthTokensClient
// Group is the client for interacting with the Group builders.
Group *GroupClient
// Item is the client for interacting with the Item builders.
Item *ItemClient
// ItemField is the client for interacting with the ItemField builders.
ItemField *ItemFieldClient
// Label is the client for interacting with the Label builders.
Label *LabelClient
// Location is the client for interacting with the Location builders.
Location *LocationClient
// User is the client for interacting with the User builders. // User is the client for interacting with the User builders.
User *UserClient User *UserClient
} }
@ -41,6 +57,11 @@ func NewClient(opts ...Option) *Client {
func (c *Client) init() { func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver) c.Schema = migrate.NewSchema(c.driver)
c.AuthTokens = NewAuthTokensClient(c.config) c.AuthTokens = NewAuthTokensClient(c.config)
c.Group = NewGroupClient(c.config)
c.Item = NewItemClient(c.config)
c.ItemField = NewItemFieldClient(c.config)
c.Label = NewLabelClient(c.config)
c.Location = NewLocationClient(c.config)
c.User = NewUserClient(c.config) c.User = NewUserClient(c.config)
} }
@ -64,7 +85,7 @@ func Open(driverName, dataSourceName string, options ...Option) (*Client, error)
// is used until the transaction is committed or rolled back. // is used until the transaction is committed or rolled back.
func (c *Client) Tx(ctx context.Context) (*Tx, error) { func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok { if _, ok := c.driver.(*txDriver); ok {
return nil, fmt.Errorf("ent: cannot start a transaction within a transaction") return nil, errors.New("ent: cannot start a transaction within a transaction")
} }
tx, err := newTx(ctx, c.driver) tx, err := newTx(ctx, c.driver)
if err != nil { if err != nil {
@ -76,6 +97,11 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
ctx: ctx, ctx: ctx,
config: cfg, config: cfg,
AuthTokens: NewAuthTokensClient(cfg), AuthTokens: NewAuthTokensClient(cfg),
Group: NewGroupClient(cfg),
Item: NewItemClient(cfg),
ItemField: NewItemFieldClient(cfg),
Label: NewLabelClient(cfg),
Location: NewLocationClient(cfg),
User: NewUserClient(cfg), User: NewUserClient(cfg),
}, nil }, nil
} }
@ -83,7 +109,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
// BeginTx returns a transactional client with specified options. // BeginTx returns a transactional client with specified options.
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok { if _, ok := c.driver.(*txDriver); ok {
return nil, fmt.Errorf("ent: cannot start a transaction within a transaction") return nil, errors.New("ent: cannot start a transaction within a transaction")
} }
tx, err := c.driver.(interface { tx, err := c.driver.(interface {
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
@ -97,6 +123,11 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
ctx: ctx, ctx: ctx,
config: cfg, config: cfg,
AuthTokens: NewAuthTokensClient(cfg), AuthTokens: NewAuthTokensClient(cfg),
Group: NewGroupClient(cfg),
Item: NewItemClient(cfg),
ItemField: NewItemFieldClient(cfg),
Label: NewLabelClient(cfg),
Location: NewLocationClient(cfg),
User: NewUserClient(cfg), User: NewUserClient(cfg),
}, nil }, nil
} }
@ -107,7 +138,6 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
// AuthTokens. // AuthTokens.
// Query(). // Query().
// Count(ctx) // Count(ctx)
//
func (c *Client) Debug() *Client { func (c *Client) Debug() *Client {
if c.debug { if c.debug {
return c return c
@ -128,6 +158,11 @@ func (c *Client) Close() error {
// In order to add hooks to a specific client, call: `client.Node.Use(...)`. // In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) { func (c *Client) Use(hooks ...Hook) {
c.AuthTokens.Use(hooks...) c.AuthTokens.Use(hooks...)
c.Group.Use(hooks...)
c.Item.Use(hooks...)
c.ItemField.Use(hooks...)
c.Label.Use(hooks...)
c.Location.Use(hooks...)
c.User.Use(hooks...) c.User.Use(hooks...)
} }
@ -147,7 +182,7 @@ func (c *AuthTokensClient) Use(hooks ...Hook) {
c.hooks.AuthTokens = append(c.hooks.AuthTokens, hooks...) c.hooks.AuthTokens = append(c.hooks.AuthTokens, hooks...)
} }
// Create returns a create builder for AuthTokens. // Create returns a builder for creating a AuthTokens entity.
func (c *AuthTokensClient) Create() *AuthTokensCreate { func (c *AuthTokensClient) Create() *AuthTokensCreate {
mutation := newAuthTokensMutation(c.config, OpCreate) mutation := newAuthTokensMutation(c.config, OpCreate)
return &AuthTokensCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} return &AuthTokensCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
@ -171,7 +206,7 @@ func (c *AuthTokensClient) UpdateOne(at *AuthTokens) *AuthTokensUpdateOne {
} }
// UpdateOneID returns an update builder for the given id. // UpdateOneID returns an update builder for the given id.
func (c *AuthTokensClient) UpdateOneID(id int) *AuthTokensUpdateOne { func (c *AuthTokensClient) UpdateOneID(id uuid.UUID) *AuthTokensUpdateOne {
mutation := newAuthTokensMutation(c.config, OpUpdateOne, withAuthTokensID(id)) mutation := newAuthTokensMutation(c.config, OpUpdateOne, withAuthTokensID(id))
return &AuthTokensUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} return &AuthTokensUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
} }
@ -182,13 +217,13 @@ func (c *AuthTokensClient) Delete() *AuthTokensDelete {
return &AuthTokensDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} return &AuthTokensDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
} }
// DeleteOne returns a delete builder for the given entity. // DeleteOne returns a builder for deleting the given entity.
func (c *AuthTokensClient) DeleteOne(at *AuthTokens) *AuthTokensDeleteOne { func (c *AuthTokensClient) DeleteOne(at *AuthTokens) *AuthTokensDeleteOne {
return c.DeleteOneID(at.ID) return c.DeleteOneID(at.ID)
} }
// DeleteOneID returns a delete builder for the given id. // DeleteOne returns a builder for deleting the given entity by its id.
func (c *AuthTokensClient) DeleteOneID(id int) *AuthTokensDeleteOne { func (c *AuthTokensClient) DeleteOneID(id uuid.UUID) *AuthTokensDeleteOne {
builder := c.Delete().Where(authtokens.ID(id)) builder := c.Delete().Where(authtokens.ID(id))
builder.mutation.id = &id builder.mutation.id = &id
builder.mutation.op = OpDeleteOne builder.mutation.op = OpDeleteOne
@ -203,12 +238,12 @@ func (c *AuthTokensClient) Query() *AuthTokensQuery {
} }
// Get returns a AuthTokens entity by its id. // Get returns a AuthTokens entity by its id.
func (c *AuthTokensClient) Get(ctx context.Context, id int) (*AuthTokens, error) { func (c *AuthTokensClient) Get(ctx context.Context, id uuid.UUID) (*AuthTokens, error) {
return c.Query().Where(authtokens.ID(id)).Only(ctx) return c.Query().Where(authtokens.ID(id)).Only(ctx)
} }
// GetX is like Get, but panics if an error occurs. // GetX is like Get, but panics if an error occurs.
func (c *AuthTokensClient) GetX(ctx context.Context, id int) *AuthTokens { func (c *AuthTokensClient) GetX(ctx context.Context, id uuid.UUID) *AuthTokens {
obj, err := c.Get(ctx, id) obj, err := c.Get(ctx, id)
if err != nil { if err != nil {
panic(err) panic(err)
@ -237,6 +272,664 @@ func (c *AuthTokensClient) Hooks() []Hook {
return c.hooks.AuthTokens return c.hooks.AuthTokens
} }
// GroupClient is a client for the Group schema.
type GroupClient struct {
config
}
// NewGroupClient returns a client for the Group from the given config.
func NewGroupClient(c config) *GroupClient {
return &GroupClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `group.Hooks(f(g(h())))`.
func (c *GroupClient) Use(hooks ...Hook) {
c.hooks.Group = append(c.hooks.Group, hooks...)
}
// Create returns a builder for creating a Group entity.
func (c *GroupClient) Create() *GroupCreate {
mutation := newGroupMutation(c.config, OpCreate)
return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Group entities.
func (c *GroupClient) CreateBulk(builders ...*GroupCreate) *GroupCreateBulk {
return &GroupCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Group.
func (c *GroupClient) Update() *GroupUpdate {
mutation := newGroupMutation(c.config, OpUpdate)
return &GroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *GroupClient) UpdateOne(gr *Group) *GroupUpdateOne {
mutation := newGroupMutation(c.config, OpUpdateOne, withGroup(gr))
return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *GroupClient) UpdateOneID(id uuid.UUID) *GroupUpdateOne {
mutation := newGroupMutation(c.config, OpUpdateOne, withGroupID(id))
return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Group.
func (c *GroupClient) Delete() *GroupDelete {
mutation := newGroupMutation(c.config, OpDelete)
return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne {
return c.DeleteOneID(gr.ID)
}
// DeleteOne returns a builder for deleting the given entity by its id.
func (c *GroupClient) DeleteOneID(id uuid.UUID) *GroupDeleteOne {
builder := c.Delete().Where(group.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &GroupDeleteOne{builder}
}
// Query returns a query builder for Group.
func (c *GroupClient) Query() *GroupQuery {
return &GroupQuery{
config: c.config,
}
}
// Get returns a Group entity by its id.
func (c *GroupClient) Get(ctx context.Context, id uuid.UUID) (*Group, error) {
return c.Query().Where(group.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *GroupClient) GetX(ctx context.Context, id uuid.UUID) *Group {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryUsers queries the users edge of a Group.
func (c *GroupClient) QueryUsers(gr *Group) *UserQuery {
query := &UserQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := gr.ID
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.UsersTable, group.UsersColumn),
)
fromV = sqlgraph.Neighbors(gr.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryLocations queries the locations edge of a Group.
func (c *GroupClient) QueryLocations(gr *Group) *LocationQuery {
query := &LocationQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := gr.ID
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, id),
sqlgraph.To(location.Table, location.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.LocationsTable, group.LocationsColumn),
)
fromV = sqlgraph.Neighbors(gr.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryItems queries the items edge of a Group.
func (c *GroupClient) QueryItems(gr *Group) *ItemQuery {
query := &ItemQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := gr.ID
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, id),
sqlgraph.To(item.Table, item.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.ItemsTable, group.ItemsColumn),
)
fromV = sqlgraph.Neighbors(gr.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryLabels queries the labels edge of a Group.
func (c *GroupClient) QueryLabels(gr *Group) *LabelQuery {
query := &LabelQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := gr.ID
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, id),
sqlgraph.To(label.Table, label.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.LabelsTable, group.LabelsColumn),
)
fromV = sqlgraph.Neighbors(gr.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *GroupClient) Hooks() []Hook {
return c.hooks.Group
}
// ItemClient is a client for the Item schema.
type ItemClient struct {
config
}
// NewItemClient returns a client for the Item from the given config.
func NewItemClient(c config) *ItemClient {
return &ItemClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `item.Hooks(f(g(h())))`.
func (c *ItemClient) Use(hooks ...Hook) {
c.hooks.Item = append(c.hooks.Item, hooks...)
}
// Create returns a builder for creating a Item entity.
func (c *ItemClient) Create() *ItemCreate {
mutation := newItemMutation(c.config, OpCreate)
return &ItemCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Item entities.
func (c *ItemClient) CreateBulk(builders ...*ItemCreate) *ItemCreateBulk {
return &ItemCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Item.
func (c *ItemClient) Update() *ItemUpdate {
mutation := newItemMutation(c.config, OpUpdate)
return &ItemUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *ItemClient) UpdateOne(i *Item) *ItemUpdateOne {
mutation := newItemMutation(c.config, OpUpdateOne, withItem(i))
return &ItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *ItemClient) UpdateOneID(id uuid.UUID) *ItemUpdateOne {
mutation := newItemMutation(c.config, OpUpdateOne, withItemID(id))
return &ItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Item.
func (c *ItemClient) Delete() *ItemDelete {
mutation := newItemMutation(c.config, OpDelete)
return &ItemDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *ItemClient) DeleteOne(i *Item) *ItemDeleteOne {
return c.DeleteOneID(i.ID)
}
// DeleteOne returns a builder for deleting the given entity by its id.
func (c *ItemClient) DeleteOneID(id uuid.UUID) *ItemDeleteOne {
builder := c.Delete().Where(item.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &ItemDeleteOne{builder}
}
// Query returns a query builder for Item.
func (c *ItemClient) Query() *ItemQuery {
return &ItemQuery{
config: c.config,
}
}
// Get returns a Item entity by its id.
func (c *ItemClient) Get(ctx context.Context, id uuid.UUID) (*Item, error) {
return c.Query().Where(item.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *ItemClient) GetX(ctx context.Context, id uuid.UUID) *Item {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryGroup queries the group edge of a Item.
func (c *ItemClient) QueryGroup(i *Item) *GroupQuery {
query := &GroupQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := i.ID
step := sqlgraph.NewStep(
sqlgraph.From(item.Table, item.FieldID, id),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, item.GroupTable, item.GroupColumn),
)
fromV = sqlgraph.Neighbors(i.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryLocation queries the location edge of a Item.
func (c *ItemClient) QueryLocation(i *Item) *LocationQuery {
query := &LocationQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := i.ID
step := sqlgraph.NewStep(
sqlgraph.From(item.Table, item.FieldID, id),
sqlgraph.To(location.Table, location.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, item.LocationTable, item.LocationColumn),
)
fromV = sqlgraph.Neighbors(i.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryFields queries the fields edge of a Item.
func (c *ItemClient) QueryFields(i *Item) *ItemFieldQuery {
query := &ItemFieldQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := i.ID
step := sqlgraph.NewStep(
sqlgraph.From(item.Table, item.FieldID, id),
sqlgraph.To(itemfield.Table, itemfield.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, item.FieldsTable, item.FieldsColumn),
)
fromV = sqlgraph.Neighbors(i.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryLabel queries the label edge of a Item.
func (c *ItemClient) QueryLabel(i *Item) *LabelQuery {
query := &LabelQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := i.ID
step := sqlgraph.NewStep(
sqlgraph.From(item.Table, item.FieldID, id),
sqlgraph.To(label.Table, label.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, item.LabelTable, item.LabelPrimaryKey...),
)
fromV = sqlgraph.Neighbors(i.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *ItemClient) Hooks() []Hook {
return c.hooks.Item
}
// ItemFieldClient is a client for the ItemField schema.
type ItemFieldClient struct {
config
}
// NewItemFieldClient returns a client for the ItemField from the given config.
func NewItemFieldClient(c config) *ItemFieldClient {
return &ItemFieldClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `itemfield.Hooks(f(g(h())))`.
func (c *ItemFieldClient) Use(hooks ...Hook) {
c.hooks.ItemField = append(c.hooks.ItemField, hooks...)
}
// Create returns a builder for creating a ItemField entity.
func (c *ItemFieldClient) Create() *ItemFieldCreate {
mutation := newItemFieldMutation(c.config, OpCreate)
return &ItemFieldCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of ItemField entities.
func (c *ItemFieldClient) CreateBulk(builders ...*ItemFieldCreate) *ItemFieldCreateBulk {
return &ItemFieldCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for ItemField.
func (c *ItemFieldClient) Update() *ItemFieldUpdate {
mutation := newItemFieldMutation(c.config, OpUpdate)
return &ItemFieldUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *ItemFieldClient) UpdateOne(_if *ItemField) *ItemFieldUpdateOne {
mutation := newItemFieldMutation(c.config, OpUpdateOne, withItemField(_if))
return &ItemFieldUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *ItemFieldClient) UpdateOneID(id uuid.UUID) *ItemFieldUpdateOne {
mutation := newItemFieldMutation(c.config, OpUpdateOne, withItemFieldID(id))
return &ItemFieldUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for ItemField.
func (c *ItemFieldClient) Delete() *ItemFieldDelete {
mutation := newItemFieldMutation(c.config, OpDelete)
return &ItemFieldDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *ItemFieldClient) DeleteOne(_if *ItemField) *ItemFieldDeleteOne {
return c.DeleteOneID(_if.ID)
}
// DeleteOne returns a builder for deleting the given entity by its id.
func (c *ItemFieldClient) DeleteOneID(id uuid.UUID) *ItemFieldDeleteOne {
builder := c.Delete().Where(itemfield.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &ItemFieldDeleteOne{builder}
}
// Query returns a query builder for ItemField.
func (c *ItemFieldClient) Query() *ItemFieldQuery {
return &ItemFieldQuery{
config: c.config,
}
}
// Get returns a ItemField entity by its id.
func (c *ItemFieldClient) Get(ctx context.Context, id uuid.UUID) (*ItemField, error) {
return c.Query().Where(itemfield.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *ItemFieldClient) GetX(ctx context.Context, id uuid.UUID) *ItemField {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryItem queries the item edge of a ItemField.
func (c *ItemFieldClient) QueryItem(_if *ItemField) *ItemQuery {
query := &ItemQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := _if.ID
step := sqlgraph.NewStep(
sqlgraph.From(itemfield.Table, itemfield.FieldID, id),
sqlgraph.To(item.Table, item.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, itemfield.ItemTable, itemfield.ItemColumn),
)
fromV = sqlgraph.Neighbors(_if.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *ItemFieldClient) Hooks() []Hook {
return c.hooks.ItemField
}
// LabelClient is a client for the Label schema.
type LabelClient struct {
config
}
// NewLabelClient returns a client for the Label from the given config.
func NewLabelClient(c config) *LabelClient {
return &LabelClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `label.Hooks(f(g(h())))`.
func (c *LabelClient) Use(hooks ...Hook) {
c.hooks.Label = append(c.hooks.Label, hooks...)
}
// Create returns a builder for creating a Label entity.
func (c *LabelClient) Create() *LabelCreate {
mutation := newLabelMutation(c.config, OpCreate)
return &LabelCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Label entities.
func (c *LabelClient) CreateBulk(builders ...*LabelCreate) *LabelCreateBulk {
return &LabelCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Label.
func (c *LabelClient) Update() *LabelUpdate {
mutation := newLabelMutation(c.config, OpUpdate)
return &LabelUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *LabelClient) UpdateOne(l *Label) *LabelUpdateOne {
mutation := newLabelMutation(c.config, OpUpdateOne, withLabel(l))
return &LabelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *LabelClient) UpdateOneID(id uuid.UUID) *LabelUpdateOne {
mutation := newLabelMutation(c.config, OpUpdateOne, withLabelID(id))
return &LabelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Label.
func (c *LabelClient) Delete() *LabelDelete {
mutation := newLabelMutation(c.config, OpDelete)
return &LabelDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *LabelClient) DeleteOne(l *Label) *LabelDeleteOne {
return c.DeleteOneID(l.ID)
}
// DeleteOne returns a builder for deleting the given entity by its id.
func (c *LabelClient) DeleteOneID(id uuid.UUID) *LabelDeleteOne {
builder := c.Delete().Where(label.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &LabelDeleteOne{builder}
}
// Query returns a query builder for Label.
func (c *LabelClient) Query() *LabelQuery {
return &LabelQuery{
config: c.config,
}
}
// Get returns a Label entity by its id.
func (c *LabelClient) Get(ctx context.Context, id uuid.UUID) (*Label, error) {
return c.Query().Where(label.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *LabelClient) GetX(ctx context.Context, id uuid.UUID) *Label {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryGroup queries the group edge of a Label.
func (c *LabelClient) QueryGroup(l *Label) *GroupQuery {
query := &GroupQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := l.ID
step := sqlgraph.NewStep(
sqlgraph.From(label.Table, label.FieldID, id),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, label.GroupTable, label.GroupColumn),
)
fromV = sqlgraph.Neighbors(l.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryItems queries the items edge of a Label.
func (c *LabelClient) QueryItems(l *Label) *ItemQuery {
query := &ItemQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := l.ID
step := sqlgraph.NewStep(
sqlgraph.From(label.Table, label.FieldID, id),
sqlgraph.To(item.Table, item.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, label.ItemsTable, label.ItemsPrimaryKey...),
)
fromV = sqlgraph.Neighbors(l.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *LabelClient) Hooks() []Hook {
return c.hooks.Label
}
// LocationClient is a client for the Location schema.
type LocationClient struct {
config
}
// NewLocationClient returns a client for the Location from the given config.
func NewLocationClient(c config) *LocationClient {
return &LocationClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `location.Hooks(f(g(h())))`.
func (c *LocationClient) Use(hooks ...Hook) {
c.hooks.Location = append(c.hooks.Location, hooks...)
}
// Create returns a builder for creating a Location entity.
func (c *LocationClient) Create() *LocationCreate {
mutation := newLocationMutation(c.config, OpCreate)
return &LocationCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Location entities.
func (c *LocationClient) CreateBulk(builders ...*LocationCreate) *LocationCreateBulk {
return &LocationCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Location.
func (c *LocationClient) Update() *LocationUpdate {
mutation := newLocationMutation(c.config, OpUpdate)
return &LocationUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *LocationClient) UpdateOne(l *Location) *LocationUpdateOne {
mutation := newLocationMutation(c.config, OpUpdateOne, withLocation(l))
return &LocationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *LocationClient) UpdateOneID(id uuid.UUID) *LocationUpdateOne {
mutation := newLocationMutation(c.config, OpUpdateOne, withLocationID(id))
return &LocationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Location.
func (c *LocationClient) Delete() *LocationDelete {
mutation := newLocationMutation(c.config, OpDelete)
return &LocationDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *LocationClient) DeleteOne(l *Location) *LocationDeleteOne {
return c.DeleteOneID(l.ID)
}
// DeleteOne returns a builder for deleting the given entity by its id.
func (c *LocationClient) DeleteOneID(id uuid.UUID) *LocationDeleteOne {
builder := c.Delete().Where(location.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &LocationDeleteOne{builder}
}
// Query returns a query builder for Location.
func (c *LocationClient) Query() *LocationQuery {
return &LocationQuery{
config: c.config,
}
}
// Get returns a Location entity by its id.
func (c *LocationClient) Get(ctx context.Context, id uuid.UUID) (*Location, error) {
return c.Query().Where(location.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *LocationClient) GetX(ctx context.Context, id uuid.UUID) *Location {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryGroup queries the group edge of a Location.
func (c *LocationClient) QueryGroup(l *Location) *GroupQuery {
query := &GroupQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := l.ID
step := sqlgraph.NewStep(
sqlgraph.From(location.Table, location.FieldID, id),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, location.GroupTable, location.GroupColumn),
)
fromV = sqlgraph.Neighbors(l.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryItems queries the items edge of a Location.
func (c *LocationClient) QueryItems(l *Location) *ItemQuery {
query := &ItemQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := l.ID
step := sqlgraph.NewStep(
sqlgraph.From(location.Table, location.FieldID, id),
sqlgraph.To(item.Table, item.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, location.ItemsTable, location.ItemsColumn),
)
fromV = sqlgraph.Neighbors(l.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *LocationClient) Hooks() []Hook {
return c.hooks.Location
}
// UserClient is a client for the User schema. // UserClient is a client for the User schema.
type UserClient struct { type UserClient struct {
config config
@ -253,7 +946,7 @@ func (c *UserClient) Use(hooks ...Hook) {
c.hooks.User = append(c.hooks.User, hooks...) c.hooks.User = append(c.hooks.User, hooks...)
} }
// Create returns a create builder for User. // Create returns a builder for creating a User entity.
func (c *UserClient) Create() *UserCreate { func (c *UserClient) Create() *UserCreate {
mutation := newUserMutation(c.config, OpCreate) mutation := newUserMutation(c.config, OpCreate)
return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
@ -288,12 +981,12 @@ func (c *UserClient) Delete() *UserDelete {
return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
} }
// DeleteOne returns a delete builder for the given entity. // DeleteOne returns a builder for deleting the given entity.
func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { func (c *UserClient) DeleteOne(u *User) *UserDeleteOne {
return c.DeleteOneID(u.ID) return c.DeleteOneID(u.ID)
} }
// DeleteOneID returns a delete builder for the given id. // DeleteOne returns a builder for deleting the given entity by its id.
func (c *UserClient) DeleteOneID(id uuid.UUID) *UserDeleteOne { func (c *UserClient) DeleteOneID(id uuid.UUID) *UserDeleteOne {
builder := c.Delete().Where(user.ID(id)) builder := c.Delete().Where(user.ID(id))
builder.mutation.id = &id builder.mutation.id = &id
@ -322,6 +1015,22 @@ func (c *UserClient) GetX(ctx context.Context, id uuid.UUID) *User {
return obj return obj
} }
// QueryGroup queries the group edge of a User.
func (c *UserClient) QueryGroup(u *User) *GroupQuery {
query := &GroupQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := u.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, user.GroupTable, user.GroupColumn),
)
fromV = sqlgraph.Neighbors(u.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryAuthTokens queries the auth_tokens edge of a User. // QueryAuthTokens queries the auth_tokens edge of a User.
func (c *UserClient) QueryAuthTokens(u *User) *AuthTokensQuery { func (c *UserClient) QueryAuthTokens(u *User) *AuthTokensQuery {
query := &AuthTokensQuery{config: c.config} query := &AuthTokensQuery{config: c.config}

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
@ -25,6 +25,11 @@ type config struct {
// hooks per client, for fast access. // hooks per client, for fast access.
type hooks struct { type hooks struct {
AuthTokens []ent.Hook AuthTokens []ent.Hook
Group []ent.Hook
Item []ent.Hook
ItemField []ent.Hook
Label []ent.Hook
Location []ent.Hook
User []ent.Hook User []ent.Hook
} }

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent

View file

@ -1,14 +1,21 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"entgo.io/ent" "entgo.io/ent"
"entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/hay-kot/content/backend/ent/authtokens" "github.com/hay-kot/content/backend/ent/authtokens"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/itemfield"
"github.com/hay-kot/content/backend/ent/label"
"github.com/hay-kot/content/backend/ent/location"
"github.com/hay-kot/content/backend/ent/user" "github.com/hay-kot/content/backend/ent/user"
) )
@ -31,6 +38,11 @@ type OrderFunc func(*sql.Selector)
func columnChecker(table string) func(string) error { func columnChecker(table string) func(string) error {
checks := map[string]func(string) bool{ checks := map[string]func(string) bool{
authtokens.Table: authtokens.ValidColumn, authtokens.Table: authtokens.ValidColumn,
group.Table: group.ValidColumn,
item.Table: item.ValidColumn,
itemfield.Table: itemfield.ValidColumn,
label.Table: label.ValidColumn,
location.Table: location.ValidColumn,
user.Table: user.ValidColumn, user.Table: user.ValidColumn,
} }
check, ok := checks[table] check, ok := checks[table]
@ -81,7 +93,6 @@ type AggregateFunc func(*sql.Selector) string
// GroupBy(field1, field2). // GroupBy(field1, field2).
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")). // Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
// Scan(ctx, &v) // Scan(ctx, &v)
//
func As(fn AggregateFunc, end string) AggregateFunc { func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string { return func(s *sql.Selector) string {
return sql.As(fn(s), end) return sql.As(fn(s), end)
@ -259,3 +270,208 @@ func IsConstraintError(err error) bool {
var e *ConstraintError var e *ConstraintError
return errors.As(err, &e) return errors.As(err, &e)
} }
// selector embedded by the different Select/GroupBy builders.
type selector struct {
label string
flds *[]string
scan func(context.Context, interface{}) error
}
// ScanX is like Scan, but panics if an error occurs.
func (s *selector) ScanX(ctx context.Context, v interface{}) {
if err := s.scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (s *selector) Strings(ctx context.Context) ([]string, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (s *selector) StringsX(ctx context.Context) []string {
v, err := s.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (s *selector) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = s.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (s *selector) StringX(ctx context.Context) string {
v, err := s.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (s *selector) Ints(ctx context.Context) ([]int, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (s *selector) IntsX(ctx context.Context) []int {
v, err := s.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (s *selector) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = s.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (s *selector) IntX(ctx context.Context) int {
v, err := s.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (s *selector) Float64sX(ctx context.Context) []float64 {
v, err := s.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = s.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (s *selector) Float64X(ctx context.Context) float64 {
v, err := s.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (s *selector) BoolsX(ctx context.Context) []bool {
v, err := s.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = s.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (s *selector) BoolX(ctx context.Context) bool {
v, err := s.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
// queryHook describes an internal hook for the different sqlAll methods.
type queryHook func(context.Context, *sqlgraph.QuerySpec)

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package enttest package enttest
@ -10,6 +10,7 @@ import (
_ "github.com/hay-kot/content/backend/ent/runtime" _ "github.com/hay-kot/content/backend/ent/runtime"
"entgo.io/ent/dialect/sql/schema" "entgo.io/ent/dialect/sql/schema"
"github.com/hay-kot/content/backend/ent/migrate"
) )
type ( type (
@ -59,10 +60,7 @@ func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Cl
t.Error(err) t.Error(err)
t.FailNow() t.FailNow()
} }
if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { migrateSchema(t, c, o)
t.Error(err)
t.FailNow()
}
return c return c
} }
@ -70,9 +68,17 @@ func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Cl
func NewClient(t TestingT, opts ...Option) *ent.Client { func NewClient(t TestingT, opts ...Option) *ent.Client {
o := newOptions(opts) o := newOptions(opts)
c := ent.NewClient(o.opts...) c := ent.NewClient(o.opts...)
if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { migrateSchema(t, c, o)
return c
}
func migrateSchema(t TestingT, c *ent.Client, o *options) {
tables, err := schema.CopyTables(migrate.Tables)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil {
t.Error(err) t.Error(err)
t.FailNow() t.FailNow()
} }
return c
} }

210
backend/ent/group.go Normal file
View file

@ -0,0 +1,210 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
)
// Group is the model entity for the Group schema.
type Group struct {
config `json:"-"`
// ID of the ent.
ID uuid.UUID `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Currency holds the value of the "currency" field.
Currency group.Currency `json:"currency,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the GroupQuery when eager-loading is set.
Edges GroupEdges `json:"edges"`
}
// GroupEdges holds the relations/edges for other nodes in the graph.
type GroupEdges struct {
// Users holds the value of the users edge.
Users []*User `json:"users,omitempty"`
// Locations holds the value of the locations edge.
Locations []*Location `json:"locations,omitempty"`
// Items holds the value of the items edge.
Items []*Item `json:"items,omitempty"`
// Labels holds the value of the labels edge.
Labels []*Label `json:"labels,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [4]bool
}
// UsersOrErr returns the Users value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) UsersOrErr() ([]*User, error) {
if e.loadedTypes[0] {
return e.Users, nil
}
return nil, &NotLoadedError{edge: "users"}
}
// LocationsOrErr returns the Locations value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) LocationsOrErr() ([]*Location, error) {
if e.loadedTypes[1] {
return e.Locations, nil
}
return nil, &NotLoadedError{edge: "locations"}
}
// ItemsOrErr returns the Items value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) ItemsOrErr() ([]*Item, error) {
if e.loadedTypes[2] {
return e.Items, nil
}
return nil, &NotLoadedError{edge: "items"}
}
// LabelsOrErr returns the Labels value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) LabelsOrErr() ([]*Label, error) {
if e.loadedTypes[3] {
return e.Labels, nil
}
return nil, &NotLoadedError{edge: "labels"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Group) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case group.FieldName, group.FieldCurrency:
values[i] = new(sql.NullString)
case group.FieldCreatedAt, group.FieldUpdatedAt:
values[i] = new(sql.NullTime)
case group.FieldID:
values[i] = new(uuid.UUID)
default:
return nil, fmt.Errorf("unexpected column %q for type Group", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Group fields.
func (gr *Group) assignValues(columns []string, values []interface{}) 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 group.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
gr.ID = *value
}
case group.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
gr.CreatedAt = value.Time
}
case group.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
gr.UpdatedAt = value.Time
}
case group.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
gr.Name = value.String
}
case group.FieldCurrency:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field currency", values[i])
} else if value.Valid {
gr.Currency = group.Currency(value.String)
}
}
}
return nil
}
// QueryUsers queries the "users" edge of the Group entity.
func (gr *Group) QueryUsers() *UserQuery {
return (&GroupClient{config: gr.config}).QueryUsers(gr)
}
// QueryLocations queries the "locations" edge of the Group entity.
func (gr *Group) QueryLocations() *LocationQuery {
return (&GroupClient{config: gr.config}).QueryLocations(gr)
}
// QueryItems queries the "items" edge of the Group entity.
func (gr *Group) QueryItems() *ItemQuery {
return (&GroupClient{config: gr.config}).QueryItems(gr)
}
// QueryLabels queries the "labels" edge of the Group entity.
func (gr *Group) QueryLabels() *LabelQuery {
return (&GroupClient{config: gr.config}).QueryLabels(gr)
}
// Update returns a builder for updating this Group.
// Note that you need to call Group.Unwrap() before calling this method if this Group
// was returned from a transaction, and the transaction was committed or rolled back.
func (gr *Group) Update() *GroupUpdateOne {
return (&GroupClient{config: gr.config}).UpdateOne(gr)
}
// Unwrap unwraps the Group 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 (gr *Group) Unwrap() *Group {
_tx, ok := gr.config.driver.(*txDriver)
if !ok {
panic("ent: Group is not a transactional entity")
}
gr.config.driver = _tx.drv
return gr
}
// String implements the fmt.Stringer.
func (gr *Group) String() string {
var builder strings.Builder
builder.WriteString("Group(")
builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID))
builder.WriteString("created_at=")
builder.WriteString(gr.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(gr.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(gr.Name)
builder.WriteString(", ")
builder.WriteString("currency=")
builder.WriteString(fmt.Sprintf("%v", gr.Currency))
builder.WriteByte(')')
return builder.String()
}
// Groups is a parsable slice of Group.
type Groups []*Group
func (gr Groups) config(cfg config) {
for _i := range gr {
gr[_i].config = cfg
}
}

120
backend/ent/group/group.go Normal file
View file

@ -0,0 +1,120 @@
// Code generated by ent, DO NOT EDIT.
package group
import (
"fmt"
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the group type in the database.
Label = "group"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldCurrency holds the string denoting the currency field in the database.
FieldCurrency = "currency"
// EdgeUsers holds the string denoting the users edge name in mutations.
EdgeUsers = "users"
// EdgeLocations holds the string denoting the locations edge name in mutations.
EdgeLocations = "locations"
// EdgeItems holds the string denoting the items edge name in mutations.
EdgeItems = "items"
// EdgeLabels holds the string denoting the labels edge name in mutations.
EdgeLabels = "labels"
// Table holds the table name of the group in the database.
Table = "groups"
// UsersTable is the table that holds the users relation/edge.
UsersTable = "users"
// UsersInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UsersInverseTable = "users"
// UsersColumn is the table column denoting the users relation/edge.
UsersColumn = "group_users"
// LocationsTable is the table that holds the locations relation/edge.
LocationsTable = "locations"
// LocationsInverseTable is the table name for the Location entity.
// It exists in this package in order to avoid circular dependency with the "location" package.
LocationsInverseTable = "locations"
// LocationsColumn is the table column denoting the locations relation/edge.
LocationsColumn = "group_locations"
// ItemsTable is the table that holds the items relation/edge.
ItemsTable = "items"
// ItemsInverseTable is the table name for the Item entity.
// It exists in this package in order to avoid circular dependency with the "item" package.
ItemsInverseTable = "items"
// ItemsColumn is the table column denoting the items relation/edge.
ItemsColumn = "group_items"
// LabelsTable is the table that holds the labels relation/edge.
LabelsTable = "labels"
// LabelsInverseTable is the table name for the Label entity.
// It exists in this package in order to avoid circular dependency with the "label" package.
LabelsInverseTable = "labels"
// LabelsColumn is the table column denoting the labels relation/edge.
LabelsColumn = "group_labels"
)
// Columns holds all SQL columns for group fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldName,
FieldCurrency,
}
// 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 (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)
// Currency defines the type for the "currency" enum field.
type Currency string
// CurrencyUsd is the default value of the Currency enum.
const DefaultCurrency = CurrencyUsd
// Currency values.
const (
CurrencyUsd Currency = "usd"
)
func (c Currency) String() string {
return string(c)
}
// CurrencyValidator is a validator for the "currency" field enum values. It is called by the builders before save.
func CurrencyValidator(c Currency) error {
switch c {
case CurrencyUsd:
return nil
default:
return fmt.Errorf("group: invalid enum value for currency field: %q", c)
}
}

511
backend/ent/group/where.go Normal file
View file

@ -0,0 +1,511 @@
// Code generated by ent, DO NOT EDIT.
package group
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id uuid.UUID) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id uuid.UUID) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id uuid.UUID) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...uuid.UUID) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...uuid.UUID) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id uuid.UUID) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id uuid.UUID) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id uuid.UUID) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id uuid.UUID) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
})
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
})
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldCreatedAt), v))
})
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Group {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldCreatedAt), v...))
})
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Group {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldCreatedAt), v...))
})
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldCreatedAt), v))
})
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.Group {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldUpdatedAt), v...))
})
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.Group {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...))
})
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldName), v...))
})
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Group {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldName), v...))
})
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldName), v))
})
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Group {
return predicate.Group(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.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldName), v))
})
}
// CurrencyEQ applies the EQ predicate on the "currency" field.
func CurrencyEQ(v Currency) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCurrency), v))
})
}
// CurrencyNEQ applies the NEQ predicate on the "currency" field.
func CurrencyNEQ(v Currency) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldCurrency), v))
})
}
// CurrencyIn applies the In predicate on the "currency" field.
func CurrencyIn(vs ...Currency) predicate.Group {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldCurrency), v...))
})
}
// CurrencyNotIn applies the NotIn predicate on the "currency" field.
func CurrencyNotIn(vs ...Currency) predicate.Group {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldCurrency), v...))
})
}
// HasUsers applies the HasEdge predicate on the "users" edge.
func HasUsers() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsersTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsersTable, UsersColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUsersWith applies the HasEdge predicate on the "users" edge with a given conditions (other predicates).
func HasUsersWith(preds ...predicate.User) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsersInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsersTable, UsersColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasLocations applies the HasEdge predicate on the "locations" edge.
func HasLocations() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(LocationsTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, LocationsTable, LocationsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasLocationsWith applies the HasEdge predicate on the "locations" edge with a given conditions (other predicates).
func HasLocationsWith(preds ...predicate.Location) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(LocationsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, LocationsTable, LocationsColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasItems applies the HasEdge predicate on the "items" edge.
func HasItems() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemsTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ItemsTable, ItemsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasItemsWith applies the HasEdge predicate on the "items" edge with a given conditions (other predicates).
func HasItemsWith(preds ...predicate.Item) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ItemsTable, ItemsColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasLabels applies the HasEdge predicate on the "labels" edge.
func HasLabels() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(LabelsTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, LabelsTable, LabelsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasLabelsWith applies the HasEdge predicate on the "labels" edge with a given conditions (other predicates).
func HasLabelsWith(preds ...predicate.Label) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(LabelsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, LabelsTable, LabelsColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Group) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Group) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Group) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
p(s.Not())
})
}

494
backend/ent/group_create.go Normal file
View file

@ -0,0 +1,494 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/label"
"github.com/hay-kot/content/backend/ent/location"
"github.com/hay-kot/content/backend/ent/user"
)
// GroupCreate is the builder for creating a Group entity.
type GroupCreate struct {
config
mutation *GroupMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (gc *GroupCreate) SetCreatedAt(t time.Time) *GroupCreate {
gc.mutation.SetCreatedAt(t)
return gc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (gc *GroupCreate) SetNillableCreatedAt(t *time.Time) *GroupCreate {
if t != nil {
gc.SetCreatedAt(*t)
}
return gc
}
// SetUpdatedAt sets the "updated_at" field.
func (gc *GroupCreate) SetUpdatedAt(t time.Time) *GroupCreate {
gc.mutation.SetUpdatedAt(t)
return gc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (gc *GroupCreate) SetNillableUpdatedAt(t *time.Time) *GroupCreate {
if t != nil {
gc.SetUpdatedAt(*t)
}
return gc
}
// SetName sets the "name" field.
func (gc *GroupCreate) SetName(s string) *GroupCreate {
gc.mutation.SetName(s)
return gc
}
// SetCurrency sets the "currency" field.
func (gc *GroupCreate) SetCurrency(gr group.Currency) *GroupCreate {
gc.mutation.SetCurrency(gr)
return gc
}
// SetNillableCurrency sets the "currency" field if the given value is not nil.
func (gc *GroupCreate) SetNillableCurrency(gr *group.Currency) *GroupCreate {
if gr != nil {
gc.SetCurrency(*gr)
}
return gc
}
// SetID sets the "id" field.
func (gc *GroupCreate) SetID(u uuid.UUID) *GroupCreate {
gc.mutation.SetID(u)
return gc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (gc *GroupCreate) SetNillableID(u *uuid.UUID) *GroupCreate {
if u != nil {
gc.SetID(*u)
}
return gc
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (gc *GroupCreate) AddUserIDs(ids ...uuid.UUID) *GroupCreate {
gc.mutation.AddUserIDs(ids...)
return gc
}
// AddUsers adds the "users" edges to the User entity.
func (gc *GroupCreate) AddUsers(u ...*User) *GroupCreate {
ids := make([]uuid.UUID, len(u))
for i := range u {
ids[i] = u[i].ID
}
return gc.AddUserIDs(ids...)
}
// AddLocationIDs adds the "locations" edge to the Location entity by IDs.
func (gc *GroupCreate) AddLocationIDs(ids ...uuid.UUID) *GroupCreate {
gc.mutation.AddLocationIDs(ids...)
return gc
}
// AddLocations adds the "locations" edges to the Location entity.
func (gc *GroupCreate) AddLocations(l ...*Location) *GroupCreate {
ids := make([]uuid.UUID, len(l))
for i := range l {
ids[i] = l[i].ID
}
return gc.AddLocationIDs(ids...)
}
// AddItemIDs adds the "items" edge to the Item entity by IDs.
func (gc *GroupCreate) AddItemIDs(ids ...uuid.UUID) *GroupCreate {
gc.mutation.AddItemIDs(ids...)
return gc
}
// AddItems adds the "items" edges to the Item entity.
func (gc *GroupCreate) AddItems(i ...*Item) *GroupCreate {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return gc.AddItemIDs(ids...)
}
// AddLabelIDs adds the "labels" edge to the Label entity by IDs.
func (gc *GroupCreate) AddLabelIDs(ids ...uuid.UUID) *GroupCreate {
gc.mutation.AddLabelIDs(ids...)
return gc
}
// AddLabels adds the "labels" edges to the Label entity.
func (gc *GroupCreate) AddLabels(l ...*Label) *GroupCreate {
ids := make([]uuid.UUID, len(l))
for i := range l {
ids[i] = l[i].ID
}
return gc.AddLabelIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (gc *GroupCreate) Mutation() *GroupMutation {
return gc.mutation
}
// Save creates the Group in the database.
func (gc *GroupCreate) Save(ctx context.Context) (*Group, error) {
var (
err error
node *Group
)
gc.defaults()
if len(gc.hooks) == 0 {
if err = gc.check(); err != nil {
return nil, err
}
node, err = gc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = gc.check(); err != nil {
return nil, err
}
gc.mutation = mutation
if node, err = gc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(gc.hooks) - 1; i >= 0; i-- {
if gc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = gc.hooks[i](mut)
}
v, err := mut.Mutate(ctx, gc.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Group)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from GroupMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (gc *GroupCreate) SaveX(ctx context.Context) *Group {
v, err := gc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (gc *GroupCreate) Exec(ctx context.Context) error {
_, err := gc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gc *GroupCreate) ExecX(ctx context.Context) {
if err := gc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (gc *GroupCreate) defaults() {
if _, ok := gc.mutation.CreatedAt(); !ok {
v := group.DefaultCreatedAt()
gc.mutation.SetCreatedAt(v)
}
if _, ok := gc.mutation.UpdatedAt(); !ok {
v := group.DefaultUpdatedAt()
gc.mutation.SetUpdatedAt(v)
}
if _, ok := gc.mutation.Currency(); !ok {
v := group.DefaultCurrency
gc.mutation.SetCurrency(v)
}
if _, ok := gc.mutation.ID(); !ok {
v := group.DefaultID()
gc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (gc *GroupCreate) check() error {
if _, ok := gc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Group.created_at"`)}
}
if _, ok := gc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Group.updated_at"`)}
}
if _, ok := gc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Group.name"`)}
}
if v, ok := gc.mutation.Name(); ok {
if err := group.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Group.name": %w`, err)}
}
}
if _, ok := gc.mutation.Currency(); !ok {
return &ValidationError{Name: "currency", err: errors.New(`ent: missing required field "Group.currency"`)}
}
if v, ok := gc.mutation.Currency(); ok {
if err := group.CurrencyValidator(v); err != nil {
return &ValidationError{Name: "currency", err: fmt.Errorf(`ent: validator failed for field "Group.currency": %w`, err)}
}
}
return nil
}
func (gc *GroupCreate) sqlSave(ctx context.Context) (*Group, error) {
_node, _spec := gc.createSpec()
if err := sqlgraph.CreateNode(ctx, gc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
if _spec.ID.Value != nil {
if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
_node.ID = *id
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
return nil, err
}
}
return _node, nil
}
func (gc *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
var (
_node = &Group{config: gc.config}
_spec = &sqlgraph.CreateSpec{
Table: group.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
}
)
if id, ok := gc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := gc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: group.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := gc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: group.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := gc.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: group.FieldName,
})
_node.Name = value
}
if value, ok := gc.mutation.Currency(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeEnum,
Value: value,
Column: group.FieldCurrency,
})
_node.Currency = value
}
if nodes := gc.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.UsersTable,
Columns: []string{group.UsersColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: user.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := gc.mutation.LocationsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.LocationsTable,
Columns: []string{group.LocationsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: location.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := gc.mutation.ItemsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.ItemsTable,
Columns: []string{group.ItemsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := gc.mutation.LabelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.LabelsTable,
Columns: []string{group.LabelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: label.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// GroupCreateBulk is the builder for creating many Group entities in bulk.
type GroupCreateBulk struct {
config
builders []*GroupCreate
}
// Save creates the Group entities in the database.
func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) {
specs := make([]*sqlgraph.CreateSpec, len(gcb.builders))
nodes := make([]*Group, len(gcb.builders))
mutators := make([]Mutator, len(gcb.builders))
for i := range gcb.builders {
func(i int, root context.Context) {
builder := gcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, gcb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, gcb.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
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, gcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (gcb *GroupCreateBulk) SaveX(ctx context.Context) []*Group {
v, err := gcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (gcb *GroupCreateBulk) Exec(ctx context.Context) error {
_, err := gcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gcb *GroupCreateBulk) ExecX(ctx context.Context) {
if err := gcb.Exec(ctx); err != nil {
panic(err)
}
}

115
backend/ent/group_delete.go Normal file
View file

@ -0,0 +1,115 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/predicate"
)
// GroupDelete is the builder for deleting a Group entity.
type GroupDelete struct {
config
hooks []Hook
mutation *GroupMutation
}
// Where appends a list predicates to the GroupDelete builder.
func (gd *GroupDelete) Where(ps ...predicate.Group) *GroupDelete {
gd.mutation.Where(ps...)
return gd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (gd *GroupDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(gd.hooks) == 0 {
affected, err = gd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
gd.mutation = mutation
affected, err = gd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(gd.hooks) - 1; i >= 0; i-- {
if gd.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = gd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, gd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (gd *GroupDelete) ExecX(ctx context.Context) int {
n, err := gd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (gd *GroupDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: group.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
if ps := gd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, gd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// GroupDeleteOne is the builder for deleting a single Group entity.
type GroupDeleteOne struct {
gd *GroupDelete
}
// Exec executes the deletion query.
func (gdo *GroupDeleteOne) Exec(ctx context.Context) error {
n, err := gdo.gd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{group.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (gdo *GroupDeleteOne) ExecX(ctx context.Context) {
gdo.gd.ExecX(ctx)
}

832
backend/ent/group_query.go Normal file
View file

@ -0,0 +1,832 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/label"
"github.com/hay-kot/content/backend/ent/location"
"github.com/hay-kot/content/backend/ent/predicate"
"github.com/hay-kot/content/backend/ent/user"
)
// GroupQuery is the builder for querying Group entities.
type GroupQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Group
withUsers *UserQuery
withLocations *LocationQuery
withItems *ItemQuery
withLabels *LabelQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the GroupQuery builder.
func (gq *GroupQuery) Where(ps ...predicate.Group) *GroupQuery {
gq.predicates = append(gq.predicates, ps...)
return gq
}
// Limit adds a limit step to the query.
func (gq *GroupQuery) Limit(limit int) *GroupQuery {
gq.limit = &limit
return gq
}
// Offset adds an offset step to the query.
func (gq *GroupQuery) Offset(offset int) *GroupQuery {
gq.offset = &offset
return gq
}
// 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 (gq *GroupQuery) Unique(unique bool) *GroupQuery {
gq.unique = &unique
return gq
}
// Order adds an order step to the query.
func (gq *GroupQuery) Order(o ...OrderFunc) *GroupQuery {
gq.order = append(gq.order, o...)
return gq
}
// QueryUsers chains the current query on the "users" edge.
func (gq *GroupQuery) QueryUsers() *UserQuery {
query := &UserQuery{config: gq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := gq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.UsersTable, group.UsersColumn),
)
fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryLocations chains the current query on the "locations" edge.
func (gq *GroupQuery) QueryLocations() *LocationQuery {
query := &LocationQuery{config: gq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := gq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(location.Table, location.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.LocationsTable, group.LocationsColumn),
)
fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryItems chains the current query on the "items" edge.
func (gq *GroupQuery) QueryItems() *ItemQuery {
query := &ItemQuery{config: gq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := gq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(item.Table, item.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.ItemsTable, group.ItemsColumn),
)
fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryLabels chains the current query on the "labels" edge.
func (gq *GroupQuery) QueryLabels() *LabelQuery {
query := &LabelQuery{config: gq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := gq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(label.Table, label.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.LabelsTable, group.LabelsColumn),
)
fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Group entity from the query.
// Returns a *NotFoundError when no Group was found.
func (gq *GroupQuery) First(ctx context.Context) (*Group, error) {
nodes, err := gq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{group.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (gq *GroupQuery) FirstX(ctx context.Context) *Group {
node, err := gq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Group ID from the query.
// Returns a *NotFoundError when no Group ID was found.
func (gq *GroupQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = gq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{group.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (gq *GroupQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := gq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Group entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Group entity is found.
// Returns a *NotFoundError when no Group entities are found.
func (gq *GroupQuery) Only(ctx context.Context) (*Group, error) {
nodes, err := gq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{group.Label}
default:
return nil, &NotSingularError{group.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (gq *GroupQuery) OnlyX(ctx context.Context) *Group {
node, err := gq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Group ID in the query.
// Returns a *NotSingularError when more than one Group ID is found.
// Returns a *NotFoundError when no entities are found.
func (gq *GroupQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = gq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{group.Label}
default:
err = &NotSingularError{group.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (gq *GroupQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := gq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Groups.
func (gq *GroupQuery) All(ctx context.Context) ([]*Group, error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
return gq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (gq *GroupQuery) AllX(ctx context.Context) []*Group {
nodes, err := gq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Group IDs.
func (gq *GroupQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := gq.Select(group.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (gq *GroupQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := gq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (gq *GroupQuery) Count(ctx context.Context) (int, error) {
if err := gq.prepareQuery(ctx); err != nil {
return 0, err
}
return gq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (gq *GroupQuery) CountX(ctx context.Context) int {
count, err := gq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (gq *GroupQuery) Exist(ctx context.Context) (bool, error) {
if err := gq.prepareQuery(ctx); err != nil {
return false, err
}
return gq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (gq *GroupQuery) ExistX(ctx context.Context) bool {
exist, err := gq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the GroupQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (gq *GroupQuery) Clone() *GroupQuery {
if gq == nil {
return nil
}
return &GroupQuery{
config: gq.config,
limit: gq.limit,
offset: gq.offset,
order: append([]OrderFunc{}, gq.order...),
predicates: append([]predicate.Group{}, gq.predicates...),
withUsers: gq.withUsers.Clone(),
withLocations: gq.withLocations.Clone(),
withItems: gq.withItems.Clone(),
withLabels: gq.withLabels.Clone(),
// clone intermediate query.
sql: gq.sql.Clone(),
path: gq.path,
unique: gq.unique,
}
}
// WithUsers tells the query-builder to eager-load the nodes that are connected to
// the "users" edge. The optional arguments are used to configure the query builder of the edge.
func (gq *GroupQuery) WithUsers(opts ...func(*UserQuery)) *GroupQuery {
query := &UserQuery{config: gq.config}
for _, opt := range opts {
opt(query)
}
gq.withUsers = query
return gq
}
// WithLocations tells the query-builder to eager-load the nodes that are connected to
// the "locations" edge. The optional arguments are used to configure the query builder of the edge.
func (gq *GroupQuery) WithLocations(opts ...func(*LocationQuery)) *GroupQuery {
query := &LocationQuery{config: gq.config}
for _, opt := range opts {
opt(query)
}
gq.withLocations = query
return gq
}
// WithItems tells the query-builder to eager-load the nodes that are connected to
// the "items" edge. The optional arguments are used to configure the query builder of the edge.
func (gq *GroupQuery) WithItems(opts ...func(*ItemQuery)) *GroupQuery {
query := &ItemQuery{config: gq.config}
for _, opt := range opts {
opt(query)
}
gq.withItems = query
return gq
}
// WithLabels tells the query-builder to eager-load the nodes that are connected to
// the "labels" edge. The optional arguments are used to configure the query builder of the edge.
func (gq *GroupQuery) WithLabels(opts ...func(*LabelQuery)) *GroupQuery {
query := &LabelQuery{config: gq.config}
for _, opt := range opts {
opt(query)
}
gq.withLabels = query
return gq
}
// 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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Group.Query().
// GroupBy(group.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (gq *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy {
grbuild := &GroupGroupBy{config: gq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
return gq.sqlQuery(ctx), nil
}
grbuild.label = group.Label
grbuild.flds, grbuild.scan = &grbuild.fields, 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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// }
//
// client.Group.Query().
// Select(group.FieldCreatedAt).
// Scan(ctx, &v)
func (gq *GroupQuery) Select(fields ...string) *GroupSelect {
gq.fields = append(gq.fields, fields...)
selbuild := &GroupSelect{GroupQuery: gq}
selbuild.label = group.Label
selbuild.flds, selbuild.scan = &gq.fields, selbuild.Scan
return selbuild
}
func (gq *GroupQuery) prepareQuery(ctx context.Context) error {
for _, f := range gq.fields {
if !group.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if gq.path != nil {
prev, err := gq.path(ctx)
if err != nil {
return err
}
gq.sql = prev
}
return nil
}
func (gq *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group, error) {
var (
nodes = []*Group{}
_spec = gq.querySpec()
loadedTypes = [4]bool{
gq.withUsers != nil,
gq.withLocations != nil,
gq.withItems != nil,
gq.withLabels != nil,
}
)
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
return (*Group).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
node := &Group{config: gq.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, gq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := gq.withUsers; query != nil {
if err := gq.loadUsers(ctx, query, nodes,
func(n *Group) { n.Edges.Users = []*User{} },
func(n *Group, e *User) { n.Edges.Users = append(n.Edges.Users, e) }); err != nil {
return nil, err
}
}
if query := gq.withLocations; query != nil {
if err := gq.loadLocations(ctx, query, nodes,
func(n *Group) { n.Edges.Locations = []*Location{} },
func(n *Group, e *Location) { n.Edges.Locations = append(n.Edges.Locations, e) }); err != nil {
return nil, err
}
}
if query := gq.withItems; query != nil {
if err := gq.loadItems(ctx, query, nodes,
func(n *Group) { n.Edges.Items = []*Item{} },
func(n *Group, e *Item) { n.Edges.Items = append(n.Edges.Items, e) }); err != nil {
return nil, err
}
}
if query := gq.withLabels; query != nil {
if err := gq.loadLabels(ctx, query, nodes,
func(n *Group) { n.Edges.Labels = []*Label{} },
func(n *Group, e *Label) { n.Edges.Labels = append(n.Edges.Labels, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (gq *GroupQuery) loadUsers(ctx context.Context, query *UserQuery, nodes []*Group, init func(*Group), assign func(*Group, *User)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Group)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.User(func(s *sql.Selector) {
s.Where(sql.InValues(group.UsersColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.group_users
if fk == nil {
return fmt.Errorf(`foreign-key "group_users" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_users" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (gq *GroupQuery) loadLocations(ctx context.Context, query *LocationQuery, nodes []*Group, init func(*Group), assign func(*Group, *Location)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Group)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Location(func(s *sql.Selector) {
s.Where(sql.InValues(group.LocationsColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.group_locations
if fk == nil {
return fmt.Errorf(`foreign-key "group_locations" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_locations" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (gq *GroupQuery) loadItems(ctx context.Context, query *ItemQuery, nodes []*Group, init func(*Group), assign func(*Group, *Item)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Group)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Item(func(s *sql.Selector) {
s.Where(sql.InValues(group.ItemsColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.group_items
if fk == nil {
return fmt.Errorf(`foreign-key "group_items" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_items" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (gq *GroupQuery) loadLabels(ctx context.Context, query *LabelQuery, nodes []*Group, init func(*Group), assign func(*Group, *Label)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Group)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Label(func(s *sql.Selector) {
s.Where(sql.InValues(group.LabelsColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.group_labels
if fk == nil {
return fmt.Errorf(`foreign-key "group_labels" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_labels" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (gq *GroupQuery) sqlCount(ctx context.Context) (int, error) {
_spec := gq.querySpec()
_spec.Node.Columns = gq.fields
if len(gq.fields) > 0 {
_spec.Unique = gq.unique != nil && *gq.unique
}
return sqlgraph.CountNodes(ctx, gq.driver, _spec)
}
func (gq *GroupQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := gq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %w", err)
}
return n > 0, nil
}
func (gq *GroupQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: group.Table,
Columns: group.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
From: gq.sql,
Unique: true,
}
if unique := gq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := gq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, group.FieldID)
for i := range fields {
if fields[i] != group.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := gq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := gq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := gq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := gq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (gq *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(gq.driver.Dialect())
t1 := builder.Table(group.Table)
columns := gq.fields
if len(columns) == 0 {
columns = group.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if gq.sql != nil {
selector = gq.sql
selector.Select(selector.Columns(columns...)...)
}
if gq.unique != nil && *gq.unique {
selector.Distinct()
}
for _, p := range gq.predicates {
p(selector)
}
for _, p := range gq.order {
p(selector)
}
if offset := gq.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 := gq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// GroupGroupBy is the group-by builder for Group entities.
type GroupGroupBy struct {
config
selector
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (ggb *GroupGroupBy) Aggregate(fns ...AggregateFunc) *GroupGroupBy {
ggb.fns = append(ggb.fns, fns...)
return ggb
}
// Scan applies the group-by query and scans the result into the given value.
func (ggb *GroupGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := ggb.path(ctx)
if err != nil {
return err
}
ggb.sql = query
return ggb.sqlScan(ctx, v)
}
func (ggb *GroupGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range ggb.fields {
if !group.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := ggb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := ggb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (ggb *GroupGroupBy) sqlQuery() *sql.Selector {
selector := ggb.sql.Select()
aggregation := make([]string, 0, len(ggb.fns))
for _, fn := range ggb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(ggb.fields)+len(ggb.fns))
for _, f := range ggb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(ggb.fields...)...)
}
// GroupSelect is the builder for selecting fields of Group entities.
type GroupSelect struct {
*GroupQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (gs *GroupSelect) Scan(ctx context.Context, v interface{}) error {
if err := gs.prepareQuery(ctx); err != nil {
return err
}
gs.sql = gs.GroupQuery.sqlQuery(ctx)
return gs.sqlScan(ctx, v)
}
func (gs *GroupSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := gs.sql.Query()
if err := gs.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

1125
backend/ent/group_update.go Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package hook package hook
@ -22,6 +22,71 @@ func (f AuthTokensFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value,
return f(ctx, mv) return f(ctx, mv)
} }
// The GroupFunc type is an adapter to allow the use of ordinary
// function as Group mutator.
type GroupFunc func(context.Context, *ent.GroupMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.GroupMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", m)
}
return f(ctx, mv)
}
// The ItemFunc type is an adapter to allow the use of ordinary
// function as Item mutator.
type ItemFunc func(context.Context, *ent.ItemMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f ItemFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.ItemMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ItemMutation", m)
}
return f(ctx, mv)
}
// The ItemFieldFunc type is an adapter to allow the use of ordinary
// function as ItemField mutator.
type ItemFieldFunc func(context.Context, *ent.ItemFieldMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f ItemFieldFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.ItemFieldMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ItemFieldMutation", m)
}
return f(ctx, mv)
}
// The LabelFunc type is an adapter to allow the use of ordinary
// function as Label mutator.
type LabelFunc func(context.Context, *ent.LabelMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f LabelFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.LabelMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.LabelMutation", m)
}
return f(ctx, mv)
}
// The LocationFunc type is an adapter to allow the use of ordinary
// function as Location mutator.
type LocationFunc func(context.Context, *ent.LocationMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f LocationFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.LocationMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.LocationMutation", m)
}
return f(ctx, mv)
}
// The UserFunc type is an adapter to allow the use of ordinary // The UserFunc type is an adapter to allow the use of ordinary
// function as User mutator. // function as User mutator.
type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error) type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error)
@ -130,7 +195,6 @@ func HasFields(field string, fields ...string) Condition {
// If executes the given hook under condition. // If executes the given hook under condition.
// //
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) // hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
//
func If(hk ent.Hook, cond Condition) ent.Hook { func If(hk ent.Hook, cond Condition) ent.Hook {
return func(next ent.Mutator) ent.Mutator { return func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
@ -145,7 +209,6 @@ func If(hk ent.Hook, cond Condition) ent.Hook {
// On executes the given hook only for the given operation. // On executes the given hook only for the given operation.
// //
// hook.On(Log, ent.Delete|ent.Create) // hook.On(Log, ent.Delete|ent.Create)
//
func On(hk ent.Hook, op ent.Op) ent.Hook { func On(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, HasOp(op)) return If(hk, HasOp(op))
} }
@ -153,7 +216,6 @@ func On(hk ent.Hook, op ent.Op) ent.Hook {
// Unless skips the given hook only for the given operation. // Unless skips the given hook only for the given operation.
// //
// hook.Unless(Log, ent.Update|ent.UpdateOne) // hook.Unless(Log, ent.Update|ent.UpdateOne)
//
func Unless(hk ent.Hook, op ent.Op) ent.Hook { func Unless(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, Not(HasOp(op))) return If(hk, Not(HasOp(op)))
} }
@ -174,7 +236,6 @@ func FixedError(err error) ent.Hook {
// Reject(ent.Delete|ent.Update), // Reject(ent.Delete|ent.Update),
// } // }
// } // }
//
func Reject(op ent.Op) ent.Hook { func Reject(op ent.Op) ent.Hook {
hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
return On(hk, op) return On(hk, op)

385
backend/ent/item.go Normal file
View file

@ -0,0 +1,385 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/location"
)
// Item is the model entity for the Item schema.
type Item struct {
config `json:"-"`
// ID of the ent.
ID uuid.UUID `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Description holds the value of the "description" field.
Description string `json:"description,omitempty"`
// Notes holds the value of the "notes" field.
Notes string `json:"notes,omitempty"`
// SerialNumber holds the value of the "serial_number" field.
SerialNumber string `json:"serial_number,omitempty"`
// ModelNumber holds the value of the "model_number" field.
ModelNumber string `json:"model_number,omitempty"`
// Manufacturer holds the value of the "manufacturer" field.
Manufacturer string `json:"manufacturer,omitempty"`
// PurchaseTime holds the value of the "purchase_time" field.
PurchaseTime time.Time `json:"purchase_time,omitempty"`
// PurchaseFrom holds the value of the "purchase_from" field.
PurchaseFrom string `json:"purchase_from,omitempty"`
// PurchasePrice holds the value of the "purchase_price" field.
PurchasePrice float64 `json:"purchase_price,omitempty"`
// PurchaseReceiptID holds the value of the "purchase_receipt_id" field.
PurchaseReceiptID uuid.UUID `json:"purchase_receipt_id,omitempty"`
// SoldTime holds the value of the "sold_time" field.
SoldTime time.Time `json:"sold_time,omitempty"`
// SoldTo holds the value of the "sold_to" field.
SoldTo string `json:"sold_to,omitempty"`
// SoldPrice holds the value of the "sold_price" field.
SoldPrice float64 `json:"sold_price,omitempty"`
// SoldReceiptID holds the value of the "sold_receipt_id" field.
SoldReceiptID uuid.UUID `json:"sold_receipt_id,omitempty"`
// SoldNotes holds the value of the "sold_notes" field.
SoldNotes string `json:"sold_notes,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the ItemQuery when eager-loading is set.
Edges ItemEdges `json:"edges"`
group_items *uuid.UUID
location_items *uuid.UUID
}
// ItemEdges holds the relations/edges for other nodes in the graph.
type ItemEdges struct {
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// Location holds the value of the location edge.
Location *Location `json:"location,omitempty"`
// Fields holds the value of the fields edge.
Fields []*ItemField `json:"fields,omitempty"`
// Label holds the value of the label edge.
Label []*Label `json:"label,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [4]bool
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e ItemEdges) GroupOrErr() (*Group, error) {
if e.loadedTypes[0] {
if e.Group == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: group.Label}
}
return e.Group, nil
}
return nil, &NotLoadedError{edge: "group"}
}
// LocationOrErr returns the Location value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e ItemEdges) LocationOrErr() (*Location, error) {
if e.loadedTypes[1] {
if e.Location == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: location.Label}
}
return e.Location, nil
}
return nil, &NotLoadedError{edge: "location"}
}
// FieldsOrErr returns the Fields value or an error if the edge
// was not loaded in eager-loading.
func (e ItemEdges) FieldsOrErr() ([]*ItemField, error) {
if e.loadedTypes[2] {
return e.Fields, nil
}
return nil, &NotLoadedError{edge: "fields"}
}
// LabelOrErr returns the Label value or an error if the edge
// was not loaded in eager-loading.
func (e ItemEdges) LabelOrErr() ([]*Label, error) {
if e.loadedTypes[3] {
return e.Label, nil
}
return nil, &NotLoadedError{edge: "label"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Item) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case item.FieldPurchasePrice, item.FieldSoldPrice:
values[i] = new(sql.NullFloat64)
case item.FieldName, item.FieldDescription, item.FieldNotes, item.FieldSerialNumber, item.FieldModelNumber, item.FieldManufacturer, item.FieldPurchaseFrom, item.FieldSoldTo, item.FieldSoldNotes:
values[i] = new(sql.NullString)
case item.FieldCreatedAt, item.FieldUpdatedAt, item.FieldPurchaseTime, item.FieldSoldTime:
values[i] = new(sql.NullTime)
case item.FieldID, item.FieldPurchaseReceiptID, item.FieldSoldReceiptID:
values[i] = new(uuid.UUID)
case item.ForeignKeys[0]: // group_items
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
case item.ForeignKeys[1]: // location_items
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type Item", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Item fields.
func (i *Item) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for j := range columns {
switch columns[j] {
case item.FieldID:
if value, ok := values[j].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[j])
} else if value != nil {
i.ID = *value
}
case item.FieldCreatedAt:
if value, ok := values[j].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[j])
} else if value.Valid {
i.CreatedAt = value.Time
}
case item.FieldUpdatedAt:
if value, ok := values[j].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[j])
} else if value.Valid {
i.UpdatedAt = value.Time
}
case item.FieldName:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[j])
} else if value.Valid {
i.Name = value.String
}
case item.FieldDescription:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field description", values[j])
} else if value.Valid {
i.Description = value.String
}
case item.FieldNotes:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field notes", values[j])
} else if value.Valid {
i.Notes = value.String
}
case item.FieldSerialNumber:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field serial_number", values[j])
} else if value.Valid {
i.SerialNumber = value.String
}
case item.FieldModelNumber:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field model_number", values[j])
} else if value.Valid {
i.ModelNumber = value.String
}
case item.FieldManufacturer:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field manufacturer", values[j])
} else if value.Valid {
i.Manufacturer = value.String
}
case item.FieldPurchaseTime:
if value, ok := values[j].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field purchase_time", values[j])
} else if value.Valid {
i.PurchaseTime = value.Time
}
case item.FieldPurchaseFrom:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field purchase_from", values[j])
} else if value.Valid {
i.PurchaseFrom = value.String
}
case item.FieldPurchasePrice:
if value, ok := values[j].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field purchase_price", values[j])
} else if value.Valid {
i.PurchasePrice = value.Float64
}
case item.FieldPurchaseReceiptID:
if value, ok := values[j].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field purchase_receipt_id", values[j])
} else if value != nil {
i.PurchaseReceiptID = *value
}
case item.FieldSoldTime:
if value, ok := values[j].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field sold_time", values[j])
} else if value.Valid {
i.SoldTime = value.Time
}
case item.FieldSoldTo:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field sold_to", values[j])
} else if value.Valid {
i.SoldTo = value.String
}
case item.FieldSoldPrice:
if value, ok := values[j].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field sold_price", values[j])
} else if value.Valid {
i.SoldPrice = value.Float64
}
case item.FieldSoldReceiptID:
if value, ok := values[j].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field sold_receipt_id", values[j])
} else if value != nil {
i.SoldReceiptID = *value
}
case item.FieldSoldNotes:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field sold_notes", values[j])
} else if value.Valid {
i.SoldNotes = value.String
}
case item.ForeignKeys[0]:
if value, ok := values[j].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field group_items", values[j])
} else if value.Valid {
i.group_items = new(uuid.UUID)
*i.group_items = *value.S.(*uuid.UUID)
}
case item.ForeignKeys[1]:
if value, ok := values[j].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field location_items", values[j])
} else if value.Valid {
i.location_items = new(uuid.UUID)
*i.location_items = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryGroup queries the "group" edge of the Item entity.
func (i *Item) QueryGroup() *GroupQuery {
return (&ItemClient{config: i.config}).QueryGroup(i)
}
// QueryLocation queries the "location" edge of the Item entity.
func (i *Item) QueryLocation() *LocationQuery {
return (&ItemClient{config: i.config}).QueryLocation(i)
}
// QueryFields queries the "fields" edge of the Item entity.
func (i *Item) QueryFields() *ItemFieldQuery {
return (&ItemClient{config: i.config}).QueryFields(i)
}
// QueryLabel queries the "label" edge of the Item entity.
func (i *Item) QueryLabel() *LabelQuery {
return (&ItemClient{config: i.config}).QueryLabel(i)
}
// Update returns a builder for updating this Item.
// Note that you need to call Item.Unwrap() before calling this method if this Item
// was returned from a transaction, and the transaction was committed or rolled back.
func (i *Item) Update() *ItemUpdateOne {
return (&ItemClient{config: i.config}).UpdateOne(i)
}
// Unwrap unwraps the Item 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 (i *Item) Unwrap() *Item {
_tx, ok := i.config.driver.(*txDriver)
if !ok {
panic("ent: Item is not a transactional entity")
}
i.config.driver = _tx.drv
return i
}
// String implements the fmt.Stringer.
func (i *Item) String() string {
var builder strings.Builder
builder.WriteString("Item(")
builder.WriteString(fmt.Sprintf("id=%v, ", i.ID))
builder.WriteString("created_at=")
builder.WriteString(i.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(i.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(i.Name)
builder.WriteString(", ")
builder.WriteString("description=")
builder.WriteString(i.Description)
builder.WriteString(", ")
builder.WriteString("notes=")
builder.WriteString(i.Notes)
builder.WriteString(", ")
builder.WriteString("serial_number=")
builder.WriteString(i.SerialNumber)
builder.WriteString(", ")
builder.WriteString("model_number=")
builder.WriteString(i.ModelNumber)
builder.WriteString(", ")
builder.WriteString("manufacturer=")
builder.WriteString(i.Manufacturer)
builder.WriteString(", ")
builder.WriteString("purchase_time=")
builder.WriteString(i.PurchaseTime.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("purchase_from=")
builder.WriteString(i.PurchaseFrom)
builder.WriteString(", ")
builder.WriteString("purchase_price=")
builder.WriteString(fmt.Sprintf("%v", i.PurchasePrice))
builder.WriteString(", ")
builder.WriteString("purchase_receipt_id=")
builder.WriteString(fmt.Sprintf("%v", i.PurchaseReceiptID))
builder.WriteString(", ")
builder.WriteString("sold_time=")
builder.WriteString(i.SoldTime.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("sold_to=")
builder.WriteString(i.SoldTo)
builder.WriteString(", ")
builder.WriteString("sold_price=")
builder.WriteString(fmt.Sprintf("%v", i.SoldPrice))
builder.WriteString(", ")
builder.WriteString("sold_receipt_id=")
builder.WriteString(fmt.Sprintf("%v", i.SoldReceiptID))
builder.WriteString(", ")
builder.WriteString("sold_notes=")
builder.WriteString(i.SoldNotes)
builder.WriteByte(')')
return builder.String()
}
// Items is a parsable slice of Item.
type Items []*Item
func (i Items) config(cfg config) {
for _i := range i {
i[_i].config = cfg
}
}

165
backend/ent/item/item.go Normal file
View file

@ -0,0 +1,165 @@
// Code generated by ent, DO NOT EDIT.
package item
import (
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the item type in the database.
Label = "item"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldDescription holds the string denoting the description field in the database.
FieldDescription = "description"
// FieldNotes holds the string denoting the notes field in the database.
FieldNotes = "notes"
// FieldSerialNumber holds the string denoting the serial_number field in the database.
FieldSerialNumber = "serial_number"
// FieldModelNumber holds the string denoting the model_number field in the database.
FieldModelNumber = "model_number"
// FieldManufacturer holds the string denoting the manufacturer field in the database.
FieldManufacturer = "manufacturer"
// FieldPurchaseTime holds the string denoting the purchase_time field in the database.
FieldPurchaseTime = "purchase_time"
// FieldPurchaseFrom holds the string denoting the purchase_from field in the database.
FieldPurchaseFrom = "purchase_from"
// FieldPurchasePrice holds the string denoting the purchase_price field in the database.
FieldPurchasePrice = "purchase_price"
// FieldPurchaseReceiptID holds the string denoting the purchase_receipt_id field in the database.
FieldPurchaseReceiptID = "purchase_receipt_id"
// FieldSoldTime holds the string denoting the sold_time field in the database.
FieldSoldTime = "sold_time"
// FieldSoldTo holds the string denoting the sold_to field in the database.
FieldSoldTo = "sold_to"
// FieldSoldPrice holds the string denoting the sold_price field in the database.
FieldSoldPrice = "sold_price"
// FieldSoldReceiptID holds the string denoting the sold_receipt_id field in the database.
FieldSoldReceiptID = "sold_receipt_id"
// FieldSoldNotes holds the string denoting the sold_notes field in the database.
FieldSoldNotes = "sold_notes"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// EdgeLocation holds the string denoting the location edge name in mutations.
EdgeLocation = "location"
// EdgeFields holds the string denoting the fields edge name in mutations.
EdgeFields = "fields"
// EdgeLabel holds the string denoting the label edge name in mutations.
EdgeLabel = "label"
// Table holds the table name of the item in the database.
Table = "items"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "items"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_items"
// LocationTable is the table that holds the location relation/edge.
LocationTable = "items"
// LocationInverseTable is the table name for the Location entity.
// It exists in this package in order to avoid circular dependency with the "location" package.
LocationInverseTable = "locations"
// LocationColumn is the table column denoting the location relation/edge.
LocationColumn = "location_items"
// FieldsTable is the table that holds the fields relation/edge.
FieldsTable = "item_fields"
// FieldsInverseTable is the table name for the ItemField entity.
// It exists in this package in order to avoid circular dependency with the "itemfield" package.
FieldsInverseTable = "item_fields"
// FieldsColumn is the table column denoting the fields relation/edge.
FieldsColumn = "item_fields"
// LabelTable is the table that holds the label relation/edge. The primary key declared below.
LabelTable = "label_items"
// LabelInverseTable is the table name for the Label entity.
// It exists in this package in order to avoid circular dependency with the "label" package.
LabelInverseTable = "labels"
)
// Columns holds all SQL columns for item fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldName,
FieldDescription,
FieldNotes,
FieldSerialNumber,
FieldModelNumber,
FieldManufacturer,
FieldPurchaseTime,
FieldPurchaseFrom,
FieldPurchasePrice,
FieldPurchaseReceiptID,
FieldSoldTime,
FieldSoldTo,
FieldSoldPrice,
FieldSoldReceiptID,
FieldSoldNotes,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "items"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"group_items",
"location_items",
}
var (
// LabelPrimaryKey and LabelColumn2 are the table columns denoting the
// primary key for the label relation (M2M).
LabelPrimaryKey = []string{"label_id", "item_id"}
)
// 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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
DescriptionValidator func(string) error
// NotesValidator is a validator for the "notes" field. It is called by the builders before save.
NotesValidator func(string) error
// SerialNumberValidator is a validator for the "serial_number" field. It is called by the builders before save.
SerialNumberValidator func(string) error
// ModelNumberValidator is a validator for the "model_number" field. It is called by the builders before save.
ModelNumberValidator func(string) error
// ManufacturerValidator is a validator for the "manufacturer" field. It is called by the builders before save.
ManufacturerValidator func(string) error
// DefaultPurchasePrice holds the default value on creation for the "purchase_price" field.
DefaultPurchasePrice float64
// DefaultSoldPrice holds the default value on creation for the "sold_price" field.
DefaultSoldPrice float64
// SoldNotesValidator is a validator for the "sold_notes" field. It is called by the builders before save.
SoldNotesValidator func(string) error
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)

1917
backend/ent/item/where.go Normal file

File diff suppressed because it is too large Load diff

817
backend/ent/item_create.go Normal file
View file

@ -0,0 +1,817 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/itemfield"
"github.com/hay-kot/content/backend/ent/label"
"github.com/hay-kot/content/backend/ent/location"
)
// ItemCreate is the builder for creating a Item entity.
type ItemCreate struct {
config
mutation *ItemMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (ic *ItemCreate) SetCreatedAt(t time.Time) *ItemCreate {
ic.mutation.SetCreatedAt(t)
return ic
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (ic *ItemCreate) SetNillableCreatedAt(t *time.Time) *ItemCreate {
if t != nil {
ic.SetCreatedAt(*t)
}
return ic
}
// SetUpdatedAt sets the "updated_at" field.
func (ic *ItemCreate) SetUpdatedAt(t time.Time) *ItemCreate {
ic.mutation.SetUpdatedAt(t)
return ic
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (ic *ItemCreate) SetNillableUpdatedAt(t *time.Time) *ItemCreate {
if t != nil {
ic.SetUpdatedAt(*t)
}
return ic
}
// SetName sets the "name" field.
func (ic *ItemCreate) SetName(s string) *ItemCreate {
ic.mutation.SetName(s)
return ic
}
// SetDescription sets the "description" field.
func (ic *ItemCreate) SetDescription(s string) *ItemCreate {
ic.mutation.SetDescription(s)
return ic
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (ic *ItemCreate) SetNillableDescription(s *string) *ItemCreate {
if s != nil {
ic.SetDescription(*s)
}
return ic
}
// SetNotes sets the "notes" field.
func (ic *ItemCreate) SetNotes(s string) *ItemCreate {
ic.mutation.SetNotes(s)
return ic
}
// SetNillableNotes sets the "notes" field if the given value is not nil.
func (ic *ItemCreate) SetNillableNotes(s *string) *ItemCreate {
if s != nil {
ic.SetNotes(*s)
}
return ic
}
// SetSerialNumber sets the "serial_number" field.
func (ic *ItemCreate) SetSerialNumber(s string) *ItemCreate {
ic.mutation.SetSerialNumber(s)
return ic
}
// SetNillableSerialNumber sets the "serial_number" field if the given value is not nil.
func (ic *ItemCreate) SetNillableSerialNumber(s *string) *ItemCreate {
if s != nil {
ic.SetSerialNumber(*s)
}
return ic
}
// SetModelNumber sets the "model_number" field.
func (ic *ItemCreate) SetModelNumber(s string) *ItemCreate {
ic.mutation.SetModelNumber(s)
return ic
}
// SetNillableModelNumber sets the "model_number" field if the given value is not nil.
func (ic *ItemCreate) SetNillableModelNumber(s *string) *ItemCreate {
if s != nil {
ic.SetModelNumber(*s)
}
return ic
}
// SetManufacturer sets the "manufacturer" field.
func (ic *ItemCreate) SetManufacturer(s string) *ItemCreate {
ic.mutation.SetManufacturer(s)
return ic
}
// SetNillableManufacturer sets the "manufacturer" field if the given value is not nil.
func (ic *ItemCreate) SetNillableManufacturer(s *string) *ItemCreate {
if s != nil {
ic.SetManufacturer(*s)
}
return ic
}
// SetPurchaseTime sets the "purchase_time" field.
func (ic *ItemCreate) SetPurchaseTime(t time.Time) *ItemCreate {
ic.mutation.SetPurchaseTime(t)
return ic
}
// SetNillablePurchaseTime sets the "purchase_time" field if the given value is not nil.
func (ic *ItemCreate) SetNillablePurchaseTime(t *time.Time) *ItemCreate {
if t != nil {
ic.SetPurchaseTime(*t)
}
return ic
}
// SetPurchaseFrom sets the "purchase_from" field.
func (ic *ItemCreate) SetPurchaseFrom(s string) *ItemCreate {
ic.mutation.SetPurchaseFrom(s)
return ic
}
// SetNillablePurchaseFrom sets the "purchase_from" field if the given value is not nil.
func (ic *ItemCreate) SetNillablePurchaseFrom(s *string) *ItemCreate {
if s != nil {
ic.SetPurchaseFrom(*s)
}
return ic
}
// SetPurchasePrice sets the "purchase_price" field.
func (ic *ItemCreate) SetPurchasePrice(f float64) *ItemCreate {
ic.mutation.SetPurchasePrice(f)
return ic
}
// SetNillablePurchasePrice sets the "purchase_price" field if the given value is not nil.
func (ic *ItemCreate) SetNillablePurchasePrice(f *float64) *ItemCreate {
if f != nil {
ic.SetPurchasePrice(*f)
}
return ic
}
// SetPurchaseReceiptID sets the "purchase_receipt_id" field.
func (ic *ItemCreate) SetPurchaseReceiptID(u uuid.UUID) *ItemCreate {
ic.mutation.SetPurchaseReceiptID(u)
return ic
}
// SetNillablePurchaseReceiptID sets the "purchase_receipt_id" field if the given value is not nil.
func (ic *ItemCreate) SetNillablePurchaseReceiptID(u *uuid.UUID) *ItemCreate {
if u != nil {
ic.SetPurchaseReceiptID(*u)
}
return ic
}
// SetSoldTime sets the "sold_time" field.
func (ic *ItemCreate) SetSoldTime(t time.Time) *ItemCreate {
ic.mutation.SetSoldTime(t)
return ic
}
// SetNillableSoldTime sets the "sold_time" field if the given value is not nil.
func (ic *ItemCreate) SetNillableSoldTime(t *time.Time) *ItemCreate {
if t != nil {
ic.SetSoldTime(*t)
}
return ic
}
// SetSoldTo sets the "sold_to" field.
func (ic *ItemCreate) SetSoldTo(s string) *ItemCreate {
ic.mutation.SetSoldTo(s)
return ic
}
// SetNillableSoldTo sets the "sold_to" field if the given value is not nil.
func (ic *ItemCreate) SetNillableSoldTo(s *string) *ItemCreate {
if s != nil {
ic.SetSoldTo(*s)
}
return ic
}
// SetSoldPrice sets the "sold_price" field.
func (ic *ItemCreate) SetSoldPrice(f float64) *ItemCreate {
ic.mutation.SetSoldPrice(f)
return ic
}
// SetNillableSoldPrice sets the "sold_price" field if the given value is not nil.
func (ic *ItemCreate) SetNillableSoldPrice(f *float64) *ItemCreate {
if f != nil {
ic.SetSoldPrice(*f)
}
return ic
}
// SetSoldReceiptID sets the "sold_receipt_id" field.
func (ic *ItemCreate) SetSoldReceiptID(u uuid.UUID) *ItemCreate {
ic.mutation.SetSoldReceiptID(u)
return ic
}
// SetNillableSoldReceiptID sets the "sold_receipt_id" field if the given value is not nil.
func (ic *ItemCreate) SetNillableSoldReceiptID(u *uuid.UUID) *ItemCreate {
if u != nil {
ic.SetSoldReceiptID(*u)
}
return ic
}
// SetSoldNotes sets the "sold_notes" field.
func (ic *ItemCreate) SetSoldNotes(s string) *ItemCreate {
ic.mutation.SetSoldNotes(s)
return ic
}
// SetNillableSoldNotes sets the "sold_notes" field if the given value is not nil.
func (ic *ItemCreate) SetNillableSoldNotes(s *string) *ItemCreate {
if s != nil {
ic.SetSoldNotes(*s)
}
return ic
}
// SetID sets the "id" field.
func (ic *ItemCreate) SetID(u uuid.UUID) *ItemCreate {
ic.mutation.SetID(u)
return ic
}
// SetNillableID sets the "id" field if the given value is not nil.
func (ic *ItemCreate) SetNillableID(u *uuid.UUID) *ItemCreate {
if u != nil {
ic.SetID(*u)
}
return ic
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (ic *ItemCreate) SetGroupID(id uuid.UUID) *ItemCreate {
ic.mutation.SetGroupID(id)
return ic
}
// SetGroup sets the "group" edge to the Group entity.
func (ic *ItemCreate) SetGroup(g *Group) *ItemCreate {
return ic.SetGroupID(g.ID)
}
// SetLocationID sets the "location" edge to the Location entity by ID.
func (ic *ItemCreate) SetLocationID(id uuid.UUID) *ItemCreate {
ic.mutation.SetLocationID(id)
return ic
}
// SetNillableLocationID sets the "location" edge to the Location entity by ID if the given value is not nil.
func (ic *ItemCreate) SetNillableLocationID(id *uuid.UUID) *ItemCreate {
if id != nil {
ic = ic.SetLocationID(*id)
}
return ic
}
// SetLocation sets the "location" edge to the Location entity.
func (ic *ItemCreate) SetLocation(l *Location) *ItemCreate {
return ic.SetLocationID(l.ID)
}
// AddFieldIDs adds the "fields" edge to the ItemField entity by IDs.
func (ic *ItemCreate) AddFieldIDs(ids ...uuid.UUID) *ItemCreate {
ic.mutation.AddFieldIDs(ids...)
return ic
}
// AddFields adds the "fields" edges to the ItemField entity.
func (ic *ItemCreate) AddFields(i ...*ItemField) *ItemCreate {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return ic.AddFieldIDs(ids...)
}
// AddLabelIDs adds the "label" edge to the Label entity by IDs.
func (ic *ItemCreate) AddLabelIDs(ids ...uuid.UUID) *ItemCreate {
ic.mutation.AddLabelIDs(ids...)
return ic
}
// AddLabel adds the "label" edges to the Label entity.
func (ic *ItemCreate) AddLabel(l ...*Label) *ItemCreate {
ids := make([]uuid.UUID, len(l))
for i := range l {
ids[i] = l[i].ID
}
return ic.AddLabelIDs(ids...)
}
// Mutation returns the ItemMutation object of the builder.
func (ic *ItemCreate) Mutation() *ItemMutation {
return ic.mutation
}
// Save creates the Item in the database.
func (ic *ItemCreate) Save(ctx context.Context) (*Item, error) {
var (
err error
node *Item
)
ic.defaults()
if len(ic.hooks) == 0 {
if err = ic.check(); err != nil {
return nil, err
}
node, err = ic.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = ic.check(); err != nil {
return nil, err
}
ic.mutation = mutation
if node, err = ic.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(ic.hooks) - 1; i >= 0; i-- {
if ic.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ic.hooks[i](mut)
}
v, err := mut.Mutate(ctx, ic.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Item)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from ItemMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (ic *ItemCreate) SaveX(ctx context.Context) *Item {
v, err := ic.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ic *ItemCreate) Exec(ctx context.Context) error {
_, err := ic.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ic *ItemCreate) ExecX(ctx context.Context) {
if err := ic.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (ic *ItemCreate) defaults() {
if _, ok := ic.mutation.CreatedAt(); !ok {
v := item.DefaultCreatedAt()
ic.mutation.SetCreatedAt(v)
}
if _, ok := ic.mutation.UpdatedAt(); !ok {
v := item.DefaultUpdatedAt()
ic.mutation.SetUpdatedAt(v)
}
if _, ok := ic.mutation.PurchasePrice(); !ok {
v := item.DefaultPurchasePrice
ic.mutation.SetPurchasePrice(v)
}
if _, ok := ic.mutation.SoldPrice(); !ok {
v := item.DefaultSoldPrice
ic.mutation.SetSoldPrice(v)
}
if _, ok := ic.mutation.ID(); !ok {
v := item.DefaultID()
ic.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (ic *ItemCreate) check() error {
if _, ok := ic.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Item.created_at"`)}
}
if _, ok := ic.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Item.updated_at"`)}
}
if _, ok := ic.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Item.name"`)}
}
if v, ok := ic.mutation.Name(); ok {
if err := item.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Item.name": %w`, err)}
}
}
if v, ok := ic.mutation.Description(); ok {
if err := item.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "Item.description": %w`, err)}
}
}
if v, ok := ic.mutation.Notes(); ok {
if err := item.NotesValidator(v); err != nil {
return &ValidationError{Name: "notes", err: fmt.Errorf(`ent: validator failed for field "Item.notes": %w`, err)}
}
}
if v, ok := ic.mutation.SerialNumber(); ok {
if err := item.SerialNumberValidator(v); err != nil {
return &ValidationError{Name: "serial_number", err: fmt.Errorf(`ent: validator failed for field "Item.serial_number": %w`, err)}
}
}
if v, ok := ic.mutation.ModelNumber(); ok {
if err := item.ModelNumberValidator(v); err != nil {
return &ValidationError{Name: "model_number", err: fmt.Errorf(`ent: validator failed for field "Item.model_number": %w`, err)}
}
}
if v, ok := ic.mutation.Manufacturer(); ok {
if err := item.ManufacturerValidator(v); err != nil {
return &ValidationError{Name: "manufacturer", err: fmt.Errorf(`ent: validator failed for field "Item.manufacturer": %w`, err)}
}
}
if _, ok := ic.mutation.PurchasePrice(); !ok {
return &ValidationError{Name: "purchase_price", err: errors.New(`ent: missing required field "Item.purchase_price"`)}
}
if _, ok := ic.mutation.SoldPrice(); !ok {
return &ValidationError{Name: "sold_price", err: errors.New(`ent: missing required field "Item.sold_price"`)}
}
if v, ok := ic.mutation.SoldNotes(); ok {
if err := item.SoldNotesValidator(v); err != nil {
return &ValidationError{Name: "sold_notes", err: fmt.Errorf(`ent: validator failed for field "Item.sold_notes": %w`, err)}
}
}
if _, ok := ic.mutation.GroupID(); !ok {
return &ValidationError{Name: "group", err: errors.New(`ent: missing required edge "Item.group"`)}
}
return nil
}
func (ic *ItemCreate) sqlSave(ctx context.Context) (*Item, error) {
_node, _spec := ic.createSpec()
if err := sqlgraph.CreateNode(ctx, ic.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
if _spec.ID.Value != nil {
if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
_node.ID = *id
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
return nil, err
}
}
return _node, nil
}
func (ic *ItemCreate) createSpec() (*Item, *sqlgraph.CreateSpec) {
var (
_node = &Item{config: ic.config}
_spec = &sqlgraph.CreateSpec{
Table: item.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
}
)
if id, ok := ic.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := ic.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: item.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := ic.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: item.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := ic.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: item.FieldName,
})
_node.Name = value
}
if value, ok := ic.mutation.Description(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: item.FieldDescription,
})
_node.Description = value
}
if value, ok := ic.mutation.Notes(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: item.FieldNotes,
})
_node.Notes = value
}
if value, ok := ic.mutation.SerialNumber(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: item.FieldSerialNumber,
})
_node.SerialNumber = value
}
if value, ok := ic.mutation.ModelNumber(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: item.FieldModelNumber,
})
_node.ModelNumber = value
}
if value, ok := ic.mutation.Manufacturer(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: item.FieldManufacturer,
})
_node.Manufacturer = value
}
if value, ok := ic.mutation.PurchaseTime(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: item.FieldPurchaseTime,
})
_node.PurchaseTime = value
}
if value, ok := ic.mutation.PurchaseFrom(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: item.FieldPurchaseFrom,
})
_node.PurchaseFrom = value
}
if value, ok := ic.mutation.PurchasePrice(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeFloat64,
Value: value,
Column: item.FieldPurchasePrice,
})
_node.PurchasePrice = value
}
if value, ok := ic.mutation.PurchaseReceiptID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Value: value,
Column: item.FieldPurchaseReceiptID,
})
_node.PurchaseReceiptID = value
}
if value, ok := ic.mutation.SoldTime(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: item.FieldSoldTime,
})
_node.SoldTime = value
}
if value, ok := ic.mutation.SoldTo(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: item.FieldSoldTo,
})
_node.SoldTo = value
}
if value, ok := ic.mutation.SoldPrice(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeFloat64,
Value: value,
Column: item.FieldSoldPrice,
})
_node.SoldPrice = value
}
if value, ok := ic.mutation.SoldReceiptID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Value: value,
Column: item.FieldSoldReceiptID,
})
_node.SoldReceiptID = value
}
if value, ok := ic.mutation.SoldNotes(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: item.FieldSoldNotes,
})
_node.SoldNotes = value
}
if nodes := ic.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: item.GroupTable,
Columns: []string{item.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.group_items = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := ic.mutation.LocationIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: item.LocationTable,
Columns: []string{item.LocationColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: location.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.location_items = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := ic.mutation.FieldsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: item.FieldsTable,
Columns: []string{item.FieldsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: itemfield.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := ic.mutation.LabelIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: item.LabelTable,
Columns: item.LabelPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: label.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// ItemCreateBulk is the builder for creating many Item entities in bulk.
type ItemCreateBulk struct {
config
builders []*ItemCreate
}
// Save creates the Item entities in the database.
func (icb *ItemCreateBulk) Save(ctx context.Context) ([]*Item, error) {
specs := make([]*sqlgraph.CreateSpec, len(icb.builders))
nodes := make([]*Item, len(icb.builders))
mutators := make([]Mutator, len(icb.builders))
for i := range icb.builders {
func(i int, root context.Context) {
builder := icb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, icb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, icb.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
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, icb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (icb *ItemCreateBulk) SaveX(ctx context.Context) []*Item {
v, err := icb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (icb *ItemCreateBulk) Exec(ctx context.Context) error {
_, err := icb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (icb *ItemCreateBulk) ExecX(ctx context.Context) {
if err := icb.Exec(ctx); err != nil {
panic(err)
}
}

115
backend/ent/item_delete.go Normal file
View file

@ -0,0 +1,115 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/predicate"
)
// ItemDelete is the builder for deleting a Item entity.
type ItemDelete struct {
config
hooks []Hook
mutation *ItemMutation
}
// Where appends a list predicates to the ItemDelete builder.
func (id *ItemDelete) Where(ps ...predicate.Item) *ItemDelete {
id.mutation.Where(ps...)
return id
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (id *ItemDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(id.hooks) == 0 {
affected, err = id.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
id.mutation = mutation
affected, err = id.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(id.hooks) - 1; i >= 0; i-- {
if id.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = id.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, id.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (id *ItemDelete) ExecX(ctx context.Context) int {
n, err := id.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (id *ItemDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: item.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
if ps := id.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, id.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// ItemDeleteOne is the builder for deleting a single Item entity.
type ItemDeleteOne struct {
id *ItemDelete
}
// Exec executes the deletion query.
func (ido *ItemDeleteOne) Exec(ctx context.Context) error {
n, err := ido.id.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{item.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (ido *ItemDeleteOne) ExecX(ctx context.Context) {
ido.id.ExecX(ctx)
}

861
backend/ent/item_query.go Normal file
View file

@ -0,0 +1,861 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/itemfield"
"github.com/hay-kot/content/backend/ent/label"
"github.com/hay-kot/content/backend/ent/location"
"github.com/hay-kot/content/backend/ent/predicate"
)
// ItemQuery is the builder for querying Item entities.
type ItemQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Item
withGroup *GroupQuery
withLocation *LocationQuery
withFields *ItemFieldQuery
withLabel *LabelQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the ItemQuery builder.
func (iq *ItemQuery) Where(ps ...predicate.Item) *ItemQuery {
iq.predicates = append(iq.predicates, ps...)
return iq
}
// Limit adds a limit step to the query.
func (iq *ItemQuery) Limit(limit int) *ItemQuery {
iq.limit = &limit
return iq
}
// Offset adds an offset step to the query.
func (iq *ItemQuery) Offset(offset int) *ItemQuery {
iq.offset = &offset
return iq
}
// 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 (iq *ItemQuery) Unique(unique bool) *ItemQuery {
iq.unique = &unique
return iq
}
// Order adds an order step to the query.
func (iq *ItemQuery) Order(o ...OrderFunc) *ItemQuery {
iq.order = append(iq.order, o...)
return iq
}
// QueryGroup chains the current query on the "group" edge.
func (iq *ItemQuery) QueryGroup() *GroupQuery {
query := &GroupQuery{config: iq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := iq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := iq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(item.Table, item.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, item.GroupTable, item.GroupColumn),
)
fromU = sqlgraph.SetNeighbors(iq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryLocation chains the current query on the "location" edge.
func (iq *ItemQuery) QueryLocation() *LocationQuery {
query := &LocationQuery{config: iq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := iq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := iq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(item.Table, item.FieldID, selector),
sqlgraph.To(location.Table, location.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, item.LocationTable, item.LocationColumn),
)
fromU = sqlgraph.SetNeighbors(iq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryFields chains the current query on the "fields" edge.
func (iq *ItemQuery) QueryFields() *ItemFieldQuery {
query := &ItemFieldQuery{config: iq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := iq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := iq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(item.Table, item.FieldID, selector),
sqlgraph.To(itemfield.Table, itemfield.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, item.FieldsTable, item.FieldsColumn),
)
fromU = sqlgraph.SetNeighbors(iq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryLabel chains the current query on the "label" edge.
func (iq *ItemQuery) QueryLabel() *LabelQuery {
query := &LabelQuery{config: iq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := iq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := iq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(item.Table, item.FieldID, selector),
sqlgraph.To(label.Table, label.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, item.LabelTable, item.LabelPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(iq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Item entity from the query.
// Returns a *NotFoundError when no Item was found.
func (iq *ItemQuery) First(ctx context.Context) (*Item, error) {
nodes, err := iq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{item.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (iq *ItemQuery) FirstX(ctx context.Context) *Item {
node, err := iq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Item ID from the query.
// Returns a *NotFoundError when no Item ID was found.
func (iq *ItemQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = iq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{item.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (iq *ItemQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := iq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Item entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Item entity is found.
// Returns a *NotFoundError when no Item entities are found.
func (iq *ItemQuery) Only(ctx context.Context) (*Item, error) {
nodes, err := iq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{item.Label}
default:
return nil, &NotSingularError{item.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (iq *ItemQuery) OnlyX(ctx context.Context) *Item {
node, err := iq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Item ID in the query.
// Returns a *NotSingularError when more than one Item ID is found.
// Returns a *NotFoundError when no entities are found.
func (iq *ItemQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = iq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{item.Label}
default:
err = &NotSingularError{item.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (iq *ItemQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := iq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Items.
func (iq *ItemQuery) All(ctx context.Context) ([]*Item, error) {
if err := iq.prepareQuery(ctx); err != nil {
return nil, err
}
return iq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (iq *ItemQuery) AllX(ctx context.Context) []*Item {
nodes, err := iq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Item IDs.
func (iq *ItemQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := iq.Select(item.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (iq *ItemQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := iq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (iq *ItemQuery) Count(ctx context.Context) (int, error) {
if err := iq.prepareQuery(ctx); err != nil {
return 0, err
}
return iq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (iq *ItemQuery) CountX(ctx context.Context) int {
count, err := iq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (iq *ItemQuery) Exist(ctx context.Context) (bool, error) {
if err := iq.prepareQuery(ctx); err != nil {
return false, err
}
return iq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (iq *ItemQuery) ExistX(ctx context.Context) bool {
exist, err := iq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the ItemQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (iq *ItemQuery) Clone() *ItemQuery {
if iq == nil {
return nil
}
return &ItemQuery{
config: iq.config,
limit: iq.limit,
offset: iq.offset,
order: append([]OrderFunc{}, iq.order...),
predicates: append([]predicate.Item{}, iq.predicates...),
withGroup: iq.withGroup.Clone(),
withLocation: iq.withLocation.Clone(),
withFields: iq.withFields.Clone(),
withLabel: iq.withLabel.Clone(),
// clone intermediate query.
sql: iq.sql.Clone(),
path: iq.path,
unique: iq.unique,
}
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (iq *ItemQuery) WithGroup(opts ...func(*GroupQuery)) *ItemQuery {
query := &GroupQuery{config: iq.config}
for _, opt := range opts {
opt(query)
}
iq.withGroup = query
return iq
}
// WithLocation tells the query-builder to eager-load the nodes that are connected to
// the "location" edge. The optional arguments are used to configure the query builder of the edge.
func (iq *ItemQuery) WithLocation(opts ...func(*LocationQuery)) *ItemQuery {
query := &LocationQuery{config: iq.config}
for _, opt := range opts {
opt(query)
}
iq.withLocation = query
return iq
}
// WithFields tells the query-builder to eager-load the nodes that are connected to
// the "fields" edge. The optional arguments are used to configure the query builder of the edge.
func (iq *ItemQuery) WithFields(opts ...func(*ItemFieldQuery)) *ItemQuery {
query := &ItemFieldQuery{config: iq.config}
for _, opt := range opts {
opt(query)
}
iq.withFields = query
return iq
}
// WithLabel tells the query-builder to eager-load the nodes that are connected to
// the "label" edge. The optional arguments are used to configure the query builder of the edge.
func (iq *ItemQuery) WithLabel(opts ...func(*LabelQuery)) *ItemQuery {
query := &LabelQuery{config: iq.config}
for _, opt := range opts {
opt(query)
}
iq.withLabel = query
return iq
}
// 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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Item.Query().
// GroupBy(item.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (iq *ItemQuery) GroupBy(field string, fields ...string) *ItemGroupBy {
grbuild := &ItemGroupBy{config: iq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := iq.prepareQuery(ctx); err != nil {
return nil, err
}
return iq.sqlQuery(ctx), nil
}
grbuild.label = item.Label
grbuild.flds, grbuild.scan = &grbuild.fields, 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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// }
//
// client.Item.Query().
// Select(item.FieldCreatedAt).
// Scan(ctx, &v)
func (iq *ItemQuery) Select(fields ...string) *ItemSelect {
iq.fields = append(iq.fields, fields...)
selbuild := &ItemSelect{ItemQuery: iq}
selbuild.label = item.Label
selbuild.flds, selbuild.scan = &iq.fields, selbuild.Scan
return selbuild
}
func (iq *ItemQuery) prepareQuery(ctx context.Context) error {
for _, f := range iq.fields {
if !item.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if iq.path != nil {
prev, err := iq.path(ctx)
if err != nil {
return err
}
iq.sql = prev
}
return nil
}
func (iq *ItemQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Item, error) {
var (
nodes = []*Item{}
withFKs = iq.withFKs
_spec = iq.querySpec()
loadedTypes = [4]bool{
iq.withGroup != nil,
iq.withLocation != nil,
iq.withFields != nil,
iq.withLabel != nil,
}
)
if iq.withGroup != nil || iq.withLocation != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, item.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
return (*Item).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
node := &Item{config: iq.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, iq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := iq.withGroup; query != nil {
if err := iq.loadGroup(ctx, query, nodes, nil,
func(n *Item, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
if query := iq.withLocation; query != nil {
if err := iq.loadLocation(ctx, query, nodes, nil,
func(n *Item, e *Location) { n.Edges.Location = e }); err != nil {
return nil, err
}
}
if query := iq.withFields; query != nil {
if err := iq.loadFields(ctx, query, nodes,
func(n *Item) { n.Edges.Fields = []*ItemField{} },
func(n *Item, e *ItemField) { n.Edges.Fields = append(n.Edges.Fields, e) }); err != nil {
return nil, err
}
}
if query := iq.withLabel; query != nil {
if err := iq.loadLabel(ctx, query, nodes,
func(n *Item) { n.Edges.Label = []*Label{} },
func(n *Item, e *Label) { n.Edges.Label = append(n.Edges.Label, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (iq *ItemQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*Item, init func(*Item), assign func(*Item, *Group)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Item)
for i := range nodes {
if nodes[i].group_items == nil {
continue
}
fk := *nodes[i].group_items
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(group.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_items" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (iq *ItemQuery) loadLocation(ctx context.Context, query *LocationQuery, nodes []*Item, init func(*Item), assign func(*Item, *Location)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Item)
for i := range nodes {
if nodes[i].location_items == nil {
continue
}
fk := *nodes[i].location_items
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(location.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "location_items" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (iq *ItemQuery) loadFields(ctx context.Context, query *ItemFieldQuery, nodes []*Item, init func(*Item), assign func(*Item, *ItemField)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Item)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.InValues(item.FieldsColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.item_fields
if fk == nil {
return fmt.Errorf(`foreign-key "item_fields" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "item_fields" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (iq *ItemQuery) loadLabel(ctx context.Context, query *LabelQuery, nodes []*Item, init func(*Item), assign func(*Item, *Label)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[uuid.UUID]*Item)
nids := make(map[uuid.UUID]map[*Item]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(item.LabelTable)
s.Join(joinT).On(s.C(label.FieldID), joinT.C(item.LabelPrimaryKey[0]))
s.Where(sql.InValues(joinT.C(item.LabelPrimaryKey[1]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(item.LabelPrimaryKey[1]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
neighbors, err := query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]interface{}, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]interface{}{new(uuid.UUID)}, values...), nil
}
spec.Assign = func(columns []string, values []interface{}) error {
outValue := *values[0].(*uuid.UUID)
inValue := *values[1].(*uuid.UUID)
if nids[inValue] == nil {
nids[inValue] = map[*Item]struct{}{byID[outValue]: struct{}{}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "label" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (iq *ItemQuery) sqlCount(ctx context.Context) (int, error) {
_spec := iq.querySpec()
_spec.Node.Columns = iq.fields
if len(iq.fields) > 0 {
_spec.Unique = iq.unique != nil && *iq.unique
}
return sqlgraph.CountNodes(ctx, iq.driver, _spec)
}
func (iq *ItemQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := iq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %w", err)
}
return n > 0, nil
}
func (iq *ItemQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: item.Table,
Columns: item.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
From: iq.sql,
Unique: true,
}
if unique := iq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := iq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, item.FieldID)
for i := range fields {
if fields[i] != item.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := iq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := iq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := iq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := iq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (iq *ItemQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(iq.driver.Dialect())
t1 := builder.Table(item.Table)
columns := iq.fields
if len(columns) == 0 {
columns = item.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if iq.sql != nil {
selector = iq.sql
selector.Select(selector.Columns(columns...)...)
}
if iq.unique != nil && *iq.unique {
selector.Distinct()
}
for _, p := range iq.predicates {
p(selector)
}
for _, p := range iq.order {
p(selector)
}
if offset := iq.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 := iq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ItemGroupBy is the group-by builder for Item entities.
type ItemGroupBy struct {
config
selector
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (igb *ItemGroupBy) Aggregate(fns ...AggregateFunc) *ItemGroupBy {
igb.fns = append(igb.fns, fns...)
return igb
}
// Scan applies the group-by query and scans the result into the given value.
func (igb *ItemGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := igb.path(ctx)
if err != nil {
return err
}
igb.sql = query
return igb.sqlScan(ctx, v)
}
func (igb *ItemGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range igb.fields {
if !item.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := igb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := igb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (igb *ItemGroupBy) sqlQuery() *sql.Selector {
selector := igb.sql.Select()
aggregation := make([]string, 0, len(igb.fns))
for _, fn := range igb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(igb.fields)+len(igb.fns))
for _, f := range igb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(igb.fields...)...)
}
// ItemSelect is the builder for selecting fields of Item entities.
type ItemSelect struct {
*ItemQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (is *ItemSelect) Scan(ctx context.Context, v interface{}) error {
if err := is.prepareQuery(ctx); err != nil {
return err
}
is.sql = is.ItemQuery.sqlQuery(ctx)
return is.sqlScan(ctx, v)
}
func (is *ItemSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := is.sql.Query()
if err := is.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

1935
backend/ent/item_update.go Normal file

File diff suppressed because it is too large Load diff

236
backend/ent/itemfield.go Normal file
View file

@ -0,0 +1,236 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/itemfield"
)
// ItemField is the model entity for the ItemField schema.
type ItemField struct {
config `json:"-"`
// ID of the ent.
ID uuid.UUID `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Description holds the value of the "description" field.
Description string `json:"description,omitempty"`
// Type holds the value of the "type" field.
Type itemfield.Type `json:"type,omitempty"`
// TextValue holds the value of the "text_value" field.
TextValue string `json:"text_value,omitempty"`
// NumberValue holds the value of the "number_value" field.
NumberValue int `json:"number_value,omitempty"`
// BooleanValue holds the value of the "boolean_value" field.
BooleanValue bool `json:"boolean_value,omitempty"`
// TimeValue holds the value of the "time_value" field.
TimeValue time.Time `json:"time_value,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the ItemFieldQuery when eager-loading is set.
Edges ItemFieldEdges `json:"edges"`
item_fields *uuid.UUID
}
// ItemFieldEdges holds the relations/edges for other nodes in the graph.
type ItemFieldEdges struct {
// Item holds the value of the item edge.
Item *Item `json:"item,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// ItemOrErr returns the Item value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e ItemFieldEdges) ItemOrErr() (*Item, error) {
if e.loadedTypes[0] {
if e.Item == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: item.Label}
}
return e.Item, nil
}
return nil, &NotLoadedError{edge: "item"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*ItemField) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case itemfield.FieldBooleanValue:
values[i] = new(sql.NullBool)
case itemfield.FieldNumberValue:
values[i] = new(sql.NullInt64)
case itemfield.FieldName, itemfield.FieldDescription, itemfield.FieldType, itemfield.FieldTextValue:
values[i] = new(sql.NullString)
case itemfield.FieldCreatedAt, itemfield.FieldUpdatedAt, itemfield.FieldTimeValue:
values[i] = new(sql.NullTime)
case itemfield.FieldID:
values[i] = new(uuid.UUID)
case itemfield.ForeignKeys[0]: // item_fields
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type ItemField", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the ItemField fields.
func (_if *ItemField) assignValues(columns []string, values []interface{}) 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 itemfield.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
_if.ID = *value
}
case itemfield.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_if.CreatedAt = value.Time
}
case itemfield.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
_if.UpdatedAt = value.Time
}
case itemfield.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_if.Name = value.String
}
case itemfield.FieldDescription:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field description", values[i])
} else if value.Valid {
_if.Description = value.String
}
case itemfield.FieldType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field type", values[i])
} else if value.Valid {
_if.Type = itemfield.Type(value.String)
}
case itemfield.FieldTextValue:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field text_value", values[i])
} else if value.Valid {
_if.TextValue = value.String
}
case itemfield.FieldNumberValue:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field number_value", values[i])
} else if value.Valid {
_if.NumberValue = int(value.Int64)
}
case itemfield.FieldBooleanValue:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field boolean_value", values[i])
} else if value.Valid {
_if.BooleanValue = value.Bool
}
case itemfield.FieldTimeValue:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field time_value", values[i])
} else if value.Valid {
_if.TimeValue = value.Time
}
case itemfield.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field item_fields", values[i])
} else if value.Valid {
_if.item_fields = new(uuid.UUID)
*_if.item_fields = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryItem queries the "item" edge of the ItemField entity.
func (_if *ItemField) QueryItem() *ItemQuery {
return (&ItemFieldClient{config: _if.config}).QueryItem(_if)
}
// Update returns a builder for updating this ItemField.
// Note that you need to call ItemField.Unwrap() before calling this method if this ItemField
// was returned from a transaction, and the transaction was committed or rolled back.
func (_if *ItemField) Update() *ItemFieldUpdateOne {
return (&ItemFieldClient{config: _if.config}).UpdateOne(_if)
}
// Unwrap unwraps the ItemField 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 (_if *ItemField) Unwrap() *ItemField {
_tx, ok := _if.config.driver.(*txDriver)
if !ok {
panic("ent: ItemField is not a transactional entity")
}
_if.config.driver = _tx.drv
return _if
}
// String implements the fmt.Stringer.
func (_if *ItemField) String() string {
var builder strings.Builder
builder.WriteString("ItemField(")
builder.WriteString(fmt.Sprintf("id=%v, ", _if.ID))
builder.WriteString("created_at=")
builder.WriteString(_if.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_if.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(_if.Name)
builder.WriteString(", ")
builder.WriteString("description=")
builder.WriteString(_if.Description)
builder.WriteString(", ")
builder.WriteString("type=")
builder.WriteString(fmt.Sprintf("%v", _if.Type))
builder.WriteString(", ")
builder.WriteString("text_value=")
builder.WriteString(_if.TextValue)
builder.WriteString(", ")
builder.WriteString("number_value=")
builder.WriteString(fmt.Sprintf("%v", _if.NumberValue))
builder.WriteString(", ")
builder.WriteString("boolean_value=")
builder.WriteString(fmt.Sprintf("%v", _if.BooleanValue))
builder.WriteString(", ")
builder.WriteString("time_value=")
builder.WriteString(_if.TimeValue.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// ItemFields is a parsable slice of ItemField.
type ItemFields []*ItemField
func (_if ItemFields) config(cfg config) {
for _i := range _if {
_if[_i].config = cfg
}
}

View file

@ -0,0 +1,127 @@
// Code generated by ent, DO NOT EDIT.
package itemfield
import (
"fmt"
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the itemfield type in the database.
Label = "item_field"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldDescription holds the string denoting the description field in the database.
FieldDescription = "description"
// FieldType holds the string denoting the type field in the database.
FieldType = "type"
// FieldTextValue holds the string denoting the text_value field in the database.
FieldTextValue = "text_value"
// FieldNumberValue holds the string denoting the number_value field in the database.
FieldNumberValue = "number_value"
// FieldBooleanValue holds the string denoting the boolean_value field in the database.
FieldBooleanValue = "boolean_value"
// FieldTimeValue holds the string denoting the time_value field in the database.
FieldTimeValue = "time_value"
// EdgeItem holds the string denoting the item edge name in mutations.
EdgeItem = "item"
// Table holds the table name of the itemfield in the database.
Table = "item_fields"
// ItemTable is the table that holds the item relation/edge.
ItemTable = "item_fields"
// ItemInverseTable is the table name for the Item entity.
// It exists in this package in order to avoid circular dependency with the "item" package.
ItemInverseTable = "items"
// ItemColumn is the table column denoting the item relation/edge.
ItemColumn = "item_fields"
)
// Columns holds all SQL columns for itemfield fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldName,
FieldDescription,
FieldType,
FieldTextValue,
FieldNumberValue,
FieldBooleanValue,
FieldTimeValue,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "item_fields"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"item_fields",
}
// 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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
DescriptionValidator func(string) error
// TextValueValidator is a validator for the "text_value" field. It is called by the builders before save.
TextValueValidator func(string) error
// DefaultBooleanValue holds the default value on creation for the "boolean_value" field.
DefaultBooleanValue bool
// DefaultTimeValue holds the default value on creation for the "time_value" field.
DefaultTimeValue func() time.Time
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)
// Type defines the type for the "type" enum field.
type Type string
// Type values.
const (
TypeText Type = "text"
TypeNumber Type = "number"
TypeBoolean Type = "boolean"
TypeTime Type = "time"
)
func (_type Type) String() string {
return string(_type)
}
// TypeValidator is a validator for the "type" field enum values. It is called by the builders before save.
func TypeValidator(_type Type) error {
switch _type {
case TypeText, TypeNumber, TypeBoolean, TypeTime:
return nil
default:
return fmt.Errorf("itemfield: invalid enum value for type field: %q", _type)
}
}

View file

@ -0,0 +1,844 @@
// Code generated by ent, DO NOT EDIT.
package itemfield
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id uuid.UUID) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id uuid.UUID) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id uuid.UUID) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...uuid.UUID) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...uuid.UUID) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id uuid.UUID) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id uuid.UUID) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id uuid.UUID) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id uuid.UUID) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
})
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
})
}
// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ.
func Description(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDescription), v))
})
}
// TextValue applies equality check predicate on the "text_value" field. It's identical to TextValueEQ.
func TextValue(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldTextValue), v))
})
}
// NumberValue applies equality check predicate on the "number_value" field. It's identical to NumberValueEQ.
func NumberValue(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldNumberValue), v))
})
}
// BooleanValue applies equality check predicate on the "boolean_value" field. It's identical to BooleanValueEQ.
func BooleanValue(v bool) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldBooleanValue), v))
})
}
// TimeValue applies equality check predicate on the "time_value" field. It's identical to TimeValueEQ.
func TimeValue(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldTimeValue), v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
})
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldCreatedAt), v))
})
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldCreatedAt), v...))
})
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldCreatedAt), v...))
})
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldCreatedAt), v))
})
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldUpdatedAt), v...))
})
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...))
})
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldName), v...))
})
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldName), v...))
})
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldName), v))
})
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldName), v))
})
}
// DescriptionEQ applies the EQ predicate on the "description" field.
func DescriptionEQ(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDescription), v))
})
}
// DescriptionNEQ applies the NEQ predicate on the "description" field.
func DescriptionNEQ(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldDescription), v))
})
}
// DescriptionIn applies the In predicate on the "description" field.
func DescriptionIn(vs ...string) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldDescription), v...))
})
}
// DescriptionNotIn applies the NotIn predicate on the "description" field.
func DescriptionNotIn(vs ...string) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldDescription), v...))
})
}
// DescriptionGT applies the GT predicate on the "description" field.
func DescriptionGT(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldDescription), v))
})
}
// DescriptionGTE applies the GTE predicate on the "description" field.
func DescriptionGTE(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldDescription), v))
})
}
// DescriptionLT applies the LT predicate on the "description" field.
func DescriptionLT(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldDescription), v))
})
}
// DescriptionLTE applies the LTE predicate on the "description" field.
func DescriptionLTE(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldDescription), v))
})
}
// DescriptionContains applies the Contains predicate on the "description" field.
func DescriptionContains(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldDescription), v))
})
}
// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field.
func DescriptionHasPrefix(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldDescription), v))
})
}
// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field.
func DescriptionHasSuffix(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldDescription), v))
})
}
// DescriptionIsNil applies the IsNil predicate on the "description" field.
func DescriptionIsNil() predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldDescription)))
})
}
// DescriptionNotNil applies the NotNil predicate on the "description" field.
func DescriptionNotNil() predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldDescription)))
})
}
// DescriptionEqualFold applies the EqualFold predicate on the "description" field.
func DescriptionEqualFold(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldDescription), v))
})
}
// DescriptionContainsFold applies the ContainsFold predicate on the "description" field.
func DescriptionContainsFold(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldDescription), v))
})
}
// TypeEQ applies the EQ predicate on the "type" field.
func TypeEQ(v Type) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldType), v))
})
}
// TypeNEQ applies the NEQ predicate on the "type" field.
func TypeNEQ(v Type) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldType), v))
})
}
// TypeIn applies the In predicate on the "type" field.
func TypeIn(vs ...Type) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldType), v...))
})
}
// TypeNotIn applies the NotIn predicate on the "type" field.
func TypeNotIn(vs ...Type) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldType), v...))
})
}
// TextValueEQ applies the EQ predicate on the "text_value" field.
func TextValueEQ(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldTextValue), v))
})
}
// TextValueNEQ applies the NEQ predicate on the "text_value" field.
func TextValueNEQ(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldTextValue), v))
})
}
// TextValueIn applies the In predicate on the "text_value" field.
func TextValueIn(vs ...string) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldTextValue), v...))
})
}
// TextValueNotIn applies the NotIn predicate on the "text_value" field.
func TextValueNotIn(vs ...string) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldTextValue), v...))
})
}
// TextValueGT applies the GT predicate on the "text_value" field.
func TextValueGT(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldTextValue), v))
})
}
// TextValueGTE applies the GTE predicate on the "text_value" field.
func TextValueGTE(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldTextValue), v))
})
}
// TextValueLT applies the LT predicate on the "text_value" field.
func TextValueLT(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldTextValue), v))
})
}
// TextValueLTE applies the LTE predicate on the "text_value" field.
func TextValueLTE(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldTextValue), v))
})
}
// TextValueContains applies the Contains predicate on the "text_value" field.
func TextValueContains(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldTextValue), v))
})
}
// TextValueHasPrefix applies the HasPrefix predicate on the "text_value" field.
func TextValueHasPrefix(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldTextValue), v))
})
}
// TextValueHasSuffix applies the HasSuffix predicate on the "text_value" field.
func TextValueHasSuffix(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldTextValue), v))
})
}
// TextValueIsNil applies the IsNil predicate on the "text_value" field.
func TextValueIsNil() predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldTextValue)))
})
}
// TextValueNotNil applies the NotNil predicate on the "text_value" field.
func TextValueNotNil() predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldTextValue)))
})
}
// TextValueEqualFold applies the EqualFold predicate on the "text_value" field.
func TextValueEqualFold(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldTextValue), v))
})
}
// TextValueContainsFold applies the ContainsFold predicate on the "text_value" field.
func TextValueContainsFold(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldTextValue), v))
})
}
// NumberValueEQ applies the EQ predicate on the "number_value" field.
func NumberValueEQ(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldNumberValue), v))
})
}
// NumberValueNEQ applies the NEQ predicate on the "number_value" field.
func NumberValueNEQ(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldNumberValue), v))
})
}
// NumberValueIn applies the In predicate on the "number_value" field.
func NumberValueIn(vs ...int) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldNumberValue), v...))
})
}
// NumberValueNotIn applies the NotIn predicate on the "number_value" field.
func NumberValueNotIn(vs ...int) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldNumberValue), v...))
})
}
// NumberValueGT applies the GT predicate on the "number_value" field.
func NumberValueGT(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldNumberValue), v))
})
}
// NumberValueGTE applies the GTE predicate on the "number_value" field.
func NumberValueGTE(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldNumberValue), v))
})
}
// NumberValueLT applies the LT predicate on the "number_value" field.
func NumberValueLT(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldNumberValue), v))
})
}
// NumberValueLTE applies the LTE predicate on the "number_value" field.
func NumberValueLTE(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldNumberValue), v))
})
}
// NumberValueIsNil applies the IsNil predicate on the "number_value" field.
func NumberValueIsNil() predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldNumberValue)))
})
}
// NumberValueNotNil applies the NotNil predicate on the "number_value" field.
func NumberValueNotNil() predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldNumberValue)))
})
}
// BooleanValueEQ applies the EQ predicate on the "boolean_value" field.
func BooleanValueEQ(v bool) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldBooleanValue), v))
})
}
// BooleanValueNEQ applies the NEQ predicate on the "boolean_value" field.
func BooleanValueNEQ(v bool) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldBooleanValue), v))
})
}
// TimeValueEQ applies the EQ predicate on the "time_value" field.
func TimeValueEQ(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldTimeValue), v))
})
}
// TimeValueNEQ applies the NEQ predicate on the "time_value" field.
func TimeValueNEQ(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldTimeValue), v))
})
}
// TimeValueIn applies the In predicate on the "time_value" field.
func TimeValueIn(vs ...time.Time) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldTimeValue), v...))
})
}
// TimeValueNotIn applies the NotIn predicate on the "time_value" field.
func TimeValueNotIn(vs ...time.Time) predicate.ItemField {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldTimeValue), v...))
})
}
// TimeValueGT applies the GT predicate on the "time_value" field.
func TimeValueGT(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldTimeValue), v))
})
}
// TimeValueGTE applies the GTE predicate on the "time_value" field.
func TimeValueGTE(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldTimeValue), v))
})
}
// TimeValueLT applies the LT predicate on the "time_value" field.
func TimeValueLT(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldTimeValue), v))
})
}
// TimeValueLTE applies the LTE predicate on the "time_value" field.
func TimeValueLTE(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldTimeValue), v))
})
}
// HasItem applies the HasEdge predicate on the "item" edge.
func HasItem() predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, ItemTable, ItemColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasItemWith applies the HasEdge predicate on the "item" edge with a given conditions (other predicates).
func HasItemWith(preds ...predicate.Item) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, ItemTable, ItemColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.ItemField) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.ItemField) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.ItemField) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,516 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/itemfield"
)
// ItemFieldCreate is the builder for creating a ItemField entity.
type ItemFieldCreate struct {
config
mutation *ItemFieldMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (ifc *ItemFieldCreate) SetCreatedAt(t time.Time) *ItemFieldCreate {
ifc.mutation.SetCreatedAt(t)
return ifc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableCreatedAt(t *time.Time) *ItemFieldCreate {
if t != nil {
ifc.SetCreatedAt(*t)
}
return ifc
}
// SetUpdatedAt sets the "updated_at" field.
func (ifc *ItemFieldCreate) SetUpdatedAt(t time.Time) *ItemFieldCreate {
ifc.mutation.SetUpdatedAt(t)
return ifc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableUpdatedAt(t *time.Time) *ItemFieldCreate {
if t != nil {
ifc.SetUpdatedAt(*t)
}
return ifc
}
// SetName sets the "name" field.
func (ifc *ItemFieldCreate) SetName(s string) *ItemFieldCreate {
ifc.mutation.SetName(s)
return ifc
}
// SetDescription sets the "description" field.
func (ifc *ItemFieldCreate) SetDescription(s string) *ItemFieldCreate {
ifc.mutation.SetDescription(s)
return ifc
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableDescription(s *string) *ItemFieldCreate {
if s != nil {
ifc.SetDescription(*s)
}
return ifc
}
// SetType sets the "type" field.
func (ifc *ItemFieldCreate) SetType(i itemfield.Type) *ItemFieldCreate {
ifc.mutation.SetType(i)
return ifc
}
// SetTextValue sets the "text_value" field.
func (ifc *ItemFieldCreate) SetTextValue(s string) *ItemFieldCreate {
ifc.mutation.SetTextValue(s)
return ifc
}
// SetNillableTextValue sets the "text_value" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableTextValue(s *string) *ItemFieldCreate {
if s != nil {
ifc.SetTextValue(*s)
}
return ifc
}
// SetNumberValue sets the "number_value" field.
func (ifc *ItemFieldCreate) SetNumberValue(i int) *ItemFieldCreate {
ifc.mutation.SetNumberValue(i)
return ifc
}
// SetNillableNumberValue sets the "number_value" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableNumberValue(i *int) *ItemFieldCreate {
if i != nil {
ifc.SetNumberValue(*i)
}
return ifc
}
// SetBooleanValue sets the "boolean_value" field.
func (ifc *ItemFieldCreate) SetBooleanValue(b bool) *ItemFieldCreate {
ifc.mutation.SetBooleanValue(b)
return ifc
}
// SetNillableBooleanValue sets the "boolean_value" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableBooleanValue(b *bool) *ItemFieldCreate {
if b != nil {
ifc.SetBooleanValue(*b)
}
return ifc
}
// SetTimeValue sets the "time_value" field.
func (ifc *ItemFieldCreate) SetTimeValue(t time.Time) *ItemFieldCreate {
ifc.mutation.SetTimeValue(t)
return ifc
}
// SetNillableTimeValue sets the "time_value" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableTimeValue(t *time.Time) *ItemFieldCreate {
if t != nil {
ifc.SetTimeValue(*t)
}
return ifc
}
// SetID sets the "id" field.
func (ifc *ItemFieldCreate) SetID(u uuid.UUID) *ItemFieldCreate {
ifc.mutation.SetID(u)
return ifc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableID(u *uuid.UUID) *ItemFieldCreate {
if u != nil {
ifc.SetID(*u)
}
return ifc
}
// SetItemID sets the "item" edge to the Item entity by ID.
func (ifc *ItemFieldCreate) SetItemID(id uuid.UUID) *ItemFieldCreate {
ifc.mutation.SetItemID(id)
return ifc
}
// SetNillableItemID sets the "item" edge to the Item entity by ID if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableItemID(id *uuid.UUID) *ItemFieldCreate {
if id != nil {
ifc = ifc.SetItemID(*id)
}
return ifc
}
// SetItem sets the "item" edge to the Item entity.
func (ifc *ItemFieldCreate) SetItem(i *Item) *ItemFieldCreate {
return ifc.SetItemID(i.ID)
}
// Mutation returns the ItemFieldMutation object of the builder.
func (ifc *ItemFieldCreate) Mutation() *ItemFieldMutation {
return ifc.mutation
}
// Save creates the ItemField in the database.
func (ifc *ItemFieldCreate) Save(ctx context.Context) (*ItemField, error) {
var (
err error
node *ItemField
)
ifc.defaults()
if len(ifc.hooks) == 0 {
if err = ifc.check(); err != nil {
return nil, err
}
node, err = ifc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemFieldMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = ifc.check(); err != nil {
return nil, err
}
ifc.mutation = mutation
if node, err = ifc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(ifc.hooks) - 1; i >= 0; i-- {
if ifc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ifc.hooks[i](mut)
}
v, err := mut.Mutate(ctx, ifc.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*ItemField)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from ItemFieldMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (ifc *ItemFieldCreate) SaveX(ctx context.Context) *ItemField {
v, err := ifc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ifc *ItemFieldCreate) Exec(ctx context.Context) error {
_, err := ifc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ifc *ItemFieldCreate) ExecX(ctx context.Context) {
if err := ifc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (ifc *ItemFieldCreate) defaults() {
if _, ok := ifc.mutation.CreatedAt(); !ok {
v := itemfield.DefaultCreatedAt()
ifc.mutation.SetCreatedAt(v)
}
if _, ok := ifc.mutation.UpdatedAt(); !ok {
v := itemfield.DefaultUpdatedAt()
ifc.mutation.SetUpdatedAt(v)
}
if _, ok := ifc.mutation.BooleanValue(); !ok {
v := itemfield.DefaultBooleanValue
ifc.mutation.SetBooleanValue(v)
}
if _, ok := ifc.mutation.TimeValue(); !ok {
v := itemfield.DefaultTimeValue()
ifc.mutation.SetTimeValue(v)
}
if _, ok := ifc.mutation.ID(); !ok {
v := itemfield.DefaultID()
ifc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (ifc *ItemFieldCreate) check() error {
if _, ok := ifc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "ItemField.created_at"`)}
}
if _, ok := ifc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "ItemField.updated_at"`)}
}
if _, ok := ifc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "ItemField.name"`)}
}
if v, ok := ifc.mutation.Name(); ok {
if err := itemfield.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "ItemField.name": %w`, err)}
}
}
if v, ok := ifc.mutation.Description(); ok {
if err := itemfield.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "ItemField.description": %w`, err)}
}
}
if _, ok := ifc.mutation.GetType(); !ok {
return &ValidationError{Name: "type", err: errors.New(`ent: missing required field "ItemField.type"`)}
}
if v, ok := ifc.mutation.GetType(); ok {
if err := itemfield.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "ItemField.type": %w`, err)}
}
}
if v, ok := ifc.mutation.TextValue(); ok {
if err := itemfield.TextValueValidator(v); err != nil {
return &ValidationError{Name: "text_value", err: fmt.Errorf(`ent: validator failed for field "ItemField.text_value": %w`, err)}
}
}
if _, ok := ifc.mutation.BooleanValue(); !ok {
return &ValidationError{Name: "boolean_value", err: errors.New(`ent: missing required field "ItemField.boolean_value"`)}
}
if _, ok := ifc.mutation.TimeValue(); !ok {
return &ValidationError{Name: "time_value", err: errors.New(`ent: missing required field "ItemField.time_value"`)}
}
return nil
}
func (ifc *ItemFieldCreate) sqlSave(ctx context.Context) (*ItemField, error) {
_node, _spec := ifc.createSpec()
if err := sqlgraph.CreateNode(ctx, ifc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
if _spec.ID.Value != nil {
if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
_node.ID = *id
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
return nil, err
}
}
return _node, nil
}
func (ifc *ItemFieldCreate) createSpec() (*ItemField, *sqlgraph.CreateSpec) {
var (
_node = &ItemField{config: ifc.config}
_spec = &sqlgraph.CreateSpec{
Table: itemfield.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: itemfield.FieldID,
},
}
)
if id, ok := ifc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := ifc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := ifc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := ifc.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldName,
})
_node.Name = value
}
if value, ok := ifc.mutation.Description(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldDescription,
})
_node.Description = value
}
if value, ok := ifc.mutation.GetType(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeEnum,
Value: value,
Column: itemfield.FieldType,
})
_node.Type = value
}
if value, ok := ifc.mutation.TextValue(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldTextValue,
})
_node.TextValue = value
}
if value, ok := ifc.mutation.NumberValue(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: itemfield.FieldNumberValue,
})
_node.NumberValue = value
}
if value, ok := ifc.mutation.BooleanValue(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: itemfield.FieldBooleanValue,
})
_node.BooleanValue = value
}
if value, ok := ifc.mutation.TimeValue(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldTimeValue,
})
_node.TimeValue = value
}
if nodes := ifc.mutation.ItemIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: itemfield.ItemTable,
Columns: []string{itemfield.ItemColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.item_fields = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// ItemFieldCreateBulk is the builder for creating many ItemField entities in bulk.
type ItemFieldCreateBulk struct {
config
builders []*ItemFieldCreate
}
// Save creates the ItemField entities in the database.
func (ifcb *ItemFieldCreateBulk) Save(ctx context.Context) ([]*ItemField, error) {
specs := make([]*sqlgraph.CreateSpec, len(ifcb.builders))
nodes := make([]*ItemField, len(ifcb.builders))
mutators := make([]Mutator, len(ifcb.builders))
for i := range ifcb.builders {
func(i int, root context.Context) {
builder := ifcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemFieldMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, ifcb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, ifcb.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
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, ifcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (ifcb *ItemFieldCreateBulk) SaveX(ctx context.Context) []*ItemField {
v, err := ifcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ifcb *ItemFieldCreateBulk) Exec(ctx context.Context) error {
_, err := ifcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ifcb *ItemFieldCreateBulk) ExecX(ctx context.Context) {
if err := ifcb.Exec(ctx); err != nil {
panic(err)
}
}

View file

@ -0,0 +1,115 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/hay-kot/content/backend/ent/itemfield"
"github.com/hay-kot/content/backend/ent/predicate"
)
// ItemFieldDelete is the builder for deleting a ItemField entity.
type ItemFieldDelete struct {
config
hooks []Hook
mutation *ItemFieldMutation
}
// Where appends a list predicates to the ItemFieldDelete builder.
func (ifd *ItemFieldDelete) Where(ps ...predicate.ItemField) *ItemFieldDelete {
ifd.mutation.Where(ps...)
return ifd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (ifd *ItemFieldDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(ifd.hooks) == 0 {
affected, err = ifd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemFieldMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
ifd.mutation = mutation
affected, err = ifd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(ifd.hooks) - 1; i >= 0; i-- {
if ifd.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ifd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ifd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (ifd *ItemFieldDelete) ExecX(ctx context.Context) int {
n, err := ifd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (ifd *ItemFieldDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: itemfield.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: itemfield.FieldID,
},
},
}
if ps := ifd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, ifd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// ItemFieldDeleteOne is the builder for deleting a single ItemField entity.
type ItemFieldDeleteOne struct {
ifd *ItemFieldDelete
}
// Exec executes the deletion query.
func (ifdo *ItemFieldDeleteOne) Exec(ctx context.Context) error {
n, err := ifdo.ifd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{itemfield.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (ifdo *ItemFieldDeleteOne) ExecX(ctx context.Context) {
ifdo.ifd.ExecX(ctx)
}

View file

@ -0,0 +1,611 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/itemfield"
"github.com/hay-kot/content/backend/ent/predicate"
)
// ItemFieldQuery is the builder for querying ItemField entities.
type ItemFieldQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.ItemField
withItem *ItemQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the ItemFieldQuery builder.
func (ifq *ItemFieldQuery) Where(ps ...predicate.ItemField) *ItemFieldQuery {
ifq.predicates = append(ifq.predicates, ps...)
return ifq
}
// Limit adds a limit step to the query.
func (ifq *ItemFieldQuery) Limit(limit int) *ItemFieldQuery {
ifq.limit = &limit
return ifq
}
// Offset adds an offset step to the query.
func (ifq *ItemFieldQuery) Offset(offset int) *ItemFieldQuery {
ifq.offset = &offset
return ifq
}
// 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 (ifq *ItemFieldQuery) Unique(unique bool) *ItemFieldQuery {
ifq.unique = &unique
return ifq
}
// Order adds an order step to the query.
func (ifq *ItemFieldQuery) Order(o ...OrderFunc) *ItemFieldQuery {
ifq.order = append(ifq.order, o...)
return ifq
}
// QueryItem chains the current query on the "item" edge.
func (ifq *ItemFieldQuery) QueryItem() *ItemQuery {
query := &ItemQuery{config: ifq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := ifq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := ifq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(itemfield.Table, itemfield.FieldID, selector),
sqlgraph.To(item.Table, item.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, itemfield.ItemTable, itemfield.ItemColumn),
)
fromU = sqlgraph.SetNeighbors(ifq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first ItemField entity from the query.
// Returns a *NotFoundError when no ItemField was found.
func (ifq *ItemFieldQuery) First(ctx context.Context) (*ItemField, error) {
nodes, err := ifq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{itemfield.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (ifq *ItemFieldQuery) FirstX(ctx context.Context) *ItemField {
node, err := ifq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first ItemField ID from the query.
// Returns a *NotFoundError when no ItemField ID was found.
func (ifq *ItemFieldQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = ifq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{itemfield.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (ifq *ItemFieldQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := ifq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single ItemField entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one ItemField entity is found.
// Returns a *NotFoundError when no ItemField entities are found.
func (ifq *ItemFieldQuery) Only(ctx context.Context) (*ItemField, error) {
nodes, err := ifq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{itemfield.Label}
default:
return nil, &NotSingularError{itemfield.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (ifq *ItemFieldQuery) OnlyX(ctx context.Context) *ItemField {
node, err := ifq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only ItemField ID in the query.
// Returns a *NotSingularError when more than one ItemField ID is found.
// Returns a *NotFoundError when no entities are found.
func (ifq *ItemFieldQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = ifq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{itemfield.Label}
default:
err = &NotSingularError{itemfield.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (ifq *ItemFieldQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := ifq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of ItemFields.
func (ifq *ItemFieldQuery) All(ctx context.Context) ([]*ItemField, error) {
if err := ifq.prepareQuery(ctx); err != nil {
return nil, err
}
return ifq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (ifq *ItemFieldQuery) AllX(ctx context.Context) []*ItemField {
nodes, err := ifq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of ItemField IDs.
func (ifq *ItemFieldQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := ifq.Select(itemfield.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (ifq *ItemFieldQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := ifq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (ifq *ItemFieldQuery) Count(ctx context.Context) (int, error) {
if err := ifq.prepareQuery(ctx); err != nil {
return 0, err
}
return ifq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (ifq *ItemFieldQuery) CountX(ctx context.Context) int {
count, err := ifq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (ifq *ItemFieldQuery) Exist(ctx context.Context) (bool, error) {
if err := ifq.prepareQuery(ctx); err != nil {
return false, err
}
return ifq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (ifq *ItemFieldQuery) ExistX(ctx context.Context) bool {
exist, err := ifq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the ItemFieldQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (ifq *ItemFieldQuery) Clone() *ItemFieldQuery {
if ifq == nil {
return nil
}
return &ItemFieldQuery{
config: ifq.config,
limit: ifq.limit,
offset: ifq.offset,
order: append([]OrderFunc{}, ifq.order...),
predicates: append([]predicate.ItemField{}, ifq.predicates...),
withItem: ifq.withItem.Clone(),
// clone intermediate query.
sql: ifq.sql.Clone(),
path: ifq.path,
unique: ifq.unique,
}
}
// WithItem tells the query-builder to eager-load the nodes that are connected to
// the "item" edge. The optional arguments are used to configure the query builder of the edge.
func (ifq *ItemFieldQuery) WithItem(opts ...func(*ItemQuery)) *ItemFieldQuery {
query := &ItemQuery{config: ifq.config}
for _, opt := range opts {
opt(query)
}
ifq.withItem = query
return ifq
}
// 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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.ItemField.Query().
// GroupBy(itemfield.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (ifq *ItemFieldQuery) GroupBy(field string, fields ...string) *ItemFieldGroupBy {
grbuild := &ItemFieldGroupBy{config: ifq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := ifq.prepareQuery(ctx); err != nil {
return nil, err
}
return ifq.sqlQuery(ctx), nil
}
grbuild.label = itemfield.Label
grbuild.flds, grbuild.scan = &grbuild.fields, 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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// }
//
// client.ItemField.Query().
// Select(itemfield.FieldCreatedAt).
// Scan(ctx, &v)
func (ifq *ItemFieldQuery) Select(fields ...string) *ItemFieldSelect {
ifq.fields = append(ifq.fields, fields...)
selbuild := &ItemFieldSelect{ItemFieldQuery: ifq}
selbuild.label = itemfield.Label
selbuild.flds, selbuild.scan = &ifq.fields, selbuild.Scan
return selbuild
}
func (ifq *ItemFieldQuery) prepareQuery(ctx context.Context) error {
for _, f := range ifq.fields {
if !itemfield.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if ifq.path != nil {
prev, err := ifq.path(ctx)
if err != nil {
return err
}
ifq.sql = prev
}
return nil
}
func (ifq *ItemFieldQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ItemField, error) {
var (
nodes = []*ItemField{}
withFKs = ifq.withFKs
_spec = ifq.querySpec()
loadedTypes = [1]bool{
ifq.withItem != nil,
}
)
if ifq.withItem != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, itemfield.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
return (*ItemField).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
node := &ItemField{config: ifq.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, ifq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := ifq.withItem; query != nil {
if err := ifq.loadItem(ctx, query, nodes, nil,
func(n *ItemField, e *Item) { n.Edges.Item = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (ifq *ItemFieldQuery) loadItem(ctx context.Context, query *ItemQuery, nodes []*ItemField, init func(*ItemField), assign func(*ItemField, *Item)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*ItemField)
for i := range nodes {
if nodes[i].item_fields == nil {
continue
}
fk := *nodes[i].item_fields
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(item.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "item_fields" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (ifq *ItemFieldQuery) sqlCount(ctx context.Context) (int, error) {
_spec := ifq.querySpec()
_spec.Node.Columns = ifq.fields
if len(ifq.fields) > 0 {
_spec.Unique = ifq.unique != nil && *ifq.unique
}
return sqlgraph.CountNodes(ctx, ifq.driver, _spec)
}
func (ifq *ItemFieldQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := ifq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %w", err)
}
return n > 0, nil
}
func (ifq *ItemFieldQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: itemfield.Table,
Columns: itemfield.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: itemfield.FieldID,
},
},
From: ifq.sql,
Unique: true,
}
if unique := ifq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := ifq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, itemfield.FieldID)
for i := range fields {
if fields[i] != itemfield.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := ifq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := ifq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := ifq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := ifq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (ifq *ItemFieldQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(ifq.driver.Dialect())
t1 := builder.Table(itemfield.Table)
columns := ifq.fields
if len(columns) == 0 {
columns = itemfield.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if ifq.sql != nil {
selector = ifq.sql
selector.Select(selector.Columns(columns...)...)
}
if ifq.unique != nil && *ifq.unique {
selector.Distinct()
}
for _, p := range ifq.predicates {
p(selector)
}
for _, p := range ifq.order {
p(selector)
}
if offset := ifq.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 := ifq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ItemFieldGroupBy is the group-by builder for ItemField entities.
type ItemFieldGroupBy struct {
config
selector
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (ifgb *ItemFieldGroupBy) Aggregate(fns ...AggregateFunc) *ItemFieldGroupBy {
ifgb.fns = append(ifgb.fns, fns...)
return ifgb
}
// Scan applies the group-by query and scans the result into the given value.
func (ifgb *ItemFieldGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := ifgb.path(ctx)
if err != nil {
return err
}
ifgb.sql = query
return ifgb.sqlScan(ctx, v)
}
func (ifgb *ItemFieldGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range ifgb.fields {
if !itemfield.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := ifgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := ifgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (ifgb *ItemFieldGroupBy) sqlQuery() *sql.Selector {
selector := ifgb.sql.Select()
aggregation := make([]string, 0, len(ifgb.fns))
for _, fn := range ifgb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(ifgb.fields)+len(ifgb.fns))
for _, f := range ifgb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(ifgb.fields...)...)
}
// ItemFieldSelect is the builder for selecting fields of ItemField entities.
type ItemFieldSelect struct {
*ItemFieldQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (ifs *ItemFieldSelect) Scan(ctx context.Context, v interface{}) error {
if err := ifs.prepareQuery(ctx); err != nil {
return err
}
ifs.sql = ifs.ItemFieldQuery.sqlQuery(ctx)
return ifs.sqlScan(ctx, v)
}
func (ifs *ItemFieldSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := ifs.sql.Query()
if err := ifs.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View file

@ -0,0 +1,836 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/itemfield"
"github.com/hay-kot/content/backend/ent/predicate"
)
// ItemFieldUpdate is the builder for updating ItemField entities.
type ItemFieldUpdate struct {
config
hooks []Hook
mutation *ItemFieldMutation
}
// Where appends a list predicates to the ItemFieldUpdate builder.
func (ifu *ItemFieldUpdate) Where(ps ...predicate.ItemField) *ItemFieldUpdate {
ifu.mutation.Where(ps...)
return ifu
}
// SetUpdatedAt sets the "updated_at" field.
func (ifu *ItemFieldUpdate) SetUpdatedAt(t time.Time) *ItemFieldUpdate {
ifu.mutation.SetUpdatedAt(t)
return ifu
}
// SetName sets the "name" field.
func (ifu *ItemFieldUpdate) SetName(s string) *ItemFieldUpdate {
ifu.mutation.SetName(s)
return ifu
}
// SetDescription sets the "description" field.
func (ifu *ItemFieldUpdate) SetDescription(s string) *ItemFieldUpdate {
ifu.mutation.SetDescription(s)
return ifu
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (ifu *ItemFieldUpdate) SetNillableDescription(s *string) *ItemFieldUpdate {
if s != nil {
ifu.SetDescription(*s)
}
return ifu
}
// ClearDescription clears the value of the "description" field.
func (ifu *ItemFieldUpdate) ClearDescription() *ItemFieldUpdate {
ifu.mutation.ClearDescription()
return ifu
}
// SetType sets the "type" field.
func (ifu *ItemFieldUpdate) SetType(i itemfield.Type) *ItemFieldUpdate {
ifu.mutation.SetType(i)
return ifu
}
// SetTextValue sets the "text_value" field.
func (ifu *ItemFieldUpdate) SetTextValue(s string) *ItemFieldUpdate {
ifu.mutation.SetTextValue(s)
return ifu
}
// SetNillableTextValue sets the "text_value" field if the given value is not nil.
func (ifu *ItemFieldUpdate) SetNillableTextValue(s *string) *ItemFieldUpdate {
if s != nil {
ifu.SetTextValue(*s)
}
return ifu
}
// ClearTextValue clears the value of the "text_value" field.
func (ifu *ItemFieldUpdate) ClearTextValue() *ItemFieldUpdate {
ifu.mutation.ClearTextValue()
return ifu
}
// SetNumberValue sets the "number_value" field.
func (ifu *ItemFieldUpdate) SetNumberValue(i int) *ItemFieldUpdate {
ifu.mutation.ResetNumberValue()
ifu.mutation.SetNumberValue(i)
return ifu
}
// SetNillableNumberValue sets the "number_value" field if the given value is not nil.
func (ifu *ItemFieldUpdate) SetNillableNumberValue(i *int) *ItemFieldUpdate {
if i != nil {
ifu.SetNumberValue(*i)
}
return ifu
}
// AddNumberValue adds i to the "number_value" field.
func (ifu *ItemFieldUpdate) AddNumberValue(i int) *ItemFieldUpdate {
ifu.mutation.AddNumberValue(i)
return ifu
}
// ClearNumberValue clears the value of the "number_value" field.
func (ifu *ItemFieldUpdate) ClearNumberValue() *ItemFieldUpdate {
ifu.mutation.ClearNumberValue()
return ifu
}
// SetBooleanValue sets the "boolean_value" field.
func (ifu *ItemFieldUpdate) SetBooleanValue(b bool) *ItemFieldUpdate {
ifu.mutation.SetBooleanValue(b)
return ifu
}
// SetNillableBooleanValue sets the "boolean_value" field if the given value is not nil.
func (ifu *ItemFieldUpdate) SetNillableBooleanValue(b *bool) *ItemFieldUpdate {
if b != nil {
ifu.SetBooleanValue(*b)
}
return ifu
}
// SetTimeValue sets the "time_value" field.
func (ifu *ItemFieldUpdate) SetTimeValue(t time.Time) *ItemFieldUpdate {
ifu.mutation.SetTimeValue(t)
return ifu
}
// SetNillableTimeValue sets the "time_value" field if the given value is not nil.
func (ifu *ItemFieldUpdate) SetNillableTimeValue(t *time.Time) *ItemFieldUpdate {
if t != nil {
ifu.SetTimeValue(*t)
}
return ifu
}
// SetItemID sets the "item" edge to the Item entity by ID.
func (ifu *ItemFieldUpdate) SetItemID(id uuid.UUID) *ItemFieldUpdate {
ifu.mutation.SetItemID(id)
return ifu
}
// SetNillableItemID sets the "item" edge to the Item entity by ID if the given value is not nil.
func (ifu *ItemFieldUpdate) SetNillableItemID(id *uuid.UUID) *ItemFieldUpdate {
if id != nil {
ifu = ifu.SetItemID(*id)
}
return ifu
}
// SetItem sets the "item" edge to the Item entity.
func (ifu *ItemFieldUpdate) SetItem(i *Item) *ItemFieldUpdate {
return ifu.SetItemID(i.ID)
}
// Mutation returns the ItemFieldMutation object of the builder.
func (ifu *ItemFieldUpdate) Mutation() *ItemFieldMutation {
return ifu.mutation
}
// ClearItem clears the "item" edge to the Item entity.
func (ifu *ItemFieldUpdate) ClearItem() *ItemFieldUpdate {
ifu.mutation.ClearItem()
return ifu
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (ifu *ItemFieldUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
ifu.defaults()
if len(ifu.hooks) == 0 {
if err = ifu.check(); err != nil {
return 0, err
}
affected, err = ifu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemFieldMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = ifu.check(); err != nil {
return 0, err
}
ifu.mutation = mutation
affected, err = ifu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(ifu.hooks) - 1; i >= 0; i-- {
if ifu.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ifu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ifu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (ifu *ItemFieldUpdate) SaveX(ctx context.Context) int {
affected, err := ifu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (ifu *ItemFieldUpdate) Exec(ctx context.Context) error {
_, err := ifu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ifu *ItemFieldUpdate) ExecX(ctx context.Context) {
if err := ifu.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (ifu *ItemFieldUpdate) defaults() {
if _, ok := ifu.mutation.UpdatedAt(); !ok {
v := itemfield.UpdateDefaultUpdatedAt()
ifu.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (ifu *ItemFieldUpdate) check() error {
if v, ok := ifu.mutation.Name(); ok {
if err := itemfield.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "ItemField.name": %w`, err)}
}
}
if v, ok := ifu.mutation.Description(); ok {
if err := itemfield.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "ItemField.description": %w`, err)}
}
}
if v, ok := ifu.mutation.GetType(); ok {
if err := itemfield.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "ItemField.type": %w`, err)}
}
}
if v, ok := ifu.mutation.TextValue(); ok {
if err := itemfield.TextValueValidator(v); err != nil {
return &ValidationError{Name: "text_value", err: fmt.Errorf(`ent: validator failed for field "ItemField.text_value": %w`, err)}
}
}
return nil
}
func (ifu *ItemFieldUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: itemfield.Table,
Columns: itemfield.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: itemfield.FieldID,
},
},
}
if ps := ifu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := ifu.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldUpdatedAt,
})
}
if value, ok := ifu.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldName,
})
}
if value, ok := ifu.mutation.Description(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldDescription,
})
}
if ifu.mutation.DescriptionCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: itemfield.FieldDescription,
})
}
if value, ok := ifu.mutation.GetType(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeEnum,
Value: value,
Column: itemfield.FieldType,
})
}
if value, ok := ifu.mutation.TextValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldTextValue,
})
}
if ifu.mutation.TextValueCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: itemfield.FieldTextValue,
})
}
if value, ok := ifu.mutation.NumberValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: itemfield.FieldNumberValue,
})
}
if value, ok := ifu.mutation.AddedNumberValue(); ok {
_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: itemfield.FieldNumberValue,
})
}
if ifu.mutation.NumberValueCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: itemfield.FieldNumberValue,
})
}
if value, ok := ifu.mutation.BooleanValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: itemfield.FieldBooleanValue,
})
}
if value, ok := ifu.mutation.TimeValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldTimeValue,
})
}
if ifu.mutation.ItemCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: itemfield.ItemTable,
Columns: []string{itemfield.ItemColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := ifu.mutation.ItemIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: itemfield.ItemTable,
Columns: []string{itemfield.ItemColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if n, err = sqlgraph.UpdateNodes(ctx, ifu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{itemfield.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
return n, nil
}
// ItemFieldUpdateOne is the builder for updating a single ItemField entity.
type ItemFieldUpdateOne struct {
config
fields []string
hooks []Hook
mutation *ItemFieldMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (ifuo *ItemFieldUpdateOne) SetUpdatedAt(t time.Time) *ItemFieldUpdateOne {
ifuo.mutation.SetUpdatedAt(t)
return ifuo
}
// SetName sets the "name" field.
func (ifuo *ItemFieldUpdateOne) SetName(s string) *ItemFieldUpdateOne {
ifuo.mutation.SetName(s)
return ifuo
}
// SetDescription sets the "description" field.
func (ifuo *ItemFieldUpdateOne) SetDescription(s string) *ItemFieldUpdateOne {
ifuo.mutation.SetDescription(s)
return ifuo
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (ifuo *ItemFieldUpdateOne) SetNillableDescription(s *string) *ItemFieldUpdateOne {
if s != nil {
ifuo.SetDescription(*s)
}
return ifuo
}
// ClearDescription clears the value of the "description" field.
func (ifuo *ItemFieldUpdateOne) ClearDescription() *ItemFieldUpdateOne {
ifuo.mutation.ClearDescription()
return ifuo
}
// SetType sets the "type" field.
func (ifuo *ItemFieldUpdateOne) SetType(i itemfield.Type) *ItemFieldUpdateOne {
ifuo.mutation.SetType(i)
return ifuo
}
// SetTextValue sets the "text_value" field.
func (ifuo *ItemFieldUpdateOne) SetTextValue(s string) *ItemFieldUpdateOne {
ifuo.mutation.SetTextValue(s)
return ifuo
}
// SetNillableTextValue sets the "text_value" field if the given value is not nil.
func (ifuo *ItemFieldUpdateOne) SetNillableTextValue(s *string) *ItemFieldUpdateOne {
if s != nil {
ifuo.SetTextValue(*s)
}
return ifuo
}
// ClearTextValue clears the value of the "text_value" field.
func (ifuo *ItemFieldUpdateOne) ClearTextValue() *ItemFieldUpdateOne {
ifuo.mutation.ClearTextValue()
return ifuo
}
// SetNumberValue sets the "number_value" field.
func (ifuo *ItemFieldUpdateOne) SetNumberValue(i int) *ItemFieldUpdateOne {
ifuo.mutation.ResetNumberValue()
ifuo.mutation.SetNumberValue(i)
return ifuo
}
// SetNillableNumberValue sets the "number_value" field if the given value is not nil.
func (ifuo *ItemFieldUpdateOne) SetNillableNumberValue(i *int) *ItemFieldUpdateOne {
if i != nil {
ifuo.SetNumberValue(*i)
}
return ifuo
}
// AddNumberValue adds i to the "number_value" field.
func (ifuo *ItemFieldUpdateOne) AddNumberValue(i int) *ItemFieldUpdateOne {
ifuo.mutation.AddNumberValue(i)
return ifuo
}
// ClearNumberValue clears the value of the "number_value" field.
func (ifuo *ItemFieldUpdateOne) ClearNumberValue() *ItemFieldUpdateOne {
ifuo.mutation.ClearNumberValue()
return ifuo
}
// SetBooleanValue sets the "boolean_value" field.
func (ifuo *ItemFieldUpdateOne) SetBooleanValue(b bool) *ItemFieldUpdateOne {
ifuo.mutation.SetBooleanValue(b)
return ifuo
}
// SetNillableBooleanValue sets the "boolean_value" field if the given value is not nil.
func (ifuo *ItemFieldUpdateOne) SetNillableBooleanValue(b *bool) *ItemFieldUpdateOne {
if b != nil {
ifuo.SetBooleanValue(*b)
}
return ifuo
}
// SetTimeValue sets the "time_value" field.
func (ifuo *ItemFieldUpdateOne) SetTimeValue(t time.Time) *ItemFieldUpdateOne {
ifuo.mutation.SetTimeValue(t)
return ifuo
}
// SetNillableTimeValue sets the "time_value" field if the given value is not nil.
func (ifuo *ItemFieldUpdateOne) SetNillableTimeValue(t *time.Time) *ItemFieldUpdateOne {
if t != nil {
ifuo.SetTimeValue(*t)
}
return ifuo
}
// SetItemID sets the "item" edge to the Item entity by ID.
func (ifuo *ItemFieldUpdateOne) SetItemID(id uuid.UUID) *ItemFieldUpdateOne {
ifuo.mutation.SetItemID(id)
return ifuo
}
// SetNillableItemID sets the "item" edge to the Item entity by ID if the given value is not nil.
func (ifuo *ItemFieldUpdateOne) SetNillableItemID(id *uuid.UUID) *ItemFieldUpdateOne {
if id != nil {
ifuo = ifuo.SetItemID(*id)
}
return ifuo
}
// SetItem sets the "item" edge to the Item entity.
func (ifuo *ItemFieldUpdateOne) SetItem(i *Item) *ItemFieldUpdateOne {
return ifuo.SetItemID(i.ID)
}
// Mutation returns the ItemFieldMutation object of the builder.
func (ifuo *ItemFieldUpdateOne) Mutation() *ItemFieldMutation {
return ifuo.mutation
}
// ClearItem clears the "item" edge to the Item entity.
func (ifuo *ItemFieldUpdateOne) ClearItem() *ItemFieldUpdateOne {
ifuo.mutation.ClearItem()
return ifuo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (ifuo *ItemFieldUpdateOne) Select(field string, fields ...string) *ItemFieldUpdateOne {
ifuo.fields = append([]string{field}, fields...)
return ifuo
}
// Save executes the query and returns the updated ItemField entity.
func (ifuo *ItemFieldUpdateOne) Save(ctx context.Context) (*ItemField, error) {
var (
err error
node *ItemField
)
ifuo.defaults()
if len(ifuo.hooks) == 0 {
if err = ifuo.check(); err != nil {
return nil, err
}
node, err = ifuo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemFieldMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = ifuo.check(); err != nil {
return nil, err
}
ifuo.mutation = mutation
node, err = ifuo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(ifuo.hooks) - 1; i >= 0; i-- {
if ifuo.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ifuo.hooks[i](mut)
}
v, err := mut.Mutate(ctx, ifuo.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*ItemField)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from ItemFieldMutation", v)
}
node = nv
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (ifuo *ItemFieldUpdateOne) SaveX(ctx context.Context) *ItemField {
node, err := ifuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (ifuo *ItemFieldUpdateOne) Exec(ctx context.Context) error {
_, err := ifuo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ifuo *ItemFieldUpdateOne) ExecX(ctx context.Context) {
if err := ifuo.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (ifuo *ItemFieldUpdateOne) defaults() {
if _, ok := ifuo.mutation.UpdatedAt(); !ok {
v := itemfield.UpdateDefaultUpdatedAt()
ifuo.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (ifuo *ItemFieldUpdateOne) check() error {
if v, ok := ifuo.mutation.Name(); ok {
if err := itemfield.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "ItemField.name": %w`, err)}
}
}
if v, ok := ifuo.mutation.Description(); ok {
if err := itemfield.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "ItemField.description": %w`, err)}
}
}
if v, ok := ifuo.mutation.GetType(); ok {
if err := itemfield.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "ItemField.type": %w`, err)}
}
}
if v, ok := ifuo.mutation.TextValue(); ok {
if err := itemfield.TextValueValidator(v); err != nil {
return &ValidationError{Name: "text_value", err: fmt.Errorf(`ent: validator failed for field "ItemField.text_value": %w`, err)}
}
}
return nil
}
func (ifuo *ItemFieldUpdateOne) sqlSave(ctx context.Context) (_node *ItemField, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: itemfield.Table,
Columns: itemfield.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: itemfield.FieldID,
},
},
}
id, ok := ifuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "ItemField.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := ifuo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, itemfield.FieldID)
for _, f := range fields {
if !itemfield.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != itemfield.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := ifuo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := ifuo.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldUpdatedAt,
})
}
if value, ok := ifuo.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldName,
})
}
if value, ok := ifuo.mutation.Description(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldDescription,
})
}
if ifuo.mutation.DescriptionCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: itemfield.FieldDescription,
})
}
if value, ok := ifuo.mutation.GetType(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeEnum,
Value: value,
Column: itemfield.FieldType,
})
}
if value, ok := ifuo.mutation.TextValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldTextValue,
})
}
if ifuo.mutation.TextValueCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: itemfield.FieldTextValue,
})
}
if value, ok := ifuo.mutation.NumberValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: itemfield.FieldNumberValue,
})
}
if value, ok := ifuo.mutation.AddedNumberValue(); ok {
_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: itemfield.FieldNumberValue,
})
}
if ifuo.mutation.NumberValueCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: itemfield.FieldNumberValue,
})
}
if value, ok := ifuo.mutation.BooleanValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: itemfield.FieldBooleanValue,
})
}
if value, ok := ifuo.mutation.TimeValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldTimeValue,
})
}
if ifuo.mutation.ItemCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: itemfield.ItemTable,
Columns: []string{itemfield.ItemColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := ifuo.mutation.ItemIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: itemfield.ItemTable,
Columns: []string{itemfield.ItemColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &ItemField{config: ifuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, ifuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{itemfield.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
return _node, nil
}

204
backend/ent/label.go Normal file
View file

@ -0,0 +1,204 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/label"
)
// Label is the model entity for the Label schema.
type Label struct {
config `json:"-"`
// ID of the ent.
ID uuid.UUID `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Description holds the value of the "description" field.
Description string `json:"description,omitempty"`
// Color holds the value of the "color" field.
Color string `json:"color,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the LabelQuery when eager-loading is set.
Edges LabelEdges `json:"edges"`
group_labels *uuid.UUID
}
// LabelEdges holds the relations/edges for other nodes in the graph.
type LabelEdges struct {
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// Items holds the value of the items edge.
Items []*Item `json:"items,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e LabelEdges) GroupOrErr() (*Group, error) {
if e.loadedTypes[0] {
if e.Group == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: group.Label}
}
return e.Group, nil
}
return nil, &NotLoadedError{edge: "group"}
}
// ItemsOrErr returns the Items value or an error if the edge
// was not loaded in eager-loading.
func (e LabelEdges) ItemsOrErr() ([]*Item, error) {
if e.loadedTypes[1] {
return e.Items, nil
}
return nil, &NotLoadedError{edge: "items"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Label) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case label.FieldName, label.FieldDescription, label.FieldColor:
values[i] = new(sql.NullString)
case label.FieldCreatedAt, label.FieldUpdatedAt:
values[i] = new(sql.NullTime)
case label.FieldID:
values[i] = new(uuid.UUID)
case label.ForeignKeys[0]: // group_labels
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type Label", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Label fields.
func (l *Label) assignValues(columns []string, values []interface{}) 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 label.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
l.ID = *value
}
case label.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
l.CreatedAt = value.Time
}
case label.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
l.UpdatedAt = value.Time
}
case label.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
l.Name = value.String
}
case label.FieldDescription:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field description", values[i])
} else if value.Valid {
l.Description = value.String
}
case label.FieldColor:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field color", values[i])
} else if value.Valid {
l.Color = value.String
}
case label.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field group_labels", values[i])
} else if value.Valid {
l.group_labels = new(uuid.UUID)
*l.group_labels = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryGroup queries the "group" edge of the Label entity.
func (l *Label) QueryGroup() *GroupQuery {
return (&LabelClient{config: l.config}).QueryGroup(l)
}
// QueryItems queries the "items" edge of the Label entity.
func (l *Label) QueryItems() *ItemQuery {
return (&LabelClient{config: l.config}).QueryItems(l)
}
// Update returns a builder for updating this Label.
// Note that you need to call Label.Unwrap() before calling this method if this Label
// was returned from a transaction, and the transaction was committed or rolled back.
func (l *Label) Update() *LabelUpdateOne {
return (&LabelClient{config: l.config}).UpdateOne(l)
}
// Unwrap unwraps the Label 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 (l *Label) Unwrap() *Label {
_tx, ok := l.config.driver.(*txDriver)
if !ok {
panic("ent: Label is not a transactional entity")
}
l.config.driver = _tx.drv
return l
}
// String implements the fmt.Stringer.
func (l *Label) String() string {
var builder strings.Builder
builder.WriteString("Label(")
builder.WriteString(fmt.Sprintf("id=%v, ", l.ID))
builder.WriteString("created_at=")
builder.WriteString(l.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(l.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(l.Name)
builder.WriteString(", ")
builder.WriteString("description=")
builder.WriteString(l.Description)
builder.WriteString(", ")
builder.WriteString("color=")
builder.WriteString(l.Color)
builder.WriteByte(')')
return builder.String()
}
// Labels is a parsable slice of Label.
type Labels []*Label
func (l Labels) config(cfg config) {
for _i := range l {
l[_i].config = cfg
}
}

View file

@ -0,0 +1,98 @@
// Code generated by ent, DO NOT EDIT.
package label
import (
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the label type in the database.
Label = "label"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldDescription holds the string denoting the description field in the database.
FieldDescription = "description"
// FieldColor holds the string denoting the color field in the database.
FieldColor = "color"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// EdgeItems holds the string denoting the items edge name in mutations.
EdgeItems = "items"
// Table holds the table name of the label in the database.
Table = "labels"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "labels"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_labels"
// ItemsTable is the table that holds the items relation/edge. The primary key declared below.
ItemsTable = "label_items"
// ItemsInverseTable is the table name for the Item entity.
// It exists in this package in order to avoid circular dependency with the "item" package.
ItemsInverseTable = "items"
)
// Columns holds all SQL columns for label fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldName,
FieldDescription,
FieldColor,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "labels"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"group_labels",
}
var (
// ItemsPrimaryKey and ItemsColumn2 are the table columns denoting the
// primary key for the items relation (M2M).
ItemsPrimaryKey = []string{"label_id", "item_id"}
)
// 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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
DescriptionValidator func(string) error
// ColorValidator is a validator for the "color" field. It is called by the builders before save.
ColorValidator func(string) error
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)

659
backend/ent/label/where.go Normal file
View file

@ -0,0 +1,659 @@
// Code generated by ent, DO NOT EDIT.
package label
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id uuid.UUID) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id uuid.UUID) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id uuid.UUID) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...uuid.UUID) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...uuid.UUID) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id uuid.UUID) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id uuid.UUID) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id uuid.UUID) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id uuid.UUID) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
})
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
})
}
// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ.
func Description(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDescription), v))
})
}
// Color applies equality check predicate on the "color" field. It's identical to ColorEQ.
func Color(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldColor), v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
})
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldCreatedAt), v))
})
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Label {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldCreatedAt), v...))
})
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Label {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldCreatedAt), v...))
})
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldCreatedAt), v))
})
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.Label {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldUpdatedAt), v...))
})
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.Label {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...))
})
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldName), v...))
})
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Label {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldName), v...))
})
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldName), v))
})
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Label {
return predicate.Label(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.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldName), v))
})
}
// DescriptionEQ applies the EQ predicate on the "description" field.
func DescriptionEQ(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDescription), v))
})
}
// DescriptionNEQ applies the NEQ predicate on the "description" field.
func DescriptionNEQ(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldDescription), v))
})
}
// DescriptionIn applies the In predicate on the "description" field.
func DescriptionIn(vs ...string) predicate.Label {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldDescription), v...))
})
}
// DescriptionNotIn applies the NotIn predicate on the "description" field.
func DescriptionNotIn(vs ...string) predicate.Label {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldDescription), v...))
})
}
// DescriptionGT applies the GT predicate on the "description" field.
func DescriptionGT(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldDescription), v))
})
}
// DescriptionGTE applies the GTE predicate on the "description" field.
func DescriptionGTE(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldDescription), v))
})
}
// DescriptionLT applies the LT predicate on the "description" field.
func DescriptionLT(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldDescription), v))
})
}
// DescriptionLTE applies the LTE predicate on the "description" field.
func DescriptionLTE(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldDescription), v))
})
}
// DescriptionContains applies the Contains predicate on the "description" field.
func DescriptionContains(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldDescription), v))
})
}
// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field.
func DescriptionHasPrefix(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldDescription), v))
})
}
// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field.
func DescriptionHasSuffix(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldDescription), v))
})
}
// DescriptionIsNil applies the IsNil predicate on the "description" field.
func DescriptionIsNil() predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldDescription)))
})
}
// DescriptionNotNil applies the NotNil predicate on the "description" field.
func DescriptionNotNil() predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldDescription)))
})
}
// DescriptionEqualFold applies the EqualFold predicate on the "description" field.
func DescriptionEqualFold(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldDescription), v))
})
}
// DescriptionContainsFold applies the ContainsFold predicate on the "description" field.
func DescriptionContainsFold(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldDescription), v))
})
}
// ColorEQ applies the EQ predicate on the "color" field.
func ColorEQ(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldColor), v))
})
}
// ColorNEQ applies the NEQ predicate on the "color" field.
func ColorNEQ(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldColor), v))
})
}
// ColorIn applies the In predicate on the "color" field.
func ColorIn(vs ...string) predicate.Label {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldColor), v...))
})
}
// ColorNotIn applies the NotIn predicate on the "color" field.
func ColorNotIn(vs ...string) predicate.Label {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldColor), v...))
})
}
// ColorGT applies the GT predicate on the "color" field.
func ColorGT(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldColor), v))
})
}
// ColorGTE applies the GTE predicate on the "color" field.
func ColorGTE(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldColor), v))
})
}
// ColorLT applies the LT predicate on the "color" field.
func ColorLT(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldColor), v))
})
}
// ColorLTE applies the LTE predicate on the "color" field.
func ColorLTE(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldColor), v))
})
}
// ColorContains applies the Contains predicate on the "color" field.
func ColorContains(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldColor), v))
})
}
// ColorHasPrefix applies the HasPrefix predicate on the "color" field.
func ColorHasPrefix(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldColor), v))
})
}
// ColorHasSuffix applies the HasSuffix predicate on the "color" field.
func ColorHasSuffix(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldColor), v))
})
}
// ColorIsNil applies the IsNil predicate on the "color" field.
func ColorIsNil() predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldColor)))
})
}
// ColorNotNil applies the NotNil predicate on the "color" field.
func ColorNotNil() predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldColor)))
})
}
// ColorEqualFold applies the EqualFold predicate on the "color" field.
func ColorEqualFold(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldColor), v))
})
}
// ColorContainsFold applies the ContainsFold predicate on the "color" field.
func ColorContainsFold(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldColor), v))
})
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.Label {
return predicate.Label(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasItems applies the HasEdge predicate on the "items" edge.
func HasItems() predicate.Label {
return predicate.Label(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemsTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, ItemsTable, ItemsPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasItemsWith applies the HasEdge predicate on the "items" edge with a given conditions (other predicates).
func HasItemsWith(preds ...predicate.Item) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, ItemsTable, ItemsPrimaryKey...),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Label) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Label) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Label) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
p(s.Not())
})
}

444
backend/ent/label_create.go Normal file
View file

@ -0,0 +1,444 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/label"
)
// LabelCreate is the builder for creating a Label entity.
type LabelCreate struct {
config
mutation *LabelMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (lc *LabelCreate) SetCreatedAt(t time.Time) *LabelCreate {
lc.mutation.SetCreatedAt(t)
return lc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (lc *LabelCreate) SetNillableCreatedAt(t *time.Time) *LabelCreate {
if t != nil {
lc.SetCreatedAt(*t)
}
return lc
}
// SetUpdatedAt sets the "updated_at" field.
func (lc *LabelCreate) SetUpdatedAt(t time.Time) *LabelCreate {
lc.mutation.SetUpdatedAt(t)
return lc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (lc *LabelCreate) SetNillableUpdatedAt(t *time.Time) *LabelCreate {
if t != nil {
lc.SetUpdatedAt(*t)
}
return lc
}
// SetName sets the "name" field.
func (lc *LabelCreate) SetName(s string) *LabelCreate {
lc.mutation.SetName(s)
return lc
}
// SetDescription sets the "description" field.
func (lc *LabelCreate) SetDescription(s string) *LabelCreate {
lc.mutation.SetDescription(s)
return lc
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (lc *LabelCreate) SetNillableDescription(s *string) *LabelCreate {
if s != nil {
lc.SetDescription(*s)
}
return lc
}
// SetColor sets the "color" field.
func (lc *LabelCreate) SetColor(s string) *LabelCreate {
lc.mutation.SetColor(s)
return lc
}
// SetNillableColor sets the "color" field if the given value is not nil.
func (lc *LabelCreate) SetNillableColor(s *string) *LabelCreate {
if s != nil {
lc.SetColor(*s)
}
return lc
}
// SetID sets the "id" field.
func (lc *LabelCreate) SetID(u uuid.UUID) *LabelCreate {
lc.mutation.SetID(u)
return lc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (lc *LabelCreate) SetNillableID(u *uuid.UUID) *LabelCreate {
if u != nil {
lc.SetID(*u)
}
return lc
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (lc *LabelCreate) SetGroupID(id uuid.UUID) *LabelCreate {
lc.mutation.SetGroupID(id)
return lc
}
// SetGroup sets the "group" edge to the Group entity.
func (lc *LabelCreate) SetGroup(g *Group) *LabelCreate {
return lc.SetGroupID(g.ID)
}
// AddItemIDs adds the "items" edge to the Item entity by IDs.
func (lc *LabelCreate) AddItemIDs(ids ...uuid.UUID) *LabelCreate {
lc.mutation.AddItemIDs(ids...)
return lc
}
// AddItems adds the "items" edges to the Item entity.
func (lc *LabelCreate) AddItems(i ...*Item) *LabelCreate {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return lc.AddItemIDs(ids...)
}
// Mutation returns the LabelMutation object of the builder.
func (lc *LabelCreate) Mutation() *LabelMutation {
return lc.mutation
}
// Save creates the Label in the database.
func (lc *LabelCreate) Save(ctx context.Context) (*Label, error) {
var (
err error
node *Label
)
lc.defaults()
if len(lc.hooks) == 0 {
if err = lc.check(); err != nil {
return nil, err
}
node, err = lc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LabelMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = lc.check(); err != nil {
return nil, err
}
lc.mutation = mutation
if node, err = lc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(lc.hooks) - 1; i >= 0; i-- {
if lc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = lc.hooks[i](mut)
}
v, err := mut.Mutate(ctx, lc.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Label)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from LabelMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (lc *LabelCreate) SaveX(ctx context.Context) *Label {
v, err := lc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (lc *LabelCreate) Exec(ctx context.Context) error {
_, err := lc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (lc *LabelCreate) ExecX(ctx context.Context) {
if err := lc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (lc *LabelCreate) defaults() {
if _, ok := lc.mutation.CreatedAt(); !ok {
v := label.DefaultCreatedAt()
lc.mutation.SetCreatedAt(v)
}
if _, ok := lc.mutation.UpdatedAt(); !ok {
v := label.DefaultUpdatedAt()
lc.mutation.SetUpdatedAt(v)
}
if _, ok := lc.mutation.ID(); !ok {
v := label.DefaultID()
lc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (lc *LabelCreate) check() error {
if _, ok := lc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Label.created_at"`)}
}
if _, ok := lc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Label.updated_at"`)}
}
if _, ok := lc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Label.name"`)}
}
if v, ok := lc.mutation.Name(); ok {
if err := label.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Label.name": %w`, err)}
}
}
if v, ok := lc.mutation.Description(); ok {
if err := label.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "Label.description": %w`, err)}
}
}
if v, ok := lc.mutation.Color(); ok {
if err := label.ColorValidator(v); err != nil {
return &ValidationError{Name: "color", err: fmt.Errorf(`ent: validator failed for field "Label.color": %w`, err)}
}
}
if _, ok := lc.mutation.GroupID(); !ok {
return &ValidationError{Name: "group", err: errors.New(`ent: missing required edge "Label.group"`)}
}
return nil
}
func (lc *LabelCreate) sqlSave(ctx context.Context) (*Label, error) {
_node, _spec := lc.createSpec()
if err := sqlgraph.CreateNode(ctx, lc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
if _spec.ID.Value != nil {
if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
_node.ID = *id
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
return nil, err
}
}
return _node, nil
}
func (lc *LabelCreate) createSpec() (*Label, *sqlgraph.CreateSpec) {
var (
_node = &Label{config: lc.config}
_spec = &sqlgraph.CreateSpec{
Table: label.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: label.FieldID,
},
}
)
if id, ok := lc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := lc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: label.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := lc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: label.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := lc.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldName,
})
_node.Name = value
}
if value, ok := lc.mutation.Description(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldDescription,
})
_node.Description = value
}
if value, ok := lc.mutation.Color(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldColor,
})
_node.Color = value
}
if nodes := lc.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: label.GroupTable,
Columns: []string{label.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.group_labels = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := lc.mutation.ItemsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// LabelCreateBulk is the builder for creating many Label entities in bulk.
type LabelCreateBulk struct {
config
builders []*LabelCreate
}
// Save creates the Label entities in the database.
func (lcb *LabelCreateBulk) Save(ctx context.Context) ([]*Label, error) {
specs := make([]*sqlgraph.CreateSpec, len(lcb.builders))
nodes := make([]*Label, len(lcb.builders))
mutators := make([]Mutator, len(lcb.builders))
for i := range lcb.builders {
func(i int, root context.Context) {
builder := lcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LabelMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, lcb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, lcb.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
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, lcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (lcb *LabelCreateBulk) SaveX(ctx context.Context) []*Label {
v, err := lcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (lcb *LabelCreateBulk) Exec(ctx context.Context) error {
_, err := lcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (lcb *LabelCreateBulk) ExecX(ctx context.Context) {
if err := lcb.Exec(ctx); err != nil {
panic(err)
}
}

115
backend/ent/label_delete.go Normal file
View file

@ -0,0 +1,115 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/hay-kot/content/backend/ent/label"
"github.com/hay-kot/content/backend/ent/predicate"
)
// LabelDelete is the builder for deleting a Label entity.
type LabelDelete struct {
config
hooks []Hook
mutation *LabelMutation
}
// Where appends a list predicates to the LabelDelete builder.
func (ld *LabelDelete) Where(ps ...predicate.Label) *LabelDelete {
ld.mutation.Where(ps...)
return ld
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (ld *LabelDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(ld.hooks) == 0 {
affected, err = ld.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LabelMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
ld.mutation = mutation
affected, err = ld.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(ld.hooks) - 1; i >= 0; i-- {
if ld.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ld.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ld.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (ld *LabelDelete) ExecX(ctx context.Context) int {
n, err := ld.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (ld *LabelDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: label.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: label.FieldID,
},
},
}
if ps := ld.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, ld.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// LabelDeleteOne is the builder for deleting a single Label entity.
type LabelDeleteOne struct {
ld *LabelDelete
}
// Exec executes the deletion query.
func (ldo *LabelDeleteOne) Exec(ctx context.Context) error {
n, err := ldo.ld.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{label.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (ldo *LabelDeleteOne) ExecX(ctx context.Context) {
ldo.ld.ExecX(ctx)
}

714
backend/ent/label_query.go Normal file
View file

@ -0,0 +1,714 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/label"
"github.com/hay-kot/content/backend/ent/predicate"
)
// LabelQuery is the builder for querying Label entities.
type LabelQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Label
withGroup *GroupQuery
withItems *ItemQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the LabelQuery builder.
func (lq *LabelQuery) Where(ps ...predicate.Label) *LabelQuery {
lq.predicates = append(lq.predicates, ps...)
return lq
}
// Limit adds a limit step to the query.
func (lq *LabelQuery) Limit(limit int) *LabelQuery {
lq.limit = &limit
return lq
}
// Offset adds an offset step to the query.
func (lq *LabelQuery) Offset(offset int) *LabelQuery {
lq.offset = &offset
return lq
}
// 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 (lq *LabelQuery) Unique(unique bool) *LabelQuery {
lq.unique = &unique
return lq
}
// Order adds an order step to the query.
func (lq *LabelQuery) Order(o ...OrderFunc) *LabelQuery {
lq.order = append(lq.order, o...)
return lq
}
// QueryGroup chains the current query on the "group" edge.
func (lq *LabelQuery) QueryGroup() *GroupQuery {
query := &GroupQuery{config: lq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := lq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(label.Table, label.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, label.GroupTable, label.GroupColumn),
)
fromU = sqlgraph.SetNeighbors(lq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryItems chains the current query on the "items" edge.
func (lq *LabelQuery) QueryItems() *ItemQuery {
query := &ItemQuery{config: lq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := lq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(label.Table, label.FieldID, selector),
sqlgraph.To(item.Table, item.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, label.ItemsTable, label.ItemsPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(lq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Label entity from the query.
// Returns a *NotFoundError when no Label was found.
func (lq *LabelQuery) First(ctx context.Context) (*Label, error) {
nodes, err := lq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{label.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (lq *LabelQuery) FirstX(ctx context.Context) *Label {
node, err := lq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Label ID from the query.
// Returns a *NotFoundError when no Label ID was found.
func (lq *LabelQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = lq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{label.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (lq *LabelQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := lq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Label entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Label entity is found.
// Returns a *NotFoundError when no Label entities are found.
func (lq *LabelQuery) Only(ctx context.Context) (*Label, error) {
nodes, err := lq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{label.Label}
default:
return nil, &NotSingularError{label.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (lq *LabelQuery) OnlyX(ctx context.Context) *Label {
node, err := lq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Label ID in the query.
// Returns a *NotSingularError when more than one Label ID is found.
// Returns a *NotFoundError when no entities are found.
func (lq *LabelQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = lq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{label.Label}
default:
err = &NotSingularError{label.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (lq *LabelQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := lq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Labels.
func (lq *LabelQuery) All(ctx context.Context) ([]*Label, error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
return lq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (lq *LabelQuery) AllX(ctx context.Context) []*Label {
nodes, err := lq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Label IDs.
func (lq *LabelQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := lq.Select(label.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (lq *LabelQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := lq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (lq *LabelQuery) Count(ctx context.Context) (int, error) {
if err := lq.prepareQuery(ctx); err != nil {
return 0, err
}
return lq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (lq *LabelQuery) CountX(ctx context.Context) int {
count, err := lq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (lq *LabelQuery) Exist(ctx context.Context) (bool, error) {
if err := lq.prepareQuery(ctx); err != nil {
return false, err
}
return lq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (lq *LabelQuery) ExistX(ctx context.Context) bool {
exist, err := lq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the LabelQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (lq *LabelQuery) Clone() *LabelQuery {
if lq == nil {
return nil
}
return &LabelQuery{
config: lq.config,
limit: lq.limit,
offset: lq.offset,
order: append([]OrderFunc{}, lq.order...),
predicates: append([]predicate.Label{}, lq.predicates...),
withGroup: lq.withGroup.Clone(),
withItems: lq.withItems.Clone(),
// clone intermediate query.
sql: lq.sql.Clone(),
path: lq.path,
unique: lq.unique,
}
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (lq *LabelQuery) WithGroup(opts ...func(*GroupQuery)) *LabelQuery {
query := &GroupQuery{config: lq.config}
for _, opt := range opts {
opt(query)
}
lq.withGroup = query
return lq
}
// WithItems tells the query-builder to eager-load the nodes that are connected to
// the "items" edge. The optional arguments are used to configure the query builder of the edge.
func (lq *LabelQuery) WithItems(opts ...func(*ItemQuery)) *LabelQuery {
query := &ItemQuery{config: lq.config}
for _, opt := range opts {
opt(query)
}
lq.withItems = query
return lq
}
// 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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Label.Query().
// GroupBy(label.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (lq *LabelQuery) GroupBy(field string, fields ...string) *LabelGroupBy {
grbuild := &LabelGroupBy{config: lq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
return lq.sqlQuery(ctx), nil
}
grbuild.label = label.Label
grbuild.flds, grbuild.scan = &grbuild.fields, 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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// }
//
// client.Label.Query().
// Select(label.FieldCreatedAt).
// Scan(ctx, &v)
func (lq *LabelQuery) Select(fields ...string) *LabelSelect {
lq.fields = append(lq.fields, fields...)
selbuild := &LabelSelect{LabelQuery: lq}
selbuild.label = label.Label
selbuild.flds, selbuild.scan = &lq.fields, selbuild.Scan
return selbuild
}
func (lq *LabelQuery) prepareQuery(ctx context.Context) error {
for _, f := range lq.fields {
if !label.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if lq.path != nil {
prev, err := lq.path(ctx)
if err != nil {
return err
}
lq.sql = prev
}
return nil
}
func (lq *LabelQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Label, error) {
var (
nodes = []*Label{}
withFKs = lq.withFKs
_spec = lq.querySpec()
loadedTypes = [2]bool{
lq.withGroup != nil,
lq.withItems != nil,
}
)
if lq.withGroup != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, label.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
return (*Label).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
node := &Label{config: lq.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, lq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := lq.withGroup; query != nil {
if err := lq.loadGroup(ctx, query, nodes, nil,
func(n *Label, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
if query := lq.withItems; query != nil {
if err := lq.loadItems(ctx, query, nodes,
func(n *Label) { n.Edges.Items = []*Item{} },
func(n *Label, e *Item) { n.Edges.Items = append(n.Edges.Items, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (lq *LabelQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*Label, init func(*Label), assign func(*Label, *Group)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Label)
for i := range nodes {
if nodes[i].group_labels == nil {
continue
}
fk := *nodes[i].group_labels
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(group.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_labels" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (lq *LabelQuery) loadItems(ctx context.Context, query *ItemQuery, nodes []*Label, init func(*Label), assign func(*Label, *Item)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[uuid.UUID]*Label)
nids := make(map[uuid.UUID]map[*Label]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(label.ItemsTable)
s.Join(joinT).On(s.C(item.FieldID), joinT.C(label.ItemsPrimaryKey[1]))
s.Where(sql.InValues(joinT.C(label.ItemsPrimaryKey[0]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(label.ItemsPrimaryKey[0]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
neighbors, err := query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]interface{}, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]interface{}{new(uuid.UUID)}, values...), nil
}
spec.Assign = func(columns []string, values []interface{}) error {
outValue := *values[0].(*uuid.UUID)
inValue := *values[1].(*uuid.UUID)
if nids[inValue] == nil {
nids[inValue] = map[*Label]struct{}{byID[outValue]: struct{}{}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "items" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (lq *LabelQuery) sqlCount(ctx context.Context) (int, error) {
_spec := lq.querySpec()
_spec.Node.Columns = lq.fields
if len(lq.fields) > 0 {
_spec.Unique = lq.unique != nil && *lq.unique
}
return sqlgraph.CountNodes(ctx, lq.driver, _spec)
}
func (lq *LabelQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := lq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %w", err)
}
return n > 0, nil
}
func (lq *LabelQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: label.Table,
Columns: label.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: label.FieldID,
},
},
From: lq.sql,
Unique: true,
}
if unique := lq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := lq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, label.FieldID)
for i := range fields {
if fields[i] != label.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := lq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := lq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := lq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := lq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (lq *LabelQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(lq.driver.Dialect())
t1 := builder.Table(label.Table)
columns := lq.fields
if len(columns) == 0 {
columns = label.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if lq.sql != nil {
selector = lq.sql
selector.Select(selector.Columns(columns...)...)
}
if lq.unique != nil && *lq.unique {
selector.Distinct()
}
for _, p := range lq.predicates {
p(selector)
}
for _, p := range lq.order {
p(selector)
}
if offset := lq.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 := lq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// LabelGroupBy is the group-by builder for Label entities.
type LabelGroupBy struct {
config
selector
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (lgb *LabelGroupBy) Aggregate(fns ...AggregateFunc) *LabelGroupBy {
lgb.fns = append(lgb.fns, fns...)
return lgb
}
// Scan applies the group-by query and scans the result into the given value.
func (lgb *LabelGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := lgb.path(ctx)
if err != nil {
return err
}
lgb.sql = query
return lgb.sqlScan(ctx, v)
}
func (lgb *LabelGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range lgb.fields {
if !label.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := lgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := lgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (lgb *LabelGroupBy) sqlQuery() *sql.Selector {
selector := lgb.sql.Select()
aggregation := make([]string, 0, len(lgb.fns))
for _, fn := range lgb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(lgb.fields)+len(lgb.fns))
for _, f := range lgb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(lgb.fields...)...)
}
// LabelSelect is the builder for selecting fields of Label entities.
type LabelSelect struct {
*LabelQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (ls *LabelSelect) Scan(ctx context.Context, v interface{}) error {
if err := ls.prepareQuery(ctx); err != nil {
return err
}
ls.sql = ls.LabelQuery.sqlQuery(ctx)
return ls.sqlScan(ctx, v)
}
func (ls *LabelSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := ls.sql.Query()
if err := ls.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

793
backend/ent/label_update.go Normal file
View file

@ -0,0 +1,793 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/label"
"github.com/hay-kot/content/backend/ent/predicate"
)
// LabelUpdate is the builder for updating Label entities.
type LabelUpdate struct {
config
hooks []Hook
mutation *LabelMutation
}
// Where appends a list predicates to the LabelUpdate builder.
func (lu *LabelUpdate) Where(ps ...predicate.Label) *LabelUpdate {
lu.mutation.Where(ps...)
return lu
}
// SetUpdatedAt sets the "updated_at" field.
func (lu *LabelUpdate) SetUpdatedAt(t time.Time) *LabelUpdate {
lu.mutation.SetUpdatedAt(t)
return lu
}
// SetName sets the "name" field.
func (lu *LabelUpdate) SetName(s string) *LabelUpdate {
lu.mutation.SetName(s)
return lu
}
// SetDescription sets the "description" field.
func (lu *LabelUpdate) SetDescription(s string) *LabelUpdate {
lu.mutation.SetDescription(s)
return lu
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (lu *LabelUpdate) SetNillableDescription(s *string) *LabelUpdate {
if s != nil {
lu.SetDescription(*s)
}
return lu
}
// ClearDescription clears the value of the "description" field.
func (lu *LabelUpdate) ClearDescription() *LabelUpdate {
lu.mutation.ClearDescription()
return lu
}
// SetColor sets the "color" field.
func (lu *LabelUpdate) SetColor(s string) *LabelUpdate {
lu.mutation.SetColor(s)
return lu
}
// SetNillableColor sets the "color" field if the given value is not nil.
func (lu *LabelUpdate) SetNillableColor(s *string) *LabelUpdate {
if s != nil {
lu.SetColor(*s)
}
return lu
}
// ClearColor clears the value of the "color" field.
func (lu *LabelUpdate) ClearColor() *LabelUpdate {
lu.mutation.ClearColor()
return lu
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (lu *LabelUpdate) SetGroupID(id uuid.UUID) *LabelUpdate {
lu.mutation.SetGroupID(id)
return lu
}
// SetGroup sets the "group" edge to the Group entity.
func (lu *LabelUpdate) SetGroup(g *Group) *LabelUpdate {
return lu.SetGroupID(g.ID)
}
// AddItemIDs adds the "items" edge to the Item entity by IDs.
func (lu *LabelUpdate) AddItemIDs(ids ...uuid.UUID) *LabelUpdate {
lu.mutation.AddItemIDs(ids...)
return lu
}
// AddItems adds the "items" edges to the Item entity.
func (lu *LabelUpdate) AddItems(i ...*Item) *LabelUpdate {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return lu.AddItemIDs(ids...)
}
// Mutation returns the LabelMutation object of the builder.
func (lu *LabelUpdate) Mutation() *LabelMutation {
return lu.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (lu *LabelUpdate) ClearGroup() *LabelUpdate {
lu.mutation.ClearGroup()
return lu
}
// ClearItems clears all "items" edges to the Item entity.
func (lu *LabelUpdate) ClearItems() *LabelUpdate {
lu.mutation.ClearItems()
return lu
}
// RemoveItemIDs removes the "items" edge to Item entities by IDs.
func (lu *LabelUpdate) RemoveItemIDs(ids ...uuid.UUID) *LabelUpdate {
lu.mutation.RemoveItemIDs(ids...)
return lu
}
// RemoveItems removes "items" edges to Item entities.
func (lu *LabelUpdate) RemoveItems(i ...*Item) *LabelUpdate {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return lu.RemoveItemIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (lu *LabelUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
lu.defaults()
if len(lu.hooks) == 0 {
if err = lu.check(); err != nil {
return 0, err
}
affected, err = lu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LabelMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = lu.check(); err != nil {
return 0, err
}
lu.mutation = mutation
affected, err = lu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(lu.hooks) - 1; i >= 0; i-- {
if lu.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = lu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, lu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (lu *LabelUpdate) SaveX(ctx context.Context) int {
affected, err := lu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (lu *LabelUpdate) Exec(ctx context.Context) error {
_, err := lu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (lu *LabelUpdate) ExecX(ctx context.Context) {
if err := lu.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (lu *LabelUpdate) defaults() {
if _, ok := lu.mutation.UpdatedAt(); !ok {
v := label.UpdateDefaultUpdatedAt()
lu.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (lu *LabelUpdate) check() error {
if v, ok := lu.mutation.Name(); ok {
if err := label.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Label.name": %w`, err)}
}
}
if v, ok := lu.mutation.Description(); ok {
if err := label.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "Label.description": %w`, err)}
}
}
if v, ok := lu.mutation.Color(); ok {
if err := label.ColorValidator(v); err != nil {
return &ValidationError{Name: "color", err: fmt.Errorf(`ent: validator failed for field "Label.color": %w`, err)}
}
}
if _, ok := lu.mutation.GroupID(); lu.mutation.GroupCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Label.group"`)
}
return nil
}
func (lu *LabelUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: label.Table,
Columns: label.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: label.FieldID,
},
},
}
if ps := lu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := lu.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: label.FieldUpdatedAt,
})
}
if value, ok := lu.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldName,
})
}
if value, ok := lu.mutation.Description(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldDescription,
})
}
if lu.mutation.DescriptionCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: label.FieldDescription,
})
}
if value, ok := lu.mutation.Color(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldColor,
})
}
if lu.mutation.ColorCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: label.FieldColor,
})
}
if lu.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: label.GroupTable,
Columns: []string{label.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := lu.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: label.GroupTable,
Columns: []string{label.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if lu.mutation.ItemsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := lu.mutation.RemovedItemsIDs(); len(nodes) > 0 && !lu.mutation.ItemsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := lu.mutation.ItemsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if n, err = sqlgraph.UpdateNodes(ctx, lu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{label.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
return n, nil
}
// LabelUpdateOne is the builder for updating a single Label entity.
type LabelUpdateOne struct {
config
fields []string
hooks []Hook
mutation *LabelMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (luo *LabelUpdateOne) SetUpdatedAt(t time.Time) *LabelUpdateOne {
luo.mutation.SetUpdatedAt(t)
return luo
}
// SetName sets the "name" field.
func (luo *LabelUpdateOne) SetName(s string) *LabelUpdateOne {
luo.mutation.SetName(s)
return luo
}
// SetDescription sets the "description" field.
func (luo *LabelUpdateOne) SetDescription(s string) *LabelUpdateOne {
luo.mutation.SetDescription(s)
return luo
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (luo *LabelUpdateOne) SetNillableDescription(s *string) *LabelUpdateOne {
if s != nil {
luo.SetDescription(*s)
}
return luo
}
// ClearDescription clears the value of the "description" field.
func (luo *LabelUpdateOne) ClearDescription() *LabelUpdateOne {
luo.mutation.ClearDescription()
return luo
}
// SetColor sets the "color" field.
func (luo *LabelUpdateOne) SetColor(s string) *LabelUpdateOne {
luo.mutation.SetColor(s)
return luo
}
// SetNillableColor sets the "color" field if the given value is not nil.
func (luo *LabelUpdateOne) SetNillableColor(s *string) *LabelUpdateOne {
if s != nil {
luo.SetColor(*s)
}
return luo
}
// ClearColor clears the value of the "color" field.
func (luo *LabelUpdateOne) ClearColor() *LabelUpdateOne {
luo.mutation.ClearColor()
return luo
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (luo *LabelUpdateOne) SetGroupID(id uuid.UUID) *LabelUpdateOne {
luo.mutation.SetGroupID(id)
return luo
}
// SetGroup sets the "group" edge to the Group entity.
func (luo *LabelUpdateOne) SetGroup(g *Group) *LabelUpdateOne {
return luo.SetGroupID(g.ID)
}
// AddItemIDs adds the "items" edge to the Item entity by IDs.
func (luo *LabelUpdateOne) AddItemIDs(ids ...uuid.UUID) *LabelUpdateOne {
luo.mutation.AddItemIDs(ids...)
return luo
}
// AddItems adds the "items" edges to the Item entity.
func (luo *LabelUpdateOne) AddItems(i ...*Item) *LabelUpdateOne {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return luo.AddItemIDs(ids...)
}
// Mutation returns the LabelMutation object of the builder.
func (luo *LabelUpdateOne) Mutation() *LabelMutation {
return luo.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (luo *LabelUpdateOne) ClearGroup() *LabelUpdateOne {
luo.mutation.ClearGroup()
return luo
}
// ClearItems clears all "items" edges to the Item entity.
func (luo *LabelUpdateOne) ClearItems() *LabelUpdateOne {
luo.mutation.ClearItems()
return luo
}
// RemoveItemIDs removes the "items" edge to Item entities by IDs.
func (luo *LabelUpdateOne) RemoveItemIDs(ids ...uuid.UUID) *LabelUpdateOne {
luo.mutation.RemoveItemIDs(ids...)
return luo
}
// RemoveItems removes "items" edges to Item entities.
func (luo *LabelUpdateOne) RemoveItems(i ...*Item) *LabelUpdateOne {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return luo.RemoveItemIDs(ids...)
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (luo *LabelUpdateOne) Select(field string, fields ...string) *LabelUpdateOne {
luo.fields = append([]string{field}, fields...)
return luo
}
// Save executes the query and returns the updated Label entity.
func (luo *LabelUpdateOne) Save(ctx context.Context) (*Label, error) {
var (
err error
node *Label
)
luo.defaults()
if len(luo.hooks) == 0 {
if err = luo.check(); err != nil {
return nil, err
}
node, err = luo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LabelMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = luo.check(); err != nil {
return nil, err
}
luo.mutation = mutation
node, err = luo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(luo.hooks) - 1; i >= 0; i-- {
if luo.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = luo.hooks[i](mut)
}
v, err := mut.Mutate(ctx, luo.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Label)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from LabelMutation", v)
}
node = nv
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (luo *LabelUpdateOne) SaveX(ctx context.Context) *Label {
node, err := luo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (luo *LabelUpdateOne) Exec(ctx context.Context) error {
_, err := luo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (luo *LabelUpdateOne) ExecX(ctx context.Context) {
if err := luo.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (luo *LabelUpdateOne) defaults() {
if _, ok := luo.mutation.UpdatedAt(); !ok {
v := label.UpdateDefaultUpdatedAt()
luo.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (luo *LabelUpdateOne) check() error {
if v, ok := luo.mutation.Name(); ok {
if err := label.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Label.name": %w`, err)}
}
}
if v, ok := luo.mutation.Description(); ok {
if err := label.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "Label.description": %w`, err)}
}
}
if v, ok := luo.mutation.Color(); ok {
if err := label.ColorValidator(v); err != nil {
return &ValidationError{Name: "color", err: fmt.Errorf(`ent: validator failed for field "Label.color": %w`, err)}
}
}
if _, ok := luo.mutation.GroupID(); luo.mutation.GroupCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Label.group"`)
}
return nil
}
func (luo *LabelUpdateOne) sqlSave(ctx context.Context) (_node *Label, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: label.Table,
Columns: label.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: label.FieldID,
},
},
}
id, ok := luo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Label.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := luo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, label.FieldID)
for _, f := range fields {
if !label.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != label.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := luo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := luo.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: label.FieldUpdatedAt,
})
}
if value, ok := luo.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldName,
})
}
if value, ok := luo.mutation.Description(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldDescription,
})
}
if luo.mutation.DescriptionCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: label.FieldDescription,
})
}
if value, ok := luo.mutation.Color(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldColor,
})
}
if luo.mutation.ColorCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: label.FieldColor,
})
}
if luo.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: label.GroupTable,
Columns: []string{label.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := luo.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: label.GroupTable,
Columns: []string{label.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if luo.mutation.ItemsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := luo.mutation.RemovedItemsIDs(); len(nodes) > 0 && !luo.mutation.ItemsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := luo.mutation.ItemsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Label{config: luo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, luo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{label.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
return _node, nil
}

193
backend/ent/location.go Normal file
View file

@ -0,0 +1,193 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/location"
)
// Location is the model entity for the Location schema.
type Location struct {
config `json:"-"`
// ID of the ent.
ID uuid.UUID `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Description holds the value of the "description" field.
Description string `json:"description,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the LocationQuery when eager-loading is set.
Edges LocationEdges `json:"edges"`
group_locations *uuid.UUID
}
// LocationEdges holds the relations/edges for other nodes in the graph.
type LocationEdges struct {
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// Items holds the value of the items edge.
Items []*Item `json:"items,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e LocationEdges) GroupOrErr() (*Group, error) {
if e.loadedTypes[0] {
if e.Group == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: group.Label}
}
return e.Group, nil
}
return nil, &NotLoadedError{edge: "group"}
}
// ItemsOrErr returns the Items value or an error if the edge
// was not loaded in eager-loading.
func (e LocationEdges) ItemsOrErr() ([]*Item, error) {
if e.loadedTypes[1] {
return e.Items, nil
}
return nil, &NotLoadedError{edge: "items"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Location) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case location.FieldName, location.FieldDescription:
values[i] = new(sql.NullString)
case location.FieldCreatedAt, location.FieldUpdatedAt:
values[i] = new(sql.NullTime)
case location.FieldID:
values[i] = new(uuid.UUID)
case location.ForeignKeys[0]: // group_locations
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type Location", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Location fields.
func (l *Location) assignValues(columns []string, values []interface{}) 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 location.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
l.ID = *value
}
case location.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
l.CreatedAt = value.Time
}
case location.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
l.UpdatedAt = value.Time
}
case location.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
l.Name = value.String
}
case location.FieldDescription:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field description", values[i])
} else if value.Valid {
l.Description = value.String
}
case location.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field group_locations", values[i])
} else if value.Valid {
l.group_locations = new(uuid.UUID)
*l.group_locations = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryGroup queries the "group" edge of the Location entity.
func (l *Location) QueryGroup() *GroupQuery {
return (&LocationClient{config: l.config}).QueryGroup(l)
}
// QueryItems queries the "items" edge of the Location entity.
func (l *Location) QueryItems() *ItemQuery {
return (&LocationClient{config: l.config}).QueryItems(l)
}
// Update returns a builder for updating this Location.
// Note that you need to call Location.Unwrap() before calling this method if this Location
// was returned from a transaction, and the transaction was committed or rolled back.
func (l *Location) Update() *LocationUpdateOne {
return (&LocationClient{config: l.config}).UpdateOne(l)
}
// Unwrap unwraps the Location 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 (l *Location) Unwrap() *Location {
_tx, ok := l.config.driver.(*txDriver)
if !ok {
panic("ent: Location is not a transactional entity")
}
l.config.driver = _tx.drv
return l
}
// String implements the fmt.Stringer.
func (l *Location) String() string {
var builder strings.Builder
builder.WriteString("Location(")
builder.WriteString(fmt.Sprintf("id=%v, ", l.ID))
builder.WriteString("created_at=")
builder.WriteString(l.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(l.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(l.Name)
builder.WriteString(", ")
builder.WriteString("description=")
builder.WriteString(l.Description)
builder.WriteByte(')')
return builder.String()
}
// Locations is a parsable slice of Location.
type Locations []*Location
func (l Locations) config(cfg config) {
for _i := range l {
l[_i].config = cfg
}
}

View file

@ -0,0 +1,89 @@
// Code generated by ent, DO NOT EDIT.
package location
import (
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the location type in the database.
Label = "location"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldDescription holds the string denoting the description field in the database.
FieldDescription = "description"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// EdgeItems holds the string denoting the items edge name in mutations.
EdgeItems = "items"
// Table holds the table name of the location in the database.
Table = "locations"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "locations"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_locations"
// ItemsTable is the table that holds the items relation/edge.
ItemsTable = "items"
// ItemsInverseTable is the table name for the Item entity.
// It exists in this package in order to avoid circular dependency with the "item" package.
ItemsInverseTable = "items"
// ItemsColumn is the table column denoting the items relation/edge.
ItemsColumn = "location_items"
)
// Columns holds all SQL columns for location fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldName,
FieldDescription,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "locations"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"group_locations",
}
// 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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
DescriptionValidator func(string) error
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)

View file

@ -0,0 +1,539 @@
// Code generated by ent, DO NOT EDIT.
package location
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id uuid.UUID) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id uuid.UUID) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id uuid.UUID) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...uuid.UUID) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...uuid.UUID) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id uuid.UUID) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id uuid.UUID) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id uuid.UUID) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id uuid.UUID) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
})
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
})
}
// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ.
func Description(v string) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDescription), v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
})
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldCreatedAt), v))
})
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Location {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldCreatedAt), v...))
})
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Location {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldCreatedAt), v...))
})
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldCreatedAt), v))
})
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.Location {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldUpdatedAt), v...))
})
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.Location {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...))
})
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldName), v...))
})
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Location {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldName), v...))
})
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldName), v))
})
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Location {
return predicate.Location(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.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldName), v))
})
}
// DescriptionEQ applies the EQ predicate on the "description" field.
func DescriptionEQ(v string) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDescription), v))
})
}
// DescriptionNEQ applies the NEQ predicate on the "description" field.
func DescriptionNEQ(v string) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldDescription), v))
})
}
// DescriptionIn applies the In predicate on the "description" field.
func DescriptionIn(vs ...string) predicate.Location {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldDescription), v...))
})
}
// DescriptionNotIn applies the NotIn predicate on the "description" field.
func DescriptionNotIn(vs ...string) predicate.Location {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldDescription), v...))
})
}
// DescriptionGT applies the GT predicate on the "description" field.
func DescriptionGT(v string) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldDescription), v))
})
}
// DescriptionGTE applies the GTE predicate on the "description" field.
func DescriptionGTE(v string) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldDescription), v))
})
}
// DescriptionLT applies the LT predicate on the "description" field.
func DescriptionLT(v string) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldDescription), v))
})
}
// DescriptionLTE applies the LTE predicate on the "description" field.
func DescriptionLTE(v string) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldDescription), v))
})
}
// DescriptionContains applies the Contains predicate on the "description" field.
func DescriptionContains(v string) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldDescription), v))
})
}
// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field.
func DescriptionHasPrefix(v string) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldDescription), v))
})
}
// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field.
func DescriptionHasSuffix(v string) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldDescription), v))
})
}
// DescriptionIsNil applies the IsNil predicate on the "description" field.
func DescriptionIsNil() predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldDescription)))
})
}
// DescriptionNotNil applies the NotNil predicate on the "description" field.
func DescriptionNotNil() predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldDescription)))
})
}
// DescriptionEqualFold applies the EqualFold predicate on the "description" field.
func DescriptionEqualFold(v string) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldDescription), v))
})
}
// DescriptionContainsFold applies the ContainsFold predicate on the "description" field.
func DescriptionContainsFold(v string) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldDescription), v))
})
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.Location {
return predicate.Location(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasItems applies the HasEdge predicate on the "items" edge.
func HasItems() predicate.Location {
return predicate.Location(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemsTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ItemsTable, ItemsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasItemsWith applies the HasEdge predicate on the "items" edge with a given conditions (other predicates).
func HasItemsWith(preds ...predicate.Item) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ItemsTable, ItemsColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Location) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Location) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Location) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,417 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/location"
)
// LocationCreate is the builder for creating a Location entity.
type LocationCreate struct {
config
mutation *LocationMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (lc *LocationCreate) SetCreatedAt(t time.Time) *LocationCreate {
lc.mutation.SetCreatedAt(t)
return lc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (lc *LocationCreate) SetNillableCreatedAt(t *time.Time) *LocationCreate {
if t != nil {
lc.SetCreatedAt(*t)
}
return lc
}
// SetUpdatedAt sets the "updated_at" field.
func (lc *LocationCreate) SetUpdatedAt(t time.Time) *LocationCreate {
lc.mutation.SetUpdatedAt(t)
return lc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (lc *LocationCreate) SetNillableUpdatedAt(t *time.Time) *LocationCreate {
if t != nil {
lc.SetUpdatedAt(*t)
}
return lc
}
// SetName sets the "name" field.
func (lc *LocationCreate) SetName(s string) *LocationCreate {
lc.mutation.SetName(s)
return lc
}
// SetDescription sets the "description" field.
func (lc *LocationCreate) SetDescription(s string) *LocationCreate {
lc.mutation.SetDescription(s)
return lc
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (lc *LocationCreate) SetNillableDescription(s *string) *LocationCreate {
if s != nil {
lc.SetDescription(*s)
}
return lc
}
// SetID sets the "id" field.
func (lc *LocationCreate) SetID(u uuid.UUID) *LocationCreate {
lc.mutation.SetID(u)
return lc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (lc *LocationCreate) SetNillableID(u *uuid.UUID) *LocationCreate {
if u != nil {
lc.SetID(*u)
}
return lc
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (lc *LocationCreate) SetGroupID(id uuid.UUID) *LocationCreate {
lc.mutation.SetGroupID(id)
return lc
}
// SetGroup sets the "group" edge to the Group entity.
func (lc *LocationCreate) SetGroup(g *Group) *LocationCreate {
return lc.SetGroupID(g.ID)
}
// AddItemIDs adds the "items" edge to the Item entity by IDs.
func (lc *LocationCreate) AddItemIDs(ids ...uuid.UUID) *LocationCreate {
lc.mutation.AddItemIDs(ids...)
return lc
}
// AddItems adds the "items" edges to the Item entity.
func (lc *LocationCreate) AddItems(i ...*Item) *LocationCreate {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return lc.AddItemIDs(ids...)
}
// Mutation returns the LocationMutation object of the builder.
func (lc *LocationCreate) Mutation() *LocationMutation {
return lc.mutation
}
// Save creates the Location in the database.
func (lc *LocationCreate) Save(ctx context.Context) (*Location, error) {
var (
err error
node *Location
)
lc.defaults()
if len(lc.hooks) == 0 {
if err = lc.check(); err != nil {
return nil, err
}
node, err = lc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LocationMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = lc.check(); err != nil {
return nil, err
}
lc.mutation = mutation
if node, err = lc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(lc.hooks) - 1; i >= 0; i-- {
if lc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = lc.hooks[i](mut)
}
v, err := mut.Mutate(ctx, lc.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Location)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from LocationMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (lc *LocationCreate) SaveX(ctx context.Context) *Location {
v, err := lc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (lc *LocationCreate) Exec(ctx context.Context) error {
_, err := lc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (lc *LocationCreate) ExecX(ctx context.Context) {
if err := lc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (lc *LocationCreate) defaults() {
if _, ok := lc.mutation.CreatedAt(); !ok {
v := location.DefaultCreatedAt()
lc.mutation.SetCreatedAt(v)
}
if _, ok := lc.mutation.UpdatedAt(); !ok {
v := location.DefaultUpdatedAt()
lc.mutation.SetUpdatedAt(v)
}
if _, ok := lc.mutation.ID(); !ok {
v := location.DefaultID()
lc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (lc *LocationCreate) check() error {
if _, ok := lc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Location.created_at"`)}
}
if _, ok := lc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Location.updated_at"`)}
}
if _, ok := lc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Location.name"`)}
}
if v, ok := lc.mutation.Name(); ok {
if err := location.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Location.name": %w`, err)}
}
}
if v, ok := lc.mutation.Description(); ok {
if err := location.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "Location.description": %w`, err)}
}
}
if _, ok := lc.mutation.GroupID(); !ok {
return &ValidationError{Name: "group", err: errors.New(`ent: missing required edge "Location.group"`)}
}
return nil
}
func (lc *LocationCreate) sqlSave(ctx context.Context) (*Location, error) {
_node, _spec := lc.createSpec()
if err := sqlgraph.CreateNode(ctx, lc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
if _spec.ID.Value != nil {
if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
_node.ID = *id
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
return nil, err
}
}
return _node, nil
}
func (lc *LocationCreate) createSpec() (*Location, *sqlgraph.CreateSpec) {
var (
_node = &Location{config: lc.config}
_spec = &sqlgraph.CreateSpec{
Table: location.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: location.FieldID,
},
}
)
if id, ok := lc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := lc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: location.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := lc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: location.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := lc.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: location.FieldName,
})
_node.Name = value
}
if value, ok := lc.mutation.Description(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: location.FieldDescription,
})
_node.Description = value
}
if nodes := lc.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: location.GroupTable,
Columns: []string{location.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.group_locations = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := lc.mutation.ItemsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: location.ItemsTable,
Columns: []string{location.ItemsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// LocationCreateBulk is the builder for creating many Location entities in bulk.
type LocationCreateBulk struct {
config
builders []*LocationCreate
}
// Save creates the Location entities in the database.
func (lcb *LocationCreateBulk) Save(ctx context.Context) ([]*Location, error) {
specs := make([]*sqlgraph.CreateSpec, len(lcb.builders))
nodes := make([]*Location, len(lcb.builders))
mutators := make([]Mutator, len(lcb.builders))
for i := range lcb.builders {
func(i int, root context.Context) {
builder := lcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LocationMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, lcb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, lcb.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
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, lcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (lcb *LocationCreateBulk) SaveX(ctx context.Context) []*Location {
v, err := lcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (lcb *LocationCreateBulk) Exec(ctx context.Context) error {
_, err := lcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (lcb *LocationCreateBulk) ExecX(ctx context.Context) {
if err := lcb.Exec(ctx); err != nil {
panic(err)
}
}

View file

@ -0,0 +1,115 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/hay-kot/content/backend/ent/location"
"github.com/hay-kot/content/backend/ent/predicate"
)
// LocationDelete is the builder for deleting a Location entity.
type LocationDelete struct {
config
hooks []Hook
mutation *LocationMutation
}
// Where appends a list predicates to the LocationDelete builder.
func (ld *LocationDelete) Where(ps ...predicate.Location) *LocationDelete {
ld.mutation.Where(ps...)
return ld
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (ld *LocationDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(ld.hooks) == 0 {
affected, err = ld.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LocationMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
ld.mutation = mutation
affected, err = ld.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(ld.hooks) - 1; i >= 0; i-- {
if ld.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ld.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ld.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (ld *LocationDelete) ExecX(ctx context.Context) int {
n, err := ld.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (ld *LocationDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: location.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: location.FieldID,
},
},
}
if ps := ld.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, ld.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// LocationDeleteOne is the builder for deleting a single Location entity.
type LocationDeleteOne struct {
ld *LocationDelete
}
// Exec executes the deletion query.
func (ldo *LocationDeleteOne) Exec(ctx context.Context) error {
n, err := ldo.ld.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{location.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (ldo *LocationDeleteOne) ExecX(ctx context.Context) {
ldo.ld.ExecX(ctx)
}

View file

@ -0,0 +1,687 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/location"
"github.com/hay-kot/content/backend/ent/predicate"
)
// LocationQuery is the builder for querying Location entities.
type LocationQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Location
withGroup *GroupQuery
withItems *ItemQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the LocationQuery builder.
func (lq *LocationQuery) Where(ps ...predicate.Location) *LocationQuery {
lq.predicates = append(lq.predicates, ps...)
return lq
}
// Limit adds a limit step to the query.
func (lq *LocationQuery) Limit(limit int) *LocationQuery {
lq.limit = &limit
return lq
}
// Offset adds an offset step to the query.
func (lq *LocationQuery) Offset(offset int) *LocationQuery {
lq.offset = &offset
return lq
}
// 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 (lq *LocationQuery) Unique(unique bool) *LocationQuery {
lq.unique = &unique
return lq
}
// Order adds an order step to the query.
func (lq *LocationQuery) Order(o ...OrderFunc) *LocationQuery {
lq.order = append(lq.order, o...)
return lq
}
// QueryGroup chains the current query on the "group" edge.
func (lq *LocationQuery) QueryGroup() *GroupQuery {
query := &GroupQuery{config: lq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := lq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(location.Table, location.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, location.GroupTable, location.GroupColumn),
)
fromU = sqlgraph.SetNeighbors(lq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryItems chains the current query on the "items" edge.
func (lq *LocationQuery) QueryItems() *ItemQuery {
query := &ItemQuery{config: lq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := lq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(location.Table, location.FieldID, selector),
sqlgraph.To(item.Table, item.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, location.ItemsTable, location.ItemsColumn),
)
fromU = sqlgraph.SetNeighbors(lq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Location entity from the query.
// Returns a *NotFoundError when no Location was found.
func (lq *LocationQuery) First(ctx context.Context) (*Location, error) {
nodes, err := lq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{location.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (lq *LocationQuery) FirstX(ctx context.Context) *Location {
node, err := lq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Location ID from the query.
// Returns a *NotFoundError when no Location ID was found.
func (lq *LocationQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = lq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{location.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (lq *LocationQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := lq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Location entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Location entity is found.
// Returns a *NotFoundError when no Location entities are found.
func (lq *LocationQuery) Only(ctx context.Context) (*Location, error) {
nodes, err := lq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{location.Label}
default:
return nil, &NotSingularError{location.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (lq *LocationQuery) OnlyX(ctx context.Context) *Location {
node, err := lq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Location ID in the query.
// Returns a *NotSingularError when more than one Location ID is found.
// Returns a *NotFoundError when no entities are found.
func (lq *LocationQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = lq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{location.Label}
default:
err = &NotSingularError{location.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (lq *LocationQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := lq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Locations.
func (lq *LocationQuery) All(ctx context.Context) ([]*Location, error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
return lq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (lq *LocationQuery) AllX(ctx context.Context) []*Location {
nodes, err := lq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Location IDs.
func (lq *LocationQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := lq.Select(location.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (lq *LocationQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := lq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (lq *LocationQuery) Count(ctx context.Context) (int, error) {
if err := lq.prepareQuery(ctx); err != nil {
return 0, err
}
return lq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (lq *LocationQuery) CountX(ctx context.Context) int {
count, err := lq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (lq *LocationQuery) Exist(ctx context.Context) (bool, error) {
if err := lq.prepareQuery(ctx); err != nil {
return false, err
}
return lq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (lq *LocationQuery) ExistX(ctx context.Context) bool {
exist, err := lq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the LocationQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (lq *LocationQuery) Clone() *LocationQuery {
if lq == nil {
return nil
}
return &LocationQuery{
config: lq.config,
limit: lq.limit,
offset: lq.offset,
order: append([]OrderFunc{}, lq.order...),
predicates: append([]predicate.Location{}, lq.predicates...),
withGroup: lq.withGroup.Clone(),
withItems: lq.withItems.Clone(),
// clone intermediate query.
sql: lq.sql.Clone(),
path: lq.path,
unique: lq.unique,
}
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (lq *LocationQuery) WithGroup(opts ...func(*GroupQuery)) *LocationQuery {
query := &GroupQuery{config: lq.config}
for _, opt := range opts {
opt(query)
}
lq.withGroup = query
return lq
}
// WithItems tells the query-builder to eager-load the nodes that are connected to
// the "items" edge. The optional arguments are used to configure the query builder of the edge.
func (lq *LocationQuery) WithItems(opts ...func(*ItemQuery)) *LocationQuery {
query := &ItemQuery{config: lq.config}
for _, opt := range opts {
opt(query)
}
lq.withItems = query
return lq
}
// 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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Location.Query().
// GroupBy(location.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (lq *LocationQuery) GroupBy(field string, fields ...string) *LocationGroupBy {
grbuild := &LocationGroupBy{config: lq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
return lq.sqlQuery(ctx), nil
}
grbuild.label = location.Label
grbuild.flds, grbuild.scan = &grbuild.fields, 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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// }
//
// client.Location.Query().
// Select(location.FieldCreatedAt).
// Scan(ctx, &v)
func (lq *LocationQuery) Select(fields ...string) *LocationSelect {
lq.fields = append(lq.fields, fields...)
selbuild := &LocationSelect{LocationQuery: lq}
selbuild.label = location.Label
selbuild.flds, selbuild.scan = &lq.fields, selbuild.Scan
return selbuild
}
func (lq *LocationQuery) prepareQuery(ctx context.Context) error {
for _, f := range lq.fields {
if !location.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if lq.path != nil {
prev, err := lq.path(ctx)
if err != nil {
return err
}
lq.sql = prev
}
return nil
}
func (lq *LocationQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Location, error) {
var (
nodes = []*Location{}
withFKs = lq.withFKs
_spec = lq.querySpec()
loadedTypes = [2]bool{
lq.withGroup != nil,
lq.withItems != nil,
}
)
if lq.withGroup != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, location.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
return (*Location).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
node := &Location{config: lq.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, lq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := lq.withGroup; query != nil {
if err := lq.loadGroup(ctx, query, nodes, nil,
func(n *Location, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
if query := lq.withItems; query != nil {
if err := lq.loadItems(ctx, query, nodes,
func(n *Location) { n.Edges.Items = []*Item{} },
func(n *Location, e *Item) { n.Edges.Items = append(n.Edges.Items, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (lq *LocationQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*Location, init func(*Location), assign func(*Location, *Group)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Location)
for i := range nodes {
if nodes[i].group_locations == nil {
continue
}
fk := *nodes[i].group_locations
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(group.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_locations" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (lq *LocationQuery) loadItems(ctx context.Context, query *ItemQuery, nodes []*Location, init func(*Location), assign func(*Location, *Item)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Location)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Item(func(s *sql.Selector) {
s.Where(sql.InValues(location.ItemsColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.location_items
if fk == nil {
return fmt.Errorf(`foreign-key "location_items" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "location_items" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (lq *LocationQuery) sqlCount(ctx context.Context) (int, error) {
_spec := lq.querySpec()
_spec.Node.Columns = lq.fields
if len(lq.fields) > 0 {
_spec.Unique = lq.unique != nil && *lq.unique
}
return sqlgraph.CountNodes(ctx, lq.driver, _spec)
}
func (lq *LocationQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := lq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %w", err)
}
return n > 0, nil
}
func (lq *LocationQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: location.Table,
Columns: location.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: location.FieldID,
},
},
From: lq.sql,
Unique: true,
}
if unique := lq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := lq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, location.FieldID)
for i := range fields {
if fields[i] != location.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := lq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := lq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := lq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := lq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (lq *LocationQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(lq.driver.Dialect())
t1 := builder.Table(location.Table)
columns := lq.fields
if len(columns) == 0 {
columns = location.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if lq.sql != nil {
selector = lq.sql
selector.Select(selector.Columns(columns...)...)
}
if lq.unique != nil && *lq.unique {
selector.Distinct()
}
for _, p := range lq.predicates {
p(selector)
}
for _, p := range lq.order {
p(selector)
}
if offset := lq.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 := lq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// LocationGroupBy is the group-by builder for Location entities.
type LocationGroupBy struct {
config
selector
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (lgb *LocationGroupBy) Aggregate(fns ...AggregateFunc) *LocationGroupBy {
lgb.fns = append(lgb.fns, fns...)
return lgb
}
// Scan applies the group-by query and scans the result into the given value.
func (lgb *LocationGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := lgb.path(ctx)
if err != nil {
return err
}
lgb.sql = query
return lgb.sqlScan(ctx, v)
}
func (lgb *LocationGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range lgb.fields {
if !location.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := lgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := lgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (lgb *LocationGroupBy) sqlQuery() *sql.Selector {
selector := lgb.sql.Select()
aggregation := make([]string, 0, len(lgb.fns))
for _, fn := range lgb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(lgb.fields)+len(lgb.fns))
for _, f := range lgb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(lgb.fields...)...)
}
// LocationSelect is the builder for selecting fields of Location entities.
type LocationSelect struct {
*LocationQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (ls *LocationSelect) Scan(ctx context.Context, v interface{}) error {
if err := ls.prepareQuery(ctx); err != nil {
return err
}
ls.sql = ls.LocationQuery.sqlQuery(ctx)
return ls.sqlScan(ctx, v)
}
func (ls *LocationSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := ls.sql.Query()
if err := ls.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View file

@ -0,0 +1,717 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/location"
"github.com/hay-kot/content/backend/ent/predicate"
)
// LocationUpdate is the builder for updating Location entities.
type LocationUpdate struct {
config
hooks []Hook
mutation *LocationMutation
}
// Where appends a list predicates to the LocationUpdate builder.
func (lu *LocationUpdate) Where(ps ...predicate.Location) *LocationUpdate {
lu.mutation.Where(ps...)
return lu
}
// SetUpdatedAt sets the "updated_at" field.
func (lu *LocationUpdate) SetUpdatedAt(t time.Time) *LocationUpdate {
lu.mutation.SetUpdatedAt(t)
return lu
}
// SetName sets the "name" field.
func (lu *LocationUpdate) SetName(s string) *LocationUpdate {
lu.mutation.SetName(s)
return lu
}
// SetDescription sets the "description" field.
func (lu *LocationUpdate) SetDescription(s string) *LocationUpdate {
lu.mutation.SetDescription(s)
return lu
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (lu *LocationUpdate) SetNillableDescription(s *string) *LocationUpdate {
if s != nil {
lu.SetDescription(*s)
}
return lu
}
// ClearDescription clears the value of the "description" field.
func (lu *LocationUpdate) ClearDescription() *LocationUpdate {
lu.mutation.ClearDescription()
return lu
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (lu *LocationUpdate) SetGroupID(id uuid.UUID) *LocationUpdate {
lu.mutation.SetGroupID(id)
return lu
}
// SetGroup sets the "group" edge to the Group entity.
func (lu *LocationUpdate) SetGroup(g *Group) *LocationUpdate {
return lu.SetGroupID(g.ID)
}
// AddItemIDs adds the "items" edge to the Item entity by IDs.
func (lu *LocationUpdate) AddItemIDs(ids ...uuid.UUID) *LocationUpdate {
lu.mutation.AddItemIDs(ids...)
return lu
}
// AddItems adds the "items" edges to the Item entity.
func (lu *LocationUpdate) AddItems(i ...*Item) *LocationUpdate {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return lu.AddItemIDs(ids...)
}
// Mutation returns the LocationMutation object of the builder.
func (lu *LocationUpdate) Mutation() *LocationMutation {
return lu.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (lu *LocationUpdate) ClearGroup() *LocationUpdate {
lu.mutation.ClearGroup()
return lu
}
// ClearItems clears all "items" edges to the Item entity.
func (lu *LocationUpdate) ClearItems() *LocationUpdate {
lu.mutation.ClearItems()
return lu
}
// RemoveItemIDs removes the "items" edge to Item entities by IDs.
func (lu *LocationUpdate) RemoveItemIDs(ids ...uuid.UUID) *LocationUpdate {
lu.mutation.RemoveItemIDs(ids...)
return lu
}
// RemoveItems removes "items" edges to Item entities.
func (lu *LocationUpdate) RemoveItems(i ...*Item) *LocationUpdate {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return lu.RemoveItemIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (lu *LocationUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
lu.defaults()
if len(lu.hooks) == 0 {
if err = lu.check(); err != nil {
return 0, err
}
affected, err = lu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LocationMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = lu.check(); err != nil {
return 0, err
}
lu.mutation = mutation
affected, err = lu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(lu.hooks) - 1; i >= 0; i-- {
if lu.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = lu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, lu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (lu *LocationUpdate) SaveX(ctx context.Context) int {
affected, err := lu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (lu *LocationUpdate) Exec(ctx context.Context) error {
_, err := lu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (lu *LocationUpdate) ExecX(ctx context.Context) {
if err := lu.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (lu *LocationUpdate) defaults() {
if _, ok := lu.mutation.UpdatedAt(); !ok {
v := location.UpdateDefaultUpdatedAt()
lu.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (lu *LocationUpdate) check() error {
if v, ok := lu.mutation.Name(); ok {
if err := location.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Location.name": %w`, err)}
}
}
if v, ok := lu.mutation.Description(); ok {
if err := location.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "Location.description": %w`, err)}
}
}
if _, ok := lu.mutation.GroupID(); lu.mutation.GroupCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Location.group"`)
}
return nil
}
func (lu *LocationUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: location.Table,
Columns: location.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: location.FieldID,
},
},
}
if ps := lu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := lu.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: location.FieldUpdatedAt,
})
}
if value, ok := lu.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: location.FieldName,
})
}
if value, ok := lu.mutation.Description(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: location.FieldDescription,
})
}
if lu.mutation.DescriptionCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: location.FieldDescription,
})
}
if lu.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: location.GroupTable,
Columns: []string{location.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := lu.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: location.GroupTable,
Columns: []string{location.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if lu.mutation.ItemsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: location.ItemsTable,
Columns: []string{location.ItemsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := lu.mutation.RemovedItemsIDs(); len(nodes) > 0 && !lu.mutation.ItemsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: location.ItemsTable,
Columns: []string{location.ItemsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := lu.mutation.ItemsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: location.ItemsTable,
Columns: []string{location.ItemsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if n, err = sqlgraph.UpdateNodes(ctx, lu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{location.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
return n, nil
}
// LocationUpdateOne is the builder for updating a single Location entity.
type LocationUpdateOne struct {
config
fields []string
hooks []Hook
mutation *LocationMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (luo *LocationUpdateOne) SetUpdatedAt(t time.Time) *LocationUpdateOne {
luo.mutation.SetUpdatedAt(t)
return luo
}
// SetName sets the "name" field.
func (luo *LocationUpdateOne) SetName(s string) *LocationUpdateOne {
luo.mutation.SetName(s)
return luo
}
// SetDescription sets the "description" field.
func (luo *LocationUpdateOne) SetDescription(s string) *LocationUpdateOne {
luo.mutation.SetDescription(s)
return luo
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (luo *LocationUpdateOne) SetNillableDescription(s *string) *LocationUpdateOne {
if s != nil {
luo.SetDescription(*s)
}
return luo
}
// ClearDescription clears the value of the "description" field.
func (luo *LocationUpdateOne) ClearDescription() *LocationUpdateOne {
luo.mutation.ClearDescription()
return luo
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (luo *LocationUpdateOne) SetGroupID(id uuid.UUID) *LocationUpdateOne {
luo.mutation.SetGroupID(id)
return luo
}
// SetGroup sets the "group" edge to the Group entity.
func (luo *LocationUpdateOne) SetGroup(g *Group) *LocationUpdateOne {
return luo.SetGroupID(g.ID)
}
// AddItemIDs adds the "items" edge to the Item entity by IDs.
func (luo *LocationUpdateOne) AddItemIDs(ids ...uuid.UUID) *LocationUpdateOne {
luo.mutation.AddItemIDs(ids...)
return luo
}
// AddItems adds the "items" edges to the Item entity.
func (luo *LocationUpdateOne) AddItems(i ...*Item) *LocationUpdateOne {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return luo.AddItemIDs(ids...)
}
// Mutation returns the LocationMutation object of the builder.
func (luo *LocationUpdateOne) Mutation() *LocationMutation {
return luo.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (luo *LocationUpdateOne) ClearGroup() *LocationUpdateOne {
luo.mutation.ClearGroup()
return luo
}
// ClearItems clears all "items" edges to the Item entity.
func (luo *LocationUpdateOne) ClearItems() *LocationUpdateOne {
luo.mutation.ClearItems()
return luo
}
// RemoveItemIDs removes the "items" edge to Item entities by IDs.
func (luo *LocationUpdateOne) RemoveItemIDs(ids ...uuid.UUID) *LocationUpdateOne {
luo.mutation.RemoveItemIDs(ids...)
return luo
}
// RemoveItems removes "items" edges to Item entities.
func (luo *LocationUpdateOne) RemoveItems(i ...*Item) *LocationUpdateOne {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return luo.RemoveItemIDs(ids...)
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (luo *LocationUpdateOne) Select(field string, fields ...string) *LocationUpdateOne {
luo.fields = append([]string{field}, fields...)
return luo
}
// Save executes the query and returns the updated Location entity.
func (luo *LocationUpdateOne) Save(ctx context.Context) (*Location, error) {
var (
err error
node *Location
)
luo.defaults()
if len(luo.hooks) == 0 {
if err = luo.check(); err != nil {
return nil, err
}
node, err = luo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LocationMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = luo.check(); err != nil {
return nil, err
}
luo.mutation = mutation
node, err = luo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(luo.hooks) - 1; i >= 0; i-- {
if luo.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = luo.hooks[i](mut)
}
v, err := mut.Mutate(ctx, luo.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Location)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from LocationMutation", v)
}
node = nv
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (luo *LocationUpdateOne) SaveX(ctx context.Context) *Location {
node, err := luo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (luo *LocationUpdateOne) Exec(ctx context.Context) error {
_, err := luo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (luo *LocationUpdateOne) ExecX(ctx context.Context) {
if err := luo.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (luo *LocationUpdateOne) defaults() {
if _, ok := luo.mutation.UpdatedAt(); !ok {
v := location.UpdateDefaultUpdatedAt()
luo.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (luo *LocationUpdateOne) check() error {
if v, ok := luo.mutation.Name(); ok {
if err := location.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Location.name": %w`, err)}
}
}
if v, ok := luo.mutation.Description(); ok {
if err := location.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "Location.description": %w`, err)}
}
}
if _, ok := luo.mutation.GroupID(); luo.mutation.GroupCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Location.group"`)
}
return nil
}
func (luo *LocationUpdateOne) sqlSave(ctx context.Context) (_node *Location, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: location.Table,
Columns: location.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: location.FieldID,
},
},
}
id, ok := luo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Location.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := luo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, location.FieldID)
for _, f := range fields {
if !location.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != location.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := luo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := luo.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: location.FieldUpdatedAt,
})
}
if value, ok := luo.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: location.FieldName,
})
}
if value, ok := luo.mutation.Description(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: location.FieldDescription,
})
}
if luo.mutation.DescriptionCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: location.FieldDescription,
})
}
if luo.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: location.GroupTable,
Columns: []string{location.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := luo.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: location.GroupTable,
Columns: []string{location.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if luo.mutation.ItemsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: location.ItemsTable,
Columns: []string{location.ItemsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := luo.mutation.RemovedItemsIDs(); len(nodes) > 0 && !luo.mutation.ItemsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: location.ItemsTable,
Columns: []string{location.ItemsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := luo.mutation.ItemsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: location.ItemsTable,
Columns: []string{location.ItemsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Location{config: luo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, luo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{location.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
return _node, nil
}

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package migrate package migrate
@ -28,9 +28,6 @@ var (
// and therefore, it's recommended to enable this option to get more // and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes. // flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex WithDropIndex = schema.WithDropIndex
// WithFixture sets the foreign-key renaming option to the migration when upgrading
// ent from v0.1.0 (issue-#285). Defaults to false.
WithFixture = schema.WithFixture
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys WithForeignKeys = schema.WithForeignKeys
) )
@ -45,11 +42,16 @@ func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources. // Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
return Create(ctx, s, Tables, opts...)
}
// Create creates all table resources using the given schema driver.
func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...) migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil { if err != nil {
return fmt.Errorf("ent/migrate: %w", err) return fmt.Errorf("ent/migrate: %w", err)
} }
return migrate.Create(ctx, Tables...) return migrate.Create(ctx, tables...)
} }
// WriteTo writes the schema changes to w instead of running them against the database. // WriteTo writes the schema changes to w instead of running them against the database.
@ -57,15 +59,6 @@ func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { // if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err) // log.Fatal(err)
// } // }
//
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
drv := &schema.WriteDriver{ return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
Writer: w,
Driver: s.drv,
}
migrate, err := schema.NewMigrate(drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, Tables...)
} }

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package migrate package migrate
@ -10,10 +10,11 @@ import (
var ( var (
// AuthTokensColumns holds the columns for the "auth_tokens" table. // AuthTokensColumns holds the columns for the "auth_tokens" table.
AuthTokensColumns = []*schema.Column{ AuthTokensColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true}, {Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "token", Type: field.TypeBytes, Unique: true}, {Name: "token", Type: field.TypeBytes, Unique: true},
{Name: "expires_at", Type: field.TypeTime}, {Name: "expires_at", Type: field.TypeTime},
{Name: "created_at", Type: field.TypeTime},
{Name: "user_auth_tokens", Type: field.TypeUUID, Nullable: true}, {Name: "user_auth_tokens", Type: field.TypeUUID, Nullable: true},
} }
// AuthTokensTable holds the schema information for the "auth_tokens" table. // AuthTokensTable holds the schema information for the "auth_tokens" table.
@ -24,7 +25,7 @@ var (
ForeignKeys: []*schema.ForeignKey{ ForeignKeys: []*schema.ForeignKey{
{ {
Symbol: "auth_tokens_users_auth_tokens", Symbol: "auth_tokens_users_auth_tokens",
Columns: []*schema.Column{AuthTokensColumns[4]}, Columns: []*schema.Column{AuthTokensColumns[5]},
RefColumns: []*schema.Column{UsersColumns[0]}, RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.SetNull, OnDelete: schema.SetNull,
}, },
@ -33,31 +34,213 @@ var (
{ {
Name: "authtokens_token", Name: "authtokens_token",
Unique: false, Unique: false,
Columns: []*schema.Column{AuthTokensColumns[1]}, Columns: []*schema.Column{AuthTokensColumns[3]},
},
},
}
// GroupsColumns holds the columns for the "groups" table.
GroupsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Size: 255},
{Name: "currency", Type: field.TypeEnum, Enums: []string{"usd"}, Default: "usd"},
}
// GroupsTable holds the schema information for the "groups" table.
GroupsTable = &schema.Table{
Name: "groups",
Columns: GroupsColumns,
PrimaryKey: []*schema.Column{GroupsColumns[0]},
}
// ItemsColumns holds the columns for the "items" table.
ItemsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Size: 255},
{Name: "description", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "notes", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "serial_number", Type: field.TypeString, Nullable: true, Size: 255},
{Name: "model_number", Type: field.TypeString, Nullable: true, Size: 255},
{Name: "manufacturer", Type: field.TypeString, Nullable: true, Size: 255},
{Name: "purchase_time", Type: field.TypeTime, Nullable: true},
{Name: "purchase_from", Type: field.TypeString, Nullable: true},
{Name: "purchase_price", Type: field.TypeFloat64, Default: 0},
{Name: "purchase_receipt_id", Type: field.TypeUUID, Nullable: true},
{Name: "sold_time", Type: field.TypeTime, Nullable: true},
{Name: "sold_to", Type: field.TypeString, Nullable: true},
{Name: "sold_price", Type: field.TypeFloat64, Default: 0},
{Name: "sold_receipt_id", Type: field.TypeUUID, Nullable: true},
{Name: "sold_notes", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "group_items", Type: field.TypeUUID},
{Name: "location_items", Type: field.TypeUUID, Nullable: true},
}
// ItemsTable holds the schema information for the "items" table.
ItemsTable = &schema.Table{
Name: "items",
Columns: ItemsColumns,
PrimaryKey: []*schema.Column{ItemsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "items_groups_items",
Columns: []*schema.Column{ItemsColumns[18]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "items_locations_items",
Columns: []*schema.Column{ItemsColumns[19]},
RefColumns: []*schema.Column{LocationsColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// ItemFieldsColumns holds the columns for the "item_fields" table.
ItemFieldsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Size: 255},
{Name: "description", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "type", Type: field.TypeEnum, Enums: []string{"text", "number", "boolean", "time"}},
{Name: "text_value", Type: field.TypeString, Nullable: true, Size: 500},
{Name: "number_value", Type: field.TypeInt, Nullable: true},
{Name: "boolean_value", Type: field.TypeBool, Default: false},
{Name: "time_value", Type: field.TypeTime},
{Name: "item_fields", Type: field.TypeUUID, Nullable: true},
}
// ItemFieldsTable holds the schema information for the "item_fields" table.
ItemFieldsTable = &schema.Table{
Name: "item_fields",
Columns: ItemFieldsColumns,
PrimaryKey: []*schema.Column{ItemFieldsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "item_fields_items_fields",
Columns: []*schema.Column{ItemFieldsColumns[10]},
RefColumns: []*schema.Column{ItemsColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// LabelsColumns holds the columns for the "labels" table.
LabelsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Size: 255},
{Name: "description", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "color", Type: field.TypeString, Nullable: true, Size: 255},
{Name: "group_labels", Type: field.TypeUUID},
}
// LabelsTable holds the schema information for the "labels" table.
LabelsTable = &schema.Table{
Name: "labels",
Columns: LabelsColumns,
PrimaryKey: []*schema.Column{LabelsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "labels_groups_labels",
Columns: []*schema.Column{LabelsColumns[6]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.NoAction,
},
},
}
// LocationsColumns holds the columns for the "locations" table.
LocationsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Size: 255},
{Name: "description", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "group_locations", Type: field.TypeUUID},
}
// LocationsTable holds the schema information for the "locations" table.
LocationsTable = &schema.Table{
Name: "locations",
Columns: LocationsColumns,
PrimaryKey: []*schema.Column{LocationsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "locations_groups_locations",
Columns: []*schema.Column{LocationsColumns[5]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.NoAction,
}, },
}, },
} }
// UsersColumns holds the columns for the "users" table. // UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{ UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID}, {Name: "id", Type: field.TypeUUID},
{Name: "name", Type: field.TypeString}, {Name: "created_at", Type: field.TypeTime},
{Name: "email", Type: field.TypeString, Unique: true}, {Name: "updated_at", Type: field.TypeTime},
{Name: "password", Type: field.TypeString}, {Name: "name", Type: field.TypeString, Size: 255},
{Name: "email", Type: field.TypeString, Unique: true, Size: 255},
{Name: "password", Type: field.TypeString, Size: 255},
{Name: "is_superuser", Type: field.TypeBool, Default: false}, {Name: "is_superuser", Type: field.TypeBool, Default: false},
{Name: "group_users", Type: field.TypeUUID},
} }
// UsersTable holds the schema information for the "users" table. // UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{ UsersTable = &schema.Table{
Name: "users", Name: "users",
Columns: UsersColumns, Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]}, PrimaryKey: []*schema.Column{UsersColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "users_groups_users",
Columns: []*schema.Column{UsersColumns[7]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.NoAction,
},
},
}
// LabelItemsColumns holds the columns for the "label_items" table.
LabelItemsColumns = []*schema.Column{
{Name: "label_id", Type: field.TypeUUID},
{Name: "item_id", Type: field.TypeUUID},
}
// LabelItemsTable holds the schema information for the "label_items" table.
LabelItemsTable = &schema.Table{
Name: "label_items",
Columns: LabelItemsColumns,
PrimaryKey: []*schema.Column{LabelItemsColumns[0], LabelItemsColumns[1]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "label_items_label_id",
Columns: []*schema.Column{LabelItemsColumns[0]},
RefColumns: []*schema.Column{LabelsColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "label_items_item_id",
Columns: []*schema.Column{LabelItemsColumns[1]},
RefColumns: []*schema.Column{ItemsColumns[0]},
OnDelete: schema.Cascade,
},
},
} }
// Tables holds all the tables in the schema. // Tables holds all the tables in the schema.
Tables = []*schema.Table{ Tables = []*schema.Table{
AuthTokensTable, AuthTokensTable,
GroupsTable,
ItemsTable,
ItemFieldsTable,
LabelsTable,
LocationsTable,
UsersTable, UsersTable,
LabelItemsTable,
} }
) )
func init() { func init() {
AuthTokensTable.ForeignKeys[0].RefTable = UsersTable AuthTokensTable.ForeignKeys[0].RefTable = UsersTable
ItemsTable.ForeignKeys[0].RefTable = GroupsTable
ItemsTable.ForeignKeys[1].RefTable = LocationsTable
ItemFieldsTable.ForeignKeys[0].RefTable = ItemsTable
LabelsTable.ForeignKeys[0].RefTable = GroupsTable
LocationsTable.ForeignKeys[0].RefTable = GroupsTable
UsersTable.ForeignKeys[0].RefTable = GroupsTable
LabelItemsTable.ForeignKeys[0].RefTable = LabelsTable
LabelItemsTable.ForeignKeys[1].RefTable = ItemsTable
} }

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package predicate package predicate
@ -9,5 +9,20 @@ import (
// AuthTokens is the predicate function for authtokens builders. // AuthTokens is the predicate function for authtokens builders.
type AuthTokens func(*sql.Selector) type AuthTokens func(*sql.Selector)
// Group is the predicate function for group builders.
type Group func(*sql.Selector)
// Item is the predicate function for item builders.
type Item func(*sql.Selector)
// ItemField is the predicate function for itemfield builders.
type ItemField func(*sql.Selector)
// Label is the predicate function for label builders.
type Label func(*sql.Selector)
// Location is the predicate function for location builders.
type Location func(*sql.Selector)
// User is the predicate function for user builders. // User is the predicate function for user builders.
type User func(*sql.Selector) type User func(*sql.Selector)

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
@ -7,6 +7,11 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/authtokens" "github.com/hay-kot/content/backend/ent/authtokens"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/item"
"github.com/hay-kot/content/backend/ent/itemfield"
"github.com/hay-kot/content/backend/ent/label"
"github.com/hay-kot/content/backend/ent/location"
"github.com/hay-kot/content/backend/ent/schema" "github.com/hay-kot/content/backend/ent/schema"
"github.com/hay-kot/content/backend/ent/user" "github.com/hay-kot/content/backend/ent/user"
) )
@ -15,36 +20,357 @@ import (
// (default values, validators, hooks and policies) and stitches it // (default values, validators, hooks and policies) and stitches it
// to their package variables. // to their package variables.
func init() { func init() {
authtokensMixin := schema.AuthTokens{}.Mixin()
authtokensMixinFields0 := authtokensMixin[0].Fields()
_ = authtokensMixinFields0
authtokensFields := schema.AuthTokens{}.Fields() authtokensFields := schema.AuthTokens{}.Fields()
_ = authtokensFields _ = authtokensFields
// authtokensDescCreatedAt is the schema descriptor for created_at field.
authtokensDescCreatedAt := authtokensMixinFields0[1].Descriptor()
// authtokens.DefaultCreatedAt holds the default value on creation for the created_at field.
authtokens.DefaultCreatedAt = authtokensDescCreatedAt.Default.(func() time.Time)
// authtokensDescUpdatedAt is the schema descriptor for updated_at field.
authtokensDescUpdatedAt := authtokensMixinFields0[2].Descriptor()
// authtokens.DefaultUpdatedAt holds the default value on creation for the updated_at field.
authtokens.DefaultUpdatedAt = authtokensDescUpdatedAt.Default.(func() time.Time)
// authtokens.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
authtokens.UpdateDefaultUpdatedAt = authtokensDescUpdatedAt.UpdateDefault.(func() time.Time)
// authtokensDescExpiresAt is the schema descriptor for expires_at field. // authtokensDescExpiresAt is the schema descriptor for expires_at field.
authtokensDescExpiresAt := authtokensFields[1].Descriptor() authtokensDescExpiresAt := authtokensFields[1].Descriptor()
// authtokens.DefaultExpiresAt holds the default value on creation for the expires_at field. // authtokens.DefaultExpiresAt holds the default value on creation for the expires_at field.
authtokens.DefaultExpiresAt = authtokensDescExpiresAt.Default.(func() time.Time) authtokens.DefaultExpiresAt = authtokensDescExpiresAt.Default.(func() time.Time)
// authtokensDescCreatedAt is the schema descriptor for created_at field. // authtokensDescID is the schema descriptor for id field.
authtokensDescCreatedAt := authtokensFields[2].Descriptor() authtokensDescID := authtokensMixinFields0[0].Descriptor()
// authtokens.DefaultCreatedAt holds the default value on creation for the created_at field. // authtokens.DefaultID holds the default value on creation for the id field.
authtokens.DefaultCreatedAt = authtokensDescCreatedAt.Default.(func() time.Time) authtokens.DefaultID = authtokensDescID.Default.(func() uuid.UUID)
groupMixin := schema.Group{}.Mixin()
groupMixinFields0 := groupMixin[0].Fields()
_ = groupMixinFields0
groupFields := schema.Group{}.Fields()
_ = groupFields
// groupDescCreatedAt is the schema descriptor for created_at field.
groupDescCreatedAt := groupMixinFields0[1].Descriptor()
// group.DefaultCreatedAt holds the default value on creation for the created_at field.
group.DefaultCreatedAt = groupDescCreatedAt.Default.(func() time.Time)
// groupDescUpdatedAt is the schema descriptor for updated_at field.
groupDescUpdatedAt := groupMixinFields0[2].Descriptor()
// group.DefaultUpdatedAt holds the default value on creation for the updated_at field.
group.DefaultUpdatedAt = groupDescUpdatedAt.Default.(func() time.Time)
// group.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
group.UpdateDefaultUpdatedAt = groupDescUpdatedAt.UpdateDefault.(func() time.Time)
// groupDescName is the schema descriptor for name field.
groupDescName := groupFields[0].Descriptor()
// group.NameValidator is a validator for the "name" field. It is called by the builders before save.
group.NameValidator = func() func(string) error {
validators := groupDescName.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(name string) error {
for _, fn := range fns {
if err := fn(name); err != nil {
return err
}
}
return nil
}
}()
// groupDescID is the schema descriptor for id field.
groupDescID := groupMixinFields0[0].Descriptor()
// group.DefaultID holds the default value on creation for the id field.
group.DefaultID = groupDescID.Default.(func() uuid.UUID)
itemMixin := schema.Item{}.Mixin()
itemMixinFields0 := itemMixin[0].Fields()
_ = itemMixinFields0
itemMixinFields1 := itemMixin[1].Fields()
_ = itemMixinFields1
itemFields := schema.Item{}.Fields()
_ = itemFields
// itemDescCreatedAt is the schema descriptor for created_at field.
itemDescCreatedAt := itemMixinFields0[1].Descriptor()
// item.DefaultCreatedAt holds the default value on creation for the created_at field.
item.DefaultCreatedAt = itemDescCreatedAt.Default.(func() time.Time)
// itemDescUpdatedAt is the schema descriptor for updated_at field.
itemDescUpdatedAt := itemMixinFields0[2].Descriptor()
// item.DefaultUpdatedAt holds the default value on creation for the updated_at field.
item.DefaultUpdatedAt = itemDescUpdatedAt.Default.(func() time.Time)
// item.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
item.UpdateDefaultUpdatedAt = itemDescUpdatedAt.UpdateDefault.(func() time.Time)
// itemDescName is the schema descriptor for name field.
itemDescName := itemMixinFields1[0].Descriptor()
// item.NameValidator is a validator for the "name" field. It is called by the builders before save.
item.NameValidator = func() func(string) error {
validators := itemDescName.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(name string) error {
for _, fn := range fns {
if err := fn(name); err != nil {
return err
}
}
return nil
}
}()
// itemDescDescription is the schema descriptor for description field.
itemDescDescription := itemMixinFields1[1].Descriptor()
// item.DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
item.DescriptionValidator = itemDescDescription.Validators[0].(func(string) error)
// itemDescNotes is the schema descriptor for notes field.
itemDescNotes := itemFields[0].Descriptor()
// item.NotesValidator is a validator for the "notes" field. It is called by the builders before save.
item.NotesValidator = itemDescNotes.Validators[0].(func(string) error)
// itemDescSerialNumber is the schema descriptor for serial_number field.
itemDescSerialNumber := itemFields[1].Descriptor()
// item.SerialNumberValidator is a validator for the "serial_number" field. It is called by the builders before save.
item.SerialNumberValidator = itemDescSerialNumber.Validators[0].(func(string) error)
// itemDescModelNumber is the schema descriptor for model_number field.
itemDescModelNumber := itemFields[2].Descriptor()
// item.ModelNumberValidator is a validator for the "model_number" field. It is called by the builders before save.
item.ModelNumberValidator = itemDescModelNumber.Validators[0].(func(string) error)
// itemDescManufacturer is the schema descriptor for manufacturer field.
itemDescManufacturer := itemFields[3].Descriptor()
// item.ManufacturerValidator is a validator for the "manufacturer" field. It is called by the builders before save.
item.ManufacturerValidator = itemDescManufacturer.Validators[0].(func(string) error)
// itemDescPurchasePrice is the schema descriptor for purchase_price field.
itemDescPurchasePrice := itemFields[6].Descriptor()
// item.DefaultPurchasePrice holds the default value on creation for the purchase_price field.
item.DefaultPurchasePrice = itemDescPurchasePrice.Default.(float64)
// itemDescSoldPrice is the schema descriptor for sold_price field.
itemDescSoldPrice := itemFields[10].Descriptor()
// item.DefaultSoldPrice holds the default value on creation for the sold_price field.
item.DefaultSoldPrice = itemDescSoldPrice.Default.(float64)
// itemDescSoldNotes is the schema descriptor for sold_notes field.
itemDescSoldNotes := itemFields[12].Descriptor()
// item.SoldNotesValidator is a validator for the "sold_notes" field. It is called by the builders before save.
item.SoldNotesValidator = itemDescSoldNotes.Validators[0].(func(string) error)
// itemDescID is the schema descriptor for id field.
itemDescID := itemMixinFields0[0].Descriptor()
// item.DefaultID holds the default value on creation for the id field.
item.DefaultID = itemDescID.Default.(func() uuid.UUID)
itemfieldMixin := schema.ItemField{}.Mixin()
itemfieldMixinFields0 := itemfieldMixin[0].Fields()
_ = itemfieldMixinFields0
itemfieldMixinFields1 := itemfieldMixin[1].Fields()
_ = itemfieldMixinFields1
itemfieldFields := schema.ItemField{}.Fields()
_ = itemfieldFields
// itemfieldDescCreatedAt is the schema descriptor for created_at field.
itemfieldDescCreatedAt := itemfieldMixinFields0[1].Descriptor()
// itemfield.DefaultCreatedAt holds the default value on creation for the created_at field.
itemfield.DefaultCreatedAt = itemfieldDescCreatedAt.Default.(func() time.Time)
// itemfieldDescUpdatedAt is the schema descriptor for updated_at field.
itemfieldDescUpdatedAt := itemfieldMixinFields0[2].Descriptor()
// itemfield.DefaultUpdatedAt holds the default value on creation for the updated_at field.
itemfield.DefaultUpdatedAt = itemfieldDescUpdatedAt.Default.(func() time.Time)
// itemfield.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
itemfield.UpdateDefaultUpdatedAt = itemfieldDescUpdatedAt.UpdateDefault.(func() time.Time)
// itemfieldDescName is the schema descriptor for name field.
itemfieldDescName := itemfieldMixinFields1[0].Descriptor()
// itemfield.NameValidator is a validator for the "name" field. It is called by the builders before save.
itemfield.NameValidator = func() func(string) error {
validators := itemfieldDescName.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(name string) error {
for _, fn := range fns {
if err := fn(name); err != nil {
return err
}
}
return nil
}
}()
// itemfieldDescDescription is the schema descriptor for description field.
itemfieldDescDescription := itemfieldMixinFields1[1].Descriptor()
// itemfield.DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
itemfield.DescriptionValidator = itemfieldDescDescription.Validators[0].(func(string) error)
// itemfieldDescTextValue is the schema descriptor for text_value field.
itemfieldDescTextValue := itemfieldFields[1].Descriptor()
// itemfield.TextValueValidator is a validator for the "text_value" field. It is called by the builders before save.
itemfield.TextValueValidator = itemfieldDescTextValue.Validators[0].(func(string) error)
// itemfieldDescBooleanValue is the schema descriptor for boolean_value field.
itemfieldDescBooleanValue := itemfieldFields[3].Descriptor()
// itemfield.DefaultBooleanValue holds the default value on creation for the boolean_value field.
itemfield.DefaultBooleanValue = itemfieldDescBooleanValue.Default.(bool)
// itemfieldDescTimeValue is the schema descriptor for time_value field.
itemfieldDescTimeValue := itemfieldFields[4].Descriptor()
// itemfield.DefaultTimeValue holds the default value on creation for the time_value field.
itemfield.DefaultTimeValue = itemfieldDescTimeValue.Default.(func() time.Time)
// itemfieldDescID is the schema descriptor for id field.
itemfieldDescID := itemfieldMixinFields0[0].Descriptor()
// itemfield.DefaultID holds the default value on creation for the id field.
itemfield.DefaultID = itemfieldDescID.Default.(func() uuid.UUID)
labelMixin := schema.Label{}.Mixin()
labelMixinFields0 := labelMixin[0].Fields()
_ = labelMixinFields0
labelMixinFields1 := labelMixin[1].Fields()
_ = labelMixinFields1
labelFields := schema.Label{}.Fields()
_ = labelFields
// labelDescCreatedAt is the schema descriptor for created_at field.
labelDescCreatedAt := labelMixinFields0[1].Descriptor()
// label.DefaultCreatedAt holds the default value on creation for the created_at field.
label.DefaultCreatedAt = labelDescCreatedAt.Default.(func() time.Time)
// labelDescUpdatedAt is the schema descriptor for updated_at field.
labelDescUpdatedAt := labelMixinFields0[2].Descriptor()
// label.DefaultUpdatedAt holds the default value on creation for the updated_at field.
label.DefaultUpdatedAt = labelDescUpdatedAt.Default.(func() time.Time)
// label.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
label.UpdateDefaultUpdatedAt = labelDescUpdatedAt.UpdateDefault.(func() time.Time)
// labelDescName is the schema descriptor for name field.
labelDescName := labelMixinFields1[0].Descriptor()
// label.NameValidator is a validator for the "name" field. It is called by the builders before save.
label.NameValidator = func() func(string) error {
validators := labelDescName.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(name string) error {
for _, fn := range fns {
if err := fn(name); err != nil {
return err
}
}
return nil
}
}()
// labelDescDescription is the schema descriptor for description field.
labelDescDescription := labelMixinFields1[1].Descriptor()
// label.DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
label.DescriptionValidator = labelDescDescription.Validators[0].(func(string) error)
// labelDescColor is the schema descriptor for color field.
labelDescColor := labelFields[0].Descriptor()
// label.ColorValidator is a validator for the "color" field. It is called by the builders before save.
label.ColorValidator = labelDescColor.Validators[0].(func(string) error)
// labelDescID is the schema descriptor for id field.
labelDescID := labelMixinFields0[0].Descriptor()
// label.DefaultID holds the default value on creation for the id field.
label.DefaultID = labelDescID.Default.(func() uuid.UUID)
locationMixin := schema.Location{}.Mixin()
locationMixinFields0 := locationMixin[0].Fields()
_ = locationMixinFields0
locationMixinFields1 := locationMixin[1].Fields()
_ = locationMixinFields1
locationFields := schema.Location{}.Fields()
_ = locationFields
// locationDescCreatedAt is the schema descriptor for created_at field.
locationDescCreatedAt := locationMixinFields0[1].Descriptor()
// location.DefaultCreatedAt holds the default value on creation for the created_at field.
location.DefaultCreatedAt = locationDescCreatedAt.Default.(func() time.Time)
// locationDescUpdatedAt is the schema descriptor for updated_at field.
locationDescUpdatedAt := locationMixinFields0[2].Descriptor()
// location.DefaultUpdatedAt holds the default value on creation for the updated_at field.
location.DefaultUpdatedAt = locationDescUpdatedAt.Default.(func() time.Time)
// location.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
location.UpdateDefaultUpdatedAt = locationDescUpdatedAt.UpdateDefault.(func() time.Time)
// locationDescName is the schema descriptor for name field.
locationDescName := locationMixinFields1[0].Descriptor()
// location.NameValidator is a validator for the "name" field. It is called by the builders before save.
location.NameValidator = func() func(string) error {
validators := locationDescName.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(name string) error {
for _, fn := range fns {
if err := fn(name); err != nil {
return err
}
}
return nil
}
}()
// locationDescDescription is the schema descriptor for description field.
locationDescDescription := locationMixinFields1[1].Descriptor()
// location.DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
location.DescriptionValidator = locationDescDescription.Validators[0].(func(string) error)
// locationDescID is the schema descriptor for id field.
locationDescID := locationMixinFields0[0].Descriptor()
// location.DefaultID holds the default value on creation for the id field.
location.DefaultID = locationDescID.Default.(func() uuid.UUID)
userMixin := schema.User{}.Mixin()
userMixinFields0 := userMixin[0].Fields()
_ = userMixinFields0
userFields := schema.User{}.Fields() userFields := schema.User{}.Fields()
_ = userFields _ = userFields
// userDescCreatedAt is the schema descriptor for created_at field.
userDescCreatedAt := userMixinFields0[1].Descriptor()
// user.DefaultCreatedAt holds the default value on creation for the created_at field.
user.DefaultCreatedAt = userDescCreatedAt.Default.(func() time.Time)
// userDescUpdatedAt is the schema descriptor for updated_at field.
userDescUpdatedAt := userMixinFields0[2].Descriptor()
// user.DefaultUpdatedAt holds the default value on creation for the updated_at field.
user.DefaultUpdatedAt = userDescUpdatedAt.Default.(func() time.Time)
// user.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
user.UpdateDefaultUpdatedAt = userDescUpdatedAt.UpdateDefault.(func() time.Time)
// userDescName is the schema descriptor for name field. // userDescName is the schema descriptor for name field.
userDescName := userFields[1].Descriptor() userDescName := userFields[0].Descriptor()
// user.NameValidator is a validator for the "name" field. It is called by the builders before save. // user.NameValidator is a validator for the "name" field. It is called by the builders before save.
user.NameValidator = userDescName.Validators[0].(func(string) error) user.NameValidator = func() func(string) error {
validators := userDescName.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(name string) error {
for _, fn := range fns {
if err := fn(name); err != nil {
return err
}
}
return nil
}
}()
// userDescEmail is the schema descriptor for email field. // userDescEmail is the schema descriptor for email field.
userDescEmail := userFields[2].Descriptor() userDescEmail := userFields[1].Descriptor()
// user.EmailValidator is a validator for the "email" field. It is called by the builders before save. // user.EmailValidator is a validator for the "email" field. It is called by the builders before save.
user.EmailValidator = userDescEmail.Validators[0].(func(string) error) user.EmailValidator = func() func(string) error {
validators := userDescEmail.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(email string) error {
for _, fn := range fns {
if err := fn(email); err != nil {
return err
}
}
return nil
}
}()
// userDescPassword is the schema descriptor for password field. // userDescPassword is the schema descriptor for password field.
userDescPassword := userFields[3].Descriptor() userDescPassword := userFields[2].Descriptor()
// user.PasswordValidator is a validator for the "password" field. It is called by the builders before save. // user.PasswordValidator is a validator for the "password" field. It is called by the builders before save.
user.PasswordValidator = userDescPassword.Validators[0].(func(string) error) user.PasswordValidator = func() func(string) error {
validators := userDescPassword.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(password string) error {
for _, fn := range fns {
if err := fn(password); err != nil {
return err
}
}
return nil
}
}()
// userDescIsSuperuser is the schema descriptor for is_superuser field. // userDescIsSuperuser is the schema descriptor for is_superuser field.
userDescIsSuperuser := userFields[4].Descriptor() userDescIsSuperuser := userFields[3].Descriptor()
// user.DefaultIsSuperuser holds the default value on creation for the is_superuser field. // user.DefaultIsSuperuser holds the default value on creation for the is_superuser field.
user.DefaultIsSuperuser = userDescIsSuperuser.Default.(bool) user.DefaultIsSuperuser = userDescIsSuperuser.Default.(bool)
// userDescID is the schema descriptor for id field. // userDescID is the schema descriptor for id field.
userDescID := userFields[0].Descriptor() userDescID := userMixinFields0[0].Descriptor()
// user.DefaultID holds the default value on creation for the id field. // user.DefaultID holds the default value on creation for the id field.
user.DefaultID = userDescID.Default.(func() uuid.UUID) user.DefaultID = userDescID.Default.(func() uuid.UUID)
} }

View file

@ -1,10 +1,10 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package runtime package runtime
// The schema-stitching logic is generated in github.com/hay-kot/content/backend/ent/runtime.go // The schema-stitching logic is generated in github.com/hay-kot/content/backend/ent/runtime.go
const ( const (
Version = "v0.10.0" // Version of ent codegen. Version = "v0.11.2" // Version of ent codegen.
Sum = "h1:9cBomE1fh+WX34DPYQL7tDNAIvhKa3tXvwxuLyhYCMo=" // Sum of ent codegen. Sum = "h1:UM2/BUhF2FfsxPHRxLjQbhqJNaDdVlOwNIAMLs2jyto=" // Sum of ent codegen.
) )

View file

@ -7,6 +7,7 @@ import (
"entgo.io/ent/schema/edge" "entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field" "entgo.io/ent/schema/field"
"entgo.io/ent/schema/index" "entgo.io/ent/schema/index"
"github.com/hay-kot/content/backend/ent/schema/mixins"
) )
// AuthTokens holds the schema definition for the AuthTokens entity. // AuthTokens holds the schema definition for the AuthTokens entity.
@ -14,6 +15,12 @@ type AuthTokens struct {
ent.Schema ent.Schema
} }
func (AuthTokens) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
}
}
// Fields of the AuthTokens. // Fields of the AuthTokens.
func (AuthTokens) Fields() []ent.Field { func (AuthTokens) Fields() []ent.Field {
return []ent.Field{ return []ent.Field{
@ -21,8 +28,6 @@ func (AuthTokens) Fields() []ent.Field {
Unique(), Unique(),
field.Time("expires_at"). field.Time("expires_at").
Default(func() time.Time { return time.Now().Add(time.Hour * 24 * 7) }), Default(func() time.Time { return time.Now().Add(time.Hour * 24 * 7) }),
field.Time("created_at").
Default(time.Now),
} }
} }

View file

@ -0,0 +1,41 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/hay-kot/content/backend/ent/schema/mixins"
)
// Group holds the schema definition for the Group entity.
type Group struct {
ent.Schema
}
func (Group) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
}
}
// Fields of the Home.
func (Group) Fields() []ent.Field {
return []ent.Field{
field.String("name").
MaxLen(255).
NotEmpty(),
field.Enum("currency").
Default("usd").
Values("usd"), // TODO: add more currencies
}
}
// Edges of the Home.
func (Group) Edges() []ent.Edge {
return []ent.Edge{
edge.To("users", User.Type),
edge.To("locations", Location.Type),
edge.To("items", Item.Type),
edge.To("labels", Label.Type),
}
}

View file

@ -0,0 +1,80 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/schema/mixins"
)
// Item holds the schema definition for the Item entity.
type Item struct {
ent.Schema
}
func (Item) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
mixins.DetailsMixin{},
}
}
// Fields of the Item.
func (Item) Fields() []ent.Field {
return []ent.Field{
field.String("notes").
MaxLen(1000).
Optional(),
// ------------------------------------
// item identification
field.String("serial_number").
MaxLen(255).
Optional(),
field.String("model_number").
MaxLen(255).
Optional(),
field.String("manufacturer").
MaxLen(255).
Optional(),
// ------------------------------------
// item purchase
field.Time("purchase_time").
Optional(),
field.String("purchase_from").
Optional(),
field.Float("purchase_price").
Default(0),
field.UUID("purchase_receipt_id", uuid.UUID{}).
Optional(),
// ------------------------------------
// Sold Details
field.Time("sold_time").
Optional(),
field.String("sold_to").
Optional(),
field.Float("sold_price").
Default(0),
field.UUID("sold_receipt_id", uuid.UUID{}).
Optional(),
field.String("sold_notes").
MaxLen(1000).
Optional(),
}
}
// Edges of the Item.
func (Item) Edges() []ent.Edge {
return []ent.Edge{
edge.From("group", Group.Type).
Ref("items").
Required().
Unique(),
edge.From("location", Location.Type).
Ref("items").
Unique(),
edge.To("fields", ItemField.Type),
edge.From("label", Label.Type).
Ref("items"),
}
}

View file

@ -0,0 +1,48 @@
package schema
import (
"time"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/hay-kot/content/backend/ent/schema/mixins"
)
// ItemField holds the schema definition for the ItemField entity.
type ItemField struct {
ent.Schema
}
func (ItemField) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
mixins.DetailsMixin{},
}
}
// Fields of the ItemField.
func (ItemField) Fields() []ent.Field {
return []ent.Field{
field.Enum("type").
Values("text", "number", "boolean", "time"),
field.String("text_value").
MaxLen(500).
Optional(),
field.Int("number_value").
Optional(),
field.Bool("boolean_value").
Default(false),
field.Time("time_value").
Default(time.Now),
}
}
// Edges of the ItemField.
func (ItemField) Edges() []ent.Edge {
return []ent.Edge{
edge.From("item", Item.Type).
Ref("fields").
Unique(),
}
}

View file

@ -0,0 +1,40 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/hay-kot/content/backend/ent/schema/mixins"
)
// Label holds the schema definition for the Label entity.
type Label struct {
ent.Schema
}
func (Label) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
mixins.DetailsMixin{},
}
}
// Fields of the Label.
func (Label) Fields() []ent.Field {
return []ent.Field{
field.String("color").
MaxLen(255).
Optional(),
}
}
// Edges of the Label.
func (Label) Edges() []ent.Edge {
return []ent.Edge{
edge.From("group", Group.Type).
Ref("labels").
Required().
Unique(),
edge.To("items", Item.Type),
}
}

View file

@ -0,0 +1,35 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"github.com/hay-kot/content/backend/ent/schema/mixins"
)
// Location holds the schema definition for the Location entity.
type Location struct {
ent.Schema
}
func (Location) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
mixins.DetailsMixin{},
}
}
// Fields of the Location.
func (Location) Fields() []ent.Field {
return nil
}
// Edges of the Location.
func (Location) Edges() []ent.Edge {
return []ent.Edge{
edge.From("group", Group.Type).
Ref("locations").
Unique().
Required(),
edge.To("items", Item.Type),
}
}

View file

@ -0,0 +1,42 @@
package mixins
import (
"time"
"entgo.io/ent"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/mixin"
"github.com/google/uuid"
)
type BaseMixin struct {
mixin.Schema
}
func (BaseMixin) Fields() []ent.Field {
return []ent.Field{
field.UUID("id", uuid.UUID{}).
Default(uuid.New),
field.Time("created_at").
Immutable().
Default(time.Now),
field.Time("updated_at").
Default(time.Now).
UpdateDefault(time.Now),
}
}
type DetailsMixin struct {
mixin.Schema
}
func (DetailsMixin) Fields() []ent.Field {
return []ent.Field{
field.String("name").
MaxLen(255).
NotEmpty(),
field.String("description").
MaxLen(1000).
Optional(),
}
}

View file

@ -4,7 +4,7 @@ import (
"entgo.io/ent" "entgo.io/ent"
"entgo.io/ent/schema/edge" "entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field" "entgo.io/ent/schema/field"
"github.com/google/uuid" "github.com/hay-kot/content/backend/ent/schema/mixins"
) )
// User holds the schema definition for the User entity. // User holds the schema definition for the User entity.
@ -12,17 +12,24 @@ type User struct {
ent.Schema ent.Schema
} }
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
}
}
// Fields of the User. // Fields of the User.
func (User) Fields() []ent.Field { func (User) Fields() []ent.Field {
return []ent.Field{ return []ent.Field{
field.UUID("id", uuid.UUID{}).
Default(uuid.New),
field.String("name"). field.String("name").
MaxLen(255).
NotEmpty(), NotEmpty(),
field.String("email"). field.String("email").
MaxLen(255).
NotEmpty(). NotEmpty().
Unique(), Unique(),
field.String("password"). field.String("password").
MaxLen(255).
NotEmpty(). NotEmpty().
Sensitive(), Sensitive(),
field.Bool("is_superuser"). field.Bool("is_superuser").
@ -33,6 +40,10 @@ func (User) Fields() []ent.Field {
// Edges of the User. // Edges of the User.
func (User) Edges() []ent.Edge { func (User) Edges() []ent.Edge {
return []ent.Edge{ return []ent.Edge{
edge.From("group", Group.Type).
Ref("users").
Required().
Unique(),
edge.To("auth_tokens", AuthTokens.Type), edge.To("auth_tokens", AuthTokens.Type),
} }
} }

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
@ -14,6 +14,16 @@ type Tx struct {
config config
// AuthTokens is the client for interacting with the AuthTokens builders. // AuthTokens is the client for interacting with the AuthTokens builders.
AuthTokens *AuthTokensClient AuthTokens *AuthTokensClient
// Group is the client for interacting with the Group builders.
Group *GroupClient
// Item is the client for interacting with the Item builders.
Item *ItemClient
// ItemField is the client for interacting with the ItemField builders.
ItemField *ItemFieldClient
// Label is the client for interacting with the Label builders.
Label *LabelClient
// Location is the client for interacting with the Location builders.
Location *LocationClient
// User is the client for interacting with the User builders. // User is the client for interacting with the User builders.
User *UserClient User *UserClient
@ -152,6 +162,11 @@ func (tx *Tx) Client() *Client {
func (tx *Tx) init() { func (tx *Tx) init() {
tx.AuthTokens = NewAuthTokensClient(tx.config) tx.AuthTokens = NewAuthTokensClient(tx.config)
tx.Group = NewGroupClient(tx.config)
tx.Item = NewItemClient(tx.config)
tx.ItemField = NewItemFieldClient(tx.config)
tx.Label = NewLabelClient(tx.config)
tx.Location = NewLocationClient(tx.config)
tx.User = NewUserClient(tx.config) tx.User = NewUserClient(tx.config)
} }

View file

@ -1,13 +1,15 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
import ( import (
"fmt" "fmt"
"strings" "strings"
"time"
"entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/user" "github.com/hay-kot/content/backend/ent/user"
) )
@ -16,6 +18,10 @@ type User struct {
config `json:"-"` config `json:"-"`
// ID of the ent. // ID of the ent.
ID uuid.UUID `json:"id,omitempty"` ID uuid.UUID `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Name holds the value of the "name" field. // Name holds the value of the "name" field.
Name string `json:"name,omitempty"` Name string `json:"name,omitempty"`
// Email holds the value of the "email" field. // Email holds the value of the "email" field.
@ -27,21 +33,37 @@ type User struct {
// Edges holds the relations/edges for other nodes in the graph. // Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the UserQuery when eager-loading is set. // The values are being populated by the UserQuery when eager-loading is set.
Edges UserEdges `json:"edges"` Edges UserEdges `json:"edges"`
group_users *uuid.UUID
} }
// UserEdges holds the relations/edges for other nodes in the graph. // UserEdges holds the relations/edges for other nodes in the graph.
type UserEdges struct { type UserEdges struct {
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// AuthTokens holds the value of the auth_tokens edge. // AuthTokens holds the value of the auth_tokens edge.
AuthTokens []*AuthTokens `json:"auth_tokens,omitempty"` AuthTokens []*AuthTokens `json:"auth_tokens,omitempty"`
// loadedTypes holds the information for reporting if a // loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not. // type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool loadedTypes [2]bool
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e UserEdges) GroupOrErr() (*Group, error) {
if e.loadedTypes[0] {
if e.Group == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: group.Label}
}
return e.Group, nil
}
return nil, &NotLoadedError{edge: "group"}
} }
// AuthTokensOrErr returns the AuthTokens value or an error if the edge // AuthTokensOrErr returns the AuthTokens value or an error if the edge
// was not loaded in eager-loading. // was not loaded in eager-loading.
func (e UserEdges) AuthTokensOrErr() ([]*AuthTokens, error) { func (e UserEdges) AuthTokensOrErr() ([]*AuthTokens, error) {
if e.loadedTypes[0] { if e.loadedTypes[1] {
return e.AuthTokens, nil return e.AuthTokens, nil
} }
return nil, &NotLoadedError{edge: "auth_tokens"} return nil, &NotLoadedError{edge: "auth_tokens"}
@ -56,8 +78,12 @@ func (*User) scanValues(columns []string) ([]interface{}, error) {
values[i] = new(sql.NullBool) values[i] = new(sql.NullBool)
case user.FieldName, user.FieldEmail, user.FieldPassword: case user.FieldName, user.FieldEmail, user.FieldPassword:
values[i] = new(sql.NullString) values[i] = new(sql.NullString)
case user.FieldCreatedAt, user.FieldUpdatedAt:
values[i] = new(sql.NullTime)
case user.FieldID: case user.FieldID:
values[i] = new(uuid.UUID) values[i] = new(uuid.UUID)
case user.ForeignKeys[0]: // group_users
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default: default:
return nil, fmt.Errorf("unexpected column %q for type User", columns[i]) return nil, fmt.Errorf("unexpected column %q for type User", columns[i])
} }
@ -79,6 +105,18 @@ func (u *User) assignValues(columns []string, values []interface{}) error {
} else if value != nil { } else if value != nil {
u.ID = *value u.ID = *value
} }
case user.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
u.CreatedAt = value.Time
}
case user.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
u.UpdatedAt = value.Time
}
case user.FieldName: case user.FieldName:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i]) return fmt.Errorf("unexpected type %T for field name", values[i])
@ -103,11 +141,23 @@ func (u *User) assignValues(columns []string, values []interface{}) error {
} else if value.Valid { } else if value.Valid {
u.IsSuperuser = value.Bool u.IsSuperuser = value.Bool
} }
case user.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field group_users", values[i])
} else if value.Valid {
u.group_users = new(uuid.UUID)
*u.group_users = *value.S.(*uuid.UUID)
}
} }
} }
return nil return nil
} }
// QueryGroup queries the "group" edge of the User entity.
func (u *User) QueryGroup() *GroupQuery {
return (&UserClient{config: u.config}).QueryGroup(u)
}
// QueryAuthTokens queries the "auth_tokens" edge of the User entity. // QueryAuthTokens queries the "auth_tokens" edge of the User entity.
func (u *User) QueryAuthTokens() *AuthTokensQuery { func (u *User) QueryAuthTokens() *AuthTokensQuery {
return (&UserClient{config: u.config}).QueryAuthTokens(u) return (&UserClient{config: u.config}).QueryAuthTokens(u)
@ -123,11 +173,11 @@ func (u *User) Update() *UserUpdateOne {
// Unwrap unwraps the User entity that was returned from a transaction after it was closed, // Unwrap unwraps the User 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. // so that all future queries will be executed through the driver which created the transaction.
func (u *User) Unwrap() *User { func (u *User) Unwrap() *User {
tx, ok := u.config.driver.(*txDriver) _tx, ok := u.config.driver.(*txDriver)
if !ok { if !ok {
panic("ent: User is not a transactional entity") panic("ent: User is not a transactional entity")
} }
u.config.driver = tx.drv u.config.driver = _tx.drv
return u return u
} }
@ -135,13 +185,22 @@ func (u *User) Unwrap() *User {
func (u *User) String() string { func (u *User) String() string {
var builder strings.Builder var builder strings.Builder
builder.WriteString("User(") builder.WriteString("User(")
builder.WriteString(fmt.Sprintf("id=%v", u.ID)) builder.WriteString(fmt.Sprintf("id=%v, ", u.ID))
builder.WriteString(", name=") builder.WriteString("created_at=")
builder.WriteString(u.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(u.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(u.Name) builder.WriteString(u.Name)
builder.WriteString(", email=") builder.WriteString(", ")
builder.WriteString("email=")
builder.WriteString(u.Email) builder.WriteString(u.Email)
builder.WriteString(", password=<sensitive>") builder.WriteString(", ")
builder.WriteString(", is_superuser=") builder.WriteString("password=<sensitive>")
builder.WriteString(", ")
builder.WriteString("is_superuser=")
builder.WriteString(fmt.Sprintf("%v", u.IsSuperuser)) builder.WriteString(fmt.Sprintf("%v", u.IsSuperuser))
builder.WriteByte(')') builder.WriteByte(')')
return builder.String() return builder.String()

View file

@ -1,8 +1,10 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package user package user
import ( import (
"time"
"github.com/google/uuid" "github.com/google/uuid"
) )
@ -11,6 +13,10 @@ const (
Label = "user" Label = "user"
// FieldID holds the string denoting the id field in the database. // FieldID holds the string denoting the id field in the database.
FieldID = "id" FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldName holds the string denoting the name field in the database. // FieldName holds the string denoting the name field in the database.
FieldName = "name" FieldName = "name"
// FieldEmail holds the string denoting the email field in the database. // FieldEmail holds the string denoting the email field in the database.
@ -19,10 +25,19 @@ const (
FieldPassword = "password" FieldPassword = "password"
// FieldIsSuperuser holds the string denoting the is_superuser field in the database. // FieldIsSuperuser holds the string denoting the is_superuser field in the database.
FieldIsSuperuser = "is_superuser" FieldIsSuperuser = "is_superuser"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// EdgeAuthTokens holds the string denoting the auth_tokens edge name in mutations. // EdgeAuthTokens holds the string denoting the auth_tokens edge name in mutations.
EdgeAuthTokens = "auth_tokens" EdgeAuthTokens = "auth_tokens"
// Table holds the table name of the user in the database. // Table holds the table name of the user in the database.
Table = "users" Table = "users"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "users"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_users"
// AuthTokensTable is the table that holds the auth_tokens relation/edge. // AuthTokensTable is the table that holds the auth_tokens relation/edge.
AuthTokensTable = "auth_tokens" AuthTokensTable = "auth_tokens"
// AuthTokensInverseTable is the table name for the AuthTokens entity. // AuthTokensInverseTable is the table name for the AuthTokens entity.
@ -35,12 +50,20 @@ const (
// Columns holds all SQL columns for user fields. // Columns holds all SQL columns for user fields.
var Columns = []string{ var Columns = []string{
FieldID, FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldName, FieldName,
FieldEmail, FieldEmail,
FieldPassword, FieldPassword,
FieldIsSuperuser, FieldIsSuperuser,
} }
// ForeignKeys holds the SQL foreign-keys that are owned by the "users"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"group_users",
}
// ValidColumn reports if the column name is valid (part of the table columns). // ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool { func ValidColumn(column string) bool {
for i := range Columns { for i := range Columns {
@ -48,10 +71,21 @@ func ValidColumn(column string) bool {
return true return true
} }
} }
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false return false
} }
var ( var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save. // NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error NameValidator func(string) error
// EmailValidator is a validator for the "email" field. It is called by the builders before save. // EmailValidator is a validator for the "email" field. It is called by the builders before save.

View file

@ -1,8 +1,10 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package user package user
import ( import (
"time"
"entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/dialect/sql/sqlgraph"
"github.com/google/uuid" "github.com/google/uuid"
@ -33,12 +35,6 @@ func IDNEQ(id uuid.UUID) predicate.User {
// IDIn applies the In predicate on the ID field. // IDIn applies the In predicate on the ID field.
func IDIn(ids ...uuid.UUID) predicate.User { func IDIn(ids ...uuid.UUID) predicate.User {
return predicate.User(func(s *sql.Selector) { 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(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids)) v := make([]interface{}, len(ids))
for i := range v { for i := range v {
v[i] = ids[i] v[i] = ids[i]
@ -50,12 +46,6 @@ func IDIn(ids ...uuid.UUID) predicate.User {
// IDNotIn applies the NotIn predicate on the ID field. // IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...uuid.UUID) predicate.User { func IDNotIn(ids ...uuid.UUID) predicate.User {
return predicate.User(func(s *sql.Selector) { 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(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids)) v := make([]interface{}, len(ids))
for i := range v { for i := range v {
v[i] = ids[i] v[i] = ids[i]
@ -92,6 +82,20 @@ func IDLTE(id uuid.UUID) predicate.User {
}) })
} }
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
})
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ. // Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.User { func Name(v string) predicate.User {
return predicate.User(func(s *sql.Selector) { return predicate.User(func(s *sql.Selector) {
@ -120,6 +124,134 @@ func IsSuperuser(v bool) predicate.User {
}) })
} }
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCreatedAt), v))
})
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldCreatedAt), v))
})
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.User {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.User(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldCreatedAt), v...))
})
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.User {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.User(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldCreatedAt), v...))
})
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldCreatedAt), v))
})
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldCreatedAt), v))
})
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.User {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.User(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldUpdatedAt), v...))
})
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.User {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.User(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...))
})
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUpdatedAt), v))
})
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.User {
return predicate.User(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// NameEQ applies the EQ predicate on the "name" field. // NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.User { func NameEQ(v string) predicate.User {
return predicate.User(func(s *sql.Selector) { return predicate.User(func(s *sql.Selector) {
@ -141,12 +273,6 @@ func NameIn(vs ...string) predicate.User {
v[i] = vs[i] v[i] = vs[i]
} }
return predicate.User(func(s *sql.Selector) { 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...)) s.Where(sql.In(s.C(FieldName), v...))
}) })
} }
@ -158,12 +284,6 @@ func NameNotIn(vs ...string) predicate.User {
v[i] = vs[i] v[i] = vs[i]
} }
return predicate.User(func(s *sql.Selector) { 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...)) s.Where(sql.NotIn(s.C(FieldName), v...))
}) })
} }
@ -252,12 +372,6 @@ func EmailIn(vs ...string) predicate.User {
v[i] = vs[i] v[i] = vs[i]
} }
return predicate.User(func(s *sql.Selector) { 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(FieldEmail), v...)) s.Where(sql.In(s.C(FieldEmail), v...))
}) })
} }
@ -269,12 +383,6 @@ func EmailNotIn(vs ...string) predicate.User {
v[i] = vs[i] v[i] = vs[i]
} }
return predicate.User(func(s *sql.Selector) { 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(FieldEmail), v...)) s.Where(sql.NotIn(s.C(FieldEmail), v...))
}) })
} }
@ -363,12 +471,6 @@ func PasswordIn(vs ...string) predicate.User {
v[i] = vs[i] v[i] = vs[i]
} }
return predicate.User(func(s *sql.Selector) { 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(FieldPassword), v...)) s.Where(sql.In(s.C(FieldPassword), v...))
}) })
} }
@ -380,12 +482,6 @@ func PasswordNotIn(vs ...string) predicate.User {
v[i] = vs[i] v[i] = vs[i]
} }
return predicate.User(func(s *sql.Selector) { 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(FieldPassword), v...)) s.Where(sql.NotIn(s.C(FieldPassword), v...))
}) })
} }
@ -467,6 +563,34 @@ func IsSuperuserNEQ(v bool) predicate.User {
}) })
} }
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasAuthTokens applies the HasEdge predicate on the "auth_tokens" edge. // HasAuthTokens applies the HasEdge predicate on the "auth_tokens" edge.
func HasAuthTokens() predicate.User { func HasAuthTokens() predicate.User {
return predicate.User(func(s *sql.Selector) { return predicate.User(func(s *sql.Selector) {

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
@ -6,11 +6,13 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field" "entgo.io/ent/schema/field"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/authtokens" "github.com/hay-kot/content/backend/ent/authtokens"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/user" "github.com/hay-kot/content/backend/ent/user"
) )
@ -21,6 +23,34 @@ type UserCreate struct {
hooks []Hook hooks []Hook
} }
// SetCreatedAt sets the "created_at" field.
func (uc *UserCreate) SetCreatedAt(t time.Time) *UserCreate {
uc.mutation.SetCreatedAt(t)
return uc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (uc *UserCreate) SetNillableCreatedAt(t *time.Time) *UserCreate {
if t != nil {
uc.SetCreatedAt(*t)
}
return uc
}
// SetUpdatedAt sets the "updated_at" field.
func (uc *UserCreate) SetUpdatedAt(t time.Time) *UserCreate {
uc.mutation.SetUpdatedAt(t)
return uc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (uc *UserCreate) SetNillableUpdatedAt(t *time.Time) *UserCreate {
if t != nil {
uc.SetUpdatedAt(*t)
}
return uc
}
// SetName sets the "name" field. // SetName sets the "name" field.
func (uc *UserCreate) SetName(s string) *UserCreate { func (uc *UserCreate) SetName(s string) *UserCreate {
uc.mutation.SetName(s) uc.mutation.SetName(s)
@ -67,15 +97,26 @@ func (uc *UserCreate) SetNillableID(u *uuid.UUID) *UserCreate {
return uc return uc
} }
// SetGroupID sets the "group" edge to the Group entity by ID.
func (uc *UserCreate) SetGroupID(id uuid.UUID) *UserCreate {
uc.mutation.SetGroupID(id)
return uc
}
// SetGroup sets the "group" edge to the Group entity.
func (uc *UserCreate) SetGroup(g *Group) *UserCreate {
return uc.SetGroupID(g.ID)
}
// AddAuthTokenIDs adds the "auth_tokens" edge to the AuthTokens entity by IDs. // AddAuthTokenIDs adds the "auth_tokens" edge to the AuthTokens entity by IDs.
func (uc *UserCreate) AddAuthTokenIDs(ids ...int) *UserCreate { func (uc *UserCreate) AddAuthTokenIDs(ids ...uuid.UUID) *UserCreate {
uc.mutation.AddAuthTokenIDs(ids...) uc.mutation.AddAuthTokenIDs(ids...)
return uc return uc
} }
// AddAuthTokens adds the "auth_tokens" edges to the AuthTokens entity. // AddAuthTokens adds the "auth_tokens" edges to the AuthTokens entity.
func (uc *UserCreate) AddAuthTokens(a ...*AuthTokens) *UserCreate { func (uc *UserCreate) AddAuthTokens(a ...*AuthTokens) *UserCreate {
ids := make([]int, len(a)) ids := make([]uuid.UUID, len(a))
for i := range a { for i := range a {
ids[i] = a[i].ID ids[i] = a[i].ID
} }
@ -122,9 +163,15 @@ func (uc *UserCreate) Save(ctx context.Context) (*User, error) {
} }
mut = uc.hooks[i](mut) mut = uc.hooks[i](mut)
} }
if _, err := mut.Mutate(ctx, uc.mutation); err != nil { v, err := mut.Mutate(ctx, uc.mutation)
if err != nil {
return nil, err return nil, err
} }
nv, ok := v.(*User)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from UserMutation", v)
}
node = nv
} }
return node, err return node, err
} }
@ -153,6 +200,14 @@ func (uc *UserCreate) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save. // defaults sets the default values of the builder before save.
func (uc *UserCreate) defaults() { func (uc *UserCreate) defaults() {
if _, ok := uc.mutation.CreatedAt(); !ok {
v := user.DefaultCreatedAt()
uc.mutation.SetCreatedAt(v)
}
if _, ok := uc.mutation.UpdatedAt(); !ok {
v := user.DefaultUpdatedAt()
uc.mutation.SetUpdatedAt(v)
}
if _, ok := uc.mutation.IsSuperuser(); !ok { if _, ok := uc.mutation.IsSuperuser(); !ok {
v := user.DefaultIsSuperuser v := user.DefaultIsSuperuser
uc.mutation.SetIsSuperuser(v) uc.mutation.SetIsSuperuser(v)
@ -165,6 +220,12 @@ func (uc *UserCreate) defaults() {
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (uc *UserCreate) check() error { func (uc *UserCreate) check() error {
if _, ok := uc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "User.created_at"`)}
}
if _, ok := uc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "User.updated_at"`)}
}
if _, ok := uc.mutation.Name(); !ok { if _, ok := uc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "User.name"`)} return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "User.name"`)}
} }
@ -192,6 +253,9 @@ func (uc *UserCreate) check() error {
if _, ok := uc.mutation.IsSuperuser(); !ok { if _, ok := uc.mutation.IsSuperuser(); !ok {
return &ValidationError{Name: "is_superuser", err: errors.New(`ent: missing required field "User.is_superuser"`)} return &ValidationError{Name: "is_superuser", err: errors.New(`ent: missing required field "User.is_superuser"`)}
} }
if _, ok := uc.mutation.GroupID(); !ok {
return &ValidationError{Name: "group", err: errors.New(`ent: missing required edge "User.group"`)}
}
return nil return nil
} }
@ -199,7 +263,7 @@ func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) {
_node, _spec := uc.createSpec() _node, _spec := uc.createSpec()
if err := sqlgraph.CreateNode(ctx, uc.driver, _spec); err != nil { if err := sqlgraph.CreateNode(ctx, uc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) { if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err} err = &ConstraintError{msg: err.Error(), wrap: err}
} }
return nil, err return nil, err
} }
@ -228,6 +292,22 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
_node.ID = id _node.ID = id
_spec.ID.Value = &id _spec.ID.Value = &id
} }
if value, ok := uc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: user.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := uc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: user.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := uc.mutation.Name(); ok { if value, ok := uc.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString, Type: field.TypeString,
@ -260,6 +340,26 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
}) })
_node.IsSuperuser = value _node.IsSuperuser = value
} }
if nodes := uc.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: user.GroupTable,
Columns: []string{user.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.group_users = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := uc.mutation.AuthTokensIDs(); len(nodes) > 0 { if nodes := uc.mutation.AuthTokensIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{ edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M, Rel: sqlgraph.O2M,
@ -269,7 +369,7 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
Bidi: false, Bidi: false,
Target: &sqlgraph.EdgeTarget{ Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{ IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt, Type: field.TypeUUID,
Column: authtokens.FieldID, Column: authtokens.FieldID,
}, },
}, },
@ -315,7 +415,7 @@ func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) {
// Invoke the actual operation on the latest mutation in the chain. // Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, ucb.driver, spec); err != nil { if err = sqlgraph.BatchCreate(ctx, ucb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) { if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err} err = &ConstraintError{msg: err.Error(), wrap: err}
} }
} }
} }

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
@ -84,7 +84,11 @@ func (ud *UserDelete) sqlExec(ctx context.Context) (int, error) {
} }
} }
} }
return sqlgraph.DeleteNodes(ctx, ud.driver, _spec) affected, err := sqlgraph.DeleteNodes(ctx, ud.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
} }
// UserDeleteOne is the builder for deleting a single User entity. // UserDeleteOne is the builder for deleting a single User entity.

View file

@ -1,11 +1,10 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
import ( import (
"context" "context"
"database/sql/driver" "database/sql/driver"
"errors"
"fmt" "fmt"
"math" "math"
@ -14,6 +13,7 @@ import (
"entgo.io/ent/schema/field" "entgo.io/ent/schema/field"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/authtokens" "github.com/hay-kot/content/backend/ent/authtokens"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/predicate" "github.com/hay-kot/content/backend/ent/predicate"
"github.com/hay-kot/content/backend/ent/user" "github.com/hay-kot/content/backend/ent/user"
) )
@ -27,8 +27,9 @@ type UserQuery struct {
order []OrderFunc order []OrderFunc
fields []string fields []string
predicates []predicate.User predicates []predicate.User
// eager-loading edges. withGroup *GroupQuery
withAuthTokens *AuthTokensQuery withAuthTokens *AuthTokensQuery
withFKs bool
// intermediate query (i.e. traversal path). // intermediate query (i.e. traversal path).
sql *sql.Selector sql *sql.Selector
path func(context.Context) (*sql.Selector, error) path func(context.Context) (*sql.Selector, error)
@ -65,6 +66,28 @@ func (uq *UserQuery) Order(o ...OrderFunc) *UserQuery {
return uq return uq
} }
// QueryGroup chains the current query on the "group" edge.
func (uq *UserQuery) QueryGroup() *GroupQuery {
query := &GroupQuery{config: uq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := uq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := uq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, user.GroupTable, user.GroupColumn),
)
fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryAuthTokens chains the current query on the "auth_tokens" edge. // QueryAuthTokens chains the current query on the "auth_tokens" edge.
func (uq *UserQuery) QueryAuthTokens() *AuthTokensQuery { func (uq *UserQuery) QueryAuthTokens() *AuthTokensQuery {
query := &AuthTokensQuery{config: uq.config} query := &AuthTokensQuery{config: uq.config}
@ -133,7 +156,7 @@ func (uq *UserQuery) FirstIDX(ctx context.Context) uuid.UUID {
} }
// Only returns a single User entity found by the query, ensuring it only returns one. // Only returns a single User entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when exactly one User entity is not found. // Returns a *NotSingularError when more than one User entity is found.
// Returns a *NotFoundError when no User entities are found. // Returns a *NotFoundError when no User entities are found.
func (uq *UserQuery) Only(ctx context.Context) (*User, error) { func (uq *UserQuery) Only(ctx context.Context) (*User, error) {
nodes, err := uq.Limit(2).All(ctx) nodes, err := uq.Limit(2).All(ctx)
@ -160,7 +183,7 @@ func (uq *UserQuery) OnlyX(ctx context.Context) *User {
} }
// OnlyID is like Only, but returns the only User ID in the query. // OnlyID is like Only, but returns the only User ID in the query.
// Returns a *NotSingularError when exactly one User ID is not found. // Returns a *NotSingularError when more than one User ID is found.
// Returns a *NotFoundError when no entities are found. // Returns a *NotFoundError when no entities are found.
func (uq *UserQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { func (uq *UserQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID var ids []uuid.UUID
@ -268,13 +291,26 @@ func (uq *UserQuery) Clone() *UserQuery {
offset: uq.offset, offset: uq.offset,
order: append([]OrderFunc{}, uq.order...), order: append([]OrderFunc{}, uq.order...),
predicates: append([]predicate.User{}, uq.predicates...), predicates: append([]predicate.User{}, uq.predicates...),
withGroup: uq.withGroup.Clone(),
withAuthTokens: uq.withAuthTokens.Clone(), withAuthTokens: uq.withAuthTokens.Clone(),
// clone intermediate query. // clone intermediate query.
sql: uq.sql.Clone(), sql: uq.sql.Clone(),
path: uq.path, path: uq.path,
unique: uq.unique,
} }
} }
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (uq *UserQuery) WithGroup(opts ...func(*GroupQuery)) *UserQuery {
query := &GroupQuery{config: uq.config}
for _, opt := range opts {
opt(query)
}
uq.withGroup = query
return uq
}
// WithAuthTokens tells the query-builder to eager-load the nodes that are connected to // WithAuthTokens tells the query-builder to eager-load the nodes that are connected to
// the "auth_tokens" edge. The optional arguments are used to configure the query builder of the edge. // the "auth_tokens" edge. The optional arguments are used to configure the query builder of the edge.
func (uq *UserQuery) WithAuthTokens(opts ...func(*AuthTokensQuery)) *UserQuery { func (uq *UserQuery) WithAuthTokens(opts ...func(*AuthTokensQuery)) *UserQuery {
@ -292,25 +328,26 @@ func (uq *UserQuery) WithAuthTokens(opts ...func(*AuthTokensQuery)) *UserQuery {
// Example: // Example:
// //
// var v []struct { // var v []struct {
// Name string `json:"name,omitempty"` // CreatedAt time.Time `json:"created_at,omitempty"`
// Count int `json:"count,omitempty"` // Count int `json:"count,omitempty"`
// } // }
// //
// client.User.Query(). // client.User.Query().
// GroupBy(user.FieldName). // GroupBy(user.FieldCreatedAt).
// Aggregate(ent.Count()). // Aggregate(ent.Count()).
// Scan(ctx, &v) // Scan(ctx, &v)
//
func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy { func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy {
group := &UserGroupBy{config: uq.config} grbuild := &UserGroupBy{config: uq.config}
group.fields = append([]string{field}, fields...) grbuild.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) { grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := uq.prepareQuery(ctx); err != nil { if err := uq.prepareQuery(ctx); err != nil {
return nil, err return nil, err
} }
return uq.sqlQuery(ctx), nil return uq.sqlQuery(ctx), nil
} }
return group grbuild.label = user.Label
grbuild.flds, grbuild.scan = &grbuild.fields, grbuild.Scan
return grbuild
} }
// Select allows the selection one or more fields/columns for the given query, // Select allows the selection one or more fields/columns for the given query,
@ -319,16 +356,18 @@ func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy {
// Example: // Example:
// //
// var v []struct { // var v []struct {
// Name string `json:"name,omitempty"` // CreatedAt time.Time `json:"created_at,omitempty"`
// } // }
// //
// client.User.Query(). // client.User.Query().
// Select(user.FieldName). // Select(user.FieldCreatedAt).
// Scan(ctx, &v) // Scan(ctx, &v)
//
func (uq *UserQuery) Select(fields ...string) *UserSelect { func (uq *UserQuery) Select(fields ...string) *UserSelect {
uq.fields = append(uq.fields, fields...) uq.fields = append(uq.fields, fields...)
return &UserSelect{UserQuery: uq} selbuild := &UserSelect{UserQuery: uq}
selbuild.label = user.Label
selbuild.flds, selbuild.scan = &uq.fields, selbuild.Scan
return selbuild
} }
func (uq *UserQuery) prepareQuery(ctx context.Context) error { func (uq *UserQuery) prepareQuery(ctx context.Context) error {
@ -347,41 +386,94 @@ func (uq *UserQuery) prepareQuery(ctx context.Context) error {
return nil return nil
} }
func (uq *UserQuery) sqlAll(ctx context.Context) ([]*User, error) { func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) {
var ( var (
nodes = []*User{} nodes = []*User{}
withFKs = uq.withFKs
_spec = uq.querySpec() _spec = uq.querySpec()
loadedTypes = [1]bool{ loadedTypes = [2]bool{
uq.withGroup != nil,
uq.withAuthTokens != nil, uq.withAuthTokens != nil,
} }
) )
if uq.withGroup != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, user.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]interface{}, error) { _spec.ScanValues = func(columns []string) ([]interface{}, error) {
node := &User{config: uq.config} return (*User).scanValues(nil, columns)
nodes = append(nodes, node)
return node.scanValues(columns)
} }
_spec.Assign = func(columns []string, values []interface{}) error { _spec.Assign = func(columns []string, values []interface{}) error {
if len(nodes) == 0 { node := &User{config: uq.config}
return fmt.Errorf("ent: Assign called without calling ScanValues") nodes = append(nodes, node)
}
node := nodes[len(nodes)-1]
node.Edges.loadedTypes = loadedTypes node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values) return node.assignValues(columns, values)
} }
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, uq.driver, _spec); err != nil { if err := sqlgraph.QueryNodes(ctx, uq.driver, _spec); err != nil {
return nil, err return nil, err
} }
if len(nodes) == 0 { if len(nodes) == 0 {
return nodes, nil return nodes, nil
} }
if query := uq.withGroup; query != nil {
if err := uq.loadGroup(ctx, query, nodes, nil,
func(n *User, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
if query := uq.withAuthTokens; query != nil { if query := uq.withAuthTokens; query != nil {
if err := uq.loadAuthTokens(ctx, query, nodes,
func(n *User) { n.Edges.AuthTokens = []*AuthTokens{} },
func(n *User, e *AuthTokens) { n.Edges.AuthTokens = append(n.Edges.AuthTokens, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (uq *UserQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*User, init func(*User), assign func(*User, *Group)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*User)
for i := range nodes {
if nodes[i].group_users == nil {
continue
}
fk := *nodes[i].group_users
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(group.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_users" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (uq *UserQuery) loadAuthTokens(ctx context.Context, query *AuthTokensQuery, nodes []*User, init func(*User), assign func(*User, *AuthTokens)) error {
fks := make([]driver.Value, 0, len(nodes)) fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*User) nodeids := make(map[uuid.UUID]*User)
for i := range nodes { for i := range nodes {
fks = append(fks, nodes[i].ID) fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i] nodeids[nodes[i].ID] = nodes[i]
nodes[i].Edges.AuthTokens = []*AuthTokens{} if init != nil {
init(nodes[i])
}
} }
query.withFKs = true query.withFKs = true
query.Where(predicate.AuthTokens(func(s *sql.Selector) { query.Where(predicate.AuthTokens(func(s *sql.Selector) {
@ -389,22 +481,20 @@ func (uq *UserQuery) sqlAll(ctx context.Context) ([]*User, error) {
})) }))
neighbors, err := query.All(ctx) neighbors, err := query.All(ctx)
if err != nil { if err != nil {
return nil, err return err
} }
for _, n := range neighbors { for _, n := range neighbors {
fk := n.user_auth_tokens fk := n.user_auth_tokens
if fk == nil { if fk == nil {
return nil, fmt.Errorf(`foreign-key "user_auth_tokens" is nil for node %v`, n.ID) return fmt.Errorf(`foreign-key "user_auth_tokens" is nil for node %v`, n.ID)
} }
node, ok := nodeids[*fk] node, ok := nodeids[*fk]
if !ok { if !ok {
return nil, fmt.Errorf(`unexpected foreign-key "user_auth_tokens" returned %v for node %v`, *fk, n.ID) return fmt.Errorf(`unexpected foreign-key "user_auth_tokens" returned %v for node %v`, *fk, n.ID)
} }
node.Edges.AuthTokens = append(node.Edges.AuthTokens, n) assign(node, n)
} }
} return nil
return nodes, nil
} }
func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) { func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) {
@ -507,6 +597,7 @@ func (uq *UserQuery) sqlQuery(ctx context.Context) *sql.Selector {
// UserGroupBy is the group-by builder for User entities. // UserGroupBy is the group-by builder for User entities.
type UserGroupBy struct { type UserGroupBy struct {
config config
selector
fields []string fields []string
fns []AggregateFunc fns []AggregateFunc
// intermediate query (i.e. traversal path). // intermediate query (i.e. traversal path).
@ -530,209 +621,6 @@ func (ugb *UserGroupBy) Scan(ctx context.Context, v interface{}) error {
return ugb.sqlScan(ctx, v) return ugb.sqlScan(ctx, v)
} }
// ScanX is like Scan, but panics if an error occurs.
func (ugb *UserGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := ugb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by.
// It is only allowed when executing a group-by query with one field.
func (ugb *UserGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UserGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (ugb *UserGroupBy) StringsX(ctx context.Context) []string {
v, err := ugb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (ugb *UserGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = ugb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{user.Label}
default:
err = fmt.Errorf("ent: UserGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (ugb *UserGroupBy) StringX(ctx context.Context) string {
v, err := ugb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by.
// It is only allowed when executing a group-by query with one field.
func (ugb *UserGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UserGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (ugb *UserGroupBy) IntsX(ctx context.Context) []int {
v, err := ugb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (ugb *UserGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = ugb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{user.Label}
default:
err = fmt.Errorf("ent: UserGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (ugb *UserGroupBy) IntX(ctx context.Context) int {
v, err := ugb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by.
// It is only allowed when executing a group-by query with one field.
func (ugb *UserGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UserGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (ugb *UserGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := ugb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (ugb *UserGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = ugb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{user.Label}
default:
err = fmt.Errorf("ent: UserGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (ugb *UserGroupBy) Float64X(ctx context.Context) float64 {
v, err := ugb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by.
// It is only allowed when executing a group-by query with one field.
func (ugb *UserGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UserGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (ugb *UserGroupBy) BoolsX(ctx context.Context) []bool {
v, err := ugb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (ugb *UserGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = ugb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{user.Label}
default:
err = fmt.Errorf("ent: UserGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (ugb *UserGroupBy) BoolX(ctx context.Context) bool {
v, err := ugb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (ugb *UserGroupBy) sqlScan(ctx context.Context, v interface{}) error { func (ugb *UserGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range ugb.fields { for _, f := range ugb.fields {
if !user.ValidColumn(f) { if !user.ValidColumn(f) {
@ -774,6 +662,7 @@ func (ugb *UserGroupBy) sqlQuery() *sql.Selector {
// UserSelect is the builder for selecting fields of User entities. // UserSelect is the builder for selecting fields of User entities.
type UserSelect struct { type UserSelect struct {
*UserQuery *UserQuery
selector
// intermediate query (i.e. traversal path). // intermediate query (i.e. traversal path).
sql *sql.Selector sql *sql.Selector
} }
@ -787,201 +676,6 @@ func (us *UserSelect) Scan(ctx context.Context, v interface{}) error {
return us.sqlScan(ctx, v) return us.sqlScan(ctx, v)
} }
// ScanX is like Scan, but panics if an error occurs.
func (us *UserSelect) ScanX(ctx context.Context, v interface{}) {
if err := us.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (us *UserSelect) Strings(ctx context.Context) ([]string, error) {
if len(us.fields) > 1 {
return nil, errors.New("ent: UserSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := us.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (us *UserSelect) StringsX(ctx context.Context) []string {
v, err := us.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (us *UserSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = us.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{user.Label}
default:
err = fmt.Errorf("ent: UserSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (us *UserSelect) StringX(ctx context.Context) string {
v, err := us.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (us *UserSelect) Ints(ctx context.Context) ([]int, error) {
if len(us.fields) > 1 {
return nil, errors.New("ent: UserSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := us.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (us *UserSelect) IntsX(ctx context.Context) []int {
v, err := us.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (us *UserSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = us.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{user.Label}
default:
err = fmt.Errorf("ent: UserSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (us *UserSelect) IntX(ctx context.Context) int {
v, err := us.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (us *UserSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(us.fields) > 1 {
return nil, errors.New("ent: UserSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := us.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (us *UserSelect) Float64sX(ctx context.Context) []float64 {
v, err := us.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (us *UserSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = us.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{user.Label}
default:
err = fmt.Errorf("ent: UserSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (us *UserSelect) Float64X(ctx context.Context) float64 {
v, err := us.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (us *UserSelect) Bools(ctx context.Context) ([]bool, error) {
if len(us.fields) > 1 {
return nil, errors.New("ent: UserSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := us.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (us *UserSelect) BoolsX(ctx context.Context) []bool {
v, err := us.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (us *UserSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = us.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{user.Label}
default:
err = fmt.Errorf("ent: UserSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (us *UserSelect) BoolX(ctx context.Context) bool {
v, err := us.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (us *UserSelect) sqlScan(ctx context.Context, v interface{}) error { func (us *UserSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{} rows := &sql.Rows{}
query, args := us.sql.Query() query, args := us.sql.Query()

View file

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT. // Code generated by ent, DO NOT EDIT.
package ent package ent
@ -6,11 +6,14 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"time"
"entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field" "entgo.io/ent/schema/field"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/ent/authtokens" "github.com/hay-kot/content/backend/ent/authtokens"
"github.com/hay-kot/content/backend/ent/group"
"github.com/hay-kot/content/backend/ent/predicate" "github.com/hay-kot/content/backend/ent/predicate"
"github.com/hay-kot/content/backend/ent/user" "github.com/hay-kot/content/backend/ent/user"
) )
@ -28,6 +31,12 @@ func (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate {
return uu return uu
} }
// SetUpdatedAt sets the "updated_at" field.
func (uu *UserUpdate) SetUpdatedAt(t time.Time) *UserUpdate {
uu.mutation.SetUpdatedAt(t)
return uu
}
// SetName sets the "name" field. // SetName sets the "name" field.
func (uu *UserUpdate) SetName(s string) *UserUpdate { func (uu *UserUpdate) SetName(s string) *UserUpdate {
uu.mutation.SetName(s) uu.mutation.SetName(s)
@ -60,15 +69,26 @@ func (uu *UserUpdate) SetNillableIsSuperuser(b *bool) *UserUpdate {
return uu return uu
} }
// SetGroupID sets the "group" edge to the Group entity by ID.
func (uu *UserUpdate) SetGroupID(id uuid.UUID) *UserUpdate {
uu.mutation.SetGroupID(id)
return uu
}
// SetGroup sets the "group" edge to the Group entity.
func (uu *UserUpdate) SetGroup(g *Group) *UserUpdate {
return uu.SetGroupID(g.ID)
}
// AddAuthTokenIDs adds the "auth_tokens" edge to the AuthTokens entity by IDs. // AddAuthTokenIDs adds the "auth_tokens" edge to the AuthTokens entity by IDs.
func (uu *UserUpdate) AddAuthTokenIDs(ids ...int) *UserUpdate { func (uu *UserUpdate) AddAuthTokenIDs(ids ...uuid.UUID) *UserUpdate {
uu.mutation.AddAuthTokenIDs(ids...) uu.mutation.AddAuthTokenIDs(ids...)
return uu return uu
} }
// AddAuthTokens adds the "auth_tokens" edges to the AuthTokens entity. // AddAuthTokens adds the "auth_tokens" edges to the AuthTokens entity.
func (uu *UserUpdate) AddAuthTokens(a ...*AuthTokens) *UserUpdate { func (uu *UserUpdate) AddAuthTokens(a ...*AuthTokens) *UserUpdate {
ids := make([]int, len(a)) ids := make([]uuid.UUID, len(a))
for i := range a { for i := range a {
ids[i] = a[i].ID ids[i] = a[i].ID
} }
@ -80,6 +100,12 @@ func (uu *UserUpdate) Mutation() *UserMutation {
return uu.mutation return uu.mutation
} }
// ClearGroup clears the "group" edge to the Group entity.
func (uu *UserUpdate) ClearGroup() *UserUpdate {
uu.mutation.ClearGroup()
return uu
}
// ClearAuthTokens clears all "auth_tokens" edges to the AuthTokens entity. // ClearAuthTokens clears all "auth_tokens" edges to the AuthTokens entity.
func (uu *UserUpdate) ClearAuthTokens() *UserUpdate { func (uu *UserUpdate) ClearAuthTokens() *UserUpdate {
uu.mutation.ClearAuthTokens() uu.mutation.ClearAuthTokens()
@ -87,14 +113,14 @@ func (uu *UserUpdate) ClearAuthTokens() *UserUpdate {
} }
// RemoveAuthTokenIDs removes the "auth_tokens" edge to AuthTokens entities by IDs. // RemoveAuthTokenIDs removes the "auth_tokens" edge to AuthTokens entities by IDs.
func (uu *UserUpdate) RemoveAuthTokenIDs(ids ...int) *UserUpdate { func (uu *UserUpdate) RemoveAuthTokenIDs(ids ...uuid.UUID) *UserUpdate {
uu.mutation.RemoveAuthTokenIDs(ids...) uu.mutation.RemoveAuthTokenIDs(ids...)
return uu return uu
} }
// RemoveAuthTokens removes "auth_tokens" edges to AuthTokens entities. // RemoveAuthTokens removes "auth_tokens" edges to AuthTokens entities.
func (uu *UserUpdate) RemoveAuthTokens(a ...*AuthTokens) *UserUpdate { func (uu *UserUpdate) RemoveAuthTokens(a ...*AuthTokens) *UserUpdate {
ids := make([]int, len(a)) ids := make([]uuid.UUID, len(a))
for i := range a { for i := range a {
ids[i] = a[i].ID ids[i] = a[i].ID
} }
@ -107,6 +133,7 @@ func (uu *UserUpdate) Save(ctx context.Context) (int, error) {
err error err error
affected int affected int
) )
uu.defaults()
if len(uu.hooks) == 0 { if len(uu.hooks) == 0 {
if err = uu.check(); err != nil { if err = uu.check(); err != nil {
return 0, err return 0, err
@ -161,6 +188,14 @@ func (uu *UserUpdate) ExecX(ctx context.Context) {
} }
} }
// defaults sets the default values of the builder before save.
func (uu *UserUpdate) defaults() {
if _, ok := uu.mutation.UpdatedAt(); !ok {
v := user.UpdateDefaultUpdatedAt()
uu.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (uu *UserUpdate) check() error { func (uu *UserUpdate) check() error {
if v, ok := uu.mutation.Name(); ok { if v, ok := uu.mutation.Name(); ok {
@ -178,6 +213,9 @@ func (uu *UserUpdate) check() error {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)} return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)}
} }
} }
if _, ok := uu.mutation.GroupID(); uu.mutation.GroupCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "User.group"`)
}
return nil return nil
} }
@ -199,6 +237,13 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
} }
} }
} }
if value, ok := uu.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: user.FieldUpdatedAt,
})
}
if value, ok := uu.mutation.Name(); ok { if value, ok := uu.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString, Type: field.TypeString,
@ -227,6 +272,41 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
Column: user.FieldIsSuperuser, Column: user.FieldIsSuperuser,
}) })
} }
if uu.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: user.GroupTable,
Columns: []string{user.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := uu.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: user.GroupTable,
Columns: []string{user.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if uu.mutation.AuthTokensCleared() { if uu.mutation.AuthTokensCleared() {
edge := &sqlgraph.EdgeSpec{ edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M, Rel: sqlgraph.O2M,
@ -236,7 +316,7 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
Bidi: false, Bidi: false,
Target: &sqlgraph.EdgeTarget{ Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{ IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt, Type: field.TypeUUID,
Column: authtokens.FieldID, Column: authtokens.FieldID,
}, },
}, },
@ -252,7 +332,7 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
Bidi: false, Bidi: false,
Target: &sqlgraph.EdgeTarget{ Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{ IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt, Type: field.TypeUUID,
Column: authtokens.FieldID, Column: authtokens.FieldID,
}, },
}, },
@ -271,7 +351,7 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
Bidi: false, Bidi: false,
Target: &sqlgraph.EdgeTarget{ Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{ IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt, Type: field.TypeUUID,
Column: authtokens.FieldID, Column: authtokens.FieldID,
}, },
}, },
@ -285,7 +365,7 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
if _, ok := err.(*sqlgraph.NotFoundError); ok { if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{user.Label} err = &NotFoundError{user.Label}
} else if sqlgraph.IsConstraintError(err) { } else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err} err = &ConstraintError{msg: err.Error(), wrap: err}
} }
return 0, err return 0, err
} }
@ -300,6 +380,12 @@ type UserUpdateOne struct {
mutation *UserMutation mutation *UserMutation
} }
// SetUpdatedAt sets the "updated_at" field.
func (uuo *UserUpdateOne) SetUpdatedAt(t time.Time) *UserUpdateOne {
uuo.mutation.SetUpdatedAt(t)
return uuo
}
// SetName sets the "name" field. // SetName sets the "name" field.
func (uuo *UserUpdateOne) SetName(s string) *UserUpdateOne { func (uuo *UserUpdateOne) SetName(s string) *UserUpdateOne {
uuo.mutation.SetName(s) uuo.mutation.SetName(s)
@ -332,15 +418,26 @@ func (uuo *UserUpdateOne) SetNillableIsSuperuser(b *bool) *UserUpdateOne {
return uuo return uuo
} }
// SetGroupID sets the "group" edge to the Group entity by ID.
func (uuo *UserUpdateOne) SetGroupID(id uuid.UUID) *UserUpdateOne {
uuo.mutation.SetGroupID(id)
return uuo
}
// SetGroup sets the "group" edge to the Group entity.
func (uuo *UserUpdateOne) SetGroup(g *Group) *UserUpdateOne {
return uuo.SetGroupID(g.ID)
}
// AddAuthTokenIDs adds the "auth_tokens" edge to the AuthTokens entity by IDs. // AddAuthTokenIDs adds the "auth_tokens" edge to the AuthTokens entity by IDs.
func (uuo *UserUpdateOne) AddAuthTokenIDs(ids ...int) *UserUpdateOne { func (uuo *UserUpdateOne) AddAuthTokenIDs(ids ...uuid.UUID) *UserUpdateOne {
uuo.mutation.AddAuthTokenIDs(ids...) uuo.mutation.AddAuthTokenIDs(ids...)
return uuo return uuo
} }
// AddAuthTokens adds the "auth_tokens" edges to the AuthTokens entity. // AddAuthTokens adds the "auth_tokens" edges to the AuthTokens entity.
func (uuo *UserUpdateOne) AddAuthTokens(a ...*AuthTokens) *UserUpdateOne { func (uuo *UserUpdateOne) AddAuthTokens(a ...*AuthTokens) *UserUpdateOne {
ids := make([]int, len(a)) ids := make([]uuid.UUID, len(a))
for i := range a { for i := range a {
ids[i] = a[i].ID ids[i] = a[i].ID
} }
@ -352,6 +449,12 @@ func (uuo *UserUpdateOne) Mutation() *UserMutation {
return uuo.mutation return uuo.mutation
} }
// ClearGroup clears the "group" edge to the Group entity.
func (uuo *UserUpdateOne) ClearGroup() *UserUpdateOne {
uuo.mutation.ClearGroup()
return uuo
}
// ClearAuthTokens clears all "auth_tokens" edges to the AuthTokens entity. // ClearAuthTokens clears all "auth_tokens" edges to the AuthTokens entity.
func (uuo *UserUpdateOne) ClearAuthTokens() *UserUpdateOne { func (uuo *UserUpdateOne) ClearAuthTokens() *UserUpdateOne {
uuo.mutation.ClearAuthTokens() uuo.mutation.ClearAuthTokens()
@ -359,14 +462,14 @@ func (uuo *UserUpdateOne) ClearAuthTokens() *UserUpdateOne {
} }
// RemoveAuthTokenIDs removes the "auth_tokens" edge to AuthTokens entities by IDs. // RemoveAuthTokenIDs removes the "auth_tokens" edge to AuthTokens entities by IDs.
func (uuo *UserUpdateOne) RemoveAuthTokenIDs(ids ...int) *UserUpdateOne { func (uuo *UserUpdateOne) RemoveAuthTokenIDs(ids ...uuid.UUID) *UserUpdateOne {
uuo.mutation.RemoveAuthTokenIDs(ids...) uuo.mutation.RemoveAuthTokenIDs(ids...)
return uuo return uuo
} }
// RemoveAuthTokens removes "auth_tokens" edges to AuthTokens entities. // RemoveAuthTokens removes "auth_tokens" edges to AuthTokens entities.
func (uuo *UserUpdateOne) RemoveAuthTokens(a ...*AuthTokens) *UserUpdateOne { func (uuo *UserUpdateOne) RemoveAuthTokens(a ...*AuthTokens) *UserUpdateOne {
ids := make([]int, len(a)) ids := make([]uuid.UUID, len(a))
for i := range a { for i := range a {
ids[i] = a[i].ID ids[i] = a[i].ID
} }
@ -386,6 +489,7 @@ func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) {
err error err error
node *User node *User
) )
uuo.defaults()
if len(uuo.hooks) == 0 { if len(uuo.hooks) == 0 {
if err = uuo.check(); err != nil { if err = uuo.check(); err != nil {
return nil, err return nil, err
@ -411,9 +515,15 @@ func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) {
} }
mut = uuo.hooks[i](mut) mut = uuo.hooks[i](mut)
} }
if _, err := mut.Mutate(ctx, uuo.mutation); err != nil { v, err := mut.Mutate(ctx, uuo.mutation)
if err != nil {
return nil, err return nil, err
} }
nv, ok := v.(*User)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from UserMutation", v)
}
node = nv
} }
return node, err return node, err
} }
@ -440,6 +550,14 @@ func (uuo *UserUpdateOne) ExecX(ctx context.Context) {
} }
} }
// defaults sets the default values of the builder before save.
func (uuo *UserUpdateOne) defaults() {
if _, ok := uuo.mutation.UpdatedAt(); !ok {
v := user.UpdateDefaultUpdatedAt()
uuo.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder. // check runs all checks and user-defined validators on the builder.
func (uuo *UserUpdateOne) check() error { func (uuo *UserUpdateOne) check() error {
if v, ok := uuo.mutation.Name(); ok { if v, ok := uuo.mutation.Name(); ok {
@ -457,6 +575,9 @@ func (uuo *UserUpdateOne) check() error {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)} return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)}
} }
} }
if _, ok := uuo.mutation.GroupID(); uuo.mutation.GroupCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "User.group"`)
}
return nil return nil
} }
@ -495,6 +616,13 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error)
} }
} }
} }
if value, ok := uuo.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: user.FieldUpdatedAt,
})
}
if value, ok := uuo.mutation.Name(); ok { if value, ok := uuo.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString, Type: field.TypeString,
@ -523,6 +651,41 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error)
Column: user.FieldIsSuperuser, Column: user.FieldIsSuperuser,
}) })
} }
if uuo.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: user.GroupTable,
Columns: []string{user.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := uuo.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: user.GroupTable,
Columns: []string{user.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if uuo.mutation.AuthTokensCleared() { if uuo.mutation.AuthTokensCleared() {
edge := &sqlgraph.EdgeSpec{ edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M, Rel: sqlgraph.O2M,
@ -532,7 +695,7 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error)
Bidi: false, Bidi: false,
Target: &sqlgraph.EdgeTarget{ Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{ IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt, Type: field.TypeUUID,
Column: authtokens.FieldID, Column: authtokens.FieldID,
}, },
}, },
@ -548,7 +711,7 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error)
Bidi: false, Bidi: false,
Target: &sqlgraph.EdgeTarget{ Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{ IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt, Type: field.TypeUUID,
Column: authtokens.FieldID, Column: authtokens.FieldID,
}, },
}, },
@ -567,7 +730,7 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error)
Bidi: false, Bidi: false,
Target: &sqlgraph.EdgeTarget{ Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{ IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt, Type: field.TypeUUID,
Column: authtokens.FieldID, Column: authtokens.FieldID,
}, },
}, },
@ -584,7 +747,7 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error)
if _, ok := err.(*sqlgraph.NotFoundError); ok { if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{user.Label} err = &NotFoundError{user.Label}
} else if sqlgraph.IsConstraintError(err) { } else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err} err = &ConstraintError{msg: err.Error(), wrap: err}
} }
return nil, err return nil, err
} }