From 2a3506d21bc2d38e7988311faccb65f535951dfc Mon Sep 17 00:00:00 2001 From: Achim Rohn Date: Wed, 17 Sep 2025 14:58:13 +0200 Subject: [PATCH] Add first google auth --- starter/ent/client.go | 178 +++++++- starter/ent/ent.go | 4 +- starter/ent/googleauth.go | 171 ++++++++ starter/ent/googleauth/googleauth.go | 104 +++++ starter/ent/googleauth/where.go | 184 ++++++++ starter/ent/googleauth_create.go | 273 ++++++++++++ starter/ent/googleauth_delete.go | 88 ++++ starter/ent/googleauth_query.go | 614 +++++++++++++++++++++++++++ starter/ent/googleauth_update.go | 362 ++++++++++++++++ starter/ent/hook/hook.go | 12 + starter/ent/migrate/schema.go | 24 ++ starter/ent/mutation.go | 506 +++++++++++++++++++++- starter/ent/pagination_query.go | 38 ++ starter/ent/predicate/predicate.go | 3 + starter/ent/runtime.go | 16 + starter/ent/schema/google_auth.go | 34 ++ starter/ent/tx.go | 5 +- starter/go.mod | 1 + starter/go.sum | 2 + starter/google/credentials.go | 7 + 20 files changed, 2614 insertions(+), 12 deletions(-) create mode 100644 starter/ent/googleauth.go create mode 100644 starter/ent/googleauth/googleauth.go create mode 100644 starter/ent/googleauth/where.go create mode 100644 starter/ent/googleauth_create.go create mode 100644 starter/ent/googleauth_delete.go create mode 100644 starter/ent/googleauth_query.go create mode 100644 starter/ent/googleauth_update.go create mode 100644 starter/ent/schema/google_auth.go create mode 100644 starter/google/credentials.go diff --git a/starter/ent/client.go b/starter/ent/client.go index 703fbd0..15d2c68 100644 --- a/starter/ent/client.go +++ b/starter/ent/client.go @@ -11,11 +11,13 @@ import ( "ersteller-lib/starter/ent/migrate" + "ersteller-lib/starter/ent/googleauth" "ersteller-lib/starter/ent/user" "entgo.io/ent" "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" ) // Client is the client that holds all ent builders. @@ -23,6 +25,8 @@ type Client struct { config // Schema is the client for creating, migrating and dropping schema. Schema *migrate.Schema + // GoogleAuth is the client for interacting with the GoogleAuth builders. + GoogleAuth *GoogleAuthClient // User is the client for interacting with the User builders. User *UserClient } @@ -36,6 +40,7 @@ func NewClient(opts ...Option) *Client { func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) + c.GoogleAuth = NewGoogleAuthClient(c.config) c.User = NewUserClient(c.config) } @@ -127,9 +132,10 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { cfg := c.config cfg.driver = tx return &Tx{ - ctx: ctx, - config: cfg, - User: NewUserClient(cfg), + ctx: ctx, + config: cfg, + GoogleAuth: NewGoogleAuthClient(cfg), + User: NewUserClient(cfg), }, nil } @@ -147,16 +153,17 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) cfg := c.config cfg.driver = &txDriver{tx: tx, drv: c.driver} return &Tx{ - ctx: ctx, - config: cfg, - User: NewUserClient(cfg), + ctx: ctx, + config: cfg, + GoogleAuth: NewGoogleAuthClient(cfg), + User: NewUserClient(cfg), }, nil } // Debug returns a new debug-client. It's used to get verbose logging on specific operations. // // client.Debug(). -// User. +// GoogleAuth. // Query(). // Count(ctx) func (c *Client) Debug() *Client { @@ -178,18 +185,22 @@ func (c *Client) Close() error { // Use adds the mutation hooks to all the entity clients. // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { + c.GoogleAuth.Use(hooks...) c.User.Use(hooks...) } // Intercept adds the query interceptors to all the entity clients. // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { + c.GoogleAuth.Intercept(interceptors...) c.User.Intercept(interceptors...) } // Mutate implements the ent.Mutator interface. func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { switch m := m.(type) { + case *GoogleAuthMutation: + return c.GoogleAuth.mutate(ctx, m) case *UserMutation: return c.User.mutate(ctx, m) default: @@ -197,6 +208,155 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { } } +// GoogleAuthClient is a client for the GoogleAuth schema. +type GoogleAuthClient struct { + config +} + +// NewGoogleAuthClient returns a client for the GoogleAuth from the given config. +func NewGoogleAuthClient(c config) *GoogleAuthClient { + return &GoogleAuthClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `googleauth.Hooks(f(g(h())))`. +func (c *GoogleAuthClient) Use(hooks ...Hook) { + c.hooks.GoogleAuth = append(c.hooks.GoogleAuth, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `googleauth.Intercept(f(g(h())))`. +func (c *GoogleAuthClient) Intercept(interceptors ...Interceptor) { + c.inters.GoogleAuth = append(c.inters.GoogleAuth, interceptors...) +} + +// Create returns a builder for creating a GoogleAuth entity. +func (c *GoogleAuthClient) Create() *GoogleAuthCreate { + mutation := newGoogleAuthMutation(c.config, OpCreate) + return &GoogleAuthCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of GoogleAuth entities. +func (c *GoogleAuthClient) CreateBulk(builders ...*GoogleAuthCreate) *GoogleAuthCreateBulk { + return &GoogleAuthCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *GoogleAuthClient) MapCreateBulk(slice any, setFunc func(*GoogleAuthCreate, int)) *GoogleAuthCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &GoogleAuthCreateBulk{err: fmt.Errorf("calling to GoogleAuthClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*GoogleAuthCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &GoogleAuthCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for GoogleAuth. +func (c *GoogleAuthClient) Update() *GoogleAuthUpdate { + mutation := newGoogleAuthMutation(c.config, OpUpdate) + return &GoogleAuthUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *GoogleAuthClient) UpdateOne(_m *GoogleAuth) *GoogleAuthUpdateOne { + mutation := newGoogleAuthMutation(c.config, OpUpdateOne, withGoogleAuth(_m)) + return &GoogleAuthUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *GoogleAuthClient) UpdateOneID(id int) *GoogleAuthUpdateOne { + mutation := newGoogleAuthMutation(c.config, OpUpdateOne, withGoogleAuthID(id)) + return &GoogleAuthUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for GoogleAuth. +func (c *GoogleAuthClient) Delete() *GoogleAuthDelete { + mutation := newGoogleAuthMutation(c.config, OpDelete) + return &GoogleAuthDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *GoogleAuthClient) DeleteOne(_m *GoogleAuth) *GoogleAuthDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *GoogleAuthClient) DeleteOneID(id int) *GoogleAuthDeleteOne { + builder := c.Delete().Where(googleauth.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &GoogleAuthDeleteOne{builder} +} + +// Query returns a query builder for GoogleAuth. +func (c *GoogleAuthClient) Query() *GoogleAuthQuery { + return &GoogleAuthQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeGoogleAuth}, + inters: c.Interceptors(), + } +} + +// Get returns a GoogleAuth entity by its id. +func (c *GoogleAuthClient) Get(ctx context.Context, id int) (*GoogleAuth, error) { + return c.Query().Where(googleauth.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *GoogleAuthClient) GetX(ctx context.Context, id int) *GoogleAuth { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUser queries the user edge of a GoogleAuth. +func (c *GoogleAuthClient) QueryUser(_m *GoogleAuth) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(googleauth.Table, googleauth.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, googleauth.UserTable, googleauth.UserColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *GoogleAuthClient) Hooks() []Hook { + return c.hooks.GoogleAuth +} + +// Interceptors returns the client interceptors. +func (c *GoogleAuthClient) Interceptors() []Interceptor { + return c.inters.GoogleAuth +} + +func (c *GoogleAuthClient) mutate(ctx context.Context, m *GoogleAuthMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&GoogleAuthCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&GoogleAuthUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&GoogleAuthUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&GoogleAuthDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown GoogleAuth mutation op: %q", m.Op()) + } +} + // UserClient is a client for the User schema. type UserClient struct { config @@ -333,9 +493,9 @@ func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) // hooks and interceptors per client, for fast access. type ( hooks struct { - User []ent.Hook + GoogleAuth, User []ent.Hook } inters struct { - User []ent.Interceptor + GoogleAuth, User []ent.Interceptor } ) diff --git a/starter/ent/ent.go b/starter/ent/ent.go index ebb99fa..81a123c 100644 --- a/starter/ent/ent.go +++ b/starter/ent/ent.go @@ -5,6 +5,7 @@ package ent import ( "context" "errors" + "ersteller-lib/starter/ent/googleauth" "ersteller-lib/starter/ent/user" "fmt" "reflect" @@ -73,7 +74,8 @@ var ( func checkColumn(t, c string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ - user.Table: user.ValidColumn, + googleauth.Table: googleauth.ValidColumn, + user.Table: user.ValidColumn, }) }) return columnCheck(t, c) diff --git a/starter/ent/googleauth.go b/starter/ent/googleauth.go new file mode 100644 index 0000000..c823219 --- /dev/null +++ b/starter/ent/googleauth.go @@ -0,0 +1,171 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "encoding/json" + "ersteller-lib/starter/ent/googleauth" + "ersteller-lib/starter/ent/user" + "ersteller-lib/starter/google" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// GoogleAuth is the model entity for the GoogleAuth schema. +type GoogleAuth struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at,omitempty"` + // Credentials holds the value of the "credentials" field. + Credentials google.Credentials `json:"credentials,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the GoogleAuthQuery when eager-loading is set. + Edges GoogleAuthEdges `json:"edges"` + google_auth_user *int + selectValues sql.SelectValues +} + +// GoogleAuthEdges holds the relations/edges for other nodes in the graph. +type GoogleAuthEdges struct { + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e GoogleAuthEdges) UserOrErr() (*User, error) { + if e.User != nil { + return e.User, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "user"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*GoogleAuth) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case googleauth.FieldCredentials: + values[i] = new([]byte) + case googleauth.FieldID: + values[i] = new(sql.NullInt64) + case googleauth.FieldCreatedAt, googleauth.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case googleauth.ForeignKeys[0]: // google_auth_user + 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 GoogleAuth fields. +func (_m *GoogleAuth) 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 googleauth.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case googleauth.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case googleauth.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + _m.UpdatedAt = value.Time + } + case googleauth.FieldCredentials: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field credentials", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Credentials); err != nil { + return fmt.Errorf("unmarshal field credentials: %w", err) + } + } + case googleauth.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field google_auth_user", value) + } else if value.Valid { + _m.google_auth_user = new(int) + *_m.google_auth_user = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the GoogleAuth. +// This includes values selected through modifiers, order, etc. +func (_m *GoogleAuth) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryUser queries the "user" edge of the GoogleAuth entity. +func (_m *GoogleAuth) QueryUser() *UserQuery { + return NewGoogleAuthClient(_m.config).QueryUser(_m) +} + +// Update returns a builder for updating this GoogleAuth. +// Note that you need to call GoogleAuth.Unwrap() before calling this method if this GoogleAuth +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *GoogleAuth) Update() *GoogleAuthUpdateOne { + return NewGoogleAuthClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the GoogleAuth entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *GoogleAuth) Unwrap() *GoogleAuth { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: GoogleAuth is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *GoogleAuth) String() string { + var builder strings.Builder + builder.WriteString("GoogleAuth(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("credentials=") + builder.WriteString(fmt.Sprintf("%v", _m.Credentials)) + builder.WriteByte(')') + return builder.String() +} + +// GoogleAuths is a parsable slice of GoogleAuth. +type GoogleAuths []*GoogleAuth diff --git a/starter/ent/googleauth/googleauth.go b/starter/ent/googleauth/googleauth.go new file mode 100644 index 0000000..fd52723 --- /dev/null +++ b/starter/ent/googleauth/googleauth.go @@ -0,0 +1,104 @@ +// Code generated by ent, DO NOT EDIT. + +package googleauth + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the googleauth type in the database. + Label = "google_auth" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // FieldCredentials holds the string denoting the credentials field in the database. + FieldCredentials = "credentials" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // Table holds the table name of the googleauth in the database. + Table = "google_auths" + // UserTable is the table that holds the user relation/edge. + UserTable = "google_auths" + // UserInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UserInverseTable = "users" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "google_auth_user" +) + +// Columns holds all SQL columns for googleauth fields. +var Columns = []string{ + FieldID, + FieldCreatedAt, + FieldUpdatedAt, + FieldCredentials, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "google_auths" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "google_auth_user", +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. + DefaultUpdatedAt func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time +) + +// OrderOption defines the ordering options for the GoogleAuth queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByUserField orders the results by user field. +func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...)) + } +} +func newUserStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) +} diff --git a/starter/ent/googleauth/where.go b/starter/ent/googleauth/where.go new file mode 100644 index 0000000..e2c664e --- /dev/null +++ b/starter/ent/googleauth/where.go @@ -0,0 +1,184 @@ +// Code generated by ent, DO NOT EDIT. + +package googleauth + +import ( + "ersteller-lib/starter/ent/predicate" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldLTE(FieldID, id)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.GoogleAuth { + return predicate.GoogleAuth(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.GoogleAuth { + return predicate.GoogleAuth(func(s *sql.Selector) { + step := newUserStep() + 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.GoogleAuth) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.GoogleAuth) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.GoogleAuth) predicate.GoogleAuth { + return predicate.GoogleAuth(sql.NotPredicates(p)) +} diff --git a/starter/ent/googleauth_create.go b/starter/ent/googleauth_create.go new file mode 100644 index 0000000..b0ccb63 --- /dev/null +++ b/starter/ent/googleauth_create.go @@ -0,0 +1,273 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "ersteller-lib/starter/ent/googleauth" + "ersteller-lib/starter/ent/user" + "ersteller-lib/starter/google" + "fmt" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// GoogleAuthCreate is the builder for creating a GoogleAuth entity. +type GoogleAuthCreate struct { + config + mutation *GoogleAuthMutation + hooks []Hook +} + +// SetCreatedAt sets the "created_at" field. +func (_c *GoogleAuthCreate) SetCreatedAt(v time.Time) *GoogleAuthCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *GoogleAuthCreate) SetNillableCreatedAt(v *time.Time) *GoogleAuthCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *GoogleAuthCreate) SetUpdatedAt(v time.Time) *GoogleAuthCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *GoogleAuthCreate) SetNillableUpdatedAt(v *time.Time) *GoogleAuthCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetCredentials sets the "credentials" field. +func (_c *GoogleAuthCreate) SetCredentials(v google.Credentials) *GoogleAuthCreate { + _c.mutation.SetCredentials(v) + return _c +} + +// SetUserID sets the "user" edge to the User entity by ID. +func (_c *GoogleAuthCreate) SetUserID(id int) *GoogleAuthCreate { + _c.mutation.SetUserID(id) + return _c +} + +// SetUser sets the "user" edge to the User entity. +func (_c *GoogleAuthCreate) SetUser(v *User) *GoogleAuthCreate { + return _c.SetUserID(v.ID) +} + +// Mutation returns the GoogleAuthMutation object of the builder. +func (_c *GoogleAuthCreate) Mutation() *GoogleAuthMutation { + return _c.mutation +} + +// Save creates the GoogleAuth in the database. +func (_c *GoogleAuthCreate) Save(ctx context.Context) (*GoogleAuth, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *GoogleAuthCreate) SaveX(ctx context.Context) *GoogleAuth { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *GoogleAuthCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *GoogleAuthCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *GoogleAuthCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := googleauth.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + v := googleauth.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *GoogleAuthCreate) check() error { + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "GoogleAuth.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "GoogleAuth.updated_at"`)} + } + if _, ok := _c.mutation.Credentials(); !ok { + return &ValidationError{Name: "credentials", err: errors.New(`ent: missing required field "GoogleAuth.credentials"`)} + } + if len(_c.mutation.UserIDs()) == 0 { + return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "GoogleAuth.user"`)} + } + return nil +} + +func (_c *GoogleAuthCreate) sqlSave(ctx context.Context) (*GoogleAuth, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *GoogleAuthCreate) createSpec() (*GoogleAuth, *sqlgraph.CreateSpec) { + var ( + _node = &GoogleAuth{config: _c.config} + _spec = sqlgraph.NewCreateSpec(googleauth.Table, sqlgraph.NewFieldSpec(googleauth.FieldID, field.TypeInt)) + ) + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(googleauth.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(googleauth.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := _c.mutation.Credentials(); ok { + _spec.SetField(googleauth.FieldCredentials, field.TypeJSON, value) + _node.Credentials = value + } + if nodes := _c.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: googleauth.UserTable, + Columns: []string{googleauth.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.google_auth_user = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// GoogleAuthCreateBulk is the builder for creating many GoogleAuth entities in bulk. +type GoogleAuthCreateBulk struct { + config + err error + builders []*GoogleAuthCreate +} + +// Save creates the GoogleAuth entities in the database. +func (_c *GoogleAuthCreateBulk) Save(ctx context.Context) ([]*GoogleAuth, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*GoogleAuth, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*GoogleAuthMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *GoogleAuthCreateBulk) SaveX(ctx context.Context) []*GoogleAuth { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *GoogleAuthCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *GoogleAuthCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/starter/ent/googleauth_delete.go b/starter/ent/googleauth_delete.go new file mode 100644 index 0000000..b926fef --- /dev/null +++ b/starter/ent/googleauth_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "ersteller-lib/starter/ent/googleauth" + "ersteller-lib/starter/ent/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// GoogleAuthDelete is the builder for deleting a GoogleAuth entity. +type GoogleAuthDelete struct { + config + hooks []Hook + mutation *GoogleAuthMutation +} + +// Where appends a list predicates to the GoogleAuthDelete builder. +func (_d *GoogleAuthDelete) Where(ps ...predicate.GoogleAuth) *GoogleAuthDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *GoogleAuthDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *GoogleAuthDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *GoogleAuthDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(googleauth.Table, sqlgraph.NewFieldSpec(googleauth.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// GoogleAuthDeleteOne is the builder for deleting a single GoogleAuth entity. +type GoogleAuthDeleteOne struct { + _d *GoogleAuthDelete +} + +// Where appends a list predicates to the GoogleAuthDelete builder. +func (_d *GoogleAuthDeleteOne) Where(ps ...predicate.GoogleAuth) *GoogleAuthDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *GoogleAuthDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{googleauth.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *GoogleAuthDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/starter/ent/googleauth_query.go b/starter/ent/googleauth_query.go new file mode 100644 index 0000000..018c1b0 --- /dev/null +++ b/starter/ent/googleauth_query.go @@ -0,0 +1,614 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "ersteller-lib/starter/ent/googleauth" + "ersteller-lib/starter/ent/predicate" + "ersteller-lib/starter/ent/user" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// GoogleAuthQuery is the builder for querying GoogleAuth entities. +type GoogleAuthQuery struct { + config + ctx *QueryContext + order []googleauth.OrderOption + inters []Interceptor + predicates []predicate.GoogleAuth + withUser *UserQuery + 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 GoogleAuthQuery builder. +func (_q *GoogleAuthQuery) Where(ps ...predicate.GoogleAuth) *GoogleAuthQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *GoogleAuthQuery) Limit(limit int) *GoogleAuthQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *GoogleAuthQuery) Offset(offset int) *GoogleAuthQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *GoogleAuthQuery) Unique(unique bool) *GoogleAuthQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *GoogleAuthQuery) Order(o ...googleauth.OrderOption) *GoogleAuthQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryUser chains the current query on the "user" edge. +func (_q *GoogleAuthQuery) QueryUser() *UserQuery { + query := (&UserClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(googleauth.Table, googleauth.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, googleauth.UserTable, googleauth.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first GoogleAuth entity from the query. +// Returns a *NotFoundError when no GoogleAuth was found. +func (_q *GoogleAuthQuery) First(ctx context.Context) (*GoogleAuth, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{googleauth.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *GoogleAuthQuery) FirstX(ctx context.Context) *GoogleAuth { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first GoogleAuth ID from the query. +// Returns a *NotFoundError when no GoogleAuth ID was found. +func (_q *GoogleAuthQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{googleauth.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *GoogleAuthQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single GoogleAuth entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one GoogleAuth entity is found. +// Returns a *NotFoundError when no GoogleAuth entities are found. +func (_q *GoogleAuthQuery) Only(ctx context.Context) (*GoogleAuth, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{googleauth.Label} + default: + return nil, &NotSingularError{googleauth.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *GoogleAuthQuery) OnlyX(ctx context.Context) *GoogleAuth { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only GoogleAuth ID in the query. +// Returns a *NotSingularError when more than one GoogleAuth ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *GoogleAuthQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{googleauth.Label} + default: + err = &NotSingularError{googleauth.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *GoogleAuthQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of GoogleAuths. +func (_q *GoogleAuthQuery) All(ctx context.Context) ([]*GoogleAuth, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*GoogleAuth, *GoogleAuthQuery]() + return withInterceptors[[]*GoogleAuth](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *GoogleAuthQuery) AllX(ctx context.Context) []*GoogleAuth { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of GoogleAuth IDs. +func (_q *GoogleAuthQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(googleauth.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *GoogleAuthQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *GoogleAuthQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*GoogleAuthQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *GoogleAuthQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *GoogleAuthQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *GoogleAuthQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the GoogleAuthQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *GoogleAuthQuery) Clone() *GoogleAuthQuery { + if _q == nil { + return nil + } + return &GoogleAuthQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]googleauth.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.GoogleAuth{}, _q.predicates...), + withUser: _q.withUser.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *GoogleAuthQuery) WithUser(opts ...func(*UserQuery)) *GoogleAuthQuery { + query := (&UserClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withUser = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// CreatedAt time.Time `json:"created_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.GoogleAuth.Query(). +// GroupBy(googleauth.FieldCreatedAt). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *GoogleAuthQuery) GroupBy(field string, fields ...string) *GoogleAuthGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &GoogleAuthGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = googleauth.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// CreatedAt time.Time `json:"created_at,omitempty"` +// } +// +// client.GoogleAuth.Query(). +// Select(googleauth.FieldCreatedAt). +// Scan(ctx, &v) +func (_q *GoogleAuthQuery) Select(fields ...string) *GoogleAuthSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &GoogleAuthSelect{GoogleAuthQuery: _q} + sbuild.label = googleauth.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a GoogleAuthSelect configured with the given aggregations. +func (_q *GoogleAuthQuery) Aggregate(fns ...AggregateFunc) *GoogleAuthSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *GoogleAuthQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !googleauth.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *GoogleAuthQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*GoogleAuth, error) { + var ( + nodes = []*GoogleAuth{} + withFKs = _q.withFKs + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withUser != nil, + } + ) + if _q.withUser != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, googleauth.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*GoogleAuth).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &GoogleAuth{config: _q.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, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withUser; query != nil { + if err := _q.loadUser(ctx, query, nodes, nil, + func(n *GoogleAuth, e *User) { n.Edges.User = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *GoogleAuthQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*GoogleAuth, init func(*GoogleAuth), assign func(*GoogleAuth, *User)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*GoogleAuth) + for i := range nodes { + if nodes[i].google_auth_user == nil { + continue + } + fk := *nodes[i].google_auth_user + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.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 "google_auth_user" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *GoogleAuthQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *GoogleAuthQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(googleauth.Table, googleauth.Columns, sqlgraph.NewFieldSpec(googleauth.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, googleauth.FieldID) + for i := range fields { + if fields[i] != googleauth.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *GoogleAuthQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(googleauth.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = googleauth.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// GoogleAuthGroupBy is the group-by builder for GoogleAuth entities. +type GoogleAuthGroupBy struct { + selector + build *GoogleAuthQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *GoogleAuthGroupBy) Aggregate(fns ...AggregateFunc) *GoogleAuthGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *GoogleAuthGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*GoogleAuthQuery, *GoogleAuthGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *GoogleAuthGroupBy) sqlScan(ctx context.Context, root *GoogleAuthQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// GoogleAuthSelect is the builder for selecting fields of GoogleAuth entities. +type GoogleAuthSelect struct { + *GoogleAuthQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *GoogleAuthSelect) Aggregate(fns ...AggregateFunc) *GoogleAuthSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *GoogleAuthSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*GoogleAuthQuery, *GoogleAuthSelect](ctx, _s.GoogleAuthQuery, _s, _s.inters, v) +} + +func (_s *GoogleAuthSelect) sqlScan(ctx context.Context, root *GoogleAuthQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/starter/ent/googleauth_update.go b/starter/ent/googleauth_update.go new file mode 100644 index 0000000..5bfd814 --- /dev/null +++ b/starter/ent/googleauth_update.go @@ -0,0 +1,362 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "ersteller-lib/starter/ent/googleauth" + "ersteller-lib/starter/ent/predicate" + "ersteller-lib/starter/ent/user" + "ersteller-lib/starter/google" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// GoogleAuthUpdate is the builder for updating GoogleAuth entities. +type GoogleAuthUpdate struct { + config + hooks []Hook + mutation *GoogleAuthMutation +} + +// Where appends a list predicates to the GoogleAuthUpdate builder. +func (_u *GoogleAuthUpdate) Where(ps ...predicate.GoogleAuth) *GoogleAuthUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *GoogleAuthUpdate) SetUpdatedAt(v time.Time) *GoogleAuthUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetCredentials sets the "credentials" field. +func (_u *GoogleAuthUpdate) SetCredentials(v google.Credentials) *GoogleAuthUpdate { + _u.mutation.SetCredentials(v) + return _u +} + +// SetNillableCredentials sets the "credentials" field if the given value is not nil. +func (_u *GoogleAuthUpdate) SetNillableCredentials(v *google.Credentials) *GoogleAuthUpdate { + if v != nil { + _u.SetCredentials(*v) + } + return _u +} + +// SetUserID sets the "user" edge to the User entity by ID. +func (_u *GoogleAuthUpdate) SetUserID(id int) *GoogleAuthUpdate { + _u.mutation.SetUserID(id) + return _u +} + +// SetUser sets the "user" edge to the User entity. +func (_u *GoogleAuthUpdate) SetUser(v *User) *GoogleAuthUpdate { + return _u.SetUserID(v.ID) +} + +// Mutation returns the GoogleAuthMutation object of the builder. +func (_u *GoogleAuthUpdate) Mutation() *GoogleAuthMutation { + return _u.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (_u *GoogleAuthUpdate) ClearUser() *GoogleAuthUpdate { + _u.mutation.ClearUser() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *GoogleAuthUpdate) Save(ctx context.Context) (int, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *GoogleAuthUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *GoogleAuthUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *GoogleAuthUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *GoogleAuthUpdate) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := googleauth.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *GoogleAuthUpdate) check() error { + if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "GoogleAuth.user"`) + } + return nil +} + +func (_u *GoogleAuthUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(googleauth.Table, googleauth.Columns, sqlgraph.NewFieldSpec(googleauth.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(googleauth.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.Credentials(); ok { + _spec.SetField(googleauth.FieldCredentials, field.TypeJSON, value) + } + if _u.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: googleauth.UserTable, + Columns: []string{googleauth.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: googleauth.UserTable, + Columns: []string{googleauth.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{googleauth.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// GoogleAuthUpdateOne is the builder for updating a single GoogleAuth entity. +type GoogleAuthUpdateOne struct { + config + fields []string + hooks []Hook + mutation *GoogleAuthMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *GoogleAuthUpdateOne) SetUpdatedAt(v time.Time) *GoogleAuthUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetCredentials sets the "credentials" field. +func (_u *GoogleAuthUpdateOne) SetCredentials(v google.Credentials) *GoogleAuthUpdateOne { + _u.mutation.SetCredentials(v) + return _u +} + +// SetNillableCredentials sets the "credentials" field if the given value is not nil. +func (_u *GoogleAuthUpdateOne) SetNillableCredentials(v *google.Credentials) *GoogleAuthUpdateOne { + if v != nil { + _u.SetCredentials(*v) + } + return _u +} + +// SetUserID sets the "user" edge to the User entity by ID. +func (_u *GoogleAuthUpdateOne) SetUserID(id int) *GoogleAuthUpdateOne { + _u.mutation.SetUserID(id) + return _u +} + +// SetUser sets the "user" edge to the User entity. +func (_u *GoogleAuthUpdateOne) SetUser(v *User) *GoogleAuthUpdateOne { + return _u.SetUserID(v.ID) +} + +// Mutation returns the GoogleAuthMutation object of the builder. +func (_u *GoogleAuthUpdateOne) Mutation() *GoogleAuthMutation { + return _u.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (_u *GoogleAuthUpdateOne) ClearUser() *GoogleAuthUpdateOne { + _u.mutation.ClearUser() + return _u +} + +// Where appends a list predicates to the GoogleAuthUpdate builder. +func (_u *GoogleAuthUpdateOne) Where(ps ...predicate.GoogleAuth) *GoogleAuthUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *GoogleAuthUpdateOne) Select(field string, fields ...string) *GoogleAuthUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated GoogleAuth entity. +func (_u *GoogleAuthUpdateOne) Save(ctx context.Context) (*GoogleAuth, error) { + _u.defaults() + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *GoogleAuthUpdateOne) SaveX(ctx context.Context) *GoogleAuth { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *GoogleAuthUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *GoogleAuthUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *GoogleAuthUpdateOne) defaults() { + if _, ok := _u.mutation.UpdatedAt(); !ok { + v := googleauth.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *GoogleAuthUpdateOne) check() error { + if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "GoogleAuth.user"`) + } + return nil +} + +func (_u *GoogleAuthUpdateOne) sqlSave(ctx context.Context) (_node *GoogleAuth, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(googleauth.Table, googleauth.Columns, sqlgraph.NewFieldSpec(googleauth.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "GoogleAuth.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, googleauth.FieldID) + for _, f := range fields { + if !googleauth.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != googleauth.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(googleauth.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.Credentials(); ok { + _spec.SetField(googleauth.FieldCredentials, field.TypeJSON, value) + } + if _u.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: googleauth.UserTable, + Columns: []string{googleauth.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: googleauth.UserTable, + Columns: []string{googleauth.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &GoogleAuth{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{googleauth.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/starter/ent/hook/hook.go b/starter/ent/hook/hook.go index 6361075..62e9eb5 100644 --- a/starter/ent/hook/hook.go +++ b/starter/ent/hook/hook.go @@ -8,6 +8,18 @@ import ( "fmt" ) +// The GoogleAuthFunc type is an adapter to allow the use of ordinary +// function as GoogleAuth mutator. +type GoogleAuthFunc func(context.Context, *ent.GoogleAuthMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f GoogleAuthFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.GoogleAuthMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GoogleAuthMutation", m) +} + // The UserFunc type is an adapter to allow the use of ordinary // function as User mutator. type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error) diff --git a/starter/ent/migrate/schema.go b/starter/ent/migrate/schema.go index c308b40..888a6e0 100644 --- a/starter/ent/migrate/schema.go +++ b/starter/ent/migrate/schema.go @@ -8,6 +8,28 @@ import ( ) var ( + // GoogleAuthsColumns holds the columns for the "google_auths" table. + GoogleAuthsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "credentials", Type: field.TypeJSON}, + {Name: "google_auth_user", Type: field.TypeInt}, + } + // GoogleAuthsTable holds the schema information for the "google_auths" table. + GoogleAuthsTable = &schema.Table{ + Name: "google_auths", + Columns: GoogleAuthsColumns, + PrimaryKey: []*schema.Column{GoogleAuthsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "google_auths_users_user", + Columns: []*schema.Column{GoogleAuthsColumns[4]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + } // UsersColumns holds the columns for the "users" table. UsersColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -24,9 +46,11 @@ var ( } // Tables holds all the tables in the schema. Tables = []*schema.Table{ + GoogleAuthsTable, UsersTable, } ) func init() { + GoogleAuthsTable.ForeignKeys[0].RefTable = UsersTable } diff --git a/starter/ent/mutation.go b/starter/ent/mutation.go index 6573464..4a9adbe 100644 --- a/starter/ent/mutation.go +++ b/starter/ent/mutation.go @@ -5,8 +5,10 @@ package ent import ( "context" "errors" + "ersteller-lib/starter/ent/googleauth" "ersteller-lib/starter/ent/predicate" "ersteller-lib/starter/ent/user" + "ersteller-lib/starter/google" "fmt" "sync" "time" @@ -24,9 +26,511 @@ const ( OpUpdateOne = ent.OpUpdateOne // Node types. - TypeUser = "User" + TypeGoogleAuth = "GoogleAuth" + TypeUser = "User" ) +// GoogleAuthMutation represents an operation that mutates the GoogleAuth nodes in the graph. +type GoogleAuthMutation struct { + config + op Op + typ string + id *int + created_at *time.Time + updated_at *time.Time + credentials *google.Credentials + clearedFields map[string]struct{} + user *int + cleareduser bool + done bool + oldValue func(context.Context) (*GoogleAuth, error) + predicates []predicate.GoogleAuth +} + +var _ ent.Mutation = (*GoogleAuthMutation)(nil) + +// googleauthOption allows management of the mutation configuration using functional options. +type googleauthOption func(*GoogleAuthMutation) + +// newGoogleAuthMutation creates new mutation for the GoogleAuth entity. +func newGoogleAuthMutation(c config, op Op, opts ...googleauthOption) *GoogleAuthMutation { + m := &GoogleAuthMutation{ + config: c, + op: op, + typ: TypeGoogleAuth, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withGoogleAuthID sets the ID field of the mutation. +func withGoogleAuthID(id int) googleauthOption { + return func(m *GoogleAuthMutation) { + var ( + err error + once sync.Once + value *GoogleAuth + ) + m.oldValue = func(ctx context.Context) (*GoogleAuth, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().GoogleAuth.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withGoogleAuth sets the old GoogleAuth of the mutation. +func withGoogleAuth(node *GoogleAuth) googleauthOption { + return func(m *GoogleAuthMutation) { + m.oldValue = func(context.Context) (*GoogleAuth, 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 GoogleAuthMutation) 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 GoogleAuthMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *GoogleAuthMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *GoogleAuthMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().GoogleAuth.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCreatedAt sets the "created_at" field. +func (m *GoogleAuthMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *GoogleAuthMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the GoogleAuth entity. +// If the GoogleAuth 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 *GoogleAuthMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *GoogleAuthMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *GoogleAuthMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *GoogleAuthMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the GoogleAuth entity. +// If the GoogleAuth 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 *GoogleAuthMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *GoogleAuthMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetCredentials sets the "credentials" field. +func (m *GoogleAuthMutation) SetCredentials(_go google.Credentials) { + m.credentials = &_go +} + +// Credentials returns the value of the "credentials" field in the mutation. +func (m *GoogleAuthMutation) Credentials() (r google.Credentials, exists bool) { + v := m.credentials + if v == nil { + return + } + return *v, true +} + +// OldCredentials returns the old "credentials" field's value of the GoogleAuth entity. +// If the GoogleAuth 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 *GoogleAuthMutation) OldCredentials(ctx context.Context) (v google.Credentials, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCredentials is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCredentials requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCredentials: %w", err) + } + return oldValue.Credentials, nil +} + +// ResetCredentials resets all changes to the "credentials" field. +func (m *GoogleAuthMutation) ResetCredentials() { + m.credentials = nil +} + +// SetUserID sets the "user" edge to the User entity by id. +func (m *GoogleAuthMutation) SetUserID(id int) { + m.user = &id +} + +// ClearUser clears the "user" edge to the User entity. +func (m *GoogleAuthMutation) ClearUser() { + m.cleareduser = true +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *GoogleAuthMutation) UserCleared() bool { + return m.cleareduser +} + +// UserID returns the "user" edge ID in the mutation. +func (m *GoogleAuthMutation) UserID() (id int, exists bool) { + if m.user != nil { + return *m.user, true + } + return +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *GoogleAuthMutation) UserIDs() (ids []int) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *GoogleAuthMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// Where appends a list predicates to the GoogleAuthMutation builder. +func (m *GoogleAuthMutation) Where(ps ...predicate.GoogleAuth) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the GoogleAuthMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *GoogleAuthMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.GoogleAuth, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *GoogleAuthMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *GoogleAuthMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (GoogleAuth). +func (m *GoogleAuthMutation) 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 *GoogleAuthMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.created_at != nil { + fields = append(fields, googleauth.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, googleauth.FieldUpdatedAt) + } + if m.credentials != nil { + fields = append(fields, googleauth.FieldCredentials) + } + 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 *GoogleAuthMutation) Field(name string) (ent.Value, bool) { + switch name { + case googleauth.FieldCreatedAt: + return m.CreatedAt() + case googleauth.FieldUpdatedAt: + return m.UpdatedAt() + case googleauth.FieldCredentials: + return m.Credentials() + } + 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 *GoogleAuthMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case googleauth.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case googleauth.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case googleauth.FieldCredentials: + return m.OldCredentials(ctx) + } + return nil, fmt.Errorf("unknown GoogleAuth 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 *GoogleAuthMutation) SetField(name string, value ent.Value) error { + switch name { + case googleauth.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case googleauth.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case googleauth.FieldCredentials: + v, ok := value.(google.Credentials) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCredentials(v) + return nil + } + return fmt.Errorf("unknown GoogleAuth field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *GoogleAuthMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *GoogleAuthMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *GoogleAuthMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown GoogleAuth numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *GoogleAuthMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *GoogleAuthMutation) 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 *GoogleAuthMutation) ClearField(name string) error { + return fmt.Errorf("unknown GoogleAuth 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 *GoogleAuthMutation) ResetField(name string) error { + switch name { + case googleauth.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case googleauth.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case googleauth.FieldCredentials: + m.ResetCredentials() + return nil + } + return fmt.Errorf("unknown GoogleAuth field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *GoogleAuthMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.user != nil { + edges = append(edges, googleauth.EdgeUser) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *GoogleAuthMutation) AddedIDs(name string) []ent.Value { + switch name { + case googleauth.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *GoogleAuthMutation) 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 *GoogleAuthMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *GoogleAuthMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.cleareduser { + edges = append(edges, googleauth.EdgeUser) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *GoogleAuthMutation) EdgeCleared(name string) bool { + switch name { + case googleauth.EdgeUser: + return m.cleareduser + } + 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 *GoogleAuthMutation) ClearEdge(name string) error { + switch name { + case googleauth.EdgeUser: + m.ClearUser() + return nil + } + return fmt.Errorf("unknown GoogleAuth 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 *GoogleAuthMutation) ResetEdge(name string) error { + switch name { + case googleauth.EdgeUser: + m.ResetUser() + return nil + } + return fmt.Errorf("unknown GoogleAuth edge %s", name) +} + // UserMutation represents an operation that mutates the User nodes in the graph. type UserMutation struct { config diff --git a/starter/ent/pagination_query.go b/starter/ent/pagination_query.go index 56787e2..cf2a923 100644 --- a/starter/ent/pagination_query.go +++ b/starter/ent/pagination_query.go @@ -10,6 +10,44 @@ import ( "entgo.io/ent/dialect/sql" ) +// PaginateAfterID paginates GoogleAuth by monotonically increasing "id". +// It preserves any existing filters/joins applied to the query, fetches up to "limit" items, +// and returns the next cursor (last ID of this page) and whether a next page exists. +func (q *GoogleAuthQuery) PaginateAfterID(ctx context.Context, afterID, limit int) ([]*GoogleAuth, int, bool, error) { + if limit <= 0 { + limit = 20 + } + + qq := q.Clone(). + Order(func(s *sql.Selector) { + s.OrderBy(s.C("id")) + }). + Limit(limit + 1) // fetch one extra to detect "has next" + + if afterID > 0 { + qq = qq.Where(func(s *sql.Selector) { + s.Where(sql.GT(s.C("id"), afterID)) + }) + } + + rows, err := qq.All(ctx) + if err != nil { + return nil, 0, false, err + } + + hasNext := len(rows) > limit + if hasNext { + rows = rows[:limit] + } + + next := 0 + if len(rows) > 0 { + next = rows[len(rows)-1].ID + } + + return rows, next, hasNext, nil +} + // PaginateAfterID paginates User by monotonically increasing "id". // It preserves any existing filters/joins applied to the query, fetches up to "limit" items, // and returns the next cursor (last ID of this page) and whether a next page exists. diff --git a/starter/ent/predicate/predicate.go b/starter/ent/predicate/predicate.go index af21dfe..b7abf6c 100644 --- a/starter/ent/predicate/predicate.go +++ b/starter/ent/predicate/predicate.go @@ -6,5 +6,8 @@ import ( "entgo.io/ent/dialect/sql" ) +// GoogleAuth is the predicate function for googleauth builders. +type GoogleAuth func(*sql.Selector) + // User is the predicate function for user builders. type User func(*sql.Selector) diff --git a/starter/ent/runtime.go b/starter/ent/runtime.go index 1a8dc2f..bf3abe4 100644 --- a/starter/ent/runtime.go +++ b/starter/ent/runtime.go @@ -3,6 +3,7 @@ package ent import ( + "ersteller-lib/starter/ent/googleauth" "ersteller-lib/starter/ent/schema" "ersteller-lib/starter/ent/user" "time" @@ -12,6 +13,21 @@ import ( // (default values, validators, hooks and policies) and stitches it // to their package variables. func init() { + googleauthMixin := schema.GoogleAuth{}.Mixin() + googleauthMixinFields0 := googleauthMixin[0].Fields() + _ = googleauthMixinFields0 + googleauthFields := schema.GoogleAuth{}.Fields() + _ = googleauthFields + // googleauthDescCreatedAt is the schema descriptor for created_at field. + googleauthDescCreatedAt := googleauthMixinFields0[0].Descriptor() + // googleauth.DefaultCreatedAt holds the default value on creation for the created_at field. + googleauth.DefaultCreatedAt = googleauthDescCreatedAt.Default.(func() time.Time) + // googleauthDescUpdatedAt is the schema descriptor for updated_at field. + googleauthDescUpdatedAt := googleauthMixinFields0[1].Descriptor() + // googleauth.DefaultUpdatedAt holds the default value on creation for the updated_at field. + googleauth.DefaultUpdatedAt = googleauthDescUpdatedAt.Default.(func() time.Time) + // googleauth.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + googleauth.UpdateDefaultUpdatedAt = googleauthDescUpdatedAt.UpdateDefault.(func() time.Time) userMixin := schema.User{}.Mixin() userMixinFields0 := userMixin[0].Fields() _ = userMixinFields0 diff --git a/starter/ent/schema/google_auth.go b/starter/ent/schema/google_auth.go new file mode 100644 index 0000000..47a5a7f --- /dev/null +++ b/starter/ent/schema/google_auth.go @@ -0,0 +1,34 @@ +package schema + +import ( + ersteller_ent "ersteller-lib/schema/ent" + google "ersteller-lib/starter/google" + + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +type GoogleAuth struct { + ent.Schema +} + +func (GoogleAuth) Mixin() []ent.Mixin { + return []ent.Mixin{ + ersteller_ent.TimeMixin{}, + } +} + +func (GoogleAuth) Fields() []ent.Field { + return []ent.Field{ + field.JSON("credentials", google.Credentials{}), + } +} + +func (GoogleAuth) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("user", User.Type). + Unique(). + Required(), + } +} diff --git a/starter/ent/tx.go b/starter/ent/tx.go index 8bbe7fa..cf6f435 100644 --- a/starter/ent/tx.go +++ b/starter/ent/tx.go @@ -12,6 +12,8 @@ import ( // Tx is a transactional client that is created by calling Client.Tx(). type Tx struct { config + // GoogleAuth is the client for interacting with the GoogleAuth builders. + GoogleAuth *GoogleAuthClient // User is the client for interacting with the User builders. User *UserClient @@ -145,6 +147,7 @@ func (tx *Tx) Client() *Client { } func (tx *Tx) init() { + tx.GoogleAuth = NewGoogleAuthClient(tx.config) tx.User = NewUserClient(tx.config) } @@ -155,7 +158,7 @@ func (tx *Tx) init() { // of them in order to commit or rollback the transaction. // // If a closed transaction is embedded in one of the generated entities, and the entity -// applies a query, for example: User.QueryXXX(), the query will be executed +// applies a query, for example: GoogleAuth.QueryXXX(), the query will be executed // through the driver which created this transaction. // // Note that txDriver is not goroutine safe. diff --git a/starter/go.mod b/starter/go.mod index 4fb86ab..f909913 100644 --- a/starter/go.mod +++ b/starter/go.mod @@ -7,6 +7,7 @@ require ( ersteller-lib v0.0.0 github.com/jackc/pgx/v5 v5.7.6 github.com/joho/godotenv v1.5.1 + golang.org/x/oauth2 v0.30.0 maragu.dev/gomponents v1.2.0 ) diff --git a/starter/go.sum b/starter/go.sum index a841f1c..8184f2e 100644 --- a/starter/go.sum +++ b/starter/go.sum @@ -62,6 +62,8 @@ golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ= golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc= golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I= golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= +golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= +golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU= golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/starter/google/credentials.go b/starter/google/credentials.go new file mode 100644 index 0000000..5147f22 --- /dev/null +++ b/starter/google/credentials.go @@ -0,0 +1,7 @@ +package google + +import "golang.org/x/oauth2" + +type Credentials struct { + Token oauth2.Token `json:"token"` +}