diff --git a/internal/ent/client.go b/internal/ent/client.go index 9bfeb71..8005749 100644 --- a/internal/ent/client.go +++ b/internal/ent/client.go @@ -16,6 +16,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "github.com/go-faster/bot/internal/ent/check" + "github.com/go-faster/bot/internal/ent/gitcommit" "github.com/go-faster/bot/internal/ent/gptdialog" "github.com/go-faster/bot/internal/ent/lastchannelmessage" "github.com/go-faster/bot/internal/ent/organization" @@ -36,6 +37,8 @@ type Client struct { Check *CheckClient // GPTDialog is the client for interacting with the GPTDialog builders. GPTDialog *GPTDialogClient + // GitCommit is the client for interacting with the GitCommit builders. + GitCommit *GitCommitClient // LastChannelMessage is the client for interacting with the LastChannelMessage builders. LastChannelMessage *LastChannelMessageClient // Organization is the client for interacting with the Organization builders. @@ -67,6 +70,7 @@ func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) c.Check = NewCheckClient(c.config) c.GPTDialog = NewGPTDialogClient(c.config) + c.GitCommit = NewGitCommitClient(c.config) c.LastChannelMessage = NewLastChannelMessageClient(c.config) c.Organization = NewOrganizationClient(c.config) c.PRNotification = NewPRNotificationClient(c.config) @@ -159,6 +163,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { config: cfg, Check: NewCheckClient(cfg), GPTDialog: NewGPTDialogClient(cfg), + GitCommit: NewGitCommitClient(cfg), LastChannelMessage: NewLastChannelMessageClient(cfg), Organization: NewOrganizationClient(cfg), PRNotification: NewPRNotificationClient(cfg), @@ -188,6 +193,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) config: cfg, Check: NewCheckClient(cfg), GPTDialog: NewGPTDialogClient(cfg), + GitCommit: NewGitCommitClient(cfg), LastChannelMessage: NewLastChannelMessageClient(cfg), Organization: NewOrganizationClient(cfg), PRNotification: NewPRNotificationClient(cfg), @@ -225,9 +231,9 @@ func (c *Client) Close() error { // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ - c.Check, c.GPTDialog, c.LastChannelMessage, c.Organization, c.PRNotification, - c.Repository, c.TelegramChannelState, c.TelegramSession, c.TelegramUserState, - c.User, + c.Check, c.GPTDialog, c.GitCommit, c.LastChannelMessage, c.Organization, + c.PRNotification, c.Repository, c.TelegramChannelState, c.TelegramSession, + c.TelegramUserState, c.User, } { n.Use(hooks...) } @@ -237,9 +243,9 @@ func (c *Client) Use(hooks ...Hook) { // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ - c.Check, c.GPTDialog, c.LastChannelMessage, c.Organization, c.PRNotification, - c.Repository, c.TelegramChannelState, c.TelegramSession, c.TelegramUserState, - c.User, + c.Check, c.GPTDialog, c.GitCommit, c.LastChannelMessage, c.Organization, + c.PRNotification, c.Repository, c.TelegramChannelState, c.TelegramSession, + c.TelegramUserState, c.User, } { n.Intercept(interceptors...) } @@ -252,6 +258,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.Check.mutate(ctx, m) case *GPTDialogMutation: return c.GPTDialog.mutate(ctx, m) + case *GitCommitMutation: + return c.GitCommit.mutate(ctx, m) case *LastChannelMessageMutation: return c.LastChannelMessage.mutate(ctx, m) case *OrganizationMutation: @@ -509,6 +517,140 @@ func (c *GPTDialogClient) mutate(ctx context.Context, m *GPTDialogMutation) (Val } } +// GitCommitClient is a client for the GitCommit schema. +type GitCommitClient struct { + config +} + +// NewGitCommitClient returns a client for the GitCommit from the given config. +func NewGitCommitClient(c config) *GitCommitClient { + return &GitCommitClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `gitcommit.Hooks(f(g(h())))`. +func (c *GitCommitClient) Use(hooks ...Hook) { + c.hooks.GitCommit = append(c.hooks.GitCommit, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `gitcommit.Intercept(f(g(h())))`. +func (c *GitCommitClient) Intercept(interceptors ...Interceptor) { + c.inters.GitCommit = append(c.inters.GitCommit, interceptors...) +} + +// Create returns a builder for creating a GitCommit entity. +func (c *GitCommitClient) Create() *GitCommitCreate { + mutation := newGitCommitMutation(c.config, OpCreate) + return &GitCommitCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of GitCommit entities. +func (c *GitCommitClient) CreateBulk(builders ...*GitCommitCreate) *GitCommitCreateBulk { + return &GitCommitCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for GitCommit. +func (c *GitCommitClient) Update() *GitCommitUpdate { + mutation := newGitCommitMutation(c.config, OpUpdate) + return &GitCommitUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *GitCommitClient) UpdateOne(gc *GitCommit) *GitCommitUpdateOne { + mutation := newGitCommitMutation(c.config, OpUpdateOne, withGitCommit(gc)) + return &GitCommitUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *GitCommitClient) UpdateOneID(id string) *GitCommitUpdateOne { + mutation := newGitCommitMutation(c.config, OpUpdateOne, withGitCommitID(id)) + return &GitCommitUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for GitCommit. +func (c *GitCommitClient) Delete() *GitCommitDelete { + mutation := newGitCommitMutation(c.config, OpDelete) + return &GitCommitDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *GitCommitClient) DeleteOne(gc *GitCommit) *GitCommitDeleteOne { + return c.DeleteOneID(gc.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *GitCommitClient) DeleteOneID(id string) *GitCommitDeleteOne { + builder := c.Delete().Where(gitcommit.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &GitCommitDeleteOne{builder} +} + +// Query returns a query builder for GitCommit. +func (c *GitCommitClient) Query() *GitCommitQuery { + return &GitCommitQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeGitCommit}, + inters: c.Interceptors(), + } +} + +// Get returns a GitCommit entity by its id. +func (c *GitCommitClient) Get(ctx context.Context, id string) (*GitCommit, error) { + return c.Query().Where(gitcommit.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *GitCommitClient) GetX(ctx context.Context, id string) *GitCommit { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryRepository queries the repository edge of a GitCommit. +func (c *GitCommitClient) QueryRepository(gc *GitCommit) *RepositoryQuery { + query := (&RepositoryClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := gc.ID + step := sqlgraph.NewStep( + sqlgraph.From(gitcommit.Table, gitcommit.FieldID, id), + sqlgraph.To(repository.Table, repository.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, gitcommit.RepositoryTable, gitcommit.RepositoryColumn), + ) + fromV = sqlgraph.Neighbors(gc.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *GitCommitClient) Hooks() []Hook { + return c.hooks.GitCommit +} + +// Interceptors returns the client interceptors. +func (c *GitCommitClient) Interceptors() []Interceptor { + return c.inters.GitCommit +} + +func (c *GitCommitClient) mutate(ctx context.Context, m *GitCommitMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&GitCommitCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&GitCommitUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&GitCommitUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&GitCommitDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown GitCommit mutation op: %q", m.Op()) + } +} + // LastChannelMessageClient is a client for the LastChannelMessage schema. type LastChannelMessageClient struct { config @@ -988,6 +1130,22 @@ func (c *RepositoryClient) QueryOrganization(r *Repository) *OrganizationQuery { return query } +// QueryCommits queries the commits edge of a Repository. +func (c *RepositoryClient) QueryCommits(r *Repository) *GitCommitQuery { + query := (&GitCommitClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := r.ID + step := sqlgraph.NewStep( + sqlgraph.From(repository.Table, repository.FieldID, id), + sqlgraph.To(gitcommit.Table, gitcommit.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, repository.CommitsTable, repository.CommitsColumn), + ) + fromV = sqlgraph.Neighbors(r.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *RepositoryClient) Hooks() []Hook { return c.hooks.Repository @@ -1520,12 +1678,13 @@ func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) // hooks and interceptors per client, for fast access. type ( hooks struct { - Check, GPTDialog, LastChannelMessage, Organization, PRNotification, Repository, - TelegramChannelState, TelegramSession, TelegramUserState, User []ent.Hook + Check, GPTDialog, GitCommit, LastChannelMessage, Organization, PRNotification, + Repository, TelegramChannelState, TelegramSession, TelegramUserState, + User []ent.Hook } inters struct { - Check, GPTDialog, LastChannelMessage, Organization, PRNotification, Repository, - TelegramChannelState, TelegramSession, TelegramUserState, + Check, GPTDialog, GitCommit, LastChannelMessage, Organization, PRNotification, + Repository, TelegramChannelState, TelegramSession, TelegramUserState, User []ent.Interceptor } ) diff --git a/internal/ent/ent.go b/internal/ent/ent.go index 2dd215c..df6dd90 100644 --- a/internal/ent/ent.go +++ b/internal/ent/ent.go @@ -13,6 +13,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "github.com/go-faster/bot/internal/ent/check" + "github.com/go-faster/bot/internal/ent/gitcommit" "github.com/go-faster/bot/internal/ent/gptdialog" "github.com/go-faster/bot/internal/ent/lastchannelmessage" "github.com/go-faster/bot/internal/ent/organization" @@ -84,6 +85,7 @@ func checkColumn(table, column string) error { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ check.Table: check.ValidColumn, gptdialog.Table: gptdialog.ValidColumn, + gitcommit.Table: gitcommit.ValidColumn, lastchannelmessage.Table: lastchannelmessage.ValidColumn, organization.Table: organization.ValidColumn, prnotification.Table: prnotification.ValidColumn, diff --git a/internal/ent/gitcommit.go b/internal/ent/gitcommit.go new file mode 100644 index 0000000..b0a7474 --- /dev/null +++ b/internal/ent/gitcommit.go @@ -0,0 +1,181 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/go-faster/bot/internal/ent/gitcommit" + "github.com/go-faster/bot/internal/ent/repository" +) + +// GitCommit is the model entity for the GitCommit schema. +type GitCommit struct { + config `json:"-"` + // ID of the ent. + // GitCommit SHA. + ID string `json:"id,omitempty"` + // GitCommit message. + Message string `json:"message,omitempty"` + // GitCommit author. + AuthorLogin string `json:"author_login,omitempty"` + // GitCommit author ID. + AuthorID int64 `json:"author_id,omitempty"` + // GitCommit date. + Date time.Time `json:"date,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the GitCommitQuery when eager-loading is set. + Edges GitCommitEdges `json:"edges"` + repository_commits *int64 + selectValues sql.SelectValues +} + +// GitCommitEdges holds the relations/edges for other nodes in the graph. +type GitCommitEdges struct { + // GitHub Repository. + Repository *Repository `json:"repository,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// RepositoryOrErr returns the Repository value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e GitCommitEdges) RepositoryOrErr() (*Repository, error) { + if e.loadedTypes[0] { + if e.Repository == nil { + // Edge was loaded but was not found. + return nil, &NotFoundError{label: repository.Label} + } + return e.Repository, nil + } + return nil, &NotLoadedError{edge: "repository"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*GitCommit) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case gitcommit.FieldAuthorID: + values[i] = new(sql.NullInt64) + case gitcommit.FieldID, gitcommit.FieldMessage, gitcommit.FieldAuthorLogin: + values[i] = new(sql.NullString) + case gitcommit.FieldDate: + values[i] = new(sql.NullTime) + case gitcommit.ForeignKeys[0]: // repository_commits + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the GitCommit fields. +func (gc *GitCommit) 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 gitcommit.FieldID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value.Valid { + gc.ID = value.String + } + case gitcommit.FieldMessage: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field message", values[i]) + } else if value.Valid { + gc.Message = value.String + } + case gitcommit.FieldAuthorLogin: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field author_login", values[i]) + } else if value.Valid { + gc.AuthorLogin = value.String + } + case gitcommit.FieldAuthorID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field author_id", values[i]) + } else if value.Valid { + gc.AuthorID = value.Int64 + } + case gitcommit.FieldDate: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field date", values[i]) + } else if value.Valid { + gc.Date = value.Time + } + case gitcommit.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field repository_commits", value) + } else if value.Valid { + gc.repository_commits = new(int64) + *gc.repository_commits = int64(value.Int64) + } + default: + gc.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the GitCommit. +// This includes values selected through modifiers, order, etc. +func (gc *GitCommit) Value(name string) (ent.Value, error) { + return gc.selectValues.Get(name) +} + +// QueryRepository queries the "repository" edge of the GitCommit entity. +func (gc *GitCommit) QueryRepository() *RepositoryQuery { + return NewGitCommitClient(gc.config).QueryRepository(gc) +} + +// Update returns a builder for updating this GitCommit. +// Note that you need to call GitCommit.Unwrap() before calling this method if this GitCommit +// was returned from a transaction, and the transaction was committed or rolled back. +func (gc *GitCommit) Update() *GitCommitUpdateOne { + return NewGitCommitClient(gc.config).UpdateOne(gc) +} + +// Unwrap unwraps the GitCommit 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 (gc *GitCommit) Unwrap() *GitCommit { + _tx, ok := gc.config.driver.(*txDriver) + if !ok { + panic("ent: GitCommit is not a transactional entity") + } + gc.config.driver = _tx.drv + return gc +} + +// String implements the fmt.Stringer. +func (gc *GitCommit) String() string { + var builder strings.Builder + builder.WriteString("GitCommit(") + builder.WriteString(fmt.Sprintf("id=%v, ", gc.ID)) + builder.WriteString("message=") + builder.WriteString(gc.Message) + builder.WriteString(", ") + builder.WriteString("author_login=") + builder.WriteString(gc.AuthorLogin) + builder.WriteString(", ") + builder.WriteString("author_id=") + builder.WriteString(fmt.Sprintf("%v", gc.AuthorID)) + builder.WriteString(", ") + builder.WriteString("date=") + builder.WriteString(gc.Date.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// GitCommits is a parsable slice of GitCommit. +type GitCommits []*GitCommit diff --git a/internal/ent/gitcommit/gitcommit.go b/internal/ent/gitcommit/gitcommit.go new file mode 100644 index 0000000..b13279a --- /dev/null +++ b/internal/ent/gitcommit/gitcommit.go @@ -0,0 +1,108 @@ +// Code generated by ent, DO NOT EDIT. + +package gitcommit + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the gitcommit type in the database. + Label = "git_commit" + // FieldID holds the string denoting the id field in the database. + FieldID = "sha" + // FieldMessage holds the string denoting the message field in the database. + FieldMessage = "message" + // FieldAuthorLogin holds the string denoting the author_login field in the database. + FieldAuthorLogin = "author_login" + // FieldAuthorID holds the string denoting the author_id field in the database. + FieldAuthorID = "author_id" + // FieldDate holds the string denoting the date field in the database. + FieldDate = "date" + // EdgeRepository holds the string denoting the repository edge name in mutations. + EdgeRepository = "repository" + // RepositoryFieldID holds the string denoting the ID field of the Repository. + RepositoryFieldID = "id" + // Table holds the table name of the gitcommit in the database. + Table = "git_commits" + // RepositoryTable is the table that holds the repository relation/edge. + RepositoryTable = "git_commits" + // RepositoryInverseTable is the table name for the Repository entity. + // It exists in this package in order to avoid circular dependency with the "repository" package. + RepositoryInverseTable = "repositories" + // RepositoryColumn is the table column denoting the repository relation/edge. + RepositoryColumn = "repository_commits" +) + +// Columns holds all SQL columns for gitcommit fields. +var Columns = []string{ + FieldID, + FieldMessage, + FieldAuthorLogin, + FieldAuthorID, + FieldDate, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "git_commits" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "repository_commits", +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} + +// OrderOption defines the ordering options for the GitCommit 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() +} + +// ByMessage orders the results by the message field. +func ByMessage(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMessage, opts...).ToFunc() +} + +// ByAuthorLogin orders the results by the author_login field. +func ByAuthorLogin(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAuthorLogin, opts...).ToFunc() +} + +// ByAuthorID orders the results by the author_id field. +func ByAuthorID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldAuthorID, opts...).ToFunc() +} + +// ByDate orders the results by the date field. +func ByDate(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDate, opts...).ToFunc() +} + +// ByRepositoryField orders the results by repository field. +func ByRepositoryField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRepositoryStep(), sql.OrderByField(field, opts...)) + } +} +func newRepositoryStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RepositoryInverseTable, RepositoryFieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RepositoryTable, RepositoryColumn), + ) +} diff --git a/internal/ent/gitcommit/where.go b/internal/ent/gitcommit/where.go new file mode 100644 index 0000000..332b783 --- /dev/null +++ b/internal/ent/gitcommit/where.go @@ -0,0 +1,351 @@ +// Code generated by ent, DO NOT EDIT. + +package gitcommit + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/go-faster/bot/internal/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldContainsFold(FieldID, id)) +} + +// Message applies equality check predicate on the "message" field. It's identical to MessageEQ. +func Message(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldEQ(FieldMessage, v)) +} + +// AuthorLogin applies equality check predicate on the "author_login" field. It's identical to AuthorLoginEQ. +func AuthorLogin(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldEQ(FieldAuthorLogin, v)) +} + +// AuthorID applies equality check predicate on the "author_id" field. It's identical to AuthorIDEQ. +func AuthorID(v int64) predicate.GitCommit { + return predicate.GitCommit(sql.FieldEQ(FieldAuthorID, v)) +} + +// Date applies equality check predicate on the "date" field. It's identical to DateEQ. +func Date(v time.Time) predicate.GitCommit { + return predicate.GitCommit(sql.FieldEQ(FieldDate, v)) +} + +// MessageEQ applies the EQ predicate on the "message" field. +func MessageEQ(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldEQ(FieldMessage, v)) +} + +// MessageNEQ applies the NEQ predicate on the "message" field. +func MessageNEQ(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldNEQ(FieldMessage, v)) +} + +// MessageIn applies the In predicate on the "message" field. +func MessageIn(vs ...string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldIn(FieldMessage, vs...)) +} + +// MessageNotIn applies the NotIn predicate on the "message" field. +func MessageNotIn(vs ...string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldNotIn(FieldMessage, vs...)) +} + +// MessageGT applies the GT predicate on the "message" field. +func MessageGT(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldGT(FieldMessage, v)) +} + +// MessageGTE applies the GTE predicate on the "message" field. +func MessageGTE(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldGTE(FieldMessage, v)) +} + +// MessageLT applies the LT predicate on the "message" field. +func MessageLT(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldLT(FieldMessage, v)) +} + +// MessageLTE applies the LTE predicate on the "message" field. +func MessageLTE(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldLTE(FieldMessage, v)) +} + +// MessageContains applies the Contains predicate on the "message" field. +func MessageContains(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldContains(FieldMessage, v)) +} + +// MessageHasPrefix applies the HasPrefix predicate on the "message" field. +func MessageHasPrefix(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldHasPrefix(FieldMessage, v)) +} + +// MessageHasSuffix applies the HasSuffix predicate on the "message" field. +func MessageHasSuffix(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldHasSuffix(FieldMessage, v)) +} + +// MessageEqualFold applies the EqualFold predicate on the "message" field. +func MessageEqualFold(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldEqualFold(FieldMessage, v)) +} + +// MessageContainsFold applies the ContainsFold predicate on the "message" field. +func MessageContainsFold(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldContainsFold(FieldMessage, v)) +} + +// AuthorLoginEQ applies the EQ predicate on the "author_login" field. +func AuthorLoginEQ(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldEQ(FieldAuthorLogin, v)) +} + +// AuthorLoginNEQ applies the NEQ predicate on the "author_login" field. +func AuthorLoginNEQ(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldNEQ(FieldAuthorLogin, v)) +} + +// AuthorLoginIn applies the In predicate on the "author_login" field. +func AuthorLoginIn(vs ...string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldIn(FieldAuthorLogin, vs...)) +} + +// AuthorLoginNotIn applies the NotIn predicate on the "author_login" field. +func AuthorLoginNotIn(vs ...string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldNotIn(FieldAuthorLogin, vs...)) +} + +// AuthorLoginGT applies the GT predicate on the "author_login" field. +func AuthorLoginGT(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldGT(FieldAuthorLogin, v)) +} + +// AuthorLoginGTE applies the GTE predicate on the "author_login" field. +func AuthorLoginGTE(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldGTE(FieldAuthorLogin, v)) +} + +// AuthorLoginLT applies the LT predicate on the "author_login" field. +func AuthorLoginLT(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldLT(FieldAuthorLogin, v)) +} + +// AuthorLoginLTE applies the LTE predicate on the "author_login" field. +func AuthorLoginLTE(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldLTE(FieldAuthorLogin, v)) +} + +// AuthorLoginContains applies the Contains predicate on the "author_login" field. +func AuthorLoginContains(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldContains(FieldAuthorLogin, v)) +} + +// AuthorLoginHasPrefix applies the HasPrefix predicate on the "author_login" field. +func AuthorLoginHasPrefix(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldHasPrefix(FieldAuthorLogin, v)) +} + +// AuthorLoginHasSuffix applies the HasSuffix predicate on the "author_login" field. +func AuthorLoginHasSuffix(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldHasSuffix(FieldAuthorLogin, v)) +} + +// AuthorLoginEqualFold applies the EqualFold predicate on the "author_login" field. +func AuthorLoginEqualFold(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldEqualFold(FieldAuthorLogin, v)) +} + +// AuthorLoginContainsFold applies the ContainsFold predicate on the "author_login" field. +func AuthorLoginContainsFold(v string) predicate.GitCommit { + return predicate.GitCommit(sql.FieldContainsFold(FieldAuthorLogin, v)) +} + +// AuthorIDEQ applies the EQ predicate on the "author_id" field. +func AuthorIDEQ(v int64) predicate.GitCommit { + return predicate.GitCommit(sql.FieldEQ(FieldAuthorID, v)) +} + +// AuthorIDNEQ applies the NEQ predicate on the "author_id" field. +func AuthorIDNEQ(v int64) predicate.GitCommit { + return predicate.GitCommit(sql.FieldNEQ(FieldAuthorID, v)) +} + +// AuthorIDIn applies the In predicate on the "author_id" field. +func AuthorIDIn(vs ...int64) predicate.GitCommit { + return predicate.GitCommit(sql.FieldIn(FieldAuthorID, vs...)) +} + +// AuthorIDNotIn applies the NotIn predicate on the "author_id" field. +func AuthorIDNotIn(vs ...int64) predicate.GitCommit { + return predicate.GitCommit(sql.FieldNotIn(FieldAuthorID, vs...)) +} + +// AuthorIDGT applies the GT predicate on the "author_id" field. +func AuthorIDGT(v int64) predicate.GitCommit { + return predicate.GitCommit(sql.FieldGT(FieldAuthorID, v)) +} + +// AuthorIDGTE applies the GTE predicate on the "author_id" field. +func AuthorIDGTE(v int64) predicate.GitCommit { + return predicate.GitCommit(sql.FieldGTE(FieldAuthorID, v)) +} + +// AuthorIDLT applies the LT predicate on the "author_id" field. +func AuthorIDLT(v int64) predicate.GitCommit { + return predicate.GitCommit(sql.FieldLT(FieldAuthorID, v)) +} + +// AuthorIDLTE applies the LTE predicate on the "author_id" field. +func AuthorIDLTE(v int64) predicate.GitCommit { + return predicate.GitCommit(sql.FieldLTE(FieldAuthorID, v)) +} + +// DateEQ applies the EQ predicate on the "date" field. +func DateEQ(v time.Time) predicate.GitCommit { + return predicate.GitCommit(sql.FieldEQ(FieldDate, v)) +} + +// DateNEQ applies the NEQ predicate on the "date" field. +func DateNEQ(v time.Time) predicate.GitCommit { + return predicate.GitCommit(sql.FieldNEQ(FieldDate, v)) +} + +// DateIn applies the In predicate on the "date" field. +func DateIn(vs ...time.Time) predicate.GitCommit { + return predicate.GitCommit(sql.FieldIn(FieldDate, vs...)) +} + +// DateNotIn applies the NotIn predicate on the "date" field. +func DateNotIn(vs ...time.Time) predicate.GitCommit { + return predicate.GitCommit(sql.FieldNotIn(FieldDate, vs...)) +} + +// DateGT applies the GT predicate on the "date" field. +func DateGT(v time.Time) predicate.GitCommit { + return predicate.GitCommit(sql.FieldGT(FieldDate, v)) +} + +// DateGTE applies the GTE predicate on the "date" field. +func DateGTE(v time.Time) predicate.GitCommit { + return predicate.GitCommit(sql.FieldGTE(FieldDate, v)) +} + +// DateLT applies the LT predicate on the "date" field. +func DateLT(v time.Time) predicate.GitCommit { + return predicate.GitCommit(sql.FieldLT(FieldDate, v)) +} + +// DateLTE applies the LTE predicate on the "date" field. +func DateLTE(v time.Time) predicate.GitCommit { + return predicate.GitCommit(sql.FieldLTE(FieldDate, v)) +} + +// HasRepository applies the HasEdge predicate on the "repository" edge. +func HasRepository() predicate.GitCommit { + return predicate.GitCommit(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RepositoryTable, RepositoryColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRepositoryWith applies the HasEdge predicate on the "repository" edge with a given conditions (other predicates). +func HasRepositoryWith(preds ...predicate.Repository) predicate.GitCommit { + return predicate.GitCommit(func(s *sql.Selector) { + step := newRepositoryStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.GitCommit) predicate.GitCommit { + return predicate.GitCommit(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.GitCommit) predicate.GitCommit { + return predicate.GitCommit(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.GitCommit) predicate.GitCommit { + return predicate.GitCommit(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/internal/ent/gitcommit_create.go b/internal/ent/gitcommit_create.go new file mode 100644 index 0000000..78ba145 --- /dev/null +++ b/internal/ent/gitcommit_create.go @@ -0,0 +1,699 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/go-faster/bot/internal/ent/gitcommit" + "github.com/go-faster/bot/internal/ent/repository" +) + +// GitCommitCreate is the builder for creating a GitCommit entity. +type GitCommitCreate struct { + config + mutation *GitCommitMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetMessage sets the "message" field. +func (gcc *GitCommitCreate) SetMessage(s string) *GitCommitCreate { + gcc.mutation.SetMessage(s) + return gcc +} + +// SetAuthorLogin sets the "author_login" field. +func (gcc *GitCommitCreate) SetAuthorLogin(s string) *GitCommitCreate { + gcc.mutation.SetAuthorLogin(s) + return gcc +} + +// SetAuthorID sets the "author_id" field. +func (gcc *GitCommitCreate) SetAuthorID(i int64) *GitCommitCreate { + gcc.mutation.SetAuthorID(i) + return gcc +} + +// SetDate sets the "date" field. +func (gcc *GitCommitCreate) SetDate(t time.Time) *GitCommitCreate { + gcc.mutation.SetDate(t) + return gcc +} + +// SetID sets the "id" field. +func (gcc *GitCommitCreate) SetID(s string) *GitCommitCreate { + gcc.mutation.SetID(s) + return gcc +} + +// SetRepositoryID sets the "repository" edge to the Repository entity by ID. +func (gcc *GitCommitCreate) SetRepositoryID(id int64) *GitCommitCreate { + gcc.mutation.SetRepositoryID(id) + return gcc +} + +// SetNillableRepositoryID sets the "repository" edge to the Repository entity by ID if the given value is not nil. +func (gcc *GitCommitCreate) SetNillableRepositoryID(id *int64) *GitCommitCreate { + if id != nil { + gcc = gcc.SetRepositoryID(*id) + } + return gcc +} + +// SetRepository sets the "repository" edge to the Repository entity. +func (gcc *GitCommitCreate) SetRepository(r *Repository) *GitCommitCreate { + return gcc.SetRepositoryID(r.ID) +} + +// Mutation returns the GitCommitMutation object of the builder. +func (gcc *GitCommitCreate) Mutation() *GitCommitMutation { + return gcc.mutation +} + +// Save creates the GitCommit in the database. +func (gcc *GitCommitCreate) Save(ctx context.Context) (*GitCommit, error) { + return withHooks[*GitCommit, GitCommitMutation](ctx, gcc.sqlSave, gcc.mutation, gcc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (gcc *GitCommitCreate) SaveX(ctx context.Context) *GitCommit { + v, err := gcc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (gcc *GitCommitCreate) Exec(ctx context.Context) error { + _, err := gcc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gcc *GitCommitCreate) ExecX(ctx context.Context) { + if err := gcc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (gcc *GitCommitCreate) check() error { + if _, ok := gcc.mutation.Message(); !ok { + return &ValidationError{Name: "message", err: errors.New(`ent: missing required field "GitCommit.message"`)} + } + if _, ok := gcc.mutation.AuthorLogin(); !ok { + return &ValidationError{Name: "author_login", err: errors.New(`ent: missing required field "GitCommit.author_login"`)} + } + if _, ok := gcc.mutation.AuthorID(); !ok { + return &ValidationError{Name: "author_id", err: errors.New(`ent: missing required field "GitCommit.author_id"`)} + } + if _, ok := gcc.mutation.Date(); !ok { + return &ValidationError{Name: "date", err: errors.New(`ent: missing required field "GitCommit.date"`)} + } + return nil +} + +func (gcc *GitCommitCreate) sqlSave(ctx context.Context) (*GitCommit, error) { + if err := gcc.check(); err != nil { + return nil, err + } + _node, _spec := gcc.createSpec() + if err := sqlgraph.CreateNode(ctx, gcc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(string); ok { + _node.ID = id + } else { + return nil, fmt.Errorf("unexpected GitCommit.ID type: %T", _spec.ID.Value) + } + } + gcc.mutation.id = &_node.ID + gcc.mutation.done = true + return _node, nil +} + +func (gcc *GitCommitCreate) createSpec() (*GitCommit, *sqlgraph.CreateSpec) { + var ( + _node = &GitCommit{config: gcc.config} + _spec = sqlgraph.NewCreateSpec(gitcommit.Table, sqlgraph.NewFieldSpec(gitcommit.FieldID, field.TypeString)) + ) + _spec.OnConflict = gcc.conflict + if id, ok := gcc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := gcc.mutation.Message(); ok { + _spec.SetField(gitcommit.FieldMessage, field.TypeString, value) + _node.Message = value + } + if value, ok := gcc.mutation.AuthorLogin(); ok { + _spec.SetField(gitcommit.FieldAuthorLogin, field.TypeString, value) + _node.AuthorLogin = value + } + if value, ok := gcc.mutation.AuthorID(); ok { + _spec.SetField(gitcommit.FieldAuthorID, field.TypeInt64, value) + _node.AuthorID = value + } + if value, ok := gcc.mutation.Date(); ok { + _spec.SetField(gitcommit.FieldDate, field.TypeTime, value) + _node.Date = value + } + if nodes := gcc.mutation.RepositoryIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: gitcommit.RepositoryTable, + Columns: []string{gitcommit.RepositoryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(repository.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.repository_commits = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.GitCommit.Create(). +// SetMessage(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.GitCommitUpsert) { +// SetMessage(v+v). +// }). +// Exec(ctx) +func (gcc *GitCommitCreate) OnConflict(opts ...sql.ConflictOption) *GitCommitUpsertOne { + gcc.conflict = opts + return &GitCommitUpsertOne{ + create: gcc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.GitCommit.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (gcc *GitCommitCreate) OnConflictColumns(columns ...string) *GitCommitUpsertOne { + gcc.conflict = append(gcc.conflict, sql.ConflictColumns(columns...)) + return &GitCommitUpsertOne{ + create: gcc, + } +} + +type ( + // GitCommitUpsertOne is the builder for "upsert"-ing + // one GitCommit node. + GitCommitUpsertOne struct { + create *GitCommitCreate + } + + // GitCommitUpsert is the "OnConflict" setter. + GitCommitUpsert struct { + *sql.UpdateSet + } +) + +// SetMessage sets the "message" field. +func (u *GitCommitUpsert) SetMessage(v string) *GitCommitUpsert { + u.Set(gitcommit.FieldMessage, v) + return u +} + +// UpdateMessage sets the "message" field to the value that was provided on create. +func (u *GitCommitUpsert) UpdateMessage() *GitCommitUpsert { + u.SetExcluded(gitcommit.FieldMessage) + return u +} + +// SetAuthorLogin sets the "author_login" field. +func (u *GitCommitUpsert) SetAuthorLogin(v string) *GitCommitUpsert { + u.Set(gitcommit.FieldAuthorLogin, v) + return u +} + +// UpdateAuthorLogin sets the "author_login" field to the value that was provided on create. +func (u *GitCommitUpsert) UpdateAuthorLogin() *GitCommitUpsert { + u.SetExcluded(gitcommit.FieldAuthorLogin) + return u +} + +// SetAuthorID sets the "author_id" field. +func (u *GitCommitUpsert) SetAuthorID(v int64) *GitCommitUpsert { + u.Set(gitcommit.FieldAuthorID, v) + return u +} + +// UpdateAuthorID sets the "author_id" field to the value that was provided on create. +func (u *GitCommitUpsert) UpdateAuthorID() *GitCommitUpsert { + u.SetExcluded(gitcommit.FieldAuthorID) + return u +} + +// AddAuthorID adds v to the "author_id" field. +func (u *GitCommitUpsert) AddAuthorID(v int64) *GitCommitUpsert { + u.Add(gitcommit.FieldAuthorID, v) + return u +} + +// SetDate sets the "date" field. +func (u *GitCommitUpsert) SetDate(v time.Time) *GitCommitUpsert { + u.Set(gitcommit.FieldDate, v) + return u +} + +// UpdateDate sets the "date" field to the value that was provided on create. +func (u *GitCommitUpsert) UpdateDate() *GitCommitUpsert { + u.SetExcluded(gitcommit.FieldDate) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.GitCommit.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(gitcommit.FieldID) +// }), +// ). +// Exec(ctx) +func (u *GitCommitUpsertOne) UpdateNewValues() *GitCommitUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(gitcommit.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.GitCommit.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *GitCommitUpsertOne) Ignore() *GitCommitUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *GitCommitUpsertOne) DoNothing() *GitCommitUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the GitCommitCreate.OnConflict +// documentation for more info. +func (u *GitCommitUpsertOne) Update(set func(*GitCommitUpsert)) *GitCommitUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&GitCommitUpsert{UpdateSet: update}) + })) + return u +} + +// SetMessage sets the "message" field. +func (u *GitCommitUpsertOne) SetMessage(v string) *GitCommitUpsertOne { + return u.Update(func(s *GitCommitUpsert) { + s.SetMessage(v) + }) +} + +// UpdateMessage sets the "message" field to the value that was provided on create. +func (u *GitCommitUpsertOne) UpdateMessage() *GitCommitUpsertOne { + return u.Update(func(s *GitCommitUpsert) { + s.UpdateMessage() + }) +} + +// SetAuthorLogin sets the "author_login" field. +func (u *GitCommitUpsertOne) SetAuthorLogin(v string) *GitCommitUpsertOne { + return u.Update(func(s *GitCommitUpsert) { + s.SetAuthorLogin(v) + }) +} + +// UpdateAuthorLogin sets the "author_login" field to the value that was provided on create. +func (u *GitCommitUpsertOne) UpdateAuthorLogin() *GitCommitUpsertOne { + return u.Update(func(s *GitCommitUpsert) { + s.UpdateAuthorLogin() + }) +} + +// SetAuthorID sets the "author_id" field. +func (u *GitCommitUpsertOne) SetAuthorID(v int64) *GitCommitUpsertOne { + return u.Update(func(s *GitCommitUpsert) { + s.SetAuthorID(v) + }) +} + +// AddAuthorID adds v to the "author_id" field. +func (u *GitCommitUpsertOne) AddAuthorID(v int64) *GitCommitUpsertOne { + return u.Update(func(s *GitCommitUpsert) { + s.AddAuthorID(v) + }) +} + +// UpdateAuthorID sets the "author_id" field to the value that was provided on create. +func (u *GitCommitUpsertOne) UpdateAuthorID() *GitCommitUpsertOne { + return u.Update(func(s *GitCommitUpsert) { + s.UpdateAuthorID() + }) +} + +// SetDate sets the "date" field. +func (u *GitCommitUpsertOne) SetDate(v time.Time) *GitCommitUpsertOne { + return u.Update(func(s *GitCommitUpsert) { + s.SetDate(v) + }) +} + +// UpdateDate sets the "date" field to the value that was provided on create. +func (u *GitCommitUpsertOne) UpdateDate() *GitCommitUpsertOne { + return u.Update(func(s *GitCommitUpsert) { + s.UpdateDate() + }) +} + +// Exec executes the query. +func (u *GitCommitUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for GitCommitCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *GitCommitUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *GitCommitUpsertOne) ID(ctx context.Context) (id string, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("ent: GitCommitUpsertOne.ID is not supported by MySQL driver. Use GitCommitUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *GitCommitUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// GitCommitCreateBulk is the builder for creating many GitCommit entities in bulk. +type GitCommitCreateBulk struct { + config + builders []*GitCommitCreate + conflict []sql.ConflictOption +} + +// Save creates the GitCommit entities in the database. +func (gccb *GitCommitCreateBulk) Save(ctx context.Context) ([]*GitCommit, error) { + specs := make([]*sqlgraph.CreateSpec, len(gccb.builders)) + nodes := make([]*GitCommit, len(gccb.builders)) + mutators := make([]Mutator, len(gccb.builders)) + for i := range gccb.builders { + func(i int, root context.Context) { + builder := gccb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*GitCommitMutation) + 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, gccb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = gccb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, gccb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, gccb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (gccb *GitCommitCreateBulk) SaveX(ctx context.Context) []*GitCommit { + v, err := gccb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (gccb *GitCommitCreateBulk) Exec(ctx context.Context) error { + _, err := gccb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gccb *GitCommitCreateBulk) ExecX(ctx context.Context) { + if err := gccb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.GitCommit.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.GitCommitUpsert) { +// SetMessage(v+v). +// }). +// Exec(ctx) +func (gccb *GitCommitCreateBulk) OnConflict(opts ...sql.ConflictOption) *GitCommitUpsertBulk { + gccb.conflict = opts + return &GitCommitUpsertBulk{ + create: gccb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.GitCommit.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (gccb *GitCommitCreateBulk) OnConflictColumns(columns ...string) *GitCommitUpsertBulk { + gccb.conflict = append(gccb.conflict, sql.ConflictColumns(columns...)) + return &GitCommitUpsertBulk{ + create: gccb, + } +} + +// GitCommitUpsertBulk is the builder for "upsert"-ing +// a bulk of GitCommit nodes. +type GitCommitUpsertBulk struct { + create *GitCommitCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.GitCommit.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(gitcommit.FieldID) +// }), +// ). +// Exec(ctx) +func (u *GitCommitUpsertBulk) UpdateNewValues() *GitCommitUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(gitcommit.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.GitCommit.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *GitCommitUpsertBulk) Ignore() *GitCommitUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *GitCommitUpsertBulk) DoNothing() *GitCommitUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the GitCommitCreateBulk.OnConflict +// documentation for more info. +func (u *GitCommitUpsertBulk) Update(set func(*GitCommitUpsert)) *GitCommitUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&GitCommitUpsert{UpdateSet: update}) + })) + return u +} + +// SetMessage sets the "message" field. +func (u *GitCommitUpsertBulk) SetMessage(v string) *GitCommitUpsertBulk { + return u.Update(func(s *GitCommitUpsert) { + s.SetMessage(v) + }) +} + +// UpdateMessage sets the "message" field to the value that was provided on create. +func (u *GitCommitUpsertBulk) UpdateMessage() *GitCommitUpsertBulk { + return u.Update(func(s *GitCommitUpsert) { + s.UpdateMessage() + }) +} + +// SetAuthorLogin sets the "author_login" field. +func (u *GitCommitUpsertBulk) SetAuthorLogin(v string) *GitCommitUpsertBulk { + return u.Update(func(s *GitCommitUpsert) { + s.SetAuthorLogin(v) + }) +} + +// UpdateAuthorLogin sets the "author_login" field to the value that was provided on create. +func (u *GitCommitUpsertBulk) UpdateAuthorLogin() *GitCommitUpsertBulk { + return u.Update(func(s *GitCommitUpsert) { + s.UpdateAuthorLogin() + }) +} + +// SetAuthorID sets the "author_id" field. +func (u *GitCommitUpsertBulk) SetAuthorID(v int64) *GitCommitUpsertBulk { + return u.Update(func(s *GitCommitUpsert) { + s.SetAuthorID(v) + }) +} + +// AddAuthorID adds v to the "author_id" field. +func (u *GitCommitUpsertBulk) AddAuthorID(v int64) *GitCommitUpsertBulk { + return u.Update(func(s *GitCommitUpsert) { + s.AddAuthorID(v) + }) +} + +// UpdateAuthorID sets the "author_id" field to the value that was provided on create. +func (u *GitCommitUpsertBulk) UpdateAuthorID() *GitCommitUpsertBulk { + return u.Update(func(s *GitCommitUpsert) { + s.UpdateAuthorID() + }) +} + +// SetDate sets the "date" field. +func (u *GitCommitUpsertBulk) SetDate(v time.Time) *GitCommitUpsertBulk { + return u.Update(func(s *GitCommitUpsert) { + s.SetDate(v) + }) +} + +// UpdateDate sets the "date" field to the value that was provided on create. +func (u *GitCommitUpsertBulk) UpdateDate() *GitCommitUpsertBulk { + return u.Update(func(s *GitCommitUpsert) { + s.UpdateDate() + }) +} + +// Exec executes the query. +func (u *GitCommitUpsertBulk) Exec(ctx context.Context) error { + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the GitCommitCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for GitCommitCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *GitCommitUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/gitcommit_delete.go b/internal/ent/gitcommit_delete.go new file mode 100644 index 0000000..f1cc6b9 --- /dev/null +++ b/internal/ent/gitcommit_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/go-faster/bot/internal/ent/gitcommit" + "github.com/go-faster/bot/internal/ent/predicate" +) + +// GitCommitDelete is the builder for deleting a GitCommit entity. +type GitCommitDelete struct { + config + hooks []Hook + mutation *GitCommitMutation +} + +// Where appends a list predicates to the GitCommitDelete builder. +func (gcd *GitCommitDelete) Where(ps ...predicate.GitCommit) *GitCommitDelete { + gcd.mutation.Where(ps...) + return gcd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (gcd *GitCommitDelete) Exec(ctx context.Context) (int, error) { + return withHooks[int, GitCommitMutation](ctx, gcd.sqlExec, gcd.mutation, gcd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (gcd *GitCommitDelete) ExecX(ctx context.Context) int { + n, err := gcd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (gcd *GitCommitDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(gitcommit.Table, sqlgraph.NewFieldSpec(gitcommit.FieldID, field.TypeString)) + if ps := gcd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, gcd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + gcd.mutation.done = true + return affected, err +} + +// GitCommitDeleteOne is the builder for deleting a single GitCommit entity. +type GitCommitDeleteOne struct { + gcd *GitCommitDelete +} + +// Where appends a list predicates to the GitCommitDelete builder. +func (gcdo *GitCommitDeleteOne) Where(ps ...predicate.GitCommit) *GitCommitDeleteOne { + gcdo.gcd.mutation.Where(ps...) + return gcdo +} + +// Exec executes the deletion query. +func (gcdo *GitCommitDeleteOne) Exec(ctx context.Context) error { + n, err := gcdo.gcd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{gitcommit.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (gcdo *GitCommitDeleteOne) ExecX(ctx context.Context) { + if err := gcdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/internal/ent/gitcommit_query.go b/internal/ent/gitcommit_query.go new file mode 100644 index 0000000..e548357 --- /dev/null +++ b/internal/ent/gitcommit_query.go @@ -0,0 +1,613 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/go-faster/bot/internal/ent/gitcommit" + "github.com/go-faster/bot/internal/ent/predicate" + "github.com/go-faster/bot/internal/ent/repository" +) + +// GitCommitQuery is the builder for querying GitCommit entities. +type GitCommitQuery struct { + config + ctx *QueryContext + order []gitcommit.OrderOption + inters []Interceptor + predicates []predicate.GitCommit + withRepository *RepositoryQuery + withFKs bool + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the GitCommitQuery builder. +func (gcq *GitCommitQuery) Where(ps ...predicate.GitCommit) *GitCommitQuery { + gcq.predicates = append(gcq.predicates, ps...) + return gcq +} + +// Limit the number of records to be returned by this query. +func (gcq *GitCommitQuery) Limit(limit int) *GitCommitQuery { + gcq.ctx.Limit = &limit + return gcq +} + +// Offset to start from. +func (gcq *GitCommitQuery) Offset(offset int) *GitCommitQuery { + gcq.ctx.Offset = &offset + return gcq +} + +// 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 (gcq *GitCommitQuery) Unique(unique bool) *GitCommitQuery { + gcq.ctx.Unique = &unique + return gcq +} + +// Order specifies how the records should be ordered. +func (gcq *GitCommitQuery) Order(o ...gitcommit.OrderOption) *GitCommitQuery { + gcq.order = append(gcq.order, o...) + return gcq +} + +// QueryRepository chains the current query on the "repository" edge. +func (gcq *GitCommitQuery) QueryRepository() *RepositoryQuery { + query := (&RepositoryClient{config: gcq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := gcq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := gcq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(gitcommit.Table, gitcommit.FieldID, selector), + sqlgraph.To(repository.Table, repository.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, gitcommit.RepositoryTable, gitcommit.RepositoryColumn), + ) + fromU = sqlgraph.SetNeighbors(gcq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first GitCommit entity from the query. +// Returns a *NotFoundError when no GitCommit was found. +func (gcq *GitCommitQuery) First(ctx context.Context) (*GitCommit, error) { + nodes, err := gcq.Limit(1).All(setContextOp(ctx, gcq.ctx, "First")) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{gitcommit.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (gcq *GitCommitQuery) FirstX(ctx context.Context) *GitCommit { + node, err := gcq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first GitCommit ID from the query. +// Returns a *NotFoundError when no GitCommit ID was found. +func (gcq *GitCommitQuery) FirstID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = gcq.Limit(1).IDs(setContextOp(ctx, gcq.ctx, "FirstID")); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{gitcommit.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (gcq *GitCommitQuery) FirstIDX(ctx context.Context) string { + id, err := gcq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single GitCommit entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one GitCommit entity is found. +// Returns a *NotFoundError when no GitCommit entities are found. +func (gcq *GitCommitQuery) Only(ctx context.Context) (*GitCommit, error) { + nodes, err := gcq.Limit(2).All(setContextOp(ctx, gcq.ctx, "Only")) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{gitcommit.Label} + default: + return nil, &NotSingularError{gitcommit.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (gcq *GitCommitQuery) OnlyX(ctx context.Context) *GitCommit { + node, err := gcq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only GitCommit ID in the query. +// Returns a *NotSingularError when more than one GitCommit ID is found. +// Returns a *NotFoundError when no entities are found. +func (gcq *GitCommitQuery) OnlyID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = gcq.Limit(2).IDs(setContextOp(ctx, gcq.ctx, "OnlyID")); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{gitcommit.Label} + default: + err = &NotSingularError{gitcommit.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (gcq *GitCommitQuery) OnlyIDX(ctx context.Context) string { + id, err := gcq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of GitCommits. +func (gcq *GitCommitQuery) All(ctx context.Context) ([]*GitCommit, error) { + ctx = setContextOp(ctx, gcq.ctx, "All") + if err := gcq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*GitCommit, *GitCommitQuery]() + return withInterceptors[[]*GitCommit](ctx, gcq, qr, gcq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (gcq *GitCommitQuery) AllX(ctx context.Context) []*GitCommit { + nodes, err := gcq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of GitCommit IDs. +func (gcq *GitCommitQuery) IDs(ctx context.Context) (ids []string, err error) { + if gcq.ctx.Unique == nil && gcq.path != nil { + gcq.Unique(true) + } + ctx = setContextOp(ctx, gcq.ctx, "IDs") + if err = gcq.Select(gitcommit.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (gcq *GitCommitQuery) IDsX(ctx context.Context) []string { + ids, err := gcq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (gcq *GitCommitQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, gcq.ctx, "Count") + if err := gcq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, gcq, querierCount[*GitCommitQuery](), gcq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (gcq *GitCommitQuery) CountX(ctx context.Context) int { + count, err := gcq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (gcq *GitCommitQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, gcq.ctx, "Exist") + switch _, err := gcq.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 (gcq *GitCommitQuery) ExistX(ctx context.Context) bool { + exist, err := gcq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the GitCommitQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (gcq *GitCommitQuery) Clone() *GitCommitQuery { + if gcq == nil { + return nil + } + return &GitCommitQuery{ + config: gcq.config, + ctx: gcq.ctx.Clone(), + order: append([]gitcommit.OrderOption{}, gcq.order...), + inters: append([]Interceptor{}, gcq.inters...), + predicates: append([]predicate.GitCommit{}, gcq.predicates...), + withRepository: gcq.withRepository.Clone(), + // clone intermediate query. + sql: gcq.sql.Clone(), + path: gcq.path, + } +} + +// WithRepository tells the query-builder to eager-load the nodes that are connected to +// the "repository" edge. The optional arguments are used to configure the query builder of the edge. +func (gcq *GitCommitQuery) WithRepository(opts ...func(*RepositoryQuery)) *GitCommitQuery { + query := (&RepositoryClient{config: gcq.config}).Query() + for _, opt := range opts { + opt(query) + } + gcq.withRepository = query + return gcq +} + +// 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 { +// Message string `json:"message,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.GitCommit.Query(). +// GroupBy(gitcommit.FieldMessage). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (gcq *GitCommitQuery) GroupBy(field string, fields ...string) *GitCommitGroupBy { + gcq.ctx.Fields = append([]string{field}, fields...) + grbuild := &GitCommitGroupBy{build: gcq} + grbuild.flds = &gcq.ctx.Fields + grbuild.label = gitcommit.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 { +// Message string `json:"message,omitempty"` +// } +// +// client.GitCommit.Query(). +// Select(gitcommit.FieldMessage). +// Scan(ctx, &v) +func (gcq *GitCommitQuery) Select(fields ...string) *GitCommitSelect { + gcq.ctx.Fields = append(gcq.ctx.Fields, fields...) + sbuild := &GitCommitSelect{GitCommitQuery: gcq} + sbuild.label = gitcommit.Label + sbuild.flds, sbuild.scan = &gcq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a GitCommitSelect configured with the given aggregations. +func (gcq *GitCommitQuery) Aggregate(fns ...AggregateFunc) *GitCommitSelect { + return gcq.Select().Aggregate(fns...) +} + +func (gcq *GitCommitQuery) prepareQuery(ctx context.Context) error { + for _, inter := range gcq.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, gcq); err != nil { + return err + } + } + } + for _, f := range gcq.ctx.Fields { + if !gitcommit.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if gcq.path != nil { + prev, err := gcq.path(ctx) + if err != nil { + return err + } + gcq.sql = prev + } + return nil +} + +func (gcq *GitCommitQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*GitCommit, error) { + var ( + nodes = []*GitCommit{} + withFKs = gcq.withFKs + _spec = gcq.querySpec() + loadedTypes = [1]bool{ + gcq.withRepository != nil, + } + ) + if gcq.withRepository != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, gitcommit.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*GitCommit).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &GitCommit{config: gcq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, gcq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := gcq.withRepository; query != nil { + if err := gcq.loadRepository(ctx, query, nodes, nil, + func(n *GitCommit, e *Repository) { n.Edges.Repository = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (gcq *GitCommitQuery) loadRepository(ctx context.Context, query *RepositoryQuery, nodes []*GitCommit, init func(*GitCommit), assign func(*GitCommit, *Repository)) error { + ids := make([]int64, 0, len(nodes)) + nodeids := make(map[int64][]*GitCommit) + for i := range nodes { + if nodes[i].repository_commits == nil { + continue + } + fk := *nodes[i].repository_commits + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(repository.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "repository_commits" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (gcq *GitCommitQuery) sqlCount(ctx context.Context) (int, error) { + _spec := gcq.querySpec() + _spec.Node.Columns = gcq.ctx.Fields + if len(gcq.ctx.Fields) > 0 { + _spec.Unique = gcq.ctx.Unique != nil && *gcq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, gcq.driver, _spec) +} + +func (gcq *GitCommitQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(gitcommit.Table, gitcommit.Columns, sqlgraph.NewFieldSpec(gitcommit.FieldID, field.TypeString)) + _spec.From = gcq.sql + if unique := gcq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if gcq.path != nil { + _spec.Unique = true + } + if fields := gcq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, gitcommit.FieldID) + for i := range fields { + if fields[i] != gitcommit.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := gcq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := gcq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := gcq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := gcq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (gcq *GitCommitQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(gcq.driver.Dialect()) + t1 := builder.Table(gitcommit.Table) + columns := gcq.ctx.Fields + if len(columns) == 0 { + columns = gitcommit.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if gcq.sql != nil { + selector = gcq.sql + selector.Select(selector.Columns(columns...)...) + } + if gcq.ctx.Unique != nil && *gcq.ctx.Unique { + selector.Distinct() + } + for _, p := range gcq.predicates { + p(selector) + } + for _, p := range gcq.order { + p(selector) + } + if offset := gcq.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 := gcq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// GitCommitGroupBy is the group-by builder for GitCommit entities. +type GitCommitGroupBy struct { + selector + build *GitCommitQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (gcgb *GitCommitGroupBy) Aggregate(fns ...AggregateFunc) *GitCommitGroupBy { + gcgb.fns = append(gcgb.fns, fns...) + return gcgb +} + +// Scan applies the selector query and scans the result into the given value. +func (gcgb *GitCommitGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, gcgb.build.ctx, "GroupBy") + if err := gcgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*GitCommitQuery, *GitCommitGroupBy](ctx, gcgb.build, gcgb, gcgb.build.inters, v) +} + +func (gcgb *GitCommitGroupBy) sqlScan(ctx context.Context, root *GitCommitQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(gcgb.fns)) + for _, fn := range gcgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*gcgb.flds)+len(gcgb.fns)) + for _, f := range *gcgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*gcgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := gcgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// GitCommitSelect is the builder for selecting fields of GitCommit entities. +type GitCommitSelect struct { + *GitCommitQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (gcs *GitCommitSelect) Aggregate(fns ...AggregateFunc) *GitCommitSelect { + gcs.fns = append(gcs.fns, fns...) + return gcs +} + +// Scan applies the selector query and scans the result into the given value. +func (gcs *GitCommitSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, gcs.ctx, "Select") + if err := gcs.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*GitCommitQuery, *GitCommitSelect](ctx, gcs.GitCommitQuery, gcs, gcs.inters, v) +} + +func (gcs *GitCommitSelect) sqlScan(ctx context.Context, root *GitCommitQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(gcs.fns)) + for _, fn := range gcs.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*gcs.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 := gcs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/internal/ent/gitcommit_update.go b/internal/ent/gitcommit_update.go new file mode 100644 index 0000000..ee792c5 --- /dev/null +++ b/internal/ent/gitcommit_update.go @@ -0,0 +1,377 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/go-faster/bot/internal/ent/gitcommit" + "github.com/go-faster/bot/internal/ent/predicate" + "github.com/go-faster/bot/internal/ent/repository" +) + +// GitCommitUpdate is the builder for updating GitCommit entities. +type GitCommitUpdate struct { + config + hooks []Hook + mutation *GitCommitMutation +} + +// Where appends a list predicates to the GitCommitUpdate builder. +func (gcu *GitCommitUpdate) Where(ps ...predicate.GitCommit) *GitCommitUpdate { + gcu.mutation.Where(ps...) + return gcu +} + +// SetMessage sets the "message" field. +func (gcu *GitCommitUpdate) SetMessage(s string) *GitCommitUpdate { + gcu.mutation.SetMessage(s) + return gcu +} + +// SetAuthorLogin sets the "author_login" field. +func (gcu *GitCommitUpdate) SetAuthorLogin(s string) *GitCommitUpdate { + gcu.mutation.SetAuthorLogin(s) + return gcu +} + +// SetAuthorID sets the "author_id" field. +func (gcu *GitCommitUpdate) SetAuthorID(i int64) *GitCommitUpdate { + gcu.mutation.ResetAuthorID() + gcu.mutation.SetAuthorID(i) + return gcu +} + +// AddAuthorID adds i to the "author_id" field. +func (gcu *GitCommitUpdate) AddAuthorID(i int64) *GitCommitUpdate { + gcu.mutation.AddAuthorID(i) + return gcu +} + +// SetDate sets the "date" field. +func (gcu *GitCommitUpdate) SetDate(t time.Time) *GitCommitUpdate { + gcu.mutation.SetDate(t) + return gcu +} + +// SetRepositoryID sets the "repository" edge to the Repository entity by ID. +func (gcu *GitCommitUpdate) SetRepositoryID(id int64) *GitCommitUpdate { + gcu.mutation.SetRepositoryID(id) + return gcu +} + +// SetNillableRepositoryID sets the "repository" edge to the Repository entity by ID if the given value is not nil. +func (gcu *GitCommitUpdate) SetNillableRepositoryID(id *int64) *GitCommitUpdate { + if id != nil { + gcu = gcu.SetRepositoryID(*id) + } + return gcu +} + +// SetRepository sets the "repository" edge to the Repository entity. +func (gcu *GitCommitUpdate) SetRepository(r *Repository) *GitCommitUpdate { + return gcu.SetRepositoryID(r.ID) +} + +// Mutation returns the GitCommitMutation object of the builder. +func (gcu *GitCommitUpdate) Mutation() *GitCommitMutation { + return gcu.mutation +} + +// ClearRepository clears the "repository" edge to the Repository entity. +func (gcu *GitCommitUpdate) ClearRepository() *GitCommitUpdate { + gcu.mutation.ClearRepository() + return gcu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (gcu *GitCommitUpdate) Save(ctx context.Context) (int, error) { + return withHooks[int, GitCommitMutation](ctx, gcu.sqlSave, gcu.mutation, gcu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (gcu *GitCommitUpdate) SaveX(ctx context.Context) int { + affected, err := gcu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (gcu *GitCommitUpdate) Exec(ctx context.Context) error { + _, err := gcu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gcu *GitCommitUpdate) ExecX(ctx context.Context) { + if err := gcu.Exec(ctx); err != nil { + panic(err) + } +} + +func (gcu *GitCommitUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(gitcommit.Table, gitcommit.Columns, sqlgraph.NewFieldSpec(gitcommit.FieldID, field.TypeString)) + if ps := gcu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := gcu.mutation.Message(); ok { + _spec.SetField(gitcommit.FieldMessage, field.TypeString, value) + } + if value, ok := gcu.mutation.AuthorLogin(); ok { + _spec.SetField(gitcommit.FieldAuthorLogin, field.TypeString, value) + } + if value, ok := gcu.mutation.AuthorID(); ok { + _spec.SetField(gitcommit.FieldAuthorID, field.TypeInt64, value) + } + if value, ok := gcu.mutation.AddedAuthorID(); ok { + _spec.AddField(gitcommit.FieldAuthorID, field.TypeInt64, value) + } + if value, ok := gcu.mutation.Date(); ok { + _spec.SetField(gitcommit.FieldDate, field.TypeTime, value) + } + if gcu.mutation.RepositoryCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: gitcommit.RepositoryTable, + Columns: []string{gitcommit.RepositoryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(repository.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := gcu.mutation.RepositoryIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: gitcommit.RepositoryTable, + Columns: []string{gitcommit.RepositoryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(repository.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, gcu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{gitcommit.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + gcu.mutation.done = true + return n, nil +} + +// GitCommitUpdateOne is the builder for updating a single GitCommit entity. +type GitCommitUpdateOne struct { + config + fields []string + hooks []Hook + mutation *GitCommitMutation +} + +// SetMessage sets the "message" field. +func (gcuo *GitCommitUpdateOne) SetMessage(s string) *GitCommitUpdateOne { + gcuo.mutation.SetMessage(s) + return gcuo +} + +// SetAuthorLogin sets the "author_login" field. +func (gcuo *GitCommitUpdateOne) SetAuthorLogin(s string) *GitCommitUpdateOne { + gcuo.mutation.SetAuthorLogin(s) + return gcuo +} + +// SetAuthorID sets the "author_id" field. +func (gcuo *GitCommitUpdateOne) SetAuthorID(i int64) *GitCommitUpdateOne { + gcuo.mutation.ResetAuthorID() + gcuo.mutation.SetAuthorID(i) + return gcuo +} + +// AddAuthorID adds i to the "author_id" field. +func (gcuo *GitCommitUpdateOne) AddAuthorID(i int64) *GitCommitUpdateOne { + gcuo.mutation.AddAuthorID(i) + return gcuo +} + +// SetDate sets the "date" field. +func (gcuo *GitCommitUpdateOne) SetDate(t time.Time) *GitCommitUpdateOne { + gcuo.mutation.SetDate(t) + return gcuo +} + +// SetRepositoryID sets the "repository" edge to the Repository entity by ID. +func (gcuo *GitCommitUpdateOne) SetRepositoryID(id int64) *GitCommitUpdateOne { + gcuo.mutation.SetRepositoryID(id) + return gcuo +} + +// SetNillableRepositoryID sets the "repository" edge to the Repository entity by ID if the given value is not nil. +func (gcuo *GitCommitUpdateOne) SetNillableRepositoryID(id *int64) *GitCommitUpdateOne { + if id != nil { + gcuo = gcuo.SetRepositoryID(*id) + } + return gcuo +} + +// SetRepository sets the "repository" edge to the Repository entity. +func (gcuo *GitCommitUpdateOne) SetRepository(r *Repository) *GitCommitUpdateOne { + return gcuo.SetRepositoryID(r.ID) +} + +// Mutation returns the GitCommitMutation object of the builder. +func (gcuo *GitCommitUpdateOne) Mutation() *GitCommitMutation { + return gcuo.mutation +} + +// ClearRepository clears the "repository" edge to the Repository entity. +func (gcuo *GitCommitUpdateOne) ClearRepository() *GitCommitUpdateOne { + gcuo.mutation.ClearRepository() + return gcuo +} + +// Where appends a list predicates to the GitCommitUpdate builder. +func (gcuo *GitCommitUpdateOne) Where(ps ...predicate.GitCommit) *GitCommitUpdateOne { + gcuo.mutation.Where(ps...) + return gcuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (gcuo *GitCommitUpdateOne) Select(field string, fields ...string) *GitCommitUpdateOne { + gcuo.fields = append([]string{field}, fields...) + return gcuo +} + +// Save executes the query and returns the updated GitCommit entity. +func (gcuo *GitCommitUpdateOne) Save(ctx context.Context) (*GitCommit, error) { + return withHooks[*GitCommit, GitCommitMutation](ctx, gcuo.sqlSave, gcuo.mutation, gcuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (gcuo *GitCommitUpdateOne) SaveX(ctx context.Context) *GitCommit { + node, err := gcuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (gcuo *GitCommitUpdateOne) Exec(ctx context.Context) error { + _, err := gcuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gcuo *GitCommitUpdateOne) ExecX(ctx context.Context) { + if err := gcuo.Exec(ctx); err != nil { + panic(err) + } +} + +func (gcuo *GitCommitUpdateOne) sqlSave(ctx context.Context) (_node *GitCommit, err error) { + _spec := sqlgraph.NewUpdateSpec(gitcommit.Table, gitcommit.Columns, sqlgraph.NewFieldSpec(gitcommit.FieldID, field.TypeString)) + id, ok := gcuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "GitCommit.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := gcuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, gitcommit.FieldID) + for _, f := range fields { + if !gitcommit.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != gitcommit.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := gcuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := gcuo.mutation.Message(); ok { + _spec.SetField(gitcommit.FieldMessage, field.TypeString, value) + } + if value, ok := gcuo.mutation.AuthorLogin(); ok { + _spec.SetField(gitcommit.FieldAuthorLogin, field.TypeString, value) + } + if value, ok := gcuo.mutation.AuthorID(); ok { + _spec.SetField(gitcommit.FieldAuthorID, field.TypeInt64, value) + } + if value, ok := gcuo.mutation.AddedAuthorID(); ok { + _spec.AddField(gitcommit.FieldAuthorID, field.TypeInt64, value) + } + if value, ok := gcuo.mutation.Date(); ok { + _spec.SetField(gitcommit.FieldDate, field.TypeTime, value) + } + if gcuo.mutation.RepositoryCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: gitcommit.RepositoryTable, + Columns: []string{gitcommit.RepositoryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(repository.FieldID, field.TypeInt64), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := gcuo.mutation.RepositoryIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: gitcommit.RepositoryTable, + Columns: []string{gitcommit.RepositoryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(repository.FieldID, field.TypeInt64), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &GitCommit{config: gcuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, gcuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{gitcommit.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + gcuo.mutation.done = true + return _node, nil +} diff --git a/internal/ent/hook/hook.go b/internal/ent/hook/hook.go index c5954f9..fc7966b 100644 --- a/internal/ent/hook/hook.go +++ b/internal/ent/hook/hook.go @@ -33,6 +33,18 @@ func (f GPTDialogFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, e return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GPTDialogMutation", m) } +// The GitCommitFunc type is an adapter to allow the use of ordinary +// function as GitCommit mutator. +type GitCommitFunc func(context.Context, *ent.GitCommitMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f GitCommitFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.GitCommitMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GitCommitMutation", m) +} + // The LastChannelMessageFunc type is an adapter to allow the use of ordinary // function as LastChannelMessage mutator. type LastChannelMessageFunc func(context.Context, *ent.LastChannelMessageMutation) (ent.Value, error) diff --git a/internal/ent/intercept/intercept.go b/internal/ent/intercept/intercept.go index 63c496b..5b1caf0 100644 --- a/internal/ent/intercept/intercept.go +++ b/internal/ent/intercept/intercept.go @@ -9,6 +9,7 @@ import ( "entgo.io/ent/dialect/sql" "github.com/go-faster/bot/internal/ent" "github.com/go-faster/bot/internal/ent/check" + "github.com/go-faster/bot/internal/ent/gitcommit" "github.com/go-faster/bot/internal/ent/gptdialog" "github.com/go-faster/bot/internal/ent/lastchannelmessage" "github.com/go-faster/bot/internal/ent/organization" @@ -131,6 +132,33 @@ func (f TraverseGPTDialog) Traverse(ctx context.Context, q ent.Query) error { return fmt.Errorf("unexpected query type %T. expect *ent.GPTDialogQuery", q) } +// The GitCommitFunc type is an adapter to allow the use of ordinary function as a Querier. +type GitCommitFunc func(context.Context, *ent.GitCommitQuery) (ent.Value, error) + +// Query calls f(ctx, q). +func (f GitCommitFunc) Query(ctx context.Context, q ent.Query) (ent.Value, error) { + if q, ok := q.(*ent.GitCommitQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *ent.GitCommitQuery", q) +} + +// The TraverseGitCommit type is an adapter to allow the use of ordinary function as Traverser. +type TraverseGitCommit func(context.Context, *ent.GitCommitQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseGitCommit) Intercept(next ent.Querier) ent.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseGitCommit) Traverse(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.GitCommitQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *ent.GitCommitQuery", q) +} + // The LastChannelMessageFunc type is an adapter to allow the use of ordinary function as a Querier. type LastChannelMessageFunc func(context.Context, *ent.LastChannelMessageQuery) (ent.Value, error) @@ -354,6 +382,8 @@ func NewQuery(q ent.Query) (Query, error) { return &query[*ent.CheckQuery, predicate.Check, check.OrderOption]{typ: ent.TypeCheck, tq: q}, nil case *ent.GPTDialogQuery: return &query[*ent.GPTDialogQuery, predicate.GPTDialog, gptdialog.OrderOption]{typ: ent.TypeGPTDialog, tq: q}, nil + case *ent.GitCommitQuery: + return &query[*ent.GitCommitQuery, predicate.GitCommit, gitcommit.OrderOption]{typ: ent.TypeGitCommit, tq: q}, nil case *ent.LastChannelMessageQuery: return &query[*ent.LastChannelMessageQuery, predicate.LastChannelMessage, lastchannelmessage.OrderOption]{typ: ent.TypeLastChannelMessage, tq: q}, nil case *ent.OrganizationQuery: diff --git a/internal/ent/migrate/schema.go b/internal/ent/migrate/schema.go index 9e0ae98..95303b2 100644 --- a/internal/ent/migrate/schema.go +++ b/internal/ent/migrate/schema.go @@ -54,6 +54,29 @@ var ( }, }, } + // GitCommitsColumns holds the columns for the "git_commits" table. + GitCommitsColumns = []*schema.Column{ + {Name: "sha", Type: field.TypeString, Unique: true}, + {Name: "message", Type: field.TypeString}, + {Name: "author_login", Type: field.TypeString}, + {Name: "author_id", Type: field.TypeInt64}, + {Name: "date", Type: field.TypeTime}, + {Name: "repository_commits", Type: field.TypeInt64, Nullable: true}, + } + // GitCommitsTable holds the schema information for the "git_commits" table. + GitCommitsTable = &schema.Table{ + Name: "git_commits", + Columns: GitCommitsColumns, + PrimaryKey: []*schema.Column{GitCommitsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "git_commits_repositories_commits", + Columns: []*schema.Column{GitCommitsColumns[5]}, + RefColumns: []*schema.Column{RepositoriesColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } // LastChannelMessagesColumns holds the columns for the "last_channel_messages" table. LastChannelMessagesColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt64, Increment: true}, @@ -196,6 +219,7 @@ var ( Tables = []*schema.Table{ ChecksTable, GptDialogsTable, + GitCommitsTable, LastChannelMessagesTable, OrganizationsTable, PrNotificationsTable, @@ -208,6 +232,7 @@ var ( ) func init() { + GitCommitsTable.ForeignKeys[0].RefTable = RepositoriesTable RepositoriesTable.ForeignKeys[0].RefTable = OrganizationsTable TelegramChannelStatesTable.ForeignKeys[0].RefTable = TelegramUserStatesTable } diff --git a/internal/ent/mutation.go b/internal/ent/mutation.go index 589403c..ec2a7d6 100644 --- a/internal/ent/mutation.go +++ b/internal/ent/mutation.go @@ -12,6 +12,7 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" "github.com/go-faster/bot/internal/ent/check" + "github.com/go-faster/bot/internal/ent/gitcommit" "github.com/go-faster/bot/internal/ent/gptdialog" "github.com/go-faster/bot/internal/ent/lastchannelmessage" "github.com/go-faster/bot/internal/ent/organization" @@ -36,6 +37,7 @@ const ( // Node types. TypeCheck = "Check" TypeGPTDialog = "GPTDialog" + TypeGitCommit = "GitCommit" TypeLastChannelMessage = "LastChannelMessage" TypeOrganization = "Organization" TypePRNotification = "PRNotification" @@ -1460,6 +1462,603 @@ func (m *GPTDialogMutation) ResetEdge(name string) error { return fmt.Errorf("unknown GPTDialog edge %s", name) } +// GitCommitMutation represents an operation that mutates the GitCommit nodes in the graph. +type GitCommitMutation struct { + config + op Op + typ string + id *string + message *string + author_login *string + author_id *int64 + addauthor_id *int64 + date *time.Time + clearedFields map[string]struct{} + repository *int64 + clearedrepository bool + done bool + oldValue func(context.Context) (*GitCommit, error) + predicates []predicate.GitCommit +} + +var _ ent.Mutation = (*GitCommitMutation)(nil) + +// gitcommitOption allows management of the mutation configuration using functional options. +type gitcommitOption func(*GitCommitMutation) + +// newGitCommitMutation creates new mutation for the GitCommit entity. +func newGitCommitMutation(c config, op Op, opts ...gitcommitOption) *GitCommitMutation { + m := &GitCommitMutation{ + config: c, + op: op, + typ: TypeGitCommit, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withGitCommitID sets the ID field of the mutation. +func withGitCommitID(id string) gitcommitOption { + return func(m *GitCommitMutation) { + var ( + err error + once sync.Once + value *GitCommit + ) + m.oldValue = func(ctx context.Context) (*GitCommit, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().GitCommit.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withGitCommit sets the old GitCommit of the mutation. +func withGitCommit(node *GitCommit) gitcommitOption { + return func(m *GitCommitMutation) { + m.oldValue = func(context.Context) (*GitCommit, 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 GitCommitMutation) 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 GitCommitMutation) 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 +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of GitCommit entities. +func (m *GitCommitMutation) SetID(id string) { + m.id = &id +} + +// 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 *GitCommitMutation) ID() (id string, 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 *GitCommitMutation) IDs(ctx context.Context) ([]string, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []string{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().GitCommit.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetMessage sets the "message" field. +func (m *GitCommitMutation) SetMessage(s string) { + m.message = &s +} + +// Message returns the value of the "message" field in the mutation. +func (m *GitCommitMutation) Message() (r string, exists bool) { + v := m.message + if v == nil { + return + } + return *v, true +} + +// OldMessage returns the old "message" field's value of the GitCommit entity. +// If the GitCommit 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 *GitCommitMutation) OldMessage(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMessage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMessage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMessage: %w", err) + } + return oldValue.Message, nil +} + +// ResetMessage resets all changes to the "message" field. +func (m *GitCommitMutation) ResetMessage() { + m.message = nil +} + +// SetAuthorLogin sets the "author_login" field. +func (m *GitCommitMutation) SetAuthorLogin(s string) { + m.author_login = &s +} + +// AuthorLogin returns the value of the "author_login" field in the mutation. +func (m *GitCommitMutation) AuthorLogin() (r string, exists bool) { + v := m.author_login + if v == nil { + return + } + return *v, true +} + +// OldAuthorLogin returns the old "author_login" field's value of the GitCommit entity. +// If the GitCommit 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 *GitCommitMutation) OldAuthorLogin(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAuthorLogin is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAuthorLogin requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAuthorLogin: %w", err) + } + return oldValue.AuthorLogin, nil +} + +// ResetAuthorLogin resets all changes to the "author_login" field. +func (m *GitCommitMutation) ResetAuthorLogin() { + m.author_login = nil +} + +// SetAuthorID sets the "author_id" field. +func (m *GitCommitMutation) SetAuthorID(i int64) { + m.author_id = &i + m.addauthor_id = nil +} + +// AuthorID returns the value of the "author_id" field in the mutation. +func (m *GitCommitMutation) AuthorID() (r int64, exists bool) { + v := m.author_id + if v == nil { + return + } + return *v, true +} + +// OldAuthorID returns the old "author_id" field's value of the GitCommit entity. +// If the GitCommit 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 *GitCommitMutation) OldAuthorID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAuthorID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAuthorID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAuthorID: %w", err) + } + return oldValue.AuthorID, nil +} + +// AddAuthorID adds i to the "author_id" field. +func (m *GitCommitMutation) AddAuthorID(i int64) { + if m.addauthor_id != nil { + *m.addauthor_id += i + } else { + m.addauthor_id = &i + } +} + +// AddedAuthorID returns the value that was added to the "author_id" field in this mutation. +func (m *GitCommitMutation) AddedAuthorID() (r int64, exists bool) { + v := m.addauthor_id + if v == nil { + return + } + return *v, true +} + +// ResetAuthorID resets all changes to the "author_id" field. +func (m *GitCommitMutation) ResetAuthorID() { + m.author_id = nil + m.addauthor_id = nil +} + +// SetDate sets the "date" field. +func (m *GitCommitMutation) SetDate(t time.Time) { + m.date = &t +} + +// Date returns the value of the "date" field in the mutation. +func (m *GitCommitMutation) Date() (r time.Time, exists bool) { + v := m.date + if v == nil { + return + } + return *v, true +} + +// OldDate returns the old "date" field's value of the GitCommit entity. +// If the GitCommit 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 *GitCommitMutation) OldDate(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDate is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDate requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDate: %w", err) + } + return oldValue.Date, nil +} + +// ResetDate resets all changes to the "date" field. +func (m *GitCommitMutation) ResetDate() { + m.date = nil +} + +// SetRepositoryID sets the "repository" edge to the Repository entity by id. +func (m *GitCommitMutation) SetRepositoryID(id int64) { + m.repository = &id +} + +// ClearRepository clears the "repository" edge to the Repository entity. +func (m *GitCommitMutation) ClearRepository() { + m.clearedrepository = true +} + +// RepositoryCleared reports if the "repository" edge to the Repository entity was cleared. +func (m *GitCommitMutation) RepositoryCleared() bool { + return m.clearedrepository +} + +// RepositoryID returns the "repository" edge ID in the mutation. +func (m *GitCommitMutation) RepositoryID() (id int64, exists bool) { + if m.repository != nil { + return *m.repository, true + } + return +} + +// RepositoryIDs returns the "repository" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// RepositoryID instead. It exists only for internal usage by the builders. +func (m *GitCommitMutation) RepositoryIDs() (ids []int64) { + if id := m.repository; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRepository resets all changes to the "repository" edge. +func (m *GitCommitMutation) ResetRepository() { + m.repository = nil + m.clearedrepository = false +} + +// Where appends a list predicates to the GitCommitMutation builder. +func (m *GitCommitMutation) Where(ps ...predicate.GitCommit) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the GitCommitMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *GitCommitMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.GitCommit, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *GitCommitMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *GitCommitMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (GitCommit). +func (m *GitCommitMutation) 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 *GitCommitMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.message != nil { + fields = append(fields, gitcommit.FieldMessage) + } + if m.author_login != nil { + fields = append(fields, gitcommit.FieldAuthorLogin) + } + if m.author_id != nil { + fields = append(fields, gitcommit.FieldAuthorID) + } + if m.date != nil { + fields = append(fields, gitcommit.FieldDate) + } + 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 *GitCommitMutation) Field(name string) (ent.Value, bool) { + switch name { + case gitcommit.FieldMessage: + return m.Message() + case gitcommit.FieldAuthorLogin: + return m.AuthorLogin() + case gitcommit.FieldAuthorID: + return m.AuthorID() + case gitcommit.FieldDate: + return m.Date() + } + 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 *GitCommitMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case gitcommit.FieldMessage: + return m.OldMessage(ctx) + case gitcommit.FieldAuthorLogin: + return m.OldAuthorLogin(ctx) + case gitcommit.FieldAuthorID: + return m.OldAuthorID(ctx) + case gitcommit.FieldDate: + return m.OldDate(ctx) + } + return nil, fmt.Errorf("unknown GitCommit 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 *GitCommitMutation) SetField(name string, value ent.Value) error { + switch name { + case gitcommit.FieldMessage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMessage(v) + return nil + case gitcommit.FieldAuthorLogin: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAuthorLogin(v) + return nil + case gitcommit.FieldAuthorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAuthorID(v) + return nil + case gitcommit.FieldDate: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDate(v) + return nil + } + return fmt.Errorf("unknown GitCommit field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *GitCommitMutation) AddedFields() []string { + var fields []string + if m.addauthor_id != nil { + fields = append(fields, gitcommit.FieldAuthorID) + } + 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 *GitCommitMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case gitcommit.FieldAuthorID: + return m.AddedAuthorID() + } + 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 *GitCommitMutation) AddField(name string, value ent.Value) error { + switch name { + case gitcommit.FieldAuthorID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddAuthorID(v) + return nil + } + return fmt.Errorf("unknown GitCommit numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *GitCommitMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *GitCommitMutation) 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 *GitCommitMutation) ClearField(name string) error { + return fmt.Errorf("unknown GitCommit 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 *GitCommitMutation) ResetField(name string) error { + switch name { + case gitcommit.FieldMessage: + m.ResetMessage() + return nil + case gitcommit.FieldAuthorLogin: + m.ResetAuthorLogin() + return nil + case gitcommit.FieldAuthorID: + m.ResetAuthorID() + return nil + case gitcommit.FieldDate: + m.ResetDate() + return nil + } + return fmt.Errorf("unknown GitCommit field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *GitCommitMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.repository != nil { + edges = append(edges, gitcommit.EdgeRepository) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *GitCommitMutation) AddedIDs(name string) []ent.Value { + switch name { + case gitcommit.EdgeRepository: + if id := m.repository; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *GitCommitMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *GitCommitMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *GitCommitMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedrepository { + edges = append(edges, gitcommit.EdgeRepository) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *GitCommitMutation) EdgeCleared(name string) bool { + switch name { + case gitcommit.EdgeRepository: + return m.clearedrepository + } + 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 *GitCommitMutation) ClearEdge(name string) error { + switch name { + case gitcommit.EdgeRepository: + m.ClearRepository() + return nil + } + return fmt.Errorf("unknown GitCommit 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 *GitCommitMutation) ResetEdge(name string) error { + switch name { + case gitcommit.EdgeRepository: + m.ResetRepository() + return nil + } + return fmt.Errorf("unknown GitCommit edge %s", name) +} + // LastChannelMessageMutation represents an operation that mutates the LastChannelMessage nodes in the graph. type LastChannelMessageMutation struct { config @@ -3042,6 +3641,9 @@ type RepositoryMutation struct { clearedFields map[string]struct{} organization *int64 clearedorganization bool + commits map[string]struct{} + removedcommits map[string]struct{} + clearedcommits bool done bool oldValue func(context.Context) (*Repository, error) predicates []predicate.Repository @@ -3445,6 +4047,60 @@ func (m *RepositoryMutation) ResetOrganization() { m.clearedorganization = false } +// AddCommitIDs adds the "commits" edge to the GitCommit entity by ids. +func (m *RepositoryMutation) AddCommitIDs(ids ...string) { + if m.commits == nil { + m.commits = make(map[string]struct{}) + } + for i := range ids { + m.commits[ids[i]] = struct{}{} + } +} + +// ClearCommits clears the "commits" edge to the GitCommit entity. +func (m *RepositoryMutation) ClearCommits() { + m.clearedcommits = true +} + +// CommitsCleared reports if the "commits" edge to the GitCommit entity was cleared. +func (m *RepositoryMutation) CommitsCleared() bool { + return m.clearedcommits +} + +// RemoveCommitIDs removes the "commits" edge to the GitCommit entity by IDs. +func (m *RepositoryMutation) RemoveCommitIDs(ids ...string) { + if m.removedcommits == nil { + m.removedcommits = make(map[string]struct{}) + } + for i := range ids { + delete(m.commits, ids[i]) + m.removedcommits[ids[i]] = struct{}{} + } +} + +// RemovedCommits returns the removed IDs of the "commits" edge to the GitCommit entity. +func (m *RepositoryMutation) RemovedCommitsIDs() (ids []string) { + for id := range m.removedcommits { + ids = append(ids, id) + } + return +} + +// CommitsIDs returns the "commits" edge IDs in the mutation. +func (m *RepositoryMutation) CommitsIDs() (ids []string) { + for id := range m.commits { + ids = append(ids, id) + } + return +} + +// ResetCommits resets all changes to the "commits" edge. +func (m *RepositoryMutation) ResetCommits() { + m.commits = nil + m.clearedcommits = false + m.removedcommits = nil +} + // Where appends a list predicates to the RepositoryMutation builder. func (m *RepositoryMutation) Where(ps ...predicate.Repository) { m.predicates = append(m.predicates, ps...) @@ -3684,10 +4340,13 @@ func (m *RepositoryMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *RepositoryMutation) AddedEdges() []string { - edges := make([]string, 0, 1) + edges := make([]string, 0, 2) if m.organization != nil { edges = append(edges, repository.EdgeOrganization) } + if m.commits != nil { + edges = append(edges, repository.EdgeCommits) + } return edges } @@ -3699,28 +4358,48 @@ func (m *RepositoryMutation) AddedIDs(name string) []ent.Value { if id := m.organization; id != nil { return []ent.Value{*id} } + case repository.EdgeCommits: + ids := make([]ent.Value, 0, len(m.commits)) + for id := range m.commits { + ids = append(ids, id) + } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *RepositoryMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) + edges := make([]string, 0, 2) + if m.removedcommits != nil { + edges = append(edges, repository.EdgeCommits) + } return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. func (m *RepositoryMutation) RemovedIDs(name string) []ent.Value { + switch name { + case repository.EdgeCommits: + ids := make([]ent.Value, 0, len(m.removedcommits)) + for id := range m.removedcommits { + ids = append(ids, id) + } + return ids + } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *RepositoryMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) + edges := make([]string, 0, 2) if m.clearedorganization { edges = append(edges, repository.EdgeOrganization) } + if m.clearedcommits { + edges = append(edges, repository.EdgeCommits) + } return edges } @@ -3730,6 +4409,8 @@ func (m *RepositoryMutation) EdgeCleared(name string) bool { switch name { case repository.EdgeOrganization: return m.clearedorganization + case repository.EdgeCommits: + return m.clearedcommits } return false } @@ -3752,6 +4433,9 @@ func (m *RepositoryMutation) ResetEdge(name string) error { case repository.EdgeOrganization: m.ResetOrganization() return nil + case repository.EdgeCommits: + m.ResetCommits() + return nil } return fmt.Errorf("unknown Repository edge %s", name) } diff --git a/internal/ent/predicate/predicate.go b/internal/ent/predicate/predicate.go index a885052..ee75e08 100644 --- a/internal/ent/predicate/predicate.go +++ b/internal/ent/predicate/predicate.go @@ -12,6 +12,9 @@ type Check func(*sql.Selector) // GPTDialog is the predicate function for gptdialog builders. type GPTDialog func(*sql.Selector) +// GitCommit is the predicate function for gitcommit builders. +type GitCommit func(*sql.Selector) + // LastChannelMessage is the predicate function for lastchannelmessage builders. type LastChannelMessage func(*sql.Selector) diff --git a/internal/ent/repository.go b/internal/ent/repository.go index eb64d30..03336cc 100644 --- a/internal/ent/repository.go +++ b/internal/ent/repository.go @@ -42,9 +42,12 @@ type Repository struct { type RepositoryEdges struct { // GitHub organization. Organization *Organization `json:"organization,omitempty"` + // Commits. + Commits []*GitCommit `json:"commits,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [1]bool + loadedTypes [2]bool + namedCommits map[string][]*GitCommit } // OrganizationOrErr returns the Organization value or an error if the edge @@ -60,6 +63,15 @@ func (e RepositoryEdges) OrganizationOrErr() (*Organization, error) { return nil, &NotLoadedError{edge: "organization"} } +// CommitsOrErr returns the Commits value or an error if the edge +// was not loaded in eager-loading. +func (e RepositoryEdges) CommitsOrErr() ([]*GitCommit, error) { + if e.loadedTypes[1] { + return e.Commits, nil + } + return nil, &NotLoadedError{edge: "commits"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*Repository) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -155,6 +167,11 @@ func (r *Repository) QueryOrganization() *OrganizationQuery { return NewRepositoryClient(r.config).QueryOrganization(r) } +// QueryCommits queries the "commits" edge of the Repository entity. +func (r *Repository) QueryCommits() *GitCommitQuery { + return NewRepositoryClient(r.config).QueryCommits(r) +} + // Update returns a builder for updating this Repository. // Note that you need to call Repository.Unwrap() before calling this method if this Repository // was returned from a transaction, and the transaction was committed or rolled back. @@ -199,5 +216,29 @@ func (r *Repository) String() string { return builder.String() } +// NamedCommits returns the Commits named value or an error if the edge was not +// loaded in eager-loading with this name. +func (r *Repository) NamedCommits(name string) ([]*GitCommit, error) { + if r.Edges.namedCommits == nil { + return nil, &NotLoadedError{edge: name} + } + nodes, ok := r.Edges.namedCommits[name] + if !ok { + return nil, &NotLoadedError{edge: name} + } + return nodes, nil +} + +func (r *Repository) appendNamedCommits(name string, edges ...*GitCommit) { + if r.Edges.namedCommits == nil { + r.Edges.namedCommits = make(map[string][]*GitCommit) + } + if len(edges) == 0 { + r.Edges.namedCommits[name] = []*GitCommit{} + } else { + r.Edges.namedCommits[name] = append(r.Edges.namedCommits[name], edges...) + } +} + // Repositories is a parsable slice of Repository. type Repositories []*Repository diff --git a/internal/ent/repository/repository.go b/internal/ent/repository/repository.go index 5a4a3e4..b15aeee 100644 --- a/internal/ent/repository/repository.go +++ b/internal/ent/repository/repository.go @@ -26,6 +26,10 @@ const ( FieldLastEventAt = "last_event_at" // EdgeOrganization holds the string denoting the organization edge name in mutations. EdgeOrganization = "organization" + // EdgeCommits holds the string denoting the commits edge name in mutations. + EdgeCommits = "commits" + // GitCommitFieldID holds the string denoting the ID field of the GitCommit. + GitCommitFieldID = "sha" // Table holds the table name of the repository in the database. Table = "repositories" // OrganizationTable is the table that holds the organization relation/edge. @@ -35,6 +39,13 @@ const ( OrganizationInverseTable = "organizations" // OrganizationColumn is the table column denoting the organization relation/edge. OrganizationColumn = "organization_repositories" + // CommitsTable is the table that holds the commits relation/edge. + CommitsTable = "git_commits" + // CommitsInverseTable is the table name for the GitCommit entity. + // It exists in this package in order to avoid circular dependency with the "gitcommit" package. + CommitsInverseTable = "git_commits" + // CommitsColumn is the table column denoting the commits relation/edge. + CommitsColumn = "repository_commits" ) // Columns holds all SQL columns for repository fields. @@ -118,6 +129,20 @@ func ByOrganizationField(field string, opts ...sql.OrderTermOption) OrderOption sqlgraph.OrderByNeighborTerms(s, newOrganizationStep(), sql.OrderByField(field, opts...)) } } + +// ByCommitsCount orders the results by commits count. +func ByCommitsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newCommitsStep(), opts...) + } +} + +// ByCommits orders the results by commits terms. +func ByCommits(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCommitsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newOrganizationStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -125,3 +150,10 @@ func newOrganizationStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.M2O, true, OrganizationTable, OrganizationColumn), ) } +func newCommitsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CommitsInverseTable, GitCommitFieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CommitsTable, CommitsColumn), + ) +} diff --git a/internal/ent/repository/where.go b/internal/ent/repository/where.go index 11973db..5b47c0c 100644 --- a/internal/ent/repository/where.go +++ b/internal/ent/repository/where.go @@ -478,6 +478,29 @@ func HasOrganizationWith(preds ...predicate.Organization) predicate.Repository { }) } +// HasCommits applies the HasEdge predicate on the "commits" edge. +func HasCommits() predicate.Repository { + return predicate.Repository(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CommitsTable, CommitsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCommitsWith applies the HasEdge predicate on the "commits" edge with a given conditions (other predicates). +func HasCommitsWith(preds ...predicate.GitCommit) predicate.Repository { + return predicate.Repository(func(s *sql.Selector) { + step := newCommitsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // And groups predicates with the AND operator between them. func And(predicates ...predicate.Repository) predicate.Repository { return predicate.Repository(func(s *sql.Selector) { diff --git a/internal/ent/repository_create.go b/internal/ent/repository_create.go index 191f653..ded0ff0 100644 --- a/internal/ent/repository_create.go +++ b/internal/ent/repository_create.go @@ -11,6 +11,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/go-faster/bot/internal/ent/gitcommit" "github.com/go-faster/bot/internal/ent/organization" "github.com/go-faster/bot/internal/ent/repository" ) @@ -116,6 +117,21 @@ func (rc *RepositoryCreate) SetOrganization(o *Organization) *RepositoryCreate { return rc.SetOrganizationID(o.ID) } +// AddCommitIDs adds the "commits" edge to the GitCommit entity by IDs. +func (rc *RepositoryCreate) AddCommitIDs(ids ...string) *RepositoryCreate { + rc.mutation.AddCommitIDs(ids...) + return rc +} + +// AddCommits adds the "commits" edges to the GitCommit entity. +func (rc *RepositoryCreate) AddCommits(g ...*GitCommit) *RepositoryCreate { + ids := make([]string, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return rc.AddCommitIDs(ids...) +} + // Mutation returns the RepositoryMutation object of the builder. func (rc *RepositoryCreate) Mutation() *RepositoryMutation { return rc.mutation @@ -242,6 +258,22 @@ func (rc *RepositoryCreate) createSpec() (*Repository, *sqlgraph.CreateSpec) { _node.organization_repositories = &nodes[0] _spec.Edges = append(_spec.Edges, edge) } + if nodes := rc.mutation.CommitsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repository.CommitsTable, + Columns: []string{repository.CommitsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(gitcommit.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/internal/ent/repository_query.go b/internal/ent/repository_query.go index 0230724..2c90012 100644 --- a/internal/ent/repository_query.go +++ b/internal/ent/repository_query.go @@ -4,12 +4,14 @@ package ent import ( "context" + "database/sql/driver" "fmt" "math" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/go-faster/bot/internal/ent/gitcommit" "github.com/go-faster/bot/internal/ent/organization" "github.com/go-faster/bot/internal/ent/predicate" "github.com/go-faster/bot/internal/ent/repository" @@ -23,7 +25,9 @@ type RepositoryQuery struct { inters []Interceptor predicates []predicate.Repository withOrganization *OrganizationQuery + withCommits *GitCommitQuery withFKs bool + withNamedCommits map[string]*GitCommitQuery // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -82,6 +86,28 @@ func (rq *RepositoryQuery) QueryOrganization() *OrganizationQuery { return query } +// QueryCommits chains the current query on the "commits" edge. +func (rq *RepositoryQuery) QueryCommits() *GitCommitQuery { + query := (&GitCommitClient{config: rq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := rq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := rq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(repository.Table, repository.FieldID, selector), + sqlgraph.To(gitcommit.Table, gitcommit.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, repository.CommitsTable, repository.CommitsColumn), + ) + fromU = sqlgraph.SetNeighbors(rq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first Repository entity from the query. // Returns a *NotFoundError when no Repository was found. func (rq *RepositoryQuery) First(ctx context.Context) (*Repository, error) { @@ -275,6 +301,7 @@ func (rq *RepositoryQuery) Clone() *RepositoryQuery { inters: append([]Interceptor{}, rq.inters...), predicates: append([]predicate.Repository{}, rq.predicates...), withOrganization: rq.withOrganization.Clone(), + withCommits: rq.withCommits.Clone(), // clone intermediate query. sql: rq.sql.Clone(), path: rq.path, @@ -292,6 +319,17 @@ func (rq *RepositoryQuery) WithOrganization(opts ...func(*OrganizationQuery)) *R return rq } +// WithCommits tells the query-builder to eager-load the nodes that are connected to +// the "commits" edge. The optional arguments are used to configure the query builder of the edge. +func (rq *RepositoryQuery) WithCommits(opts ...func(*GitCommitQuery)) *RepositoryQuery { + query := (&GitCommitClient{config: rq.config}).Query() + for _, opt := range opts { + opt(query) + } + rq.withCommits = query + return rq +} + // 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. // @@ -371,8 +409,9 @@ func (rq *RepositoryQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*R nodes = []*Repository{} withFKs = rq.withFKs _spec = rq.querySpec() - loadedTypes = [1]bool{ + loadedTypes = [2]bool{ rq.withOrganization != nil, + rq.withCommits != nil, } ) if rq.withOrganization != nil { @@ -405,6 +444,20 @@ func (rq *RepositoryQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*R return nil, err } } + if query := rq.withCommits; query != nil { + if err := rq.loadCommits(ctx, query, nodes, + func(n *Repository) { n.Edges.Commits = []*GitCommit{} }, + func(n *Repository, e *GitCommit) { n.Edges.Commits = append(n.Edges.Commits, e) }); err != nil { + return nil, err + } + } + for name, query := range rq.withNamedCommits { + if err := rq.loadCommits(ctx, query, nodes, + func(n *Repository) { n.appendNamedCommits(name) }, + func(n *Repository, e *GitCommit) { n.appendNamedCommits(name, e) }); err != nil { + return nil, err + } + } return nodes, nil } @@ -440,6 +493,37 @@ func (rq *RepositoryQuery) loadOrganization(ctx context.Context, query *Organiza } return nil } +func (rq *RepositoryQuery) loadCommits(ctx context.Context, query *GitCommitQuery, nodes []*Repository, init func(*Repository), assign func(*Repository, *GitCommit)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int64]*Repository) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + query.withFKs = true + query.Where(predicate.GitCommit(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(repository.CommitsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.repository_commits + if fk == nil { + return fmt.Errorf(`foreign-key "repository_commits" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "repository_commits" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} func (rq *RepositoryQuery) sqlCount(ctx context.Context) (int, error) { _spec := rq.querySpec() @@ -522,6 +606,20 @@ func (rq *RepositoryQuery) sqlQuery(ctx context.Context) *sql.Selector { return selector } +// WithNamedCommits tells the query-builder to eager-load the nodes that are connected to the "commits" +// edge with the given name. The optional arguments are used to configure the query builder of the edge. +func (rq *RepositoryQuery) WithNamedCommits(name string, opts ...func(*GitCommitQuery)) *RepositoryQuery { + query := (&GitCommitClient{config: rq.config}).Query() + for _, opt := range opts { + opt(query) + } + if rq.withNamedCommits == nil { + rq.withNamedCommits = make(map[string]*GitCommitQuery) + } + rq.withNamedCommits[name] = query + return rq +} + // RepositoryGroupBy is the group-by builder for Repository entities. type RepositoryGroupBy struct { selector diff --git a/internal/ent/repository_update.go b/internal/ent/repository_update.go index 1210174..0b0f8bb 100644 --- a/internal/ent/repository_update.go +++ b/internal/ent/repository_update.go @@ -11,6 +11,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/go-faster/bot/internal/ent/gitcommit" "github.com/go-faster/bot/internal/ent/organization" "github.com/go-faster/bot/internal/ent/predicate" "github.com/go-faster/bot/internal/ent/repository" @@ -134,6 +135,21 @@ func (ru *RepositoryUpdate) SetOrganization(o *Organization) *RepositoryUpdate { return ru.SetOrganizationID(o.ID) } +// AddCommitIDs adds the "commits" edge to the GitCommit entity by IDs. +func (ru *RepositoryUpdate) AddCommitIDs(ids ...string) *RepositoryUpdate { + ru.mutation.AddCommitIDs(ids...) + return ru +} + +// AddCommits adds the "commits" edges to the GitCommit entity. +func (ru *RepositoryUpdate) AddCommits(g ...*GitCommit) *RepositoryUpdate { + ids := make([]string, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return ru.AddCommitIDs(ids...) +} + // Mutation returns the RepositoryMutation object of the builder. func (ru *RepositoryUpdate) Mutation() *RepositoryMutation { return ru.mutation @@ -145,6 +161,27 @@ func (ru *RepositoryUpdate) ClearOrganization() *RepositoryUpdate { return ru } +// ClearCommits clears all "commits" edges to the GitCommit entity. +func (ru *RepositoryUpdate) ClearCommits() *RepositoryUpdate { + ru.mutation.ClearCommits() + return ru +} + +// RemoveCommitIDs removes the "commits" edge to GitCommit entities by IDs. +func (ru *RepositoryUpdate) RemoveCommitIDs(ids ...string) *RepositoryUpdate { + ru.mutation.RemoveCommitIDs(ids...) + return ru +} + +// RemoveCommits removes "commits" edges to GitCommit entities. +func (ru *RepositoryUpdate) RemoveCommits(g ...*GitCommit) *RepositoryUpdate { + ids := make([]string, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return ru.RemoveCommitIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (ru *RepositoryUpdate) Save(ctx context.Context) (int, error) { return withHooks[int, RepositoryMutation](ctx, ru.sqlSave, ru.mutation, ru.hooks) @@ -237,6 +274,51 @@ func (ru *RepositoryUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if ru.mutation.CommitsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repository.CommitsTable, + Columns: []string{repository.CommitsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(gitcommit.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ru.mutation.RemovedCommitsIDs(); len(nodes) > 0 && !ru.mutation.CommitsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repository.CommitsTable, + Columns: []string{repository.CommitsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(gitcommit.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ru.mutation.CommitsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repository.CommitsTable, + Columns: []string{repository.CommitsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(gitcommit.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if n, err = sqlgraph.UpdateNodes(ctx, ru.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{repository.Label} @@ -362,6 +444,21 @@ func (ruo *RepositoryUpdateOne) SetOrganization(o *Organization) *RepositoryUpda return ruo.SetOrganizationID(o.ID) } +// AddCommitIDs adds the "commits" edge to the GitCommit entity by IDs. +func (ruo *RepositoryUpdateOne) AddCommitIDs(ids ...string) *RepositoryUpdateOne { + ruo.mutation.AddCommitIDs(ids...) + return ruo +} + +// AddCommits adds the "commits" edges to the GitCommit entity. +func (ruo *RepositoryUpdateOne) AddCommits(g ...*GitCommit) *RepositoryUpdateOne { + ids := make([]string, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return ruo.AddCommitIDs(ids...) +} + // Mutation returns the RepositoryMutation object of the builder. func (ruo *RepositoryUpdateOne) Mutation() *RepositoryMutation { return ruo.mutation @@ -373,6 +470,27 @@ func (ruo *RepositoryUpdateOne) ClearOrganization() *RepositoryUpdateOne { return ruo } +// ClearCommits clears all "commits" edges to the GitCommit entity. +func (ruo *RepositoryUpdateOne) ClearCommits() *RepositoryUpdateOne { + ruo.mutation.ClearCommits() + return ruo +} + +// RemoveCommitIDs removes the "commits" edge to GitCommit entities by IDs. +func (ruo *RepositoryUpdateOne) RemoveCommitIDs(ids ...string) *RepositoryUpdateOne { + ruo.mutation.RemoveCommitIDs(ids...) + return ruo +} + +// RemoveCommits removes "commits" edges to GitCommit entities. +func (ruo *RepositoryUpdateOne) RemoveCommits(g ...*GitCommit) *RepositoryUpdateOne { + ids := make([]string, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return ruo.RemoveCommitIDs(ids...) +} + // Where appends a list predicates to the RepositoryUpdate builder. func (ruo *RepositoryUpdateOne) Where(ps ...predicate.Repository) *RepositoryUpdateOne { ruo.mutation.Where(ps...) @@ -495,6 +613,51 @@ func (ruo *RepositoryUpdateOne) sqlSave(ctx context.Context) (_node *Repository, } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if ruo.mutation.CommitsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repository.CommitsTable, + Columns: []string{repository.CommitsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(gitcommit.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ruo.mutation.RemovedCommitsIDs(); len(nodes) > 0 && !ruo.mutation.CommitsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repository.CommitsTable, + Columns: []string{repository.CommitsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(gitcommit.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ruo.mutation.CommitsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repository.CommitsTable, + Columns: []string{repository.CommitsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(gitcommit.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _node = &Repository{config: ruo.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/internal/ent/schema/commit.go b/internal/ent/schema/commit.go new file mode 100644 index 0000000..58e904e --- /dev/null +++ b/internal/ent/schema/commit.go @@ -0,0 +1,28 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +type GitCommit struct { + ent.Schema +} + +// Fields of the GitCommit. +func (GitCommit) Fields() []ent.Field { + return []ent.Field{ + field.String("id").StorageKey("sha").Immutable().Unique().Comment("GitCommit SHA."), + field.String("message").Comment("GitCommit message."), + field.String("author_login").Comment("GitCommit author."), + field.Int64("author_id").Comment("GitCommit author ID."), + field.Time("date").Comment("GitCommit date."), + } +} + +func (GitCommit) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("repository", Repository.Type).Ref("commits").Unique().Comment("GitHub Repository."), + } +} diff --git a/internal/ent/schema/repository.go b/internal/ent/schema/repository.go index 7e2b888..d0206d2 100644 --- a/internal/ent/schema/repository.go +++ b/internal/ent/schema/repository.go @@ -29,5 +29,6 @@ func (Repository) Indexes() []ent.Index { func (Repository) Edges() []ent.Edge { return []ent.Edge{ edge.From("organization", Organization.Type).Ref("repositories").Unique().Comment("GitHub organization."), + edge.To("commits", GitCommit.Type).Comment("Commits."), } } diff --git a/internal/ent/tx.go b/internal/ent/tx.go index 2b8d304..58c06c0 100644 --- a/internal/ent/tx.go +++ b/internal/ent/tx.go @@ -16,6 +16,8 @@ type Tx struct { Check *CheckClient // GPTDialog is the client for interacting with the GPTDialog builders. GPTDialog *GPTDialogClient + // GitCommit is the client for interacting with the GitCommit builders. + GitCommit *GitCommitClient // LastChannelMessage is the client for interacting with the LastChannelMessage builders. LastChannelMessage *LastChannelMessageClient // Organization is the client for interacting with the Organization builders. @@ -165,6 +167,7 @@ func (tx *Tx) Client() *Client { func (tx *Tx) init() { tx.Check = NewCheckClient(tx.config) tx.GPTDialog = NewGPTDialogClient(tx.config) + tx.GitCommit = NewGitCommitClient(tx.config) tx.LastChannelMessage = NewLastChannelMessageClient(tx.config) tx.Organization = NewOrganizationClient(tx.config) tx.PRNotification = NewPRNotificationClient(tx.config) diff --git a/internal/stat/commits.go b/internal/stat/commits.go index c030201..0adda17 100644 --- a/internal/stat/commits.go +++ b/internal/stat/commits.go @@ -15,6 +15,7 @@ import ( "golang.org/x/oauth2" "github.com/go-faster/bot/internal/ent" + "github.com/go-faster/bot/internal/ent/gitcommit" ) func NewCommit( @@ -57,7 +58,12 @@ func (w *Commit) Update(ctx context.Context) error { return errors.Wrap(err, "client") } - all, err := w.db.Repository.Query().WithOrganization().All(ctx) + tx, err := w.db.Tx(ctx) + if err != nil { + return errors.Wrap(err, "begin tx") + } + + all, err := tx.Repository.Query().WithOrganization().All(ctx) if err != nil { return errors.Wrap(err, "query repositories") } @@ -65,7 +71,7 @@ func (w *Commit) Update(ctx context.Context) error { for _, repo := range all { commits, _, err := client.Repositories.ListCommits(ctx, repo.Edges.Organization.Name, repo.Name, &github.CommitsListOptions{ ListOptions: github.ListOptions{ - PerPage: 10, + PerPage: 100, }, }) if err != nil { @@ -77,9 +83,22 @@ func (w *Commit) Update(ctx context.Context) error { zap.String("message", commit.GetCommit().GetMessage()), zap.String("repo", repo.FullName), ) + if err := tx.GitCommit.Create(). + SetID(commit.GetSHA()). + SetDate(commit.GetCommit().GetAuthor().GetDate().Time). + SetAuthorLogin(commit.GetCommit().GetAuthor().GetLogin()). + SetAuthorID(commit.GetAuthor().GetID()). + SetMessage(commit.GetCommit().GetMessage()). + OnConflictColumns(gitcommit.FieldID).Ignore().Exec(ctx); err != nil { + return errors.Wrap(err, "create commit") + } } } + if err := tx.Commit(); err != nil { + return errors.Wrap(err, "commit") + } + return nil } diff --git a/migrations/20230430162510_commit.sql b/migrations/20230430162510_commit.sql new file mode 100644 index 0000000..33305c8 --- /dev/null +++ b/migrations/20230430162510_commit.sql @@ -0,0 +1,2 @@ +-- Create "git_commits" table +CREATE TABLE "git_commits" ("sha" character varying NOT NULL, "message" character varying NOT NULL, "author_login" character varying NOT NULL, "author_id" bigint NOT NULL, "date" timestamptz NOT NULL, "repository_commits" bigint NULL, PRIMARY KEY ("sha"), CONSTRAINT "git_commits_repositories_commits" FOREIGN KEY ("repository_commits") REFERENCES "repositories" ("id") ON UPDATE NO ACTION ON DELETE SET NULL); diff --git a/migrations/atlas.sum b/migrations/atlas.sum index 68cf2a8..38d23f2 100644 --- a/migrations/atlas.sum +++ b/migrations/atlas.sum @@ -1,4 +1,4 @@ -h1:wbAshcnPCGgM654Udqi/GZ6qWytR8EDbc4AF4RaukWs= +h1:B1u4Mq2KyrjxlMYElBaIHAdIqXQjYwdEav6zJ82Op1w= 20230411163934_init.sql h1:Tbl5s0g/laXKKiLW5BfG9FXwdHcHaAg/9T+/7X1aSOA= 20230412000613_state.sql h1:cHHFpA3UmxU2elLmr4JKe8cZMtfAmJMLPjGC3MSe2tA= 20230412002223_session.sql h1:WS8XdtkA5b9BwpIZ2kKBdzoFLeqkGXqFrSSkXCaybG8= @@ -11,3 +11,4 @@ h1:wbAshcnPCGgM654Udqi/GZ6qWytR8EDbc4AF4RaukWs= 20230417145105_pr_title.sql h1:anMWDs/OLqwFWPSd6BTLXhoBho35LILoPHTTeupZpd0= 20230430144340_repository.sql h1:NwZ7wqUqMiCUc4vioR9HrIoRL4rn/wKzyWbRPo4Qn8Q= 20230430150308_organization.sql h1:O+KAnDJQjRZ/lsELIr8gFf+0j+xF17FQ20+D9ysgfNw= +20230430162510_commit.sql h1:h5cxOBBqUDzFVlj1Uc5z/qTBdnsUIxhBdHY3V6xx09w=