diff --git a/pkg/apiserver/apic.go b/pkg/apiserver/apic.go index 720b68793..ca2918bcf 100644 --- a/pkg/apiserver/apic.go +++ b/pkg/apiserver/apic.go @@ -257,7 +257,7 @@ func (a *apic) Authenticate(ctx context.Context, config *csconfig.OnlineApiClien ok bool ) - tokenString, err := a.dbClient.GetConfigItem(ctx, "apic_token") + tokenString, err := a.dbClient.GetTokenItem(ctx, "apic_token") if err != nil { log.Debugf("err when looking for a token in database: %s", err) skip = false @@ -319,7 +319,7 @@ func (a *apic) Authenticate(ctx context.Context, config *csconfig.OnlineApiClien a.apiClient.GetClient().Transport.(*apiclient.JWTTransport).Token = authResp.Token - err = a.dbClient.SetConfigItem(ctx, "apic_token", authResp.Token) + err = a.dbClient.SetTokenItem(ctx, "apic_token", authResp.Token) if err != nil { return fmt.Errorf("while setting token in db: %w", err) } diff --git a/pkg/database/config.go b/pkg/database/config.go index 89ccb1e1b..3a272a8c0 100644 --- a/pkg/database/config.go +++ b/pkg/database/config.go @@ -7,6 +7,7 @@ import ( "github.com/crowdsecurity/crowdsec/pkg/database/ent" "github.com/crowdsecurity/crowdsec/pkg/database/ent/configitem" + "github.com/crowdsecurity/crowdsec/pkg/database/ent/tokenitem" ) func (c *Client) GetConfigItem(ctx context.Context, key string) (*string, error) { @@ -35,3 +36,30 @@ func (c *Client) SetConfigItem(ctx context.Context, key string, value string) er return nil } + +func (c *Client) GetTokenItem(ctx context.Context, key string) (*string, error) { + result, err := c.Ent.TokenItem.Query().Where(tokenitem.NameEQ(key)).First(ctx) + if err != nil && ent.IsNotFound(err) { + return nil, nil + } + + if err != nil { + return nil, errors.Wrapf(QueryFail, "select config item: %s", err) + } + + return &result.Value, nil +} + +func (c *Client) SetTokenItem(ctx context.Context, key string, value string) error { + nbUpdated, err := c.Ent.TokenItem.Update().SetValue(value).Where(tokenitem.NameEQ(key)).Save(ctx) + if (err != nil && ent.IsNotFound(err)) || nbUpdated == 0 { // not found, create + err := c.Ent.TokenItem.Create().SetName(key).SetValue(value).Exec(ctx) + if err != nil { + return errors.Wrapf(QueryFail, "insert config item: %s", err) + } + } else if err != nil { + return errors.Wrapf(QueryFail, "update config item: %s", err) + } + + return nil +} diff --git a/pkg/database/ent/client.go b/pkg/database/ent/client.go index bc7c03304..70bdcd76e 100644 --- a/pkg/database/ent/client.go +++ b/pkg/database/ent/client.go @@ -26,6 +26,7 @@ import ( "github.com/crowdsecurity/crowdsec/pkg/database/ent/machine" "github.com/crowdsecurity/crowdsec/pkg/database/ent/meta" "github.com/crowdsecurity/crowdsec/pkg/database/ent/metric" + "github.com/crowdsecurity/crowdsec/pkg/database/ent/tokenitem" ) // Client is the client that holds all ent builders. @@ -55,6 +56,8 @@ type Client struct { Meta *MetaClient // Metric is the client for interacting with the Metric builders. Metric *MetricClient + // TokenItem is the client for interacting with the TokenItem builders. + TokenItem *TokenItemClient } // NewClient creates a new client configured with the given options. @@ -77,6 +80,7 @@ func (c *Client) init() { c.Machine = NewMachineClient(c.config) c.Meta = NewMetaClient(c.config) c.Metric = NewMetricClient(c.config) + c.TokenItem = NewTokenItemClient(c.config) } type ( @@ -180,6 +184,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { Machine: NewMachineClient(cfg), Meta: NewMetaClient(cfg), Metric: NewMetricClient(cfg), + TokenItem: NewTokenItemClient(cfg), }, nil } @@ -210,6 +215,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) Machine: NewMachineClient(cfg), Meta: NewMetaClient(cfg), Metric: NewMetricClient(cfg), + TokenItem: NewTokenItemClient(cfg), }, nil } @@ -240,7 +246,7 @@ func (c *Client) Close() error { func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ c.Alert, c.AllowList, c.AllowListItem, c.Bouncer, c.ConfigItem, c.Decision, - c.Event, c.Lock, c.Machine, c.Meta, c.Metric, + c.Event, c.Lock, c.Machine, c.Meta, c.Metric, c.TokenItem, } { n.Use(hooks...) } @@ -251,7 +257,7 @@ func (c *Client) Use(hooks ...Hook) { func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ c.Alert, c.AllowList, c.AllowListItem, c.Bouncer, c.ConfigItem, c.Decision, - c.Event, c.Lock, c.Machine, c.Meta, c.Metric, + c.Event, c.Lock, c.Machine, c.Meta, c.Metric, c.TokenItem, } { n.Intercept(interceptors...) } @@ -282,6 +288,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.Meta.mutate(ctx, m) case *MetricMutation: return c.Metric.mutate(ctx, m) + case *TokenItemMutation: + return c.TokenItem.mutate(ctx, m) default: return nil, fmt.Errorf("ent: unknown mutation type %T", m) } @@ -1910,14 +1918,147 @@ func (c *MetricClient) mutate(ctx context.Context, m *MetricMutation) (Value, er } } +// TokenItemClient is a client for the TokenItem schema. +type TokenItemClient struct { + config +} + +// NewTokenItemClient returns a client for the TokenItem from the given config. +func NewTokenItemClient(c config) *TokenItemClient { + return &TokenItemClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `tokenitem.Hooks(f(g(h())))`. +func (c *TokenItemClient) Use(hooks ...Hook) { + c.hooks.TokenItem = append(c.hooks.TokenItem, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `tokenitem.Intercept(f(g(h())))`. +func (c *TokenItemClient) Intercept(interceptors ...Interceptor) { + c.inters.TokenItem = append(c.inters.TokenItem, interceptors...) +} + +// Create returns a builder for creating a TokenItem entity. +func (c *TokenItemClient) Create() *TokenItemCreate { + mutation := newTokenItemMutation(c.config, OpCreate) + return &TokenItemCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of TokenItem entities. +func (c *TokenItemClient) CreateBulk(builders ...*TokenItemCreate) *TokenItemCreateBulk { + return &TokenItemCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *TokenItemClient) MapCreateBulk(slice any, setFunc func(*TokenItemCreate, int)) *TokenItemCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &TokenItemCreateBulk{err: fmt.Errorf("calling to TokenItemClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*TokenItemCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &TokenItemCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for TokenItem. +func (c *TokenItemClient) Update() *TokenItemUpdate { + mutation := newTokenItemMutation(c.config, OpUpdate) + return &TokenItemUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TokenItemClient) UpdateOne(ti *TokenItem) *TokenItemUpdateOne { + mutation := newTokenItemMutation(c.config, OpUpdateOne, withTokenItem(ti)) + return &TokenItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *TokenItemClient) UpdateOneID(id int) *TokenItemUpdateOne { + mutation := newTokenItemMutation(c.config, OpUpdateOne, withTokenItemID(id)) + return &TokenItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for TokenItem. +func (c *TokenItemClient) Delete() *TokenItemDelete { + mutation := newTokenItemMutation(c.config, OpDelete) + return &TokenItemDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *TokenItemClient) DeleteOne(ti *TokenItem) *TokenItemDeleteOne { + return c.DeleteOneID(ti.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *TokenItemClient) DeleteOneID(id int) *TokenItemDeleteOne { + builder := c.Delete().Where(tokenitem.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &TokenItemDeleteOne{builder} +} + +// Query returns a query builder for TokenItem. +func (c *TokenItemClient) Query() *TokenItemQuery { + return &TokenItemQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeTokenItem}, + inters: c.Interceptors(), + } +} + +// Get returns a TokenItem entity by its id. +func (c *TokenItemClient) Get(ctx context.Context, id int) (*TokenItem, error) { + return c.Query().Where(tokenitem.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *TokenItemClient) GetX(ctx context.Context, id int) *TokenItem { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *TokenItemClient) Hooks() []Hook { + return c.hooks.TokenItem +} + +// Interceptors returns the client interceptors. +func (c *TokenItemClient) Interceptors() []Interceptor { + return c.inters.TokenItem +} + +func (c *TokenItemClient) mutate(ctx context.Context, m *TokenItemMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&TokenItemCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&TokenItemUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&TokenItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&TokenItemDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown TokenItem mutation op: %q", m.Op()) + } +} + // hooks and interceptors per client, for fast access. type ( hooks struct { Alert, AllowList, AllowListItem, Bouncer, ConfigItem, Decision, Event, Lock, - Machine, Meta, Metric []ent.Hook + Machine, Meta, Metric, TokenItem []ent.Hook } inters struct { Alert, AllowList, AllowListItem, Bouncer, ConfigItem, Decision, Event, Lock, - Machine, Meta, Metric []ent.Interceptor + Machine, Meta, Metric, TokenItem []ent.Interceptor } ) diff --git a/pkg/database/ent/ent.go b/pkg/database/ent/ent.go index b28333afa..91d970ffb 100644 --- a/pkg/database/ent/ent.go +++ b/pkg/database/ent/ent.go @@ -23,6 +23,7 @@ import ( "github.com/crowdsecurity/crowdsec/pkg/database/ent/machine" "github.com/crowdsecurity/crowdsec/pkg/database/ent/meta" "github.com/crowdsecurity/crowdsec/pkg/database/ent/metric" + "github.com/crowdsecurity/crowdsec/pkg/database/ent/tokenitem" ) // ent aliases to avoid import conflicts in user's code. @@ -94,6 +95,7 @@ func checkColumn(table, column string) error { machine.Table: machine.ValidColumn, meta.Table: meta.ValidColumn, metric.Table: metric.ValidColumn, + tokenitem.Table: tokenitem.ValidColumn, }) }) return columnCheck(table, column) diff --git a/pkg/database/ent/hook/hook.go b/pkg/database/ent/hook/hook.go index b5ddfc812..d34b71435 100644 --- a/pkg/database/ent/hook/hook.go +++ b/pkg/database/ent/hook/hook.go @@ -141,6 +141,18 @@ func (f MetricFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, erro return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.MetricMutation", m) } +// The TokenItemFunc type is an adapter to allow the use of ordinary +// function as TokenItem mutator. +type TokenItemFunc func(context.Context, *ent.TokenItemMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f TokenItemFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.TokenItemMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TokenItemMutation", m) +} + // Condition is a hook condition function. type Condition func(context.Context, ent.Mutation) bool diff --git a/pkg/database/ent/migrate/schema.go b/pkg/database/ent/migrate/schema.go index 932c27dd7..f2c63bea4 100644 --- a/pkg/database/ent/migrate/schema.go +++ b/pkg/database/ent/migrate/schema.go @@ -325,6 +325,20 @@ var ( Columns: MetricsColumns, PrimaryKey: []*schema.Column{MetricsColumns[0]}, } + // TokenItemsColumns holds the columns for the "token_items" table. + TokenItemsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "name", Type: field.TypeString, Unique: true}, + {Name: "value", Type: field.TypeString, SchemaType: map[string]string{"mysql": "longtext", "postgres": "text"}}, + } + // TokenItemsTable holds the schema information for the "token_items" table. + TokenItemsTable = &schema.Table{ + Name: "token_items", + Columns: TokenItemsColumns, + PrimaryKey: []*schema.Column{TokenItemsColumns[0]}, + } // AllowListAllowlistItemsColumns holds the columns for the "allow_list_allowlist_items" table. AllowListAllowlistItemsColumns = []*schema.Column{ {Name: "allow_list_id", Type: field.TypeInt}, @@ -363,6 +377,7 @@ var ( MachinesTable, MetaTable, MetricsTable, + TokenItemsTable, AllowListAllowlistItemsTable, } ) diff --git a/pkg/database/ent/mutation.go b/pkg/database/ent/mutation.go index f45bd47a5..2ba523089 100644 --- a/pkg/database/ent/mutation.go +++ b/pkg/database/ent/mutation.go @@ -24,6 +24,7 @@ import ( "github.com/crowdsecurity/crowdsec/pkg/database/ent/metric" "github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate" "github.com/crowdsecurity/crowdsec/pkg/database/ent/schema" + "github.com/crowdsecurity/crowdsec/pkg/database/ent/tokenitem" ) const ( @@ -46,6 +47,7 @@ const ( TypeMachine = "Machine" TypeMeta = "Meta" TypeMetric = "Metric" + TypeTokenItem = "TokenItem" ) // AlertMutation represents an operation that mutates the Alert nodes in the graph. @@ -11197,3 +11199,491 @@ func (m *MetricMutation) ClearEdge(name string) error { func (m *MetricMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Metric edge %s", name) } + +// TokenItemMutation represents an operation that mutates the TokenItem nodes in the graph. +type TokenItemMutation struct { + config + op Op + typ string + id *int + created_at *time.Time + updated_at *time.Time + name *string + value *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*TokenItem, error) + predicates []predicate.TokenItem +} + +var _ ent.Mutation = (*TokenItemMutation)(nil) + +// tokenitemOption allows management of the mutation configuration using functional options. +type tokenitemOption func(*TokenItemMutation) + +// newTokenItemMutation creates new mutation for the TokenItem entity. +func newTokenItemMutation(c config, op Op, opts ...tokenitemOption) *TokenItemMutation { + m := &TokenItemMutation{ + config: c, + op: op, + typ: TypeTokenItem, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTokenItemID sets the ID field of the mutation. +func withTokenItemID(id int) tokenitemOption { + return func(m *TokenItemMutation) { + var ( + err error + once sync.Once + value *TokenItem + ) + m.oldValue = func(ctx context.Context) (*TokenItem, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().TokenItem.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withTokenItem sets the old TokenItem of the mutation. +func withTokenItem(node *TokenItem) tokenitemOption { + return func(m *TokenItemMutation) { + m.oldValue = func(context.Context) (*TokenItem, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m TokenItemMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m TokenItemMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *TokenItemMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *TokenItemMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().TokenItem.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCreatedAt sets the "created_at" field. +func (m *TokenItemMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TokenItemMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the TokenItem entity. +// If the TokenItem object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TokenItemMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *TokenItemMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *TokenItemMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *TokenItemMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the TokenItem entity. +// If the TokenItem object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TokenItemMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *TokenItemMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetName sets the "name" field. +func (m *TokenItemMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *TokenItemMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the TokenItem entity. +// If the TokenItem object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TokenItemMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *TokenItemMutation) ResetName() { + m.name = nil +} + +// SetValue sets the "value" field. +func (m *TokenItemMutation) SetValue(s string) { + m.value = &s +} + +// Value returns the value of the "value" field in the mutation. +func (m *TokenItemMutation) Value() (r string, exists bool) { + v := m.value + if v == nil { + return + } + return *v, true +} + +// OldValue returns the old "value" field's value of the TokenItem entity. +// If the TokenItem object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *TokenItemMutation) OldValue(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldValue is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldValue requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldValue: %w", err) + } + return oldValue.Value, nil +} + +// ResetValue resets all changes to the "value" field. +func (m *TokenItemMutation) ResetValue() { + m.value = nil +} + +// Where appends a list predicates to the TokenItemMutation builder. +func (m *TokenItemMutation) Where(ps ...predicate.TokenItem) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the TokenItemMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TokenItemMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.TokenItem, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *TokenItemMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *TokenItemMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (TokenItem). +func (m *TokenItemMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *TokenItemMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.created_at != nil { + fields = append(fields, tokenitem.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, tokenitem.FieldUpdatedAt) + } + if m.name != nil { + fields = append(fields, tokenitem.FieldName) + } + if m.value != nil { + fields = append(fields, tokenitem.FieldValue) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *TokenItemMutation) Field(name string) (ent.Value, bool) { + switch name { + case tokenitem.FieldCreatedAt: + return m.CreatedAt() + case tokenitem.FieldUpdatedAt: + return m.UpdatedAt() + case tokenitem.FieldName: + return m.Name() + case tokenitem.FieldValue: + return m.Value() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *TokenItemMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case tokenitem.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case tokenitem.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case tokenitem.FieldName: + return m.OldName(ctx) + case tokenitem.FieldValue: + return m.OldValue(ctx) + } + return nil, fmt.Errorf("unknown TokenItem field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *TokenItemMutation) SetField(name string, value ent.Value) error { + switch name { + case tokenitem.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case tokenitem.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case tokenitem.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case tokenitem.FieldValue: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetValue(v) + return nil + } + return fmt.Errorf("unknown TokenItem field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TokenItemMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *TokenItemMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *TokenItemMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown TokenItem numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TokenItemMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TokenItemMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *TokenItemMutation) ClearField(name string) error { + return fmt.Errorf("unknown TokenItem nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *TokenItemMutation) ResetField(name string) error { + switch name { + case tokenitem.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case tokenitem.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case tokenitem.FieldName: + m.ResetName() + return nil + case tokenitem.FieldValue: + m.ResetValue() + return nil + } + return fmt.Errorf("unknown TokenItem field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TokenItemMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TokenItemMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TokenItemMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TokenItemMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TokenItemMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TokenItemMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *TokenItemMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown TokenItem unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *TokenItemMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown TokenItem edge %s", name) +} diff --git a/pkg/database/ent/predicate/predicate.go b/pkg/database/ent/predicate/predicate.go index 97e574aa1..ae18e9cc2 100644 --- a/pkg/database/ent/predicate/predicate.go +++ b/pkg/database/ent/predicate/predicate.go @@ -38,3 +38,6 @@ type Meta func(*sql.Selector) // Metric is the predicate function for metric builders. type Metric func(*sql.Selector) + +// TokenItem is the predicate function for tokenitem builders. +type TokenItem func(*sql.Selector) diff --git a/pkg/database/ent/runtime.go b/pkg/database/ent/runtime.go index 989e67fda..bc93a3f89 100644 --- a/pkg/database/ent/runtime.go +++ b/pkg/database/ent/runtime.go @@ -16,6 +16,7 @@ import ( "github.com/crowdsecurity/crowdsec/pkg/database/ent/machine" "github.com/crowdsecurity/crowdsec/pkg/database/ent/meta" "github.com/crowdsecurity/crowdsec/pkg/database/ent/schema" + "github.com/crowdsecurity/crowdsec/pkg/database/ent/tokenitem" ) // The init function reads all schema descriptors with runtime code @@ -200,4 +201,16 @@ func init() { metaDescValue := metaFields[3].Descriptor() // meta.ValueValidator is a validator for the "value" field. It is called by the builders before save. meta.ValueValidator = metaDescValue.Validators[0].(func(string) error) + tokenitemFields := schema.TokenItem{}.Fields() + _ = tokenitemFields + // tokenitemDescCreatedAt is the schema descriptor for created_at field. + tokenitemDescCreatedAt := tokenitemFields[0].Descriptor() + // tokenitem.DefaultCreatedAt holds the default value on creation for the created_at field. + tokenitem.DefaultCreatedAt = tokenitemDescCreatedAt.Default.(func() time.Time) + // tokenitemDescUpdatedAt is the schema descriptor for updated_at field. + tokenitemDescUpdatedAt := tokenitemFields[1].Descriptor() + // tokenitem.DefaultUpdatedAt holds the default value on creation for the updated_at field. + tokenitem.DefaultUpdatedAt = tokenitemDescUpdatedAt.Default.(func() time.Time) + // tokenitem.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + tokenitem.UpdateDefaultUpdatedAt = tokenitemDescUpdatedAt.UpdateDefault.(func() time.Time) } diff --git a/pkg/database/ent/schema/config.go b/pkg/database/ent/schema/config.go index d526db25a..28e063ea8 100644 --- a/pkg/database/ent/schema/config.go +++ b/pkg/database/ent/schema/config.go @@ -2,6 +2,7 @@ package schema import ( "entgo.io/ent" + "entgo.io/ent/dialect" "entgo.io/ent/schema/field" "github.com/crowdsecurity/crowdsec/pkg/types" @@ -29,3 +30,29 @@ func (ConfigItem) Fields() []ent.Field { func (ConfigItem) Edges() []ent.Edge { return nil } + +type TokenItem struct { + ent.Schema +} + +func (TokenItem) Fields() []ent.Field { + return []ent.Field{ + field.Time("created_at"). + Default(types.UtcNow). + Immutable(). + StructTag(`json:"created_at"`), + field.Time("updated_at"). + Default(types.UtcNow). + UpdateDefault(types.UtcNow).StructTag(`json:"updated_at"`), + field.String("name").Unique().StructTag(`json:"name"`).Immutable(), + field.String("value"). + SchemaType(map[string]string{ + dialect.MySQL: "longtext", + dialect.Postgres: "text", + }).StructTag(`json:"value"`), // a json object + } +} + +func (TokenItem) Edges() []ent.Edge { + return nil +} diff --git a/pkg/database/ent/tokenitem.go b/pkg/database/ent/tokenitem.go new file mode 100644 index 000000000..b5b42052f --- /dev/null +++ b/pkg/database/ent/tokenitem.go @@ -0,0 +1,139 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/crowdsecurity/crowdsec/pkg/database/ent/tokenitem" +) + +// TokenItem is the model entity for the TokenItem schema. +type TokenItem struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at"` + // Name holds the value of the "name" field. + Name string `json:"name"` + // Value holds the value of the "value" field. + Value string `json:"value"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*TokenItem) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case tokenitem.FieldID: + values[i] = new(sql.NullInt64) + case tokenitem.FieldName, tokenitem.FieldValue: + values[i] = new(sql.NullString) + case tokenitem.FieldCreatedAt, tokenitem.FieldUpdatedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the TokenItem fields. +func (ti *TokenItem) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case tokenitem.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + ti.ID = int(value.Int64) + case tokenitem.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 { + ti.CreatedAt = value.Time + } + case tokenitem.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 { + ti.UpdatedAt = value.Time + } + case tokenitem.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + ti.Name = value.String + } + case tokenitem.FieldValue: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field value", values[i]) + } else if value.Valid { + ti.Value = value.String + } + default: + ti.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// GetValue returns the ent.Value that was dynamically selected and assigned to the TokenItem. +// This includes values selected through modifiers, order, etc. +func (ti *TokenItem) GetValue(name string) (ent.Value, error) { + return ti.selectValues.Get(name) +} + +// Update returns a builder for updating this TokenItem. +// Note that you need to call TokenItem.Unwrap() before calling this method if this TokenItem +// was returned from a transaction, and the transaction was committed or rolled back. +func (ti *TokenItem) Update() *TokenItemUpdateOne { + return NewTokenItemClient(ti.config).UpdateOne(ti) +} + +// Unwrap unwraps the TokenItem 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 (ti *TokenItem) Unwrap() *TokenItem { + _tx, ok := ti.config.driver.(*txDriver) + if !ok { + panic("ent: TokenItem is not a transactional entity") + } + ti.config.driver = _tx.drv + return ti +} + +// String implements the fmt.Stringer. +func (ti *TokenItem) String() string { + var builder strings.Builder + builder.WriteString("TokenItem(") + builder.WriteString(fmt.Sprintf("id=%v, ", ti.ID)) + builder.WriteString("created_at=") + builder.WriteString(ti.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(ti.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(ti.Name) + builder.WriteString(", ") + builder.WriteString("value=") + builder.WriteString(ti.Value) + builder.WriteByte(')') + return builder.String() +} + +// TokenItems is a parsable slice of TokenItem. +type TokenItems []*TokenItem diff --git a/pkg/database/ent/tokenitem/tokenitem.go b/pkg/database/ent/tokenitem/tokenitem.go new file mode 100644 index 000000000..0786a1e09 --- /dev/null +++ b/pkg/database/ent/tokenitem/tokenitem.go @@ -0,0 +1,82 @@ +// Code generated by ent, DO NOT EDIT. + +package tokenitem + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the tokenitem type in the database. + Label = "token_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" + // FieldValue holds the string denoting the value field in the database. + FieldValue = "value" + // Table holds the table name of the tokenitem in the database. + Table = "token_items" +) + +// Columns holds all SQL columns for tokenitem fields. +var Columns = []string{ + FieldID, + FieldCreatedAt, + FieldUpdatedAt, + FieldName, + FieldValue, +} + +// 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 +) + +// OrderOption defines the ordering options for the TokenItem queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByValue orders the results by the value field. +func ByValue(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldValue, opts...).ToFunc() +} diff --git a/pkg/database/ent/tokenitem/where.go b/pkg/database/ent/tokenitem/where.go new file mode 100644 index 000000000..033da397d --- /dev/null +++ b/pkg/database/ent/tokenitem/where.go @@ -0,0 +1,300 @@ +// Code generated by ent, DO NOT EDIT. + +package tokenitem + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.TokenItem { + return predicate.TokenItem(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.TokenItem { + return predicate.TokenItem(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.TokenItem { + return predicate.TokenItem(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.TokenItem { + return predicate.TokenItem(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.TokenItem { + return predicate.TokenItem(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.TokenItem { + return predicate.TokenItem(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.TokenItem { + return predicate.TokenItem(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.TokenItem { + return predicate.TokenItem(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.TokenItem { + return predicate.TokenItem(sql.FieldLTE(FieldID, id)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldEQ(FieldName, v)) +} + +// Value applies equality check predicate on the "value" field. It's identical to ValueEQ. +func Value(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldEQ(FieldValue, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.TokenItem { + return predicate.TokenItem(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldContainsFold(FieldName, v)) +} + +// ValueEQ applies the EQ predicate on the "value" field. +func ValueEQ(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldEQ(FieldValue, v)) +} + +// ValueNEQ applies the NEQ predicate on the "value" field. +func ValueNEQ(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldNEQ(FieldValue, v)) +} + +// ValueIn applies the In predicate on the "value" field. +func ValueIn(vs ...string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldIn(FieldValue, vs...)) +} + +// ValueNotIn applies the NotIn predicate on the "value" field. +func ValueNotIn(vs ...string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldNotIn(FieldValue, vs...)) +} + +// ValueGT applies the GT predicate on the "value" field. +func ValueGT(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldGT(FieldValue, v)) +} + +// ValueGTE applies the GTE predicate on the "value" field. +func ValueGTE(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldGTE(FieldValue, v)) +} + +// ValueLT applies the LT predicate on the "value" field. +func ValueLT(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldLT(FieldValue, v)) +} + +// ValueLTE applies the LTE predicate on the "value" field. +func ValueLTE(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldLTE(FieldValue, v)) +} + +// ValueContains applies the Contains predicate on the "value" field. +func ValueContains(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldContains(FieldValue, v)) +} + +// ValueHasPrefix applies the HasPrefix predicate on the "value" field. +func ValueHasPrefix(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldHasPrefix(FieldValue, v)) +} + +// ValueHasSuffix applies the HasSuffix predicate on the "value" field. +func ValueHasSuffix(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldHasSuffix(FieldValue, v)) +} + +// ValueEqualFold applies the EqualFold predicate on the "value" field. +func ValueEqualFold(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldEqualFold(FieldValue, v)) +} + +// ValueContainsFold applies the ContainsFold predicate on the "value" field. +func ValueContainsFold(v string) predicate.TokenItem { + return predicate.TokenItem(sql.FieldContainsFold(FieldValue, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.TokenItem) predicate.TokenItem { + return predicate.TokenItem(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.TokenItem) predicate.TokenItem { + return predicate.TokenItem(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.TokenItem) predicate.TokenItem { + return predicate.TokenItem(sql.NotPredicates(p)) +} diff --git a/pkg/database/ent/tokenitem_create.go b/pkg/database/ent/tokenitem_create.go new file mode 100644 index 000000000..6dd51e0a9 --- /dev/null +++ b/pkg/database/ent/tokenitem_create.go @@ -0,0 +1,253 @@ +// 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/crowdsecurity/crowdsec/pkg/database/ent/tokenitem" +) + +// TokenItemCreate is the builder for creating a TokenItem entity. +type TokenItemCreate struct { + config + mutation *TokenItemMutation + hooks []Hook +} + +// SetCreatedAt sets the "created_at" field. +func (tic *TokenItemCreate) SetCreatedAt(t time.Time) *TokenItemCreate { + tic.mutation.SetCreatedAt(t) + return tic +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (tic *TokenItemCreate) SetNillableCreatedAt(t *time.Time) *TokenItemCreate { + if t != nil { + tic.SetCreatedAt(*t) + } + return tic +} + +// SetUpdatedAt sets the "updated_at" field. +func (tic *TokenItemCreate) SetUpdatedAt(t time.Time) *TokenItemCreate { + tic.mutation.SetUpdatedAt(t) + return tic +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (tic *TokenItemCreate) SetNillableUpdatedAt(t *time.Time) *TokenItemCreate { + if t != nil { + tic.SetUpdatedAt(*t) + } + return tic +} + +// SetName sets the "name" field. +func (tic *TokenItemCreate) SetName(s string) *TokenItemCreate { + tic.mutation.SetName(s) + return tic +} + +// SetValue sets the "value" field. +func (tic *TokenItemCreate) SetValue(s string) *TokenItemCreate { + tic.mutation.SetValue(s) + return tic +} + +// Mutation returns the TokenItemMutation object of the builder. +func (tic *TokenItemCreate) Mutation() *TokenItemMutation { + return tic.mutation +} + +// Save creates the TokenItem in the database. +func (tic *TokenItemCreate) Save(ctx context.Context) (*TokenItem, error) { + tic.defaults() + return withHooks(ctx, tic.sqlSave, tic.mutation, tic.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (tic *TokenItemCreate) SaveX(ctx context.Context) *TokenItem { + v, err := tic.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tic *TokenItemCreate) Exec(ctx context.Context) error { + _, err := tic.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tic *TokenItemCreate) ExecX(ctx context.Context) { + if err := tic.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (tic *TokenItemCreate) defaults() { + if _, ok := tic.mutation.CreatedAt(); !ok { + v := tokenitem.DefaultCreatedAt() + tic.mutation.SetCreatedAt(v) + } + if _, ok := tic.mutation.UpdatedAt(); !ok { + v := tokenitem.DefaultUpdatedAt() + tic.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (tic *TokenItemCreate) check() error { + if _, ok := tic.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "TokenItem.created_at"`)} + } + if _, ok := tic.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "TokenItem.updated_at"`)} + } + if _, ok := tic.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "TokenItem.name"`)} + } + if _, ok := tic.mutation.Value(); !ok { + return &ValidationError{Name: "value", err: errors.New(`ent: missing required field "TokenItem.value"`)} + } + return nil +} + +func (tic *TokenItemCreate) sqlSave(ctx context.Context) (*TokenItem, error) { + if err := tic.check(); err != nil { + return nil, err + } + _node, _spec := tic.createSpec() + if err := sqlgraph.CreateNode(ctx, tic.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + tic.mutation.id = &_node.ID + tic.mutation.done = true + return _node, nil +} + +func (tic *TokenItemCreate) createSpec() (*TokenItem, *sqlgraph.CreateSpec) { + var ( + _node = &TokenItem{config: tic.config} + _spec = sqlgraph.NewCreateSpec(tokenitem.Table, sqlgraph.NewFieldSpec(tokenitem.FieldID, field.TypeInt)) + ) + if value, ok := tic.mutation.CreatedAt(); ok { + _spec.SetField(tokenitem.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := tic.mutation.UpdatedAt(); ok { + _spec.SetField(tokenitem.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := tic.mutation.Name(); ok { + _spec.SetField(tokenitem.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := tic.mutation.Value(); ok { + _spec.SetField(tokenitem.FieldValue, field.TypeString, value) + _node.Value = value + } + return _node, _spec +} + +// TokenItemCreateBulk is the builder for creating many TokenItem entities in bulk. +type TokenItemCreateBulk struct { + config + err error + builders []*TokenItemCreate +} + +// Save creates the TokenItem entities in the database. +func (ticb *TokenItemCreateBulk) Save(ctx context.Context) ([]*TokenItem, error) { + if ticb.err != nil { + return nil, ticb.err + } + specs := make([]*sqlgraph.CreateSpec, len(ticb.builders)) + nodes := make([]*TokenItem, len(ticb.builders)) + mutators := make([]Mutator, len(ticb.builders)) + for i := range ticb.builders { + func(i int, root context.Context) { + builder := ticb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TokenItemMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, ticb.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, ticb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(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, ticb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ticb *TokenItemCreateBulk) SaveX(ctx context.Context) []*TokenItem { + v, err := ticb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ticb *TokenItemCreateBulk) Exec(ctx context.Context) error { + _, err := ticb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ticb *TokenItemCreateBulk) ExecX(ctx context.Context) { + if err := ticb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/pkg/database/ent/tokenitem_delete.go b/pkg/database/ent/tokenitem_delete.go new file mode 100644 index 000000000..abca57788 --- /dev/null +++ b/pkg/database/ent/tokenitem_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate" + "github.com/crowdsecurity/crowdsec/pkg/database/ent/tokenitem" +) + +// TokenItemDelete is the builder for deleting a TokenItem entity. +type TokenItemDelete struct { + config + hooks []Hook + mutation *TokenItemMutation +} + +// Where appends a list predicates to the TokenItemDelete builder. +func (tid *TokenItemDelete) Where(ps ...predicate.TokenItem) *TokenItemDelete { + tid.mutation.Where(ps...) + return tid +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (tid *TokenItemDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, tid.sqlExec, tid.mutation, tid.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (tid *TokenItemDelete) ExecX(ctx context.Context) int { + n, err := tid.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (tid *TokenItemDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(tokenitem.Table, sqlgraph.NewFieldSpec(tokenitem.FieldID, field.TypeInt)) + if ps := tid.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, tid.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + tid.mutation.done = true + return affected, err +} + +// TokenItemDeleteOne is the builder for deleting a single TokenItem entity. +type TokenItemDeleteOne struct { + tid *TokenItemDelete +} + +// Where appends a list predicates to the TokenItemDelete builder. +func (tido *TokenItemDeleteOne) Where(ps ...predicate.TokenItem) *TokenItemDeleteOne { + tido.tid.mutation.Where(ps...) + return tido +} + +// Exec executes the deletion query. +func (tido *TokenItemDeleteOne) Exec(ctx context.Context) error { + n, err := tido.tid.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{tokenitem.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (tido *TokenItemDeleteOne) ExecX(ctx context.Context) { + if err := tido.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/pkg/database/ent/tokenitem_query.go b/pkg/database/ent/tokenitem_query.go new file mode 100644 index 000000000..cd353c53d --- /dev/null +++ b/pkg/database/ent/tokenitem_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate" + "github.com/crowdsecurity/crowdsec/pkg/database/ent/tokenitem" +) + +// TokenItemQuery is the builder for querying TokenItem entities. +type TokenItemQuery struct { + config + ctx *QueryContext + order []tokenitem.OrderOption + inters []Interceptor + predicates []predicate.TokenItem + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the TokenItemQuery builder. +func (tiq *TokenItemQuery) Where(ps ...predicate.TokenItem) *TokenItemQuery { + tiq.predicates = append(tiq.predicates, ps...) + return tiq +} + +// Limit the number of records to be returned by this query. +func (tiq *TokenItemQuery) Limit(limit int) *TokenItemQuery { + tiq.ctx.Limit = &limit + return tiq +} + +// Offset to start from. +func (tiq *TokenItemQuery) Offset(offset int) *TokenItemQuery { + tiq.ctx.Offset = &offset + return tiq +} + +// 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 (tiq *TokenItemQuery) Unique(unique bool) *TokenItemQuery { + tiq.ctx.Unique = &unique + return tiq +} + +// Order specifies how the records should be ordered. +func (tiq *TokenItemQuery) Order(o ...tokenitem.OrderOption) *TokenItemQuery { + tiq.order = append(tiq.order, o...) + return tiq +} + +// First returns the first TokenItem entity from the query. +// Returns a *NotFoundError when no TokenItem was found. +func (tiq *TokenItemQuery) First(ctx context.Context) (*TokenItem, error) { + nodes, err := tiq.Limit(1).All(setContextOp(ctx, tiq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{tokenitem.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (tiq *TokenItemQuery) FirstX(ctx context.Context) *TokenItem { + node, err := tiq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first TokenItem ID from the query. +// Returns a *NotFoundError when no TokenItem ID was found. +func (tiq *TokenItemQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = tiq.Limit(1).IDs(setContextOp(ctx, tiq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{tokenitem.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (tiq *TokenItemQuery) FirstIDX(ctx context.Context) int { + id, err := tiq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single TokenItem entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one TokenItem entity is found. +// Returns a *NotFoundError when no TokenItem entities are found. +func (tiq *TokenItemQuery) Only(ctx context.Context) (*TokenItem, error) { + nodes, err := tiq.Limit(2).All(setContextOp(ctx, tiq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{tokenitem.Label} + default: + return nil, &NotSingularError{tokenitem.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (tiq *TokenItemQuery) OnlyX(ctx context.Context) *TokenItem { + node, err := tiq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only TokenItem ID in the query. +// Returns a *NotSingularError when more than one TokenItem ID is found. +// Returns a *NotFoundError when no entities are found. +func (tiq *TokenItemQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = tiq.Limit(2).IDs(setContextOp(ctx, tiq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{tokenitem.Label} + default: + err = &NotSingularError{tokenitem.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (tiq *TokenItemQuery) OnlyIDX(ctx context.Context) int { + id, err := tiq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of TokenItems. +func (tiq *TokenItemQuery) All(ctx context.Context) ([]*TokenItem, error) { + ctx = setContextOp(ctx, tiq.ctx, ent.OpQueryAll) + if err := tiq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*TokenItem, *TokenItemQuery]() + return withInterceptors[[]*TokenItem](ctx, tiq, qr, tiq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (tiq *TokenItemQuery) AllX(ctx context.Context) []*TokenItem { + nodes, err := tiq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of TokenItem IDs. +func (tiq *TokenItemQuery) IDs(ctx context.Context) (ids []int, err error) { + if tiq.ctx.Unique == nil && tiq.path != nil { + tiq.Unique(true) + } + ctx = setContextOp(ctx, tiq.ctx, ent.OpQueryIDs) + if err = tiq.Select(tokenitem.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (tiq *TokenItemQuery) IDsX(ctx context.Context) []int { + ids, err := tiq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (tiq *TokenItemQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, tiq.ctx, ent.OpQueryCount) + if err := tiq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, tiq, querierCount[*TokenItemQuery](), tiq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (tiq *TokenItemQuery) CountX(ctx context.Context) int { + count, err := tiq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (tiq *TokenItemQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, tiq.ctx, ent.OpQueryExist) + switch _, err := tiq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (tiq *TokenItemQuery) ExistX(ctx context.Context) bool { + exist, err := tiq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the TokenItemQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (tiq *TokenItemQuery) Clone() *TokenItemQuery { + if tiq == nil { + return nil + } + return &TokenItemQuery{ + config: tiq.config, + ctx: tiq.ctx.Clone(), + order: append([]tokenitem.OrderOption{}, tiq.order...), + inters: append([]Interceptor{}, tiq.inters...), + predicates: append([]predicate.TokenItem{}, tiq.predicates...), + // clone intermediate query. + sql: tiq.sql.Clone(), + path: tiq.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// CreatedAt time.Time `json:"created_at"` +// Count int `json:"count,omitempty"` +// } +// +// client.TokenItem.Query(). +// GroupBy(tokenitem.FieldCreatedAt). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (tiq *TokenItemQuery) GroupBy(field string, fields ...string) *TokenItemGroupBy { + tiq.ctx.Fields = append([]string{field}, fields...) + grbuild := &TokenItemGroupBy{build: tiq} + grbuild.flds = &tiq.ctx.Fields + grbuild.label = tokenitem.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// CreatedAt time.Time `json:"created_at"` +// } +// +// client.TokenItem.Query(). +// Select(tokenitem.FieldCreatedAt). +// Scan(ctx, &v) +func (tiq *TokenItemQuery) Select(fields ...string) *TokenItemSelect { + tiq.ctx.Fields = append(tiq.ctx.Fields, fields...) + sbuild := &TokenItemSelect{TokenItemQuery: tiq} + sbuild.label = tokenitem.Label + sbuild.flds, sbuild.scan = &tiq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a TokenItemSelect configured with the given aggregations. +func (tiq *TokenItemQuery) Aggregate(fns ...AggregateFunc) *TokenItemSelect { + return tiq.Select().Aggregate(fns...) +} + +func (tiq *TokenItemQuery) prepareQuery(ctx context.Context) error { + for _, inter := range tiq.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, tiq); err != nil { + return err + } + } + } + for _, f := range tiq.ctx.Fields { + if !tokenitem.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if tiq.path != nil { + prev, err := tiq.path(ctx) + if err != nil { + return err + } + tiq.sql = prev + } + return nil +} + +func (tiq *TokenItemQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*TokenItem, error) { + var ( + nodes = []*TokenItem{} + _spec = tiq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*TokenItem).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &TokenItem{config: tiq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, tiq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (tiq *TokenItemQuery) sqlCount(ctx context.Context) (int, error) { + _spec := tiq.querySpec() + _spec.Node.Columns = tiq.ctx.Fields + if len(tiq.ctx.Fields) > 0 { + _spec.Unique = tiq.ctx.Unique != nil && *tiq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, tiq.driver, _spec) +} + +func (tiq *TokenItemQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(tokenitem.Table, tokenitem.Columns, sqlgraph.NewFieldSpec(tokenitem.FieldID, field.TypeInt)) + _spec.From = tiq.sql + if unique := tiq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if tiq.path != nil { + _spec.Unique = true + } + if fields := tiq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, tokenitem.FieldID) + for i := range fields { + if fields[i] != tokenitem.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := tiq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := tiq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := tiq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := tiq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (tiq *TokenItemQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(tiq.driver.Dialect()) + t1 := builder.Table(tokenitem.Table) + columns := tiq.ctx.Fields + if len(columns) == 0 { + columns = tokenitem.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if tiq.sql != nil { + selector = tiq.sql + selector.Select(selector.Columns(columns...)...) + } + if tiq.ctx.Unique != nil && *tiq.ctx.Unique { + selector.Distinct() + } + for _, p := range tiq.predicates { + p(selector) + } + for _, p := range tiq.order { + p(selector) + } + if offset := tiq.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := tiq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// TokenItemGroupBy is the group-by builder for TokenItem entities. +type TokenItemGroupBy struct { + selector + build *TokenItemQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (tigb *TokenItemGroupBy) Aggregate(fns ...AggregateFunc) *TokenItemGroupBy { + tigb.fns = append(tigb.fns, fns...) + return tigb +} + +// Scan applies the selector query and scans the result into the given value. +func (tigb *TokenItemGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, tigb.build.ctx, ent.OpQueryGroupBy) + if err := tigb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TokenItemQuery, *TokenItemGroupBy](ctx, tigb.build, tigb, tigb.build.inters, v) +} + +func (tigb *TokenItemGroupBy) sqlScan(ctx context.Context, root *TokenItemQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(tigb.fns)) + for _, fn := range tigb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*tigb.flds)+len(tigb.fns)) + for _, f := range *tigb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*tigb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := tigb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// TokenItemSelect is the builder for selecting fields of TokenItem entities. +type TokenItemSelect struct { + *TokenItemQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (tis *TokenItemSelect) Aggregate(fns ...AggregateFunc) *TokenItemSelect { + tis.fns = append(tis.fns, fns...) + return tis +} + +// Scan applies the selector query and scans the result into the given value. +func (tis *TokenItemSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, tis.ctx, ent.OpQuerySelect) + if err := tis.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TokenItemQuery, *TokenItemSelect](ctx, tis.TokenItemQuery, tis, tis.inters, v) +} + +func (tis *TokenItemSelect) sqlScan(ctx context.Context, root *TokenItemQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(tis.fns)) + for _, fn := range tis.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*tis.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := tis.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/pkg/database/ent/tokenitem_update.go b/pkg/database/ent/tokenitem_update.go new file mode 100644 index 000000000..dd0f2fe78 --- /dev/null +++ b/pkg/database/ent/tokenitem_update.go @@ -0,0 +1,246 @@ +// 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/crowdsecurity/crowdsec/pkg/database/ent/predicate" + "github.com/crowdsecurity/crowdsec/pkg/database/ent/tokenitem" +) + +// TokenItemUpdate is the builder for updating TokenItem entities. +type TokenItemUpdate struct { + config + hooks []Hook + mutation *TokenItemMutation +} + +// Where appends a list predicates to the TokenItemUpdate builder. +func (tiu *TokenItemUpdate) Where(ps ...predicate.TokenItem) *TokenItemUpdate { + tiu.mutation.Where(ps...) + return tiu +} + +// SetUpdatedAt sets the "updated_at" field. +func (tiu *TokenItemUpdate) SetUpdatedAt(t time.Time) *TokenItemUpdate { + tiu.mutation.SetUpdatedAt(t) + return tiu +} + +// SetValue sets the "value" field. +func (tiu *TokenItemUpdate) SetValue(s string) *TokenItemUpdate { + tiu.mutation.SetValue(s) + return tiu +} + +// SetNillableValue sets the "value" field if the given value is not nil. +func (tiu *TokenItemUpdate) SetNillableValue(s *string) *TokenItemUpdate { + if s != nil { + tiu.SetValue(*s) + } + return tiu +} + +// Mutation returns the TokenItemMutation object of the builder. +func (tiu *TokenItemUpdate) Mutation() *TokenItemMutation { + return tiu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (tiu *TokenItemUpdate) Save(ctx context.Context) (int, error) { + tiu.defaults() + return withHooks(ctx, tiu.sqlSave, tiu.mutation, tiu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (tiu *TokenItemUpdate) SaveX(ctx context.Context) int { + affected, err := tiu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (tiu *TokenItemUpdate) Exec(ctx context.Context) error { + _, err := tiu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tiu *TokenItemUpdate) ExecX(ctx context.Context) { + if err := tiu.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (tiu *TokenItemUpdate) defaults() { + if _, ok := tiu.mutation.UpdatedAt(); !ok { + v := tokenitem.UpdateDefaultUpdatedAt() + tiu.mutation.SetUpdatedAt(v) + } +} + +func (tiu *TokenItemUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(tokenitem.Table, tokenitem.Columns, sqlgraph.NewFieldSpec(tokenitem.FieldID, field.TypeInt)) + if ps := tiu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tiu.mutation.UpdatedAt(); ok { + _spec.SetField(tokenitem.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := tiu.mutation.Value(); ok { + _spec.SetField(tokenitem.FieldValue, field.TypeString, value) + } + if n, err = sqlgraph.UpdateNodes(ctx, tiu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{tokenitem.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + tiu.mutation.done = true + return n, nil +} + +// TokenItemUpdateOne is the builder for updating a single TokenItem entity. +type TokenItemUpdateOne struct { + config + fields []string + hooks []Hook + mutation *TokenItemMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (tiuo *TokenItemUpdateOne) SetUpdatedAt(t time.Time) *TokenItemUpdateOne { + tiuo.mutation.SetUpdatedAt(t) + return tiuo +} + +// SetValue sets the "value" field. +func (tiuo *TokenItemUpdateOne) SetValue(s string) *TokenItemUpdateOne { + tiuo.mutation.SetValue(s) + return tiuo +} + +// SetNillableValue sets the "value" field if the given value is not nil. +func (tiuo *TokenItemUpdateOne) SetNillableValue(s *string) *TokenItemUpdateOne { + if s != nil { + tiuo.SetValue(*s) + } + return tiuo +} + +// Mutation returns the TokenItemMutation object of the builder. +func (tiuo *TokenItemUpdateOne) Mutation() *TokenItemMutation { + return tiuo.mutation +} + +// Where appends a list predicates to the TokenItemUpdate builder. +func (tiuo *TokenItemUpdateOne) Where(ps ...predicate.TokenItem) *TokenItemUpdateOne { + tiuo.mutation.Where(ps...) + return tiuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (tiuo *TokenItemUpdateOne) Select(field string, fields ...string) *TokenItemUpdateOne { + tiuo.fields = append([]string{field}, fields...) + return tiuo +} + +// Save executes the query and returns the updated TokenItem entity. +func (tiuo *TokenItemUpdateOne) Save(ctx context.Context) (*TokenItem, error) { + tiuo.defaults() + return withHooks(ctx, tiuo.sqlSave, tiuo.mutation, tiuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (tiuo *TokenItemUpdateOne) SaveX(ctx context.Context) *TokenItem { + node, err := tiuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (tiuo *TokenItemUpdateOne) Exec(ctx context.Context) error { + _, err := tiuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tiuo *TokenItemUpdateOne) ExecX(ctx context.Context) { + if err := tiuo.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (tiuo *TokenItemUpdateOne) defaults() { + if _, ok := tiuo.mutation.UpdatedAt(); !ok { + v := tokenitem.UpdateDefaultUpdatedAt() + tiuo.mutation.SetUpdatedAt(v) + } +} + +func (tiuo *TokenItemUpdateOne) sqlSave(ctx context.Context) (_node *TokenItem, err error) { + _spec := sqlgraph.NewUpdateSpec(tokenitem.Table, tokenitem.Columns, sqlgraph.NewFieldSpec(tokenitem.FieldID, field.TypeInt)) + id, ok := tiuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "TokenItem.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := tiuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, tokenitem.FieldID) + for _, f := range fields { + if !tokenitem.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != tokenitem.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := tiuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tiuo.mutation.UpdatedAt(); ok { + _spec.SetField(tokenitem.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := tiuo.mutation.Value(); ok { + _spec.SetField(tokenitem.FieldValue, field.TypeString, value) + } + _node = &TokenItem{config: tiuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, tiuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{tokenitem.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + tiuo.mutation.done = true + return _node, nil +} diff --git a/pkg/database/ent/tx.go b/pkg/database/ent/tx.go index 69983beeb..4e8a5e555 100644 --- a/pkg/database/ent/tx.go +++ b/pkg/database/ent/tx.go @@ -34,6 +34,8 @@ type Tx struct { Meta *MetaClient // Metric is the client for interacting with the Metric builders. Metric *MetricClient + // TokenItem is the client for interacting with the TokenItem builders. + TokenItem *TokenItemClient // lazily loaded. client *Client @@ -176,6 +178,7 @@ func (tx *Tx) init() { tx.Machine = NewMachineClient(tx.config) tx.Meta = NewMetaClient(tx.config) tx.Metric = NewMetricClient(tx.config) + tx.TokenItem = NewTokenItemClient(tx.config) } // txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.