// 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/dialect/sql/sqljson"
	"entgo.io/ent/schema/field"
	"github.com/Wei-Shaw/sub2api/ent/apikey"
	"github.com/Wei-Shaw/sub2api/ent/group"
	"github.com/Wei-Shaw/sub2api/ent/predicate"
	"github.com/Wei-Shaw/sub2api/ent/usagelog"
	"github.com/Wei-Shaw/sub2api/ent/user"
)

// APIKeyUpdate is the builder for updating APIKey entities.
type APIKeyUpdate struct {
	config
	hooks    []Hook
	mutation *APIKeyMutation
}

// Where appends a list predicates to the APIKeyUpdate builder.
func (_u *APIKeyUpdate) Where(ps ...predicate.APIKey) *APIKeyUpdate {
	_u.mutation.Where(ps...)
	return _u
}

// SetUpdatedAt sets the "updated_at" field.
func (_u *APIKeyUpdate) SetUpdatedAt(v time.Time) *APIKeyUpdate {
	_u.mutation.SetUpdatedAt(v)
	return _u
}

// SetDeletedAt sets the "deleted_at" field.
func (_u *APIKeyUpdate) SetDeletedAt(v time.Time) *APIKeyUpdate {
	_u.mutation.SetDeletedAt(v)
	return _u
}

// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *APIKeyUpdate) SetNillableDeletedAt(v *time.Time) *APIKeyUpdate {
	if v != nil {
		_u.SetDeletedAt(*v)
	}
	return _u
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *APIKeyUpdate) ClearDeletedAt() *APIKeyUpdate {
	_u.mutation.ClearDeletedAt()
	return _u
}

// SetUserID sets the "user_id" field.
func (_u *APIKeyUpdate) SetUserID(v int64) *APIKeyUpdate {
	_u.mutation.SetUserID(v)
	return _u
}

// SetNillableUserID sets the "user_id" field if the given value is not nil.
func (_u *APIKeyUpdate) SetNillableUserID(v *int64) *APIKeyUpdate {
	if v != nil {
		_u.SetUserID(*v)
	}
	return _u
}

// SetKey sets the "key" field.
func (_u *APIKeyUpdate) SetKey(v string) *APIKeyUpdate {
	_u.mutation.SetKey(v)
	return _u
}

// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *APIKeyUpdate) SetNillableKey(v *string) *APIKeyUpdate {
	if v != nil {
		_u.SetKey(*v)
	}
	return _u
}

// SetName sets the "name" field.
func (_u *APIKeyUpdate) SetName(v string) *APIKeyUpdate {
	_u.mutation.SetName(v)
	return _u
}

// SetNillableName sets the "name" field if the given value is not nil.
func (_u *APIKeyUpdate) SetNillableName(v *string) *APIKeyUpdate {
	if v != nil {
		_u.SetName(*v)
	}
	return _u
}

// SetGroupID sets the "group_id" field.
func (_u *APIKeyUpdate) SetGroupID(v int64) *APIKeyUpdate {
	_u.mutation.SetGroupID(v)
	return _u
}

// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_u *APIKeyUpdate) SetNillableGroupID(v *int64) *APIKeyUpdate {
	if v != nil {
		_u.SetGroupID(*v)
	}
	return _u
}

// ClearGroupID clears the value of the "group_id" field.
func (_u *APIKeyUpdate) ClearGroupID() *APIKeyUpdate {
	_u.mutation.ClearGroupID()
	return _u
}

// SetStatus sets the "status" field.
func (_u *APIKeyUpdate) SetStatus(v string) *APIKeyUpdate {
	_u.mutation.SetStatus(v)
	return _u
}

// SetNillableStatus sets the "status" field if the given value is not nil.
func (_u *APIKeyUpdate) SetNillableStatus(v *string) *APIKeyUpdate {
	if v != nil {
		_u.SetStatus(*v)
	}
	return _u
}

// SetIPWhitelist sets the "ip_whitelist" field.
func (_u *APIKeyUpdate) SetIPWhitelist(v []string) *APIKeyUpdate {
	_u.mutation.SetIPWhitelist(v)
	return _u
}

// AppendIPWhitelist appends value to the "ip_whitelist" field.
func (_u *APIKeyUpdate) AppendIPWhitelist(v []string) *APIKeyUpdate {
	_u.mutation.AppendIPWhitelist(v)
	return _u
}

// ClearIPWhitelist clears the value of the "ip_whitelist" field.
func (_u *APIKeyUpdate) ClearIPWhitelist() *APIKeyUpdate {
	_u.mutation.ClearIPWhitelist()
	return _u
}

// SetIPBlacklist sets the "ip_blacklist" field.
func (_u *APIKeyUpdate) SetIPBlacklist(v []string) *APIKeyUpdate {
	_u.mutation.SetIPBlacklist(v)
	return _u
}

// AppendIPBlacklist appends value to the "ip_blacklist" field.
func (_u *APIKeyUpdate) AppendIPBlacklist(v []string) *APIKeyUpdate {
	_u.mutation.AppendIPBlacklist(v)
	return _u
}

// ClearIPBlacklist clears the value of the "ip_blacklist" field.
func (_u *APIKeyUpdate) ClearIPBlacklist() *APIKeyUpdate {
	_u.mutation.ClearIPBlacklist()
	return _u
}

// SetUser sets the "user" edge to the User entity.
func (_u *APIKeyUpdate) SetUser(v *User) *APIKeyUpdate {
	return _u.SetUserID(v.ID)
}

// SetGroup sets the "group" edge to the Group entity.
func (_u *APIKeyUpdate) SetGroup(v *Group) *APIKeyUpdate {
	return _u.SetGroupID(v.ID)
}

// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
func (_u *APIKeyUpdate) AddUsageLogIDs(ids ...int64) *APIKeyUpdate {
	_u.mutation.AddUsageLogIDs(ids...)
	return _u
}

// AddUsageLogs adds the "usage_logs" edges to the UsageLog entity.
func (_u *APIKeyUpdate) AddUsageLogs(v ...*UsageLog) *APIKeyUpdate {
	ids := make([]int64, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _u.AddUsageLogIDs(ids...)
}

// Mutation returns the APIKeyMutation object of the builder.
func (_u *APIKeyUpdate) Mutation() *APIKeyMutation {
	return _u.mutation
}

// ClearUser clears the "user" edge to the User entity.
func (_u *APIKeyUpdate) ClearUser() *APIKeyUpdate {
	_u.mutation.ClearUser()
	return _u
}

// ClearGroup clears the "group" edge to the Group entity.
func (_u *APIKeyUpdate) ClearGroup() *APIKeyUpdate {
	_u.mutation.ClearGroup()
	return _u
}

// ClearUsageLogs clears all "usage_logs" edges to the UsageLog entity.
func (_u *APIKeyUpdate) ClearUsageLogs() *APIKeyUpdate {
	_u.mutation.ClearUsageLogs()
	return _u
}

// RemoveUsageLogIDs removes the "usage_logs" edge to UsageLog entities by IDs.
func (_u *APIKeyUpdate) RemoveUsageLogIDs(ids ...int64) *APIKeyUpdate {
	_u.mutation.RemoveUsageLogIDs(ids...)
	return _u
}

// RemoveUsageLogs removes "usage_logs" edges to UsageLog entities.
func (_u *APIKeyUpdate) RemoveUsageLogs(v ...*UsageLog) *APIKeyUpdate {
	ids := make([]int64, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _u.RemoveUsageLogIDs(ids...)
}

// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *APIKeyUpdate) Save(ctx context.Context) (int, error) {
	if err := _u.defaults(); err != nil {
		return 0, err
	}
	return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}

// SaveX is like Save, but panics if an error occurs.
func (_u *APIKeyUpdate) SaveX(ctx context.Context) int {
	affected, err := _u.Save(ctx)
	if err != nil {
		panic(err)
	}
	return affected
}

// Exec executes the query.
func (_u *APIKeyUpdate) Exec(ctx context.Context) error {
	_, err := _u.Save(ctx)
	return err
}

// ExecX is like Exec, but panics if an error occurs.
func (_u *APIKeyUpdate) ExecX(ctx context.Context) {
	if err := _u.Exec(ctx); err != nil {
		panic(err)
	}
}

// defaults sets the default values of the builder before save.
func (_u *APIKeyUpdate) defaults() error {
	if _, ok := _u.mutation.UpdatedAt(); !ok {
		if apikey.UpdateDefaultUpdatedAt == nil {
			return fmt.Errorf("ent: uninitialized apikey.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
		}
		v := apikey.UpdateDefaultUpdatedAt()
		_u.mutation.SetUpdatedAt(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (_u *APIKeyUpdate) check() error {
	if v, ok := _u.mutation.Key(); ok {
		if err := apikey.KeyValidator(v); err != nil {
			return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "APIKey.key": %w`, err)}
		}
	}
	if v, ok := _u.mutation.Name(); ok {
		if err := apikey.NameValidator(v); err != nil {
			return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "APIKey.name": %w`, err)}
		}
	}
	if v, ok := _u.mutation.Status(); ok {
		if err := apikey.StatusValidator(v); err != nil {
			return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "APIKey.status": %w`, err)}
		}
	}
	if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
		return errors.New(`ent: clearing a required unique edge "APIKey.user"`)
	}
	return nil
}

func (_u *APIKeyUpdate) sqlSave(ctx context.Context) (_node int, err error) {
	if err := _u.check(); err != nil {
		return _node, err
	}
	_spec := sqlgraph.NewUpdateSpec(apikey.Table, apikey.Columns, sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeInt64))
	if ps := _u.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := _u.mutation.UpdatedAt(); ok {
		_spec.SetField(apikey.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := _u.mutation.DeletedAt(); ok {
		_spec.SetField(apikey.FieldDeletedAt, field.TypeTime, value)
	}
	if _u.mutation.DeletedAtCleared() {
		_spec.ClearField(apikey.FieldDeletedAt, field.TypeTime)
	}
	if value, ok := _u.mutation.Key(); ok {
		_spec.SetField(apikey.FieldKey, field.TypeString, value)
	}
	if value, ok := _u.mutation.Name(); ok {
		_spec.SetField(apikey.FieldName, field.TypeString, value)
	}
	if value, ok := _u.mutation.Status(); ok {
		_spec.SetField(apikey.FieldStatus, field.TypeString, value)
	}
	if value, ok := _u.mutation.IPWhitelist(); ok {
		_spec.SetField(apikey.FieldIPWhitelist, field.TypeJSON, value)
	}
	if value, ok := _u.mutation.AppendedIPWhitelist(); ok {
		_spec.AddModifier(func(u *sql.UpdateBuilder) {
			sqljson.Append(u, apikey.FieldIPWhitelist, value)
		})
	}
	if _u.mutation.IPWhitelistCleared() {
		_spec.ClearField(apikey.FieldIPWhitelist, field.TypeJSON)
	}
	if value, ok := _u.mutation.IPBlacklist(); ok {
		_spec.SetField(apikey.FieldIPBlacklist, field.TypeJSON, value)
	}
	if value, ok := _u.mutation.AppendedIPBlacklist(); ok {
		_spec.AddModifier(func(u *sql.UpdateBuilder) {
			sqljson.Append(u, apikey.FieldIPBlacklist, value)
		})
	}
	if _u.mutation.IPBlacklistCleared() {
		_spec.ClearField(apikey.FieldIPBlacklist, field.TypeJSON)
	}
	if _u.mutation.UserCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   apikey.UserTable,
			Columns: []string{apikey.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   apikey.UserTable,
			Columns: []string{apikey.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if _u.mutation.GroupCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   apikey.GroupTable,
			Columns: []string{apikey.GroupColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   apikey.GroupTable,
			Columns: []string{apikey.GroupColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if _u.mutation.UsageLogsCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   apikey.UsageLogsTable,
			Columns: []string{apikey.UsageLogsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := _u.mutation.RemovedUsageLogsIDs(); len(nodes) > 0 && !_u.mutation.UsageLogsCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   apikey.UsageLogsTable,
			Columns: []string{apikey.UsageLogsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := _u.mutation.UsageLogsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   apikey.UsageLogsTable,
			Columns: []string{apikey.UsageLogsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{apikey.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return 0, err
	}
	_u.mutation.done = true
	return _node, nil
}

// APIKeyUpdateOne is the builder for updating a single APIKey entity.
type APIKeyUpdateOne struct {
	config
	fields   []string
	hooks    []Hook
	mutation *APIKeyMutation
}

// SetUpdatedAt sets the "updated_at" field.
func (_u *APIKeyUpdateOne) SetUpdatedAt(v time.Time) *APIKeyUpdateOne {
	_u.mutation.SetUpdatedAt(v)
	return _u
}

// SetDeletedAt sets the "deleted_at" field.
func (_u *APIKeyUpdateOne) SetDeletedAt(v time.Time) *APIKeyUpdateOne {
	_u.mutation.SetDeletedAt(v)
	return _u
}

// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *APIKeyUpdateOne) SetNillableDeletedAt(v *time.Time) *APIKeyUpdateOne {
	if v != nil {
		_u.SetDeletedAt(*v)
	}
	return _u
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *APIKeyUpdateOne) ClearDeletedAt() *APIKeyUpdateOne {
	_u.mutation.ClearDeletedAt()
	return _u
}

// SetUserID sets the "user_id" field.
func (_u *APIKeyUpdateOne) SetUserID(v int64) *APIKeyUpdateOne {
	_u.mutation.SetUserID(v)
	return _u
}

// SetNillableUserID sets the "user_id" field if the given value is not nil.
func (_u *APIKeyUpdateOne) SetNillableUserID(v *int64) *APIKeyUpdateOne {
	if v != nil {
		_u.SetUserID(*v)
	}
	return _u
}

// SetKey sets the "key" field.
func (_u *APIKeyUpdateOne) SetKey(v string) *APIKeyUpdateOne {
	_u.mutation.SetKey(v)
	return _u
}

// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *APIKeyUpdateOne) SetNillableKey(v *string) *APIKeyUpdateOne {
	if v != nil {
		_u.SetKey(*v)
	}
	return _u
}

// SetName sets the "name" field.
func (_u *APIKeyUpdateOne) SetName(v string) *APIKeyUpdateOne {
	_u.mutation.SetName(v)
	return _u
}

// SetNillableName sets the "name" field if the given value is not nil.
func (_u *APIKeyUpdateOne) SetNillableName(v *string) *APIKeyUpdateOne {
	if v != nil {
		_u.SetName(*v)
	}
	return _u
}

// SetGroupID sets the "group_id" field.
func (_u *APIKeyUpdateOne) SetGroupID(v int64) *APIKeyUpdateOne {
	_u.mutation.SetGroupID(v)
	return _u
}

// SetNillableGroupID sets the "group_id" field if the given value is not nil.
func (_u *APIKeyUpdateOne) SetNillableGroupID(v *int64) *APIKeyUpdateOne {
	if v != nil {
		_u.SetGroupID(*v)
	}
	return _u
}

// ClearGroupID clears the value of the "group_id" field.
func (_u *APIKeyUpdateOne) ClearGroupID() *APIKeyUpdateOne {
	_u.mutation.ClearGroupID()
	return _u
}

// SetStatus sets the "status" field.
func (_u *APIKeyUpdateOne) SetStatus(v string) *APIKeyUpdateOne {
	_u.mutation.SetStatus(v)
	return _u
}

// SetNillableStatus sets the "status" field if the given value is not nil.
func (_u *APIKeyUpdateOne) SetNillableStatus(v *string) *APIKeyUpdateOne {
	if v != nil {
		_u.SetStatus(*v)
	}
	return _u
}

// SetIPWhitelist sets the "ip_whitelist" field.
func (_u *APIKeyUpdateOne) SetIPWhitelist(v []string) *APIKeyUpdateOne {
	_u.mutation.SetIPWhitelist(v)
	return _u
}

// AppendIPWhitelist appends value to the "ip_whitelist" field.
func (_u *APIKeyUpdateOne) AppendIPWhitelist(v []string) *APIKeyUpdateOne {
	_u.mutation.AppendIPWhitelist(v)
	return _u
}

// ClearIPWhitelist clears the value of the "ip_whitelist" field.
func (_u *APIKeyUpdateOne) ClearIPWhitelist() *APIKeyUpdateOne {
	_u.mutation.ClearIPWhitelist()
	return _u
}

// SetIPBlacklist sets the "ip_blacklist" field.
func (_u *APIKeyUpdateOne) SetIPBlacklist(v []string) *APIKeyUpdateOne {
	_u.mutation.SetIPBlacklist(v)
	return _u
}

// AppendIPBlacklist appends value to the "ip_blacklist" field.
func (_u *APIKeyUpdateOne) AppendIPBlacklist(v []string) *APIKeyUpdateOne {
	_u.mutation.AppendIPBlacklist(v)
	return _u
}

// ClearIPBlacklist clears the value of the "ip_blacklist" field.
func (_u *APIKeyUpdateOne) ClearIPBlacklist() *APIKeyUpdateOne {
	_u.mutation.ClearIPBlacklist()
	return _u
}

// SetUser sets the "user" edge to the User entity.
func (_u *APIKeyUpdateOne) SetUser(v *User) *APIKeyUpdateOne {
	return _u.SetUserID(v.ID)
}

// SetGroup sets the "group" edge to the Group entity.
func (_u *APIKeyUpdateOne) SetGroup(v *Group) *APIKeyUpdateOne {
	return _u.SetGroupID(v.ID)
}

// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
func (_u *APIKeyUpdateOne) AddUsageLogIDs(ids ...int64) *APIKeyUpdateOne {
	_u.mutation.AddUsageLogIDs(ids...)
	return _u
}

// AddUsageLogs adds the "usage_logs" edges to the UsageLog entity.
func (_u *APIKeyUpdateOne) AddUsageLogs(v ...*UsageLog) *APIKeyUpdateOne {
	ids := make([]int64, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _u.AddUsageLogIDs(ids...)
}

// Mutation returns the APIKeyMutation object of the builder.
func (_u *APIKeyUpdateOne) Mutation() *APIKeyMutation {
	return _u.mutation
}

// ClearUser clears the "user" edge to the User entity.
func (_u *APIKeyUpdateOne) ClearUser() *APIKeyUpdateOne {
	_u.mutation.ClearUser()
	return _u
}

// ClearGroup clears the "group" edge to the Group entity.
func (_u *APIKeyUpdateOne) ClearGroup() *APIKeyUpdateOne {
	_u.mutation.ClearGroup()
	return _u
}

// ClearUsageLogs clears all "usage_logs" edges to the UsageLog entity.
func (_u *APIKeyUpdateOne) ClearUsageLogs() *APIKeyUpdateOne {
	_u.mutation.ClearUsageLogs()
	return _u
}

// RemoveUsageLogIDs removes the "usage_logs" edge to UsageLog entities by IDs.
func (_u *APIKeyUpdateOne) RemoveUsageLogIDs(ids ...int64) *APIKeyUpdateOne {
	_u.mutation.RemoveUsageLogIDs(ids...)
	return _u
}

// RemoveUsageLogs removes "usage_logs" edges to UsageLog entities.
func (_u *APIKeyUpdateOne) RemoveUsageLogs(v ...*UsageLog) *APIKeyUpdateOne {
	ids := make([]int64, len(v))
	for i := range v {
		ids[i] = v[i].ID
	}
	return _u.RemoveUsageLogIDs(ids...)
}

// Where appends a list predicates to the APIKeyUpdate builder.
func (_u *APIKeyUpdateOne) Where(ps ...predicate.APIKey) *APIKeyUpdateOne {
	_u.mutation.Where(ps...)
	return _u
}

// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *APIKeyUpdateOne) Select(field string, fields ...string) *APIKeyUpdateOne {
	_u.fields = append([]string{field}, fields...)
	return _u
}

// Save executes the query and returns the updated APIKey entity.
func (_u *APIKeyUpdateOne) Save(ctx context.Context) (*APIKey, error) {
	if err := _u.defaults(); err != nil {
		return nil, err
	}
	return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}

// SaveX is like Save, but panics if an error occurs.
func (_u *APIKeyUpdateOne) SaveX(ctx context.Context) *APIKey {
	node, err := _u.Save(ctx)
	if err != nil {
		panic(err)
	}
	return node
}

// Exec executes the query on the entity.
func (_u *APIKeyUpdateOne) Exec(ctx context.Context) error {
	_, err := _u.Save(ctx)
	return err
}

// ExecX is like Exec, but panics if an error occurs.
func (_u *APIKeyUpdateOne) ExecX(ctx context.Context) {
	if err := _u.Exec(ctx); err != nil {
		panic(err)
	}
}

// defaults sets the default values of the builder before save.
func (_u *APIKeyUpdateOne) defaults() error {
	if _, ok := _u.mutation.UpdatedAt(); !ok {
		if apikey.UpdateDefaultUpdatedAt == nil {
			return fmt.Errorf("ent: uninitialized apikey.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
		}
		v := apikey.UpdateDefaultUpdatedAt()
		_u.mutation.SetUpdatedAt(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (_u *APIKeyUpdateOne) check() error {
	if v, ok := _u.mutation.Key(); ok {
		if err := apikey.KeyValidator(v); err != nil {
			return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "APIKey.key": %w`, err)}
		}
	}
	if v, ok := _u.mutation.Name(); ok {
		if err := apikey.NameValidator(v); err != nil {
			return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "APIKey.name": %w`, err)}
		}
	}
	if v, ok := _u.mutation.Status(); ok {
		if err := apikey.StatusValidator(v); err != nil {
			return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "APIKey.status": %w`, err)}
		}
	}
	if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
		return errors.New(`ent: clearing a required unique edge "APIKey.user"`)
	}
	return nil
}

func (_u *APIKeyUpdateOne) sqlSave(ctx context.Context) (_node *APIKey, err error) {
	if err := _u.check(); err != nil {
		return _node, err
	}
	_spec := sqlgraph.NewUpdateSpec(apikey.Table, apikey.Columns, sqlgraph.NewFieldSpec(apikey.FieldID, field.TypeInt64))
	id, ok := _u.mutation.ID()
	if !ok {
		return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "APIKey.id" for update`)}
	}
	_spec.Node.ID.Value = id
	if fields := _u.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, apikey.FieldID)
		for _, f := range fields {
			if !apikey.ValidColumn(f) {
				return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
			}
			if f != apikey.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, f)
			}
		}
	}
	if ps := _u.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := _u.mutation.UpdatedAt(); ok {
		_spec.SetField(apikey.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := _u.mutation.DeletedAt(); ok {
		_spec.SetField(apikey.FieldDeletedAt, field.TypeTime, value)
	}
	if _u.mutation.DeletedAtCleared() {
		_spec.ClearField(apikey.FieldDeletedAt, field.TypeTime)
	}
	if value, ok := _u.mutation.Key(); ok {
		_spec.SetField(apikey.FieldKey, field.TypeString, value)
	}
	if value, ok := _u.mutation.Name(); ok {
		_spec.SetField(apikey.FieldName, field.TypeString, value)
	}
	if value, ok := _u.mutation.Status(); ok {
		_spec.SetField(apikey.FieldStatus, field.TypeString, value)
	}
	if value, ok := _u.mutation.IPWhitelist(); ok {
		_spec.SetField(apikey.FieldIPWhitelist, field.TypeJSON, value)
	}
	if value, ok := _u.mutation.AppendedIPWhitelist(); ok {
		_spec.AddModifier(func(u *sql.UpdateBuilder) {
			sqljson.Append(u, apikey.FieldIPWhitelist, value)
		})
	}
	if _u.mutation.IPWhitelistCleared() {
		_spec.ClearField(apikey.FieldIPWhitelist, field.TypeJSON)
	}
	if value, ok := _u.mutation.IPBlacklist(); ok {
		_spec.SetField(apikey.FieldIPBlacklist, field.TypeJSON, value)
	}
	if value, ok := _u.mutation.AppendedIPBlacklist(); ok {
		_spec.AddModifier(func(u *sql.UpdateBuilder) {
			sqljson.Append(u, apikey.FieldIPBlacklist, value)
		})
	}
	if _u.mutation.IPBlacklistCleared() {
		_spec.ClearField(apikey.FieldIPBlacklist, field.TypeJSON)
	}
	if _u.mutation.UserCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   apikey.UserTable,
			Columns: []string{apikey.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   apikey.UserTable,
			Columns: []string{apikey.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if _u.mutation.GroupCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   apikey.GroupTable,
			Columns: []string{apikey.GroupColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   apikey.GroupTable,
			Columns: []string{apikey.GroupColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if _u.mutation.UsageLogsCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   apikey.UsageLogsTable,
			Columns: []string{apikey.UsageLogsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := _u.mutation.RemovedUsageLogsIDs(); len(nodes) > 0 && !_u.mutation.UsageLogsCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   apikey.UsageLogsTable,
			Columns: []string{apikey.UsageLogsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := _u.mutation.UsageLogsIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: false,
			Table:   apikey.UsageLogsTable,
			Columns: []string{apikey.UsageLogsColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_node = &APIKey{config: _u.config}
	_spec.Assign = _node.assignValues
	_spec.ScanValues = _node.scanValues
	if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{apikey.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	_u.mutation.done = true
	return _node, nil
}
