From 049fefed75ff7ec2e1c364a7363181398e4dfd8f Mon Sep 17 00:00:00 2001 From: Achim Rohn Date: Sun, 16 Nov 2025 19:54:42 +0100 Subject: [PATCH] Add the event service --- event/event.go | 62 +++ htmx_route.go | 6 + queue/general_queue.go | 5 +- schema/ent/client.go | 149 +++++- schema/ent/ent.go | 2 + schema/ent/event.go | 144 ++++++ schema/ent/event/event.go | 73 +++ schema/ent/event/where.go | 230 +++++++++ schema/ent/event_create.go | 241 ++++++++++ schema/ent/event_delete.go | 88 ++++ schema/ent/event_query.go | 527 ++++++++++++++++++++ schema/ent/event_update.go | 281 +++++++++++ schema/ent/generalqueue.go | 15 +- schema/ent/generalqueue/generalqueue.go | 8 + schema/ent/generalqueue/where.go | 45 ++ schema/ent/generalqueue_create.go | 13 + schema/ent/generalqueue_update.go | 54 +++ schema/ent/hook/hook.go | 12 + schema/ent/migrate/schema.go | 16 + schema/ent/mutation.go | 615 +++++++++++++++++++++++- schema/ent/pagination_query.go | 38 ++ schema/ent/predicate/predicate.go | 3 + schema/ent/runtime.go | 9 + schema/ent/schema/event.go | 23 + schema/ent/schema/general_queue.go | 1 + schema/ent/tx.go | 5 +- 26 files changed, 2656 insertions(+), 9 deletions(-) create mode 100644 event/event.go create mode 100644 schema/ent/event.go create mode 100644 schema/ent/event/event.go create mode 100644 schema/ent/event/where.go create mode 100644 schema/ent/event_create.go create mode 100644 schema/ent/event_delete.go create mode 100644 schema/ent/event_query.go create mode 100644 schema/ent/event_update.go create mode 100644 schema/ent/schema/event.go diff --git a/event/event.go b/event/event.go new file mode 100644 index 0000000..7479ff9 --- /dev/null +++ b/event/event.go @@ -0,0 +1,62 @@ +package event + +import ( + "context" + "fmt" + + . "git.gorlug.de/code/ersteller" + "git.gorlug.de/code/ersteller/schema/ent" +) + +type Service struct { + entClient *ent.Client +} + +func NewService(entClient *ent.Client) *Service { + return &Service{ + entClient: entClient, + } +} + +func (s *Service) Create(htmxContext HtmxContext, name string, data any) error { + return Create(s.entClient, htmxContext, name, data) +} + +func Should(err error) { + if err != nil { + Error("should not happen: ", err) + } +} + +func Create(entClient *ent.Client, c HtmxContext, name string, data any) error { + Debug("event", name, data) + hasAuth, authContext := c.GetAuthContext() + if !hasAuth { + return fmt.Errorf("failed to get auth context") + } + return CreateWithSession(entClient, c.GetGoContext(), authContext, name, data) +} + +func CreateWithSession(entClient *ent.Client, ctx context.Context, + auth AuthContext, name string, data any) error { + Debug("event", name, data) + var mapData JSONB + if data == nil { + mapData = make(JSONB) + } else { + mappedStruct, err := StructToMap(data) + if err != nil { + return fmt.Errorf("failed to map data to map for event create: %w", err) + } + mapData = mappedStruct + } + _, err := entClient.Event.Create(). + SetUserID(auth.UserId). + SetName(name). + SetData(mapData). + Save(ctx) + if err != nil { + return fmt.Errorf("failed to create event: %w", err) + } + return nil +} diff --git a/htmx_route.go b/htmx_route.go index 01036c5..178cce8 100644 --- a/htmx_route.go +++ b/htmx_route.go @@ -1,6 +1,7 @@ package ersteller import ( + "context" "encoding/json" "fmt" "net/http" @@ -37,6 +38,7 @@ type HtmxContext interface { GetAllRoutes() []HtmxRoute GetQueryParams() []HtmxPathParam GetAuthContext() (bool, AuthContext) + GetGoContext() context.Context } type HtmxContextImpl struct { @@ -48,6 +50,10 @@ type HtmxContextImpl struct { routes []HtmxRoute } +func (c *HtmxContextImpl) GetGoContext() context.Context { + return c.req.Context() +} + func (c *HtmxContextImpl) GetAuthContext() (bool, AuthContext) { authCtx := c.req.Context().Value(AuthContextKey) if authCtx == nil { diff --git a/queue/general_queue.go b/queue/general_queue.go index 29936e0..d99d5c3 100644 --- a/queue/general_queue.go +++ b/queue/general_queue.go @@ -284,7 +284,7 @@ func (q *GeneralQueue) processNext(ctx context.Context, handler GeneralQueueHand } // Enqueue adds a new job to the queue -func (q *GeneralQueue) Enqueue(ctx context.Context, payload any, maxRetries int, userId int, groupId int) (*ent.GeneralQueue, error) { +func (q *GeneralQueue) Enqueue(ctx context.Context, payload any, maxRetries int, userId int) (*ent.GeneralQueue, error) { now := time.Now() payloadMap, err := StructToMap(payload) @@ -300,7 +300,8 @@ func (q *GeneralQueue) Enqueue(ctx context.Context, payload any, maxRetries int, SetNumberOfTries(0). SetMaxRetries(maxRetries). SetCreatedAt(now). - SetUpdatedAt(now) + SetUpdatedAt(now). + SetUserID(userId) job, err := create.Save(ctx) diff --git a/schema/ent/client.go b/schema/ent/client.go index 7ed8e15..ecb6191 100644 --- a/schema/ent/client.go +++ b/schema/ent/client.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "git.gorlug.de/code/ersteller/schema/ent/event" "git.gorlug.de/code/ersteller/schema/ent/generalqueue" "git.gorlug.de/code/ersteller/schema/ent/generalqueuestate" ) @@ -23,6 +24,8 @@ type Client struct { config // Schema is the client for creating, migrating and dropping schema. Schema *migrate.Schema + // Event is the client for interacting with the Event builders. + Event *EventClient // GeneralQueue is the client for interacting with the GeneralQueue builders. GeneralQueue *GeneralQueueClient // GeneralQueueState is the client for interacting with the GeneralQueueState builders. @@ -38,6 +41,7 @@ func NewClient(opts ...Option) *Client { func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) + c.Event = NewEventClient(c.config) c.GeneralQueue = NewGeneralQueueClient(c.config) c.GeneralQueueState = NewGeneralQueueStateClient(c.config) } @@ -132,6 +136,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { return &Tx{ ctx: ctx, config: cfg, + Event: NewEventClient(cfg), GeneralQueue: NewGeneralQueueClient(cfg), GeneralQueueState: NewGeneralQueueStateClient(cfg), }, nil @@ -153,6 +158,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) return &Tx{ ctx: ctx, config: cfg, + Event: NewEventClient(cfg), GeneralQueue: NewGeneralQueueClient(cfg), GeneralQueueState: NewGeneralQueueStateClient(cfg), }, nil @@ -161,7 +167,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) // Debug returns a new debug-client. It's used to get verbose logging on specific operations. // // client.Debug(). -// GeneralQueue. +// Event. // Query(). // Count(ctx) func (c *Client) Debug() *Client { @@ -183,6 +189,7 @@ func (c *Client) Close() error { // Use adds the mutation hooks to all the entity clients. // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { + c.Event.Use(hooks...) c.GeneralQueue.Use(hooks...) c.GeneralQueueState.Use(hooks...) } @@ -190,6 +197,7 @@ func (c *Client) Use(hooks ...Hook) { // Intercept adds the query interceptors to all the entity clients. // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { + c.Event.Intercept(interceptors...) c.GeneralQueue.Intercept(interceptors...) c.GeneralQueueState.Intercept(interceptors...) } @@ -197,6 +205,8 @@ func (c *Client) Intercept(interceptors ...Interceptor) { // Mutate implements the ent.Mutator interface. func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { switch m := m.(type) { + case *EventMutation: + return c.Event.mutate(ctx, m) case *GeneralQueueMutation: return c.GeneralQueue.mutate(ctx, m) case *GeneralQueueStateMutation: @@ -206,6 +216,139 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { } } +// EventClient is a client for the Event schema. +type EventClient struct { + config +} + +// NewEventClient returns a client for the Event from the given config. +func NewEventClient(c config) *EventClient { + return &EventClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `event.Hooks(f(g(h())))`. +func (c *EventClient) Use(hooks ...Hook) { + c.hooks.Event = append(c.hooks.Event, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `event.Intercept(f(g(h())))`. +func (c *EventClient) Intercept(interceptors ...Interceptor) { + c.inters.Event = append(c.inters.Event, interceptors...) +} + +// Create returns a builder for creating a Event entity. +func (c *EventClient) Create() *EventCreate { + mutation := newEventMutation(c.config, OpCreate) + return &EventCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Event entities. +func (c *EventClient) CreateBulk(builders ...*EventCreate) *EventCreateBulk { + return &EventCreateBulk{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 *EventClient) MapCreateBulk(slice any, setFunc func(*EventCreate, int)) *EventCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &EventCreateBulk{err: fmt.Errorf("calling to EventClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*EventCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &EventCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Event. +func (c *EventClient) Update() *EventUpdate { + mutation := newEventMutation(c.config, OpUpdate) + return &EventUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *EventClient) UpdateOne(_m *Event) *EventUpdateOne { + mutation := newEventMutation(c.config, OpUpdateOne, withEvent(_m)) + return &EventUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *EventClient) UpdateOneID(id int) *EventUpdateOne { + mutation := newEventMutation(c.config, OpUpdateOne, withEventID(id)) + return &EventUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Event. +func (c *EventClient) Delete() *EventDelete { + mutation := newEventMutation(c.config, OpDelete) + return &EventDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *EventClient) DeleteOne(_m *Event) *EventDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *EventClient) DeleteOneID(id int) *EventDeleteOne { + builder := c.Delete().Where(event.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &EventDeleteOne{builder} +} + +// Query returns a query builder for Event. +func (c *EventClient) Query() *EventQuery { + return &EventQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeEvent}, + inters: c.Interceptors(), + } +} + +// Get returns a Event entity by its id. +func (c *EventClient) Get(ctx context.Context, id int) (*Event, error) { + return c.Query().Where(event.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *EventClient) GetX(ctx context.Context, id int) *Event { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *EventClient) Hooks() []Hook { + return c.hooks.Event +} + +// Interceptors returns the client interceptors. +func (c *EventClient) Interceptors() []Interceptor { + return c.inters.Event +} + +func (c *EventClient) mutate(ctx context.Context, m *EventMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&EventCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&EventUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&EventUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&EventDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Event mutation op: %q", m.Op()) + } +} + // GeneralQueueClient is a client for the GeneralQueue schema. type GeneralQueueClient struct { config @@ -475,9 +618,9 @@ func (c *GeneralQueueStateClient) mutate(ctx context.Context, m *GeneralQueueSta // hooks and interceptors per client, for fast access. type ( hooks struct { - GeneralQueue, GeneralQueueState []ent.Hook + Event, GeneralQueue, GeneralQueueState []ent.Hook } inters struct { - GeneralQueue, GeneralQueueState []ent.Interceptor + Event, GeneralQueue, GeneralQueueState []ent.Interceptor } ) diff --git a/schema/ent/ent.go b/schema/ent/ent.go index e10d2f5..4b6ed8c 100644 --- a/schema/ent/ent.go +++ b/schema/ent/ent.go @@ -12,6 +12,7 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "git.gorlug.de/code/ersteller/schema/ent/event" "git.gorlug.de/code/ersteller/schema/ent/generalqueue" "git.gorlug.de/code/ersteller/schema/ent/generalqueuestate" ) @@ -74,6 +75,7 @@ var ( func checkColumn(t, c string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + event.Table: event.ValidColumn, generalqueue.Table: generalqueue.ValidColumn, generalqueuestate.Table: generalqueuestate.ValidColumn, }) diff --git a/schema/ent/event.go b/schema/ent/event.go new file mode 100644 index 0000000..b27e728 --- /dev/null +++ b/schema/ent/event.go @@ -0,0 +1,144 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "git.gorlug.de/code/ersteller/schema/ent/event" +) + +// Event is the model entity for the Event schema. +type Event struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Data holds the value of the "data" field. + Data map[string]interface{} `json:"data,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int `json:"user_id,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Event) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case event.FieldData: + values[i] = new([]byte) + case event.FieldID, event.FieldUserID: + values[i] = new(sql.NullInt64) + case event.FieldName: + values[i] = new(sql.NullString) + case event.FieldCreatedAt: + 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 Event fields. +func (_m *Event) 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 event.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case event.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case event.FieldData: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field data", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Data); err != nil { + return fmt.Errorf("unmarshal field data: %w", err) + } + } + case event.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 { + _m.CreatedAt = value.Time + } + case event.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + _m.UserID = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Event. +// This includes values selected through modifiers, order, etc. +func (_m *Event) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this Event. +// Note that you need to call Event.Unwrap() before calling this method if this Event +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Event) Update() *EventUpdateOne { + return NewEventClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Event entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *Event) Unwrap() *Event { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: Event is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Event) String() string { + var builder strings.Builder + builder.WriteString("Event(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + builder.WriteString("data=") + builder.WriteString(fmt.Sprintf("%v", _m.Data)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", _m.UserID)) + builder.WriteByte(')') + return builder.String() +} + +// Events is a parsable slice of Event. +type Events []*Event diff --git a/schema/ent/event/event.go b/schema/ent/event/event.go new file mode 100644 index 0000000..9cfc5d7 --- /dev/null +++ b/schema/ent/event/event.go @@ -0,0 +1,73 @@ +// Code generated by ent, DO NOT EDIT. + +package event + +import ( + "time" + + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the event type in the database. + Label = "event" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldData holds the string denoting the data field in the database. + FieldData = "data" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // Table holds the table name of the event in the database. + Table = "events" +) + +// Columns holds all SQL columns for event fields. +var Columns = []string{ + FieldID, + FieldName, + FieldData, + FieldCreatedAt, + FieldUserID, +} + +// 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 +) + +// OrderOption defines the ordering options for the Event queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} diff --git a/schema/ent/event/where.go b/schema/ent/event/where.go new file mode 100644 index 0000000..49a82df --- /dev/null +++ b/schema/ent/event/where.go @@ -0,0 +1,230 @@ +// Code generated by ent, DO NOT EDIT. + +package event + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "git.gorlug.de/code/ersteller/schema/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Event { + return predicate.Event(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Event { + return predicate.Event(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Event { + return predicate.Event(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Event { + return predicate.Event(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Event { + return predicate.Event(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Event { + return predicate.Event(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Event { + return predicate.Event(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Event { + return predicate.Event(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Event { + return predicate.Event(sql.FieldLTE(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Event { + return predicate.Event(sql.FieldEQ(FieldName, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Event { + return predicate.Event(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int) predicate.Event { + return predicate.Event(sql.FieldEQ(FieldUserID, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Event { + return predicate.Event(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Event { + return predicate.Event(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Event { + return predicate.Event(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Event { + return predicate.Event(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Event { + return predicate.Event(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Event { + return predicate.Event(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Event { + return predicate.Event(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Event { + return predicate.Event(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Event { + return predicate.Event(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Event { + return predicate.Event(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Event { + return predicate.Event(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Event { + return predicate.Event(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Event { + return predicate.Event(sql.FieldContainsFold(FieldName, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Event { + return predicate.Event(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Event { + return predicate.Event(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Event { + return predicate.Event(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Event { + return predicate.Event(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Event { + return predicate.Event(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Event { + return predicate.Event(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Event { + return predicate.Event(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Event { + return predicate.Event(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int) predicate.Event { + return predicate.Event(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int) predicate.Event { + return predicate.Event(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int) predicate.Event { + return predicate.Event(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int) predicate.Event { + return predicate.Event(sql.FieldNotIn(FieldUserID, vs...)) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v int) predicate.Event { + return predicate.Event(sql.FieldGT(FieldUserID, v)) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v int) predicate.Event { + return predicate.Event(sql.FieldGTE(FieldUserID, v)) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v int) predicate.Event { + return predicate.Event(sql.FieldLT(FieldUserID, v)) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v int) predicate.Event { + return predicate.Event(sql.FieldLTE(FieldUserID, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Event) predicate.Event { + return predicate.Event(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Event) predicate.Event { + return predicate.Event(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Event) predicate.Event { + return predicate.Event(sql.NotPredicates(p)) +} diff --git a/schema/ent/event_create.go b/schema/ent/event_create.go new file mode 100644 index 0000000..dc5b825 --- /dev/null +++ b/schema/ent/event_create.go @@ -0,0 +1,241 @@ +// 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" + "git.gorlug.de/code/ersteller/schema/ent/event" +) + +// EventCreate is the builder for creating a Event entity. +type EventCreate struct { + config + mutation *EventMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (_c *EventCreate) SetName(v string) *EventCreate { + _c.mutation.SetName(v) + return _c +} + +// SetData sets the "data" field. +func (_c *EventCreate) SetData(v map[string]interface{}) *EventCreate { + _c.mutation.SetData(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *EventCreate) SetCreatedAt(v time.Time) *EventCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *EventCreate) SetNillableCreatedAt(v *time.Time) *EventCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUserID sets the "user_id" field. +func (_c *EventCreate) SetUserID(v int) *EventCreate { + _c.mutation.SetUserID(v) + return _c +} + +// Mutation returns the EventMutation object of the builder. +func (_c *EventCreate) Mutation() *EventMutation { + return _c.mutation +} + +// Save creates the Event in the database. +func (_c *EventCreate) Save(ctx context.Context) (*Event, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *EventCreate) SaveX(ctx context.Context) *Event { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *EventCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *EventCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *EventCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := event.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *EventCreate) check() error { + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Event.name"`)} + } + if _, ok := _c.mutation.Data(); !ok { + return &ValidationError{Name: "data", err: errors.New(`ent: missing required field "Event.data"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Event.created_at"`)} + } + if _, ok := _c.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "Event.user_id"`)} + } + return nil +} + +func (_c *EventCreate) sqlSave(ctx context.Context) (*Event, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.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) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *EventCreate) createSpec() (*Event, *sqlgraph.CreateSpec) { + var ( + _node = &Event{config: _c.config} + _spec = sqlgraph.NewCreateSpec(event.Table, sqlgraph.NewFieldSpec(event.FieldID, field.TypeInt)) + ) + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(event.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Data(); ok { + _spec.SetField(event.FieldData, field.TypeJSON, value) + _node.Data = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(event.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UserID(); ok { + _spec.SetField(event.FieldUserID, field.TypeInt, value) + _node.UserID = value + } + return _node, _spec +} + +// EventCreateBulk is the builder for creating many Event entities in bulk. +type EventCreateBulk struct { + config + err error + builders []*EventCreate +} + +// Save creates the Event entities in the database. +func (_c *EventCreateBulk) Save(ctx context.Context) ([]*Event, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Event, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*EventMutation) + 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, _c.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, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + 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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *EventCreateBulk) SaveX(ctx context.Context) []*Event { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *EventCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *EventCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/schema/ent/event_delete.go b/schema/ent/event_delete.go new file mode 100644 index 0000000..c86fbd0 --- /dev/null +++ b/schema/ent/event_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" + "git.gorlug.de/code/ersteller/schema/ent/event" + "git.gorlug.de/code/ersteller/schema/ent/predicate" +) + +// EventDelete is the builder for deleting a Event entity. +type EventDelete struct { + config + hooks []Hook + mutation *EventMutation +} + +// Where appends a list predicates to the EventDelete builder. +func (_d *EventDelete) Where(ps ...predicate.Event) *EventDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *EventDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *EventDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *EventDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(event.Table, sqlgraph.NewFieldSpec(event.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// EventDeleteOne is the builder for deleting a single Event entity. +type EventDeleteOne struct { + _d *EventDelete +} + +// Where appends a list predicates to the EventDelete builder. +func (_d *EventDeleteOne) Where(ps ...predicate.Event) *EventDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *EventDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{event.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *EventDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/schema/ent/event_query.go b/schema/ent/event_query.go new file mode 100644 index 0000000..db64e22 --- /dev/null +++ b/schema/ent/event_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" + "git.gorlug.de/code/ersteller/schema/ent/event" + "git.gorlug.de/code/ersteller/schema/ent/predicate" +) + +// EventQuery is the builder for querying Event entities. +type EventQuery struct { + config + ctx *QueryContext + order []event.OrderOption + inters []Interceptor + predicates []predicate.Event + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the EventQuery builder. +func (_q *EventQuery) Where(ps ...predicate.Event) *EventQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *EventQuery) Limit(limit int) *EventQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *EventQuery) Offset(offset int) *EventQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *EventQuery) Unique(unique bool) *EventQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *EventQuery) Order(o ...event.OrderOption) *EventQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first Event entity from the query. +// Returns a *NotFoundError when no Event was found. +func (_q *EventQuery) First(ctx context.Context) (*Event, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{event.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *EventQuery) FirstX(ctx context.Context) *Event { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Event ID from the query. +// Returns a *NotFoundError when no Event ID was found. +func (_q *EventQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{event.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *EventQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Event entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Event entity is found. +// Returns a *NotFoundError when no Event entities are found. +func (_q *EventQuery) Only(ctx context.Context) (*Event, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{event.Label} + default: + return nil, &NotSingularError{event.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *EventQuery) OnlyX(ctx context.Context) *Event { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Event ID in the query. +// Returns a *NotSingularError when more than one Event ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *EventQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{event.Label} + default: + err = &NotSingularError{event.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *EventQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Events. +func (_q *EventQuery) All(ctx context.Context) ([]*Event, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Event, *EventQuery]() + return withInterceptors[[]*Event](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *EventQuery) AllX(ctx context.Context) []*Event { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Event IDs. +func (_q *EventQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(event.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *EventQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *EventQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*EventQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *EventQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *EventQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *EventQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the EventQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *EventQuery) Clone() *EventQuery { + if _q == nil { + return nil + } + return &EventQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]event.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Event{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Event.Query(). +// GroupBy(event.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *EventQuery) GroupBy(field string, fields ...string) *EventGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &EventGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = event.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.Event.Query(). +// Select(event.FieldName). +// Scan(ctx, &v) +func (_q *EventQuery) Select(fields ...string) *EventSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &EventSelect{EventQuery: _q} + sbuild.label = event.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a EventSelect configured with the given aggregations. +func (_q *EventQuery) Aggregate(fns ...AggregateFunc) *EventSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *EventQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !event.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *EventQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Event, error) { + var ( + nodes = []*Event{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Event).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Event{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *EventQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *EventQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(event.Table, event.Columns, sqlgraph.NewFieldSpec(event.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, event.FieldID) + for i := range fields { + if fields[i] != event.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *EventQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(event.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = event.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// EventGroupBy is the group-by builder for Event entities. +type EventGroupBy struct { + selector + build *EventQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *EventGroupBy) Aggregate(fns ...AggregateFunc) *EventGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *EventGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*EventQuery, *EventGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *EventGroupBy) sqlScan(ctx context.Context, root *EventQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// EventSelect is the builder for selecting fields of Event entities. +type EventSelect struct { + *EventQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *EventSelect) Aggregate(fns ...AggregateFunc) *EventSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *EventSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*EventQuery, *EventSelect](ctx, _s.EventQuery, _s, _s.inters, v) +} + +func (_s *EventSelect) sqlScan(ctx context.Context, root *EventQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/schema/ent/event_update.go b/schema/ent/event_update.go new file mode 100644 index 0000000..40c8e7f --- /dev/null +++ b/schema/ent/event_update.go @@ -0,0 +1,281 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "git.gorlug.de/code/ersteller/schema/ent/event" + "git.gorlug.de/code/ersteller/schema/ent/predicate" +) + +// EventUpdate is the builder for updating Event entities. +type EventUpdate struct { + config + hooks []Hook + mutation *EventMutation +} + +// Where appends a list predicates to the EventUpdate builder. +func (_u *EventUpdate) Where(ps ...predicate.Event) *EventUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetName sets the "name" field. +func (_u *EventUpdate) SetName(v string) *EventUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *EventUpdate) SetNillableName(v *string) *EventUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetData sets the "data" field. +func (_u *EventUpdate) SetData(v map[string]interface{}) *EventUpdate { + _u.mutation.SetData(v) + return _u +} + +// SetUserID sets the "user_id" field. +func (_u *EventUpdate) SetUserID(v int) *EventUpdate { + _u.mutation.ResetUserID() + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *EventUpdate) SetNillableUserID(v *int) *EventUpdate { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// AddUserID adds value to the "user_id" field. +func (_u *EventUpdate) AddUserID(v int) *EventUpdate { + _u.mutation.AddUserID(v) + return _u +} + +// Mutation returns the EventMutation object of the builder. +func (_u *EventUpdate) Mutation() *EventMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *EventUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *EventUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *EventUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *EventUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *EventUpdate) sqlSave(ctx context.Context) (_node int, err error) { + _spec := sqlgraph.NewUpdateSpec(event.Table, event.Columns, sqlgraph.NewFieldSpec(event.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(event.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Data(); ok { + _spec.SetField(event.FieldData, field.TypeJSON, value) + } + if value, ok := _u.mutation.UserID(); ok { + _spec.SetField(event.FieldUserID, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedUserID(); ok { + _spec.AddField(event.FieldUserID, field.TypeInt, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{event.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// EventUpdateOne is the builder for updating a single Event entity. +type EventUpdateOne struct { + config + fields []string + hooks []Hook + mutation *EventMutation +} + +// SetName sets the "name" field. +func (_u *EventUpdateOne) SetName(v string) *EventUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *EventUpdateOne) SetNillableName(v *string) *EventUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetData sets the "data" field. +func (_u *EventUpdateOne) SetData(v map[string]interface{}) *EventUpdateOne { + _u.mutation.SetData(v) + return _u +} + +// SetUserID sets the "user_id" field. +func (_u *EventUpdateOne) SetUserID(v int) *EventUpdateOne { + _u.mutation.ResetUserID() + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *EventUpdateOne) SetNillableUserID(v *int) *EventUpdateOne { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// AddUserID adds value to the "user_id" field. +func (_u *EventUpdateOne) AddUserID(v int) *EventUpdateOne { + _u.mutation.AddUserID(v) + return _u +} + +// Mutation returns the EventMutation object of the builder. +func (_u *EventUpdateOne) Mutation() *EventMutation { + return _u.mutation +} + +// Where appends a list predicates to the EventUpdate builder. +func (_u *EventUpdateOne) Where(ps ...predicate.Event) *EventUpdateOne { + _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 *EventUpdateOne) Select(field string, fields ...string) *EventUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Event entity. +func (_u *EventUpdateOne) Save(ctx context.Context) (*Event, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *EventUpdateOne) SaveX(ctx context.Context) *Event { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *EventUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *EventUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +func (_u *EventUpdateOne) sqlSave(ctx context.Context) (_node *Event, err error) { + _spec := sqlgraph.NewUpdateSpec(event.Table, event.Columns, sqlgraph.NewFieldSpec(event.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Event.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, event.FieldID) + for _, f := range fields { + if !event.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != event.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(event.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Data(); ok { + _spec.SetField(event.FieldData, field.TypeJSON, value) + } + if value, ok := _u.mutation.UserID(); ok { + _spec.SetField(event.FieldUserID, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedUserID(); ok { + _spec.AddField(event.FieldUserID, field.TypeInt, value) + } + _node = &Event{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{event.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/schema/ent/generalqueue.go b/schema/ent/generalqueue.go index 8324c49..68ca908 100644 --- a/schema/ent/generalqueue.go +++ b/schema/ent/generalqueue.go @@ -39,7 +39,9 @@ type GeneralQueue struct { // UpdatedAt holds the value of the "updated_at" field. UpdatedAt time.Time `json:"updated_at,omitempty"` // ProcessedAt holds the value of the "processed_at" field. - ProcessedAt time.Time `json:"processed_at,omitempty"` + ProcessedAt time.Time `json:"processed_at,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int `json:"user_id,omitempty"` selectValues sql.SelectValues } @@ -50,7 +52,7 @@ func (*GeneralQueue) scanValues(columns []string) ([]any, error) { switch columns[i] { case generalqueue.FieldPayload, generalqueue.FieldFailurePayload, generalqueue.FieldResultPayload: values[i] = new([]byte) - case generalqueue.FieldID, generalqueue.FieldNumberOfTries, generalqueue.FieldMaxRetries: + case generalqueue.FieldID, generalqueue.FieldNumberOfTries, generalqueue.FieldMaxRetries, generalqueue.FieldUserID: values[i] = new(sql.NullInt64) case generalqueue.FieldName, generalqueue.FieldStatus, generalqueue.FieldErrorMessage: values[i] = new(sql.NullString) @@ -149,6 +151,12 @@ func (_m *GeneralQueue) assignValues(columns []string, values []any) error { } else if value.Valid { _m.ProcessedAt = value.Time } + case generalqueue.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + _m.UserID = int(value.Int64) + } default: _m.selectValues.Set(columns[i], values[i]) } @@ -217,6 +225,9 @@ func (_m *GeneralQueue) String() string { builder.WriteString(", ") builder.WriteString("processed_at=") builder.WriteString(_m.ProcessedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", _m.UserID)) builder.WriteByte(')') return builder.String() } diff --git a/schema/ent/generalqueue/generalqueue.go b/schema/ent/generalqueue/generalqueue.go index c782745..3c57c35 100644 --- a/schema/ent/generalqueue/generalqueue.go +++ b/schema/ent/generalqueue/generalqueue.go @@ -35,6 +35,8 @@ const ( FieldUpdatedAt = "updated_at" // FieldProcessedAt holds the string denoting the processed_at field in the database. FieldProcessedAt = "processed_at" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" // Table holds the table name of the generalqueue in the database. Table = "generalQueue" ) @@ -53,6 +55,7 @@ var Columns = []string{ FieldCreatedAt, FieldUpdatedAt, FieldProcessedAt, + FieldUserID, } // ValidColumn reports if the column name is valid (part of the table columns). @@ -144,3 +147,8 @@ func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { func ByProcessedAt(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldProcessedAt, opts...).ToFunc() } + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} diff --git a/schema/ent/generalqueue/where.go b/schema/ent/generalqueue/where.go index 832d45b..f66494e 100644 --- a/schema/ent/generalqueue/where.go +++ b/schema/ent/generalqueue/where.go @@ -89,6 +89,11 @@ func ProcessedAt(v time.Time) predicate.GeneralQueue { return predicate.GeneralQueue(sql.FieldEQ(FieldProcessedAt, v)) } +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int) predicate.GeneralQueue { + return predicate.GeneralQueue(sql.FieldEQ(FieldUserID, v)) +} + // NameEQ applies the EQ predicate on the "name" field. func NameEQ(v string) predicate.GeneralQueue { return predicate.GeneralQueue(sql.FieldEQ(FieldName, v)) @@ -479,6 +484,46 @@ func ProcessedAtNotNil() predicate.GeneralQueue { return predicate.GeneralQueue(sql.FieldNotNull(FieldProcessedAt)) } +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int) predicate.GeneralQueue { + return predicate.GeneralQueue(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int) predicate.GeneralQueue { + return predicate.GeneralQueue(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int) predicate.GeneralQueue { + return predicate.GeneralQueue(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int) predicate.GeneralQueue { + return predicate.GeneralQueue(sql.FieldNotIn(FieldUserID, vs...)) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v int) predicate.GeneralQueue { + return predicate.GeneralQueue(sql.FieldGT(FieldUserID, v)) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v int) predicate.GeneralQueue { + return predicate.GeneralQueue(sql.FieldGTE(FieldUserID, v)) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v int) predicate.GeneralQueue { + return predicate.GeneralQueue(sql.FieldLT(FieldUserID, v)) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v int) predicate.GeneralQueue { + return predicate.GeneralQueue(sql.FieldLTE(FieldUserID, v)) +} + // And groups predicates with the AND operator between them. func And(predicates ...predicate.GeneralQueue) predicate.GeneralQueue { return predicate.GeneralQueue(sql.AndPredicates(predicates...)) diff --git a/schema/ent/generalqueue_create.go b/schema/ent/generalqueue_create.go index 847496b..4cacd0a 100644 --- a/schema/ent/generalqueue_create.go +++ b/schema/ent/generalqueue_create.go @@ -118,6 +118,12 @@ func (_c *GeneralQueueCreate) SetNillableProcessedAt(v *time.Time) *GeneralQueue return _c } +// SetUserID sets the "user_id" field. +func (_c *GeneralQueueCreate) SetUserID(v int) *GeneralQueueCreate { + _c.mutation.SetUserID(v) + return _c +} + // Mutation returns the GeneralQueueMutation object of the builder. func (_c *GeneralQueueCreate) Mutation() *GeneralQueueMutation { return _c.mutation @@ -191,6 +197,9 @@ func (_c *GeneralQueueCreate) check() error { if _, ok := _c.mutation.UpdatedAt(); !ok { return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "GeneralQueue.updated_at"`)} } + if _, ok := _c.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "GeneralQueue.user_id"`)} + } return nil } @@ -261,6 +270,10 @@ func (_c *GeneralQueueCreate) createSpec() (*GeneralQueue, *sqlgraph.CreateSpec) _spec.SetField(generalqueue.FieldProcessedAt, field.TypeTime, value) _node.ProcessedAt = value } + if value, ok := _c.mutation.UserID(); ok { + _spec.SetField(generalqueue.FieldUserID, field.TypeInt, value) + _node.UserID = value + } return _node, _spec } diff --git a/schema/ent/generalqueue_update.go b/schema/ent/generalqueue_update.go index a48e841..a11bf2a 100644 --- a/schema/ent/generalqueue_update.go +++ b/schema/ent/generalqueue_update.go @@ -196,6 +196,27 @@ func (_u *GeneralQueueUpdate) ClearProcessedAt() *GeneralQueueUpdate { return _u } +// SetUserID sets the "user_id" field. +func (_u *GeneralQueueUpdate) SetUserID(v int) *GeneralQueueUpdate { + _u.mutation.ResetUserID() + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *GeneralQueueUpdate) SetNillableUserID(v *int) *GeneralQueueUpdate { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// AddUserID adds value to the "user_id" field. +func (_u *GeneralQueueUpdate) AddUserID(v int) *GeneralQueueUpdate { + _u.mutation.AddUserID(v) + return _u +} + // Mutation returns the GeneralQueueMutation object of the builder. func (_u *GeneralQueueUpdate) Mutation() *GeneralQueueMutation { return _u.mutation @@ -301,6 +322,12 @@ func (_u *GeneralQueueUpdate) sqlSave(ctx context.Context) (_node int, err error if _u.mutation.ProcessedAtCleared() { _spec.ClearField(generalqueue.FieldProcessedAt, field.TypeTime) } + if value, ok := _u.mutation.UserID(); ok { + _spec.SetField(generalqueue.FieldUserID, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedUserID(); ok { + _spec.AddField(generalqueue.FieldUserID, field.TypeInt, value) + } if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{generalqueue.Label} @@ -489,6 +516,27 @@ func (_u *GeneralQueueUpdateOne) ClearProcessedAt() *GeneralQueueUpdateOne { return _u } +// SetUserID sets the "user_id" field. +func (_u *GeneralQueueUpdateOne) SetUserID(v int) *GeneralQueueUpdateOne { + _u.mutation.ResetUserID() + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *GeneralQueueUpdateOne) SetNillableUserID(v *int) *GeneralQueueUpdateOne { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// AddUserID adds value to the "user_id" field. +func (_u *GeneralQueueUpdateOne) AddUserID(v int) *GeneralQueueUpdateOne { + _u.mutation.AddUserID(v) + return _u +} + // Mutation returns the GeneralQueueMutation object of the builder. func (_u *GeneralQueueUpdateOne) Mutation() *GeneralQueueMutation { return _u.mutation @@ -624,6 +672,12 @@ func (_u *GeneralQueueUpdateOne) sqlSave(ctx context.Context) (_node *GeneralQue if _u.mutation.ProcessedAtCleared() { _spec.ClearField(generalqueue.FieldProcessedAt, field.TypeTime) } + if value, ok := _u.mutation.UserID(); ok { + _spec.SetField(generalqueue.FieldUserID, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedUserID(); ok { + _spec.AddField(generalqueue.FieldUserID, field.TypeInt, value) + } _node = &GeneralQueue{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/schema/ent/hook/hook.go b/schema/ent/hook/hook.go index e8cfbf0..c01577f 100644 --- a/schema/ent/hook/hook.go +++ b/schema/ent/hook/hook.go @@ -9,6 +9,18 @@ import ( "git.gorlug.de/code/ersteller/schema/ent" ) +// The EventFunc type is an adapter to allow the use of ordinary +// function as Event mutator. +type EventFunc func(context.Context, *ent.EventMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f EventFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.EventMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.EventMutation", m) +} + // The GeneralQueueFunc type is an adapter to allow the use of ordinary // function as GeneralQueue mutator. type GeneralQueueFunc func(context.Context, *ent.GeneralQueueMutation) (ent.Value, error) diff --git a/schema/ent/migrate/schema.go b/schema/ent/migrate/schema.go index 234afe0..7c147c5 100644 --- a/schema/ent/migrate/schema.go +++ b/schema/ent/migrate/schema.go @@ -9,6 +9,20 @@ import ( ) var ( + // EventsColumns holds the columns for the "events" table. + EventsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString}, + {Name: "data", Type: field.TypeJSON}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "user_id", Type: field.TypeInt}, + } + // EventsTable holds the schema information for the "events" table. + EventsTable = &schema.Table{ + Name: "events", + Columns: EventsColumns, + PrimaryKey: []*schema.Column{EventsColumns[0]}, + } // GeneralQueueColumns holds the columns for the "generalQueue" table. GeneralQueueColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -23,6 +37,7 @@ var ( {Name: "created_at", Type: field.TypeTime}, {Name: "updated_at", Type: field.TypeTime}, {Name: "processed_at", Type: field.TypeTime, Nullable: true}, + {Name: "user_id", Type: field.TypeInt}, } // GeneralQueueTable holds the schema information for the "generalQueue" table. GeneralQueueTable = &schema.Table{ @@ -45,6 +60,7 @@ var ( } // Tables holds all the tables in the schema. Tables = []*schema.Table{ + EventsTable, GeneralQueueTable, GeneralQueueStateTable, } diff --git a/schema/ent/mutation.go b/schema/ent/mutation.go index f220339..c62e8e3 100644 --- a/schema/ent/mutation.go +++ b/schema/ent/mutation.go @@ -11,6 +11,7 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" + "git.gorlug.de/code/ersteller/schema/ent/event" "git.gorlug.de/code/ersteller/schema/ent/generalqueue" "git.gorlug.de/code/ersteller/schema/ent/generalqueuestate" "git.gorlug.de/code/ersteller/schema/ent/predicate" @@ -25,10 +26,535 @@ const ( OpUpdateOne = ent.OpUpdateOne // Node types. + TypeEvent = "Event" TypeGeneralQueue = "GeneralQueue" TypeGeneralQueueState = "GeneralQueueState" ) +// EventMutation represents an operation that mutates the Event nodes in the graph. +type EventMutation struct { + config + op Op + typ string + id *int + name *string + data *map[string]interface{} + created_at *time.Time + user_id *int + adduser_id *int + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Event, error) + predicates []predicate.Event +} + +var _ ent.Mutation = (*EventMutation)(nil) + +// eventOption allows management of the mutation configuration using functional options. +type eventOption func(*EventMutation) + +// newEventMutation creates new mutation for the Event entity. +func newEventMutation(c config, op Op, opts ...eventOption) *EventMutation { + m := &EventMutation{ + config: c, + op: op, + typ: TypeEvent, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withEventID sets the ID field of the mutation. +func withEventID(id int) eventOption { + return func(m *EventMutation) { + var ( + err error + once sync.Once + value *Event + ) + m.oldValue = func(ctx context.Context) (*Event, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Event.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withEvent sets the old Event of the mutation. +func withEvent(node *Event) eventOption { + return func(m *EventMutation) { + m.oldValue = func(context.Context) (*Event, 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 EventMutation) 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 EventMutation) 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 *EventMutation) 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 *EventMutation) 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().Event.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *EventMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *EventMutation) 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 Event entity. +// If the Event 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 *EventMutation) 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 *EventMutation) ResetName() { + m.name = nil +} + +// SetData sets the "data" field. +func (m *EventMutation) SetData(value map[string]interface{}) { + m.data = &value +} + +// Data returns the value of the "data" field in the mutation. +func (m *EventMutation) Data() (r map[string]interface{}, exists bool) { + v := m.data + if v == nil { + return + } + return *v, true +} + +// OldData returns the old "data" field's value of the Event entity. +// If the Event 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 *EventMutation) OldData(ctx context.Context) (v map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldData is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldData requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldData: %w", err) + } + return oldValue.Data, nil +} + +// ResetData resets all changes to the "data" field. +func (m *EventMutation) ResetData() { + m.data = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *EventMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *EventMutation) 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 Event entity. +// If the Event 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 *EventMutation) 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 *EventMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUserID sets the "user_id" field. +func (m *EventMutation) SetUserID(i int) { + m.user_id = &i + m.adduser_id = nil +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *EventMutation) UserID() (r int, exists bool) { + v := m.user_id + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the Event entity. +// If the Event 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 *EventMutation) OldUserID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// AddUserID adds i to the "user_id" field. +func (m *EventMutation) AddUserID(i int) { + if m.adduser_id != nil { + *m.adduser_id += i + } else { + m.adduser_id = &i + } +} + +// AddedUserID returns the value that was added to the "user_id" field in this mutation. +func (m *EventMutation) AddedUserID() (r int, exists bool) { + v := m.adduser_id + if v == nil { + return + } + return *v, true +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *EventMutation) ResetUserID() { + m.user_id = nil + m.adduser_id = nil +} + +// Where appends a list predicates to the EventMutation builder. +func (m *EventMutation) Where(ps ...predicate.Event) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the EventMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *EventMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Event, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *EventMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *EventMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Event). +func (m *EventMutation) 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 *EventMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.name != nil { + fields = append(fields, event.FieldName) + } + if m.data != nil { + fields = append(fields, event.FieldData) + } + if m.created_at != nil { + fields = append(fields, event.FieldCreatedAt) + } + if m.user_id != nil { + fields = append(fields, event.FieldUserID) + } + 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 *EventMutation) Field(name string) (ent.Value, bool) { + switch name { + case event.FieldName: + return m.Name() + case event.FieldData: + return m.Data() + case event.FieldCreatedAt: + return m.CreatedAt() + case event.FieldUserID: + return m.UserID() + } + 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 *EventMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case event.FieldName: + return m.OldName(ctx) + case event.FieldData: + return m.OldData(ctx) + case event.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case event.FieldUserID: + return m.OldUserID(ctx) + } + return nil, fmt.Errorf("unknown Event 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 *EventMutation) SetField(name string, value ent.Value) error { + switch name { + case event.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case event.FieldData: + v, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetData(v) + return nil + case event.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 event.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + } + return fmt.Errorf("unknown Event field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *EventMutation) AddedFields() []string { + var fields []string + if m.adduser_id != nil { + fields = append(fields, event.FieldUserID) + } + return fields +} + +// 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 *EventMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case event.FieldUserID: + return m.AddedUserID() + } + 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 *EventMutation) AddField(name string, value ent.Value) error { + switch name { + case event.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddUserID(v) + return nil + } + return fmt.Errorf("unknown Event numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *EventMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *EventMutation) 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 *EventMutation) ClearField(name string) error { + return fmt.Errorf("unknown Event 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 *EventMutation) ResetField(name string) error { + switch name { + case event.FieldName: + m.ResetName() + return nil + case event.FieldData: + m.ResetData() + return nil + case event.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case event.FieldUserID: + m.ResetUserID() + return nil + } + return fmt.Errorf("unknown Event field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *EventMutation) 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 *EventMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *EventMutation) 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 *EventMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *EventMutation) 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 *EventMutation) 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 *EventMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Event 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 *EventMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Event edge %s", name) +} + // GeneralQueueMutation represents an operation that mutates the GeneralQueue nodes in the graph. type GeneralQueueMutation struct { config @@ -48,6 +574,8 @@ type GeneralQueueMutation struct { created_at *time.Time updated_at *time.Time processed_at *time.Time + user_id *int + adduser_id *int clearedFields map[string]struct{} done bool oldValue func(context.Context) (*GeneralQueue, error) @@ -640,6 +1168,62 @@ func (m *GeneralQueueMutation) ResetProcessedAt() { delete(m.clearedFields, generalqueue.FieldProcessedAt) } +// SetUserID sets the "user_id" field. +func (m *GeneralQueueMutation) SetUserID(i int) { + m.user_id = &i + m.adduser_id = nil +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *GeneralQueueMutation) UserID() (r int, exists bool) { + v := m.user_id + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the GeneralQueue entity. +// If the GeneralQueue 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 *GeneralQueueMutation) OldUserID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// AddUserID adds i to the "user_id" field. +func (m *GeneralQueueMutation) AddUserID(i int) { + if m.adduser_id != nil { + *m.adduser_id += i + } else { + m.adduser_id = &i + } +} + +// AddedUserID returns the value that was added to the "user_id" field in this mutation. +func (m *GeneralQueueMutation) AddedUserID() (r int, exists bool) { + v := m.adduser_id + if v == nil { + return + } + return *v, true +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *GeneralQueueMutation) ResetUserID() { + m.user_id = nil + m.adduser_id = nil +} + // Where appends a list predicates to the GeneralQueueMutation builder. func (m *GeneralQueueMutation) Where(ps ...predicate.GeneralQueue) { m.predicates = append(m.predicates, ps...) @@ -674,7 +1258,7 @@ func (m *GeneralQueueMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *GeneralQueueMutation) Fields() []string { - fields := make([]string, 0, 11) + fields := make([]string, 0, 12) if m.name != nil { fields = append(fields, generalqueue.FieldName) } @@ -708,6 +1292,9 @@ func (m *GeneralQueueMutation) Fields() []string { if m.processed_at != nil { fields = append(fields, generalqueue.FieldProcessedAt) } + if m.user_id != nil { + fields = append(fields, generalqueue.FieldUserID) + } return fields } @@ -738,6 +1325,8 @@ func (m *GeneralQueueMutation) Field(name string) (ent.Value, bool) { return m.UpdatedAt() case generalqueue.FieldProcessedAt: return m.ProcessedAt() + case generalqueue.FieldUserID: + return m.UserID() } return nil, false } @@ -769,6 +1358,8 @@ func (m *GeneralQueueMutation) OldField(ctx context.Context, name string) (ent.V return m.OldUpdatedAt(ctx) case generalqueue.FieldProcessedAt: return m.OldProcessedAt(ctx) + case generalqueue.FieldUserID: + return m.OldUserID(ctx) } return nil, fmt.Errorf("unknown GeneralQueue field %s", name) } @@ -855,6 +1446,13 @@ func (m *GeneralQueueMutation) SetField(name string, value ent.Value) error { } m.SetProcessedAt(v) return nil + case generalqueue.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil } return fmt.Errorf("unknown GeneralQueue field %s", name) } @@ -869,6 +1467,9 @@ func (m *GeneralQueueMutation) AddedFields() []string { if m.addmax_retries != nil { fields = append(fields, generalqueue.FieldMaxRetries) } + if m.adduser_id != nil { + fields = append(fields, generalqueue.FieldUserID) + } return fields } @@ -881,6 +1482,8 @@ func (m *GeneralQueueMutation) AddedField(name string) (ent.Value, bool) { return m.AddedNumberOfTries() case generalqueue.FieldMaxRetries: return m.AddedMaxRetries() + case generalqueue.FieldUserID: + return m.AddedUserID() } return nil, false } @@ -904,6 +1507,13 @@ func (m *GeneralQueueMutation) AddField(name string, value ent.Value) error { } m.AddMaxRetries(v) return nil + case generalqueue.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddUserID(v) + return nil } return fmt.Errorf("unknown GeneralQueue numeric field %s", name) } @@ -991,6 +1601,9 @@ func (m *GeneralQueueMutation) ResetField(name string) error { case generalqueue.FieldProcessedAt: m.ResetProcessedAt() return nil + case generalqueue.FieldUserID: + m.ResetUserID() + return nil } return fmt.Errorf("unknown GeneralQueue field %s", name) } diff --git a/schema/ent/pagination_query.go b/schema/ent/pagination_query.go index 827f884..6cab92e 100644 --- a/schema/ent/pagination_query.go +++ b/schema/ent/pagination_query.go @@ -10,6 +10,44 @@ import ( "entgo.io/ent/dialect/sql" ) +// PaginateAfterID paginates Event by monotonically increasing "id". +// It preserves any existing filters/joins applied to the query, fetches up to "limit" items, +// and returns the next cursor (last ID of this page) and whether a next page exists. +func (q *EventQuery) PaginateAfterID(ctx context.Context, afterID, limit int) ([]*Event, int, bool, error) { + if limit <= 0 { + limit = 20 + } + + qq := q.Clone(). + Order(func(s *sql.Selector) { + s.OrderBy(s.C("id")) + }). + Limit(limit + 1) // fetch one extra to detect "has next" + + if afterID > 0 { + qq = qq.Where(func(s *sql.Selector) { + s.Where(sql.GT(s.C("id"), afterID)) + }) + } + + rows, err := qq.All(ctx) + if err != nil { + return nil, 0, false, err + } + + hasNext := len(rows) > limit + if hasNext { + rows = rows[:limit] + } + + next := 0 + if len(rows) > 0 { + next = rows[len(rows)-1].ID + } + + return rows, next, hasNext, nil +} + // PaginateAfterID paginates GeneralQueue by monotonically increasing "id". // It preserves any existing filters/joins applied to the query, fetches up to "limit" items, // and returns the next cursor (last ID of this page) and whether a next page exists. diff --git a/schema/ent/predicate/predicate.go b/schema/ent/predicate/predicate.go index 3ca7d2b..e1a2c5e 100644 --- a/schema/ent/predicate/predicate.go +++ b/schema/ent/predicate/predicate.go @@ -6,6 +6,9 @@ import ( "entgo.io/ent/dialect/sql" ) +// Event is the predicate function for event builders. +type Event func(*sql.Selector) + // GeneralQueue is the predicate function for generalqueue builders. type GeneralQueue func(*sql.Selector) diff --git a/schema/ent/runtime.go b/schema/ent/runtime.go index 006d7f6..1d98c8e 100644 --- a/schema/ent/runtime.go +++ b/schema/ent/runtime.go @@ -3,6 +3,9 @@ package ent import ( + "time" + + "git.gorlug.de/code/ersteller/schema/ent/event" "git.gorlug.de/code/ersteller/schema/ent/generalqueue" "git.gorlug.de/code/ersteller/schema/ent/generalqueuestate" "git.gorlug.de/code/ersteller/schema/ent/schema" @@ -12,6 +15,12 @@ import ( // (default values, validators, hooks and policies) and stitches it // to their package variables. func init() { + eventFields := schema.Event{}.Fields() + _ = eventFields + // eventDescCreatedAt is the schema descriptor for created_at field. + eventDescCreatedAt := eventFields[2].Descriptor() + // event.DefaultCreatedAt holds the default value on creation for the created_at field. + event.DefaultCreatedAt = eventDescCreatedAt.Default.(func() time.Time) generalqueueFields := schema.GeneralQueue{}.Fields() _ = generalqueueFields // generalqueueDescNumberOfTries is the schema descriptor for number_of_tries field. diff --git a/schema/ent/schema/event.go b/schema/ent/schema/event.go new file mode 100644 index 0000000..296250d --- /dev/null +++ b/schema/ent/schema/event.go @@ -0,0 +1,23 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/schema/field" +) + +type Event struct { + ent.Schema +} + +func (Event) Fields() []ent.Field { + return []ent.Field{ + field.String("name"), + field.JSON("data", map[string]interface{}{}), + field.Time("created_at"). + Default(time.Now). + Immutable(), + field.Int("user_id"), + } +} diff --git a/schema/ent/schema/general_queue.go b/schema/ent/schema/general_queue.go index 2cabbdc..73e948d 100644 --- a/schema/ent/schema/general_queue.go +++ b/schema/ent/schema/general_queue.go @@ -24,6 +24,7 @@ func (GeneralQueue) Fields() []ent.Field { field.Time("created_at"), field.Time("updated_at"), field.Time("processed_at").Optional(), + field.Int("user_id"), } } diff --git a/schema/ent/tx.go b/schema/ent/tx.go index 0908a2a..b6609d5 100644 --- a/schema/ent/tx.go +++ b/schema/ent/tx.go @@ -12,6 +12,8 @@ import ( // Tx is a transactional client that is created by calling Client.Tx(). type Tx struct { config + // Event is the client for interacting with the Event builders. + Event *EventClient // GeneralQueue is the client for interacting with the GeneralQueue builders. GeneralQueue *GeneralQueueClient // GeneralQueueState is the client for interacting with the GeneralQueueState builders. @@ -147,6 +149,7 @@ func (tx *Tx) Client() *Client { } func (tx *Tx) init() { + tx.Event = NewEventClient(tx.config) tx.GeneralQueue = NewGeneralQueueClient(tx.config) tx.GeneralQueueState = NewGeneralQueueStateClient(tx.config) } @@ -158,7 +161,7 @@ func (tx *Tx) init() { // of them in order to commit or rollback the transaction. // // If a closed transaction is embedded in one of the generated entities, and the entity -// applies a query, for example: GeneralQueue.QueryXXX(), the query will be executed +// applies a query, for example: Event.QueryXXX(), the query will be executed // through the driver which created this transaction. // // Note that txDriver is not goroutine safe.