go generate ent schema

This commit is contained in:
Darko Luketic 2024-08-19 13:55:36 +02:00
parent c2369cca8a
commit 6943eb83f4
26 changed files with 7831 additions and 0 deletions

201
ent/account.go Normal file
View File

@ -0,0 +1,201 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"code.icod.de/auth/accountserver/ent/account"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
)
// Account is the model entity for the Account schema.
type Account struct {
config `json:"-"`
// ID of the ent.
ID uuid.UUID `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"`
// Nickname holds the value of the "nickname" field.
Nickname string `json:"nickname,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Secret holds the value of the "secret" field.
Secret []byte `json:"secret,omitempty"`
// Aes holds the value of the "aes" field.
Aes []byte `json:"aes,omitempty"`
// X509 holds the value of the "x509" field.
X509 []byte `json:"x509,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the AccountQuery when eager-loading is set.
Edges AccountEdges `json:"edges"`
selectValues sql.SelectValues
}
// AccountEdges holds the relations/edges for other nodes in the graph.
type AccountEdges struct {
// Emails holds the value of the emails edge.
Emails []*Email `json:"emails,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// EmailsOrErr returns the Emails value or an error if the edge
// was not loaded in eager-loading.
func (e AccountEdges) EmailsOrErr() ([]*Email, error) {
if e.loadedTypes[0] {
return e.Emails, nil
}
return nil, &NotLoadedError{edge: "emails"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Account) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case account.FieldSecret, account.FieldAes, account.FieldX509:
values[i] = new([]byte)
case account.FieldNickname, account.FieldName:
values[i] = new(sql.NullString)
case account.FieldCreatedAt, account.FieldUpdatedAt:
values[i] = new(sql.NullTime)
case account.FieldID:
values[i] = new(uuid.UUID)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Account fields.
func (a *Account) 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 account.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
a.ID = *value
}
case account.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 {
a.CreatedAt = value.Time
}
case account.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 {
a.UpdatedAt = value.Time
}
case account.FieldNickname:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field nickname", values[i])
} else if value.Valid {
a.Nickname = value.String
}
case account.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
a.Name = value.String
}
case account.FieldSecret:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field secret", values[i])
} else if value != nil {
a.Secret = *value
}
case account.FieldAes:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field aes", values[i])
} else if value != nil {
a.Aes = *value
}
case account.FieldX509:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field x509", values[i])
} else if value != nil {
a.X509 = *value
}
default:
a.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Account.
// This includes values selected through modifiers, order, etc.
func (a *Account) Value(name string) (ent.Value, error) {
return a.selectValues.Get(name)
}
// QueryEmails queries the "emails" edge of the Account entity.
func (a *Account) QueryEmails() *EmailQuery {
return NewAccountClient(a.config).QueryEmails(a)
}
// Update returns a builder for updating this Account.
// Note that you need to call Account.Unwrap() before calling this method if this Account
// was returned from a transaction, and the transaction was committed or rolled back.
func (a *Account) Update() *AccountUpdateOne {
return NewAccountClient(a.config).UpdateOne(a)
}
// Unwrap unwraps the Account 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 (a *Account) Unwrap() *Account {
_tx, ok := a.config.driver.(*txDriver)
if !ok {
panic("ent: Account is not a transactional entity")
}
a.config.driver = _tx.drv
return a
}
// String implements the fmt.Stringer.
func (a *Account) String() string {
var builder strings.Builder
builder.WriteString("Account(")
builder.WriteString(fmt.Sprintf("id=%v, ", a.ID))
builder.WriteString("created_at=")
builder.WriteString(a.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(a.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("nickname=")
builder.WriteString(a.Nickname)
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(a.Name)
builder.WriteString(", ")
builder.WriteString("secret=")
builder.WriteString(fmt.Sprintf("%v", a.Secret))
builder.WriteString(", ")
builder.WriteString("aes=")
builder.WriteString(fmt.Sprintf("%v", a.Aes))
builder.WriteString(", ")
builder.WriteString("x509=")
builder.WriteString(fmt.Sprintf("%v", a.X509))
builder.WriteByte(')')
return builder.String()
}
// Accounts is a parsable slice of Account.
type Accounts []*Account

124
ent/account/account.go Normal file
View File

@ -0,0 +1,124 @@
// Code generated by ent, DO NOT EDIT.
package account
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the account type in the database.
Label = "account"
// 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"
// FieldNickname holds the string denoting the nickname field in the database.
FieldNickname = "nickname"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldSecret holds the string denoting the secret field in the database.
FieldSecret = "secret"
// FieldAes holds the string denoting the aes field in the database.
FieldAes = "aes"
// FieldX509 holds the string denoting the x509 field in the database.
FieldX509 = "x509"
// EdgeEmails holds the string denoting the emails edge name in mutations.
EdgeEmails = "emails"
// Table holds the table name of the account in the database.
Table = "accounts"
// EmailsTable is the table that holds the emails relation/edge.
EmailsTable = "emails"
// EmailsInverseTable is the table name for the Email entity.
// It exists in this package in order to avoid circular dependency with the "email" package.
EmailsInverseTable = "emails"
// EmailsColumn is the table column denoting the emails relation/edge.
EmailsColumn = "account_emails"
)
// Columns holds all SQL columns for account fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldNickname,
FieldName,
FieldSecret,
FieldAes,
FieldX509,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// AesValidator is a validator for the "aes" field. It is called by the builders before save.
AesValidator func([]byte) error
)
// OrderOption defines the ordering options for the Account 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()
}
// ByNickname orders the results by the nickname field.
func ByNickname(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldNickname, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByEmailsCount orders the results by emails count.
func ByEmailsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newEmailsStep(), opts...)
}
}
// ByEmails orders the results by emails terms.
func ByEmails(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newEmailsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newEmailsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(EmailsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, EmailsTable, EmailsColumn),
)
}

460
ent/account/where.go Normal file
View File

@ -0,0 +1,460 @@
// Code generated by ent, DO NOT EDIT.
package account
import (
"time"
"code.icod.de/auth/accountserver/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/google/uuid"
)
// ID filters vertices based on their ID field.
func ID(id uuid.UUID) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id uuid.UUID) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id uuid.UUID) predicate.Account {
return predicate.Account(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...uuid.UUID) predicate.Account {
return predicate.Account(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...uuid.UUID) predicate.Account {
return predicate.Account(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id uuid.UUID) predicate.Account {
return predicate.Account(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id uuid.UUID) predicate.Account {
return predicate.Account(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id uuid.UUID) predicate.Account {
return predicate.Account(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id uuid.UUID) predicate.Account {
return predicate.Account(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.Account {
return predicate.Account(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.Account {
return predicate.Account(sql.FieldEQ(FieldUpdatedAt, v))
}
// Nickname applies equality check predicate on the "nickname" field. It's identical to NicknameEQ.
func Nickname(v string) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldNickname, v))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldName, v))
}
// Secret applies equality check predicate on the "secret" field. It's identical to SecretEQ.
func Secret(v []byte) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldSecret, v))
}
// Aes applies equality check predicate on the "aes" field. It's identical to AesEQ.
func Aes(v []byte) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldAes, v))
}
// X509 applies equality check predicate on the "x509" field. It's identical to X509EQ.
func X509(v []byte) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldX509, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Account {
return predicate.Account(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Account {
return predicate.Account(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Account {
return predicate.Account(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Account {
return predicate.Account(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Account {
return predicate.Account(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Account {
return predicate.Account(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Account {
return predicate.Account(sql.FieldLTE(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.Account {
return predicate.Account(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.Account {
return predicate.Account(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.Account {
return predicate.Account(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.Account {
return predicate.Account(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.Account {
return predicate.Account(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.Account {
return predicate.Account(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.Account {
return predicate.Account(sql.FieldLTE(FieldUpdatedAt, v))
}
// NicknameEQ applies the EQ predicate on the "nickname" field.
func NicknameEQ(v string) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldNickname, v))
}
// NicknameNEQ applies the NEQ predicate on the "nickname" field.
func NicknameNEQ(v string) predicate.Account {
return predicate.Account(sql.FieldNEQ(FieldNickname, v))
}
// NicknameIn applies the In predicate on the "nickname" field.
func NicknameIn(vs ...string) predicate.Account {
return predicate.Account(sql.FieldIn(FieldNickname, vs...))
}
// NicknameNotIn applies the NotIn predicate on the "nickname" field.
func NicknameNotIn(vs ...string) predicate.Account {
return predicate.Account(sql.FieldNotIn(FieldNickname, vs...))
}
// NicknameGT applies the GT predicate on the "nickname" field.
func NicknameGT(v string) predicate.Account {
return predicate.Account(sql.FieldGT(FieldNickname, v))
}
// NicknameGTE applies the GTE predicate on the "nickname" field.
func NicknameGTE(v string) predicate.Account {
return predicate.Account(sql.FieldGTE(FieldNickname, v))
}
// NicknameLT applies the LT predicate on the "nickname" field.
func NicknameLT(v string) predicate.Account {
return predicate.Account(sql.FieldLT(FieldNickname, v))
}
// NicknameLTE applies the LTE predicate on the "nickname" field.
func NicknameLTE(v string) predicate.Account {
return predicate.Account(sql.FieldLTE(FieldNickname, v))
}
// NicknameContains applies the Contains predicate on the "nickname" field.
func NicknameContains(v string) predicate.Account {
return predicate.Account(sql.FieldContains(FieldNickname, v))
}
// NicknameHasPrefix applies the HasPrefix predicate on the "nickname" field.
func NicknameHasPrefix(v string) predicate.Account {
return predicate.Account(sql.FieldHasPrefix(FieldNickname, v))
}
// NicknameHasSuffix applies the HasSuffix predicate on the "nickname" field.
func NicknameHasSuffix(v string) predicate.Account {
return predicate.Account(sql.FieldHasSuffix(FieldNickname, v))
}
// NicknameEqualFold applies the EqualFold predicate on the "nickname" field.
func NicknameEqualFold(v string) predicate.Account {
return predicate.Account(sql.FieldEqualFold(FieldNickname, v))
}
// NicknameContainsFold applies the ContainsFold predicate on the "nickname" field.
func NicknameContainsFold(v string) predicate.Account {
return predicate.Account(sql.FieldContainsFold(FieldNickname, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Account {
return predicate.Account(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Account {
return predicate.Account(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Account {
return predicate.Account(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Account {
return predicate.Account(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Account {
return predicate.Account(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Account {
return predicate.Account(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Account {
return predicate.Account(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Account {
return predicate.Account(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Account {
return predicate.Account(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Account {
return predicate.Account(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Account {
return predicate.Account(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Account {
return predicate.Account(sql.FieldContainsFold(FieldName, v))
}
// SecretEQ applies the EQ predicate on the "secret" field.
func SecretEQ(v []byte) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldSecret, v))
}
// SecretNEQ applies the NEQ predicate on the "secret" field.
func SecretNEQ(v []byte) predicate.Account {
return predicate.Account(sql.FieldNEQ(FieldSecret, v))
}
// SecretIn applies the In predicate on the "secret" field.
func SecretIn(vs ...[]byte) predicate.Account {
return predicate.Account(sql.FieldIn(FieldSecret, vs...))
}
// SecretNotIn applies the NotIn predicate on the "secret" field.
func SecretNotIn(vs ...[]byte) predicate.Account {
return predicate.Account(sql.FieldNotIn(FieldSecret, vs...))
}
// SecretGT applies the GT predicate on the "secret" field.
func SecretGT(v []byte) predicate.Account {
return predicate.Account(sql.FieldGT(FieldSecret, v))
}
// SecretGTE applies the GTE predicate on the "secret" field.
func SecretGTE(v []byte) predicate.Account {
return predicate.Account(sql.FieldGTE(FieldSecret, v))
}
// SecretLT applies the LT predicate on the "secret" field.
func SecretLT(v []byte) predicate.Account {
return predicate.Account(sql.FieldLT(FieldSecret, v))
}
// SecretLTE applies the LTE predicate on the "secret" field.
func SecretLTE(v []byte) predicate.Account {
return predicate.Account(sql.FieldLTE(FieldSecret, v))
}
// AesEQ applies the EQ predicate on the "aes" field.
func AesEQ(v []byte) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldAes, v))
}
// AesNEQ applies the NEQ predicate on the "aes" field.
func AesNEQ(v []byte) predicate.Account {
return predicate.Account(sql.FieldNEQ(FieldAes, v))
}
// AesIn applies the In predicate on the "aes" field.
func AesIn(vs ...[]byte) predicate.Account {
return predicate.Account(sql.FieldIn(FieldAes, vs...))
}
// AesNotIn applies the NotIn predicate on the "aes" field.
func AesNotIn(vs ...[]byte) predicate.Account {
return predicate.Account(sql.FieldNotIn(FieldAes, vs...))
}
// AesGT applies the GT predicate on the "aes" field.
func AesGT(v []byte) predicate.Account {
return predicate.Account(sql.FieldGT(FieldAes, v))
}
// AesGTE applies the GTE predicate on the "aes" field.
func AesGTE(v []byte) predicate.Account {
return predicate.Account(sql.FieldGTE(FieldAes, v))
}
// AesLT applies the LT predicate on the "aes" field.
func AesLT(v []byte) predicate.Account {
return predicate.Account(sql.FieldLT(FieldAes, v))
}
// AesLTE applies the LTE predicate on the "aes" field.
func AesLTE(v []byte) predicate.Account {
return predicate.Account(sql.FieldLTE(FieldAes, v))
}
// X509EQ applies the EQ predicate on the "x509" field.
func X509EQ(v []byte) predicate.Account {
return predicate.Account(sql.FieldEQ(FieldX509, v))
}
// X509NEQ applies the NEQ predicate on the "x509" field.
func X509NEQ(v []byte) predicate.Account {
return predicate.Account(sql.FieldNEQ(FieldX509, v))
}
// X509In applies the In predicate on the "x509" field.
func X509In(vs ...[]byte) predicate.Account {
return predicate.Account(sql.FieldIn(FieldX509, vs...))
}
// X509NotIn applies the NotIn predicate on the "x509" field.
func X509NotIn(vs ...[]byte) predicate.Account {
return predicate.Account(sql.FieldNotIn(FieldX509, vs...))
}
// X509GT applies the GT predicate on the "x509" field.
func X509GT(v []byte) predicate.Account {
return predicate.Account(sql.FieldGT(FieldX509, v))
}
// X509GTE applies the GTE predicate on the "x509" field.
func X509GTE(v []byte) predicate.Account {
return predicate.Account(sql.FieldGTE(FieldX509, v))
}
// X509LT applies the LT predicate on the "x509" field.
func X509LT(v []byte) predicate.Account {
return predicate.Account(sql.FieldLT(FieldX509, v))
}
// X509LTE applies the LTE predicate on the "x509" field.
func X509LTE(v []byte) predicate.Account {
return predicate.Account(sql.FieldLTE(FieldX509, v))
}
// HasEmails applies the HasEdge predicate on the "emails" edge.
func HasEmails() predicate.Account {
return predicate.Account(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, EmailsTable, EmailsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasEmailsWith applies the HasEdge predicate on the "emails" edge with a given conditions (other predicates).
func HasEmailsWith(preds ...predicate.Email) predicate.Account {
return predicate.Account(func(s *sql.Selector) {
step := newEmailsStep()
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.Account) predicate.Account {
return predicate.Account(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Account) predicate.Account {
return predicate.Account(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Account) predicate.Account {
return predicate.Account(sql.NotPredicates(p))
}

341
ent/account_create.go Normal file
View File

@ -0,0 +1,341 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"code.icod.de/auth/accountserver/ent/account"
"code.icod.de/auth/accountserver/ent/email"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
)
// AccountCreate is the builder for creating a Account entity.
type AccountCreate struct {
config
mutation *AccountMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (ac *AccountCreate) SetCreatedAt(t time.Time) *AccountCreate {
ac.mutation.SetCreatedAt(t)
return ac
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (ac *AccountCreate) SetNillableCreatedAt(t *time.Time) *AccountCreate {
if t != nil {
ac.SetCreatedAt(*t)
}
return ac
}
// SetUpdatedAt sets the "updated_at" field.
func (ac *AccountCreate) SetUpdatedAt(t time.Time) *AccountCreate {
ac.mutation.SetUpdatedAt(t)
return ac
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (ac *AccountCreate) SetNillableUpdatedAt(t *time.Time) *AccountCreate {
if t != nil {
ac.SetUpdatedAt(*t)
}
return ac
}
// SetNickname sets the "nickname" field.
func (ac *AccountCreate) SetNickname(s string) *AccountCreate {
ac.mutation.SetNickname(s)
return ac
}
// SetName sets the "name" field.
func (ac *AccountCreate) SetName(s string) *AccountCreate {
ac.mutation.SetName(s)
return ac
}
// SetSecret sets the "secret" field.
func (ac *AccountCreate) SetSecret(b []byte) *AccountCreate {
ac.mutation.SetSecret(b)
return ac
}
// SetAes sets the "aes" field.
func (ac *AccountCreate) SetAes(b []byte) *AccountCreate {
ac.mutation.SetAes(b)
return ac
}
// SetX509 sets the "x509" field.
func (ac *AccountCreate) SetX509(b []byte) *AccountCreate {
ac.mutation.SetX509(b)
return ac
}
// SetID sets the "id" field.
func (ac *AccountCreate) SetID(u uuid.UUID) *AccountCreate {
ac.mutation.SetID(u)
return ac
}
// AddEmailIDs adds the "emails" edge to the Email entity by IDs.
func (ac *AccountCreate) AddEmailIDs(ids ...uuid.UUID) *AccountCreate {
ac.mutation.AddEmailIDs(ids...)
return ac
}
// AddEmails adds the "emails" edges to the Email entity.
func (ac *AccountCreate) AddEmails(e ...*Email) *AccountCreate {
ids := make([]uuid.UUID, len(e))
for i := range e {
ids[i] = e[i].ID
}
return ac.AddEmailIDs(ids...)
}
// Mutation returns the AccountMutation object of the builder.
func (ac *AccountCreate) Mutation() *AccountMutation {
return ac.mutation
}
// Save creates the Account in the database.
func (ac *AccountCreate) Save(ctx context.Context) (*Account, error) {
ac.defaults()
return withHooks(ctx, ac.sqlSave, ac.mutation, ac.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (ac *AccountCreate) SaveX(ctx context.Context) *Account {
v, err := ac.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ac *AccountCreate) Exec(ctx context.Context) error {
_, err := ac.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ac *AccountCreate) ExecX(ctx context.Context) {
if err := ac.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (ac *AccountCreate) defaults() {
if _, ok := ac.mutation.CreatedAt(); !ok {
v := account.DefaultCreatedAt()
ac.mutation.SetCreatedAt(v)
}
if _, ok := ac.mutation.UpdatedAt(); !ok {
v := account.DefaultUpdatedAt()
ac.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (ac *AccountCreate) check() error {
if _, ok := ac.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Account.created_at"`)}
}
if _, ok := ac.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Account.updated_at"`)}
}
if _, ok := ac.mutation.Nickname(); !ok {
return &ValidationError{Name: "nickname", err: errors.New(`ent: missing required field "Account.nickname"`)}
}
if _, ok := ac.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Account.name"`)}
}
if _, ok := ac.mutation.Secret(); !ok {
return &ValidationError{Name: "secret", err: errors.New(`ent: missing required field "Account.secret"`)}
}
if _, ok := ac.mutation.Aes(); !ok {
return &ValidationError{Name: "aes", err: errors.New(`ent: missing required field "Account.aes"`)}
}
if v, ok := ac.mutation.Aes(); ok {
if err := account.AesValidator(v); err != nil {
return &ValidationError{Name: "aes", err: fmt.Errorf(`ent: validator failed for field "Account.aes": %w`, err)}
}
}
if _, ok := ac.mutation.X509(); !ok {
return &ValidationError{Name: "x509", err: errors.New(`ent: missing required field "Account.x509"`)}
}
return nil
}
func (ac *AccountCreate) sqlSave(ctx context.Context) (*Account, error) {
if err := ac.check(); err != nil {
return nil, err
}
_node, _spec := ac.createSpec()
if err := sqlgraph.CreateNode(ctx, ac.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
if _spec.ID.Value != nil {
if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
_node.ID = *id
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
return nil, err
}
}
ac.mutation.id = &_node.ID
ac.mutation.done = true
return _node, nil
}
func (ac *AccountCreate) createSpec() (*Account, *sqlgraph.CreateSpec) {
var (
_node = &Account{config: ac.config}
_spec = sqlgraph.NewCreateSpec(account.Table, sqlgraph.NewFieldSpec(account.FieldID, field.TypeUUID))
)
if id, ok := ac.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := ac.mutation.CreatedAt(); ok {
_spec.SetField(account.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if value, ok := ac.mutation.UpdatedAt(); ok {
_spec.SetField(account.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = value
}
if value, ok := ac.mutation.Nickname(); ok {
_spec.SetField(account.FieldNickname, field.TypeString, value)
_node.Nickname = value
}
if value, ok := ac.mutation.Name(); ok {
_spec.SetField(account.FieldName, field.TypeString, value)
_node.Name = value
}
if value, ok := ac.mutation.Secret(); ok {
_spec.SetField(account.FieldSecret, field.TypeBytes, value)
_node.Secret = value
}
if value, ok := ac.mutation.Aes(); ok {
_spec.SetField(account.FieldAes, field.TypeBytes, value)
_node.Aes = value
}
if value, ok := ac.mutation.X509(); ok {
_spec.SetField(account.FieldX509, field.TypeBytes, value)
_node.X509 = value
}
if nodes := ac.mutation.EmailsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.EmailsTable,
Columns: []string{account.EmailsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(email.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// AccountCreateBulk is the builder for creating many Account entities in bulk.
type AccountCreateBulk struct {
config
err error
builders []*AccountCreate
}
// Save creates the Account entities in the database.
func (acb *AccountCreateBulk) Save(ctx context.Context) ([]*Account, error) {
if acb.err != nil {
return nil, acb.err
}
specs := make([]*sqlgraph.CreateSpec, len(acb.builders))
nodes := make([]*Account, len(acb.builders))
mutators := make([]Mutator, len(acb.builders))
for i := range acb.builders {
func(i int, root context.Context) {
builder := acb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AccountMutation)
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, acb.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, acb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, acb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (acb *AccountCreateBulk) SaveX(ctx context.Context) []*Account {
v, err := acb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (acb *AccountCreateBulk) Exec(ctx context.Context) error {
_, err := acb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (acb *AccountCreateBulk) ExecX(ctx context.Context) {
if err := acb.Exec(ctx); err != nil {
panic(err)
}
}

88
ent/account_delete.go Normal file
View File

@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"code.icod.de/auth/accountserver/ent/account"
"code.icod.de/auth/accountserver/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// AccountDelete is the builder for deleting a Account entity.
type AccountDelete struct {
config
hooks []Hook
mutation *AccountMutation
}
// Where appends a list predicates to the AccountDelete builder.
func (ad *AccountDelete) Where(ps ...predicate.Account) *AccountDelete {
ad.mutation.Where(ps...)
return ad
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (ad *AccountDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, ad.sqlExec, ad.mutation, ad.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (ad *AccountDelete) ExecX(ctx context.Context) int {
n, err := ad.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (ad *AccountDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(account.Table, sqlgraph.NewFieldSpec(account.FieldID, field.TypeUUID))
if ps := ad.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, ad.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
ad.mutation.done = true
return affected, err
}
// AccountDeleteOne is the builder for deleting a single Account entity.
type AccountDeleteOne struct {
ad *AccountDelete
}
// Where appends a list predicates to the AccountDelete builder.
func (ado *AccountDeleteOne) Where(ps ...predicate.Account) *AccountDeleteOne {
ado.ad.mutation.Where(ps...)
return ado
}
// Exec executes the deletion query.
func (ado *AccountDeleteOne) Exec(ctx context.Context) error {
n, err := ado.ad.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{account.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (ado *AccountDeleteOne) ExecX(ctx context.Context) {
if err := ado.Exec(ctx); err != nil {
panic(err)
}
}

608
ent/account_query.go Normal file
View File

@ -0,0 +1,608 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
"code.icod.de/auth/accountserver/ent/account"
"code.icod.de/auth/accountserver/ent/email"
"code.icod.de/auth/accountserver/ent/predicate"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
)
// AccountQuery is the builder for querying Account entities.
type AccountQuery struct {
config
ctx *QueryContext
order []account.OrderOption
inters []Interceptor
predicates []predicate.Account
withEmails *EmailQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the AccountQuery builder.
func (aq *AccountQuery) Where(ps ...predicate.Account) *AccountQuery {
aq.predicates = append(aq.predicates, ps...)
return aq
}
// Limit the number of records to be returned by this query.
func (aq *AccountQuery) Limit(limit int) *AccountQuery {
aq.ctx.Limit = &limit
return aq
}
// Offset to start from.
func (aq *AccountQuery) Offset(offset int) *AccountQuery {
aq.ctx.Offset = &offset
return aq
}
// 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 (aq *AccountQuery) Unique(unique bool) *AccountQuery {
aq.ctx.Unique = &unique
return aq
}
// Order specifies how the records should be ordered.
func (aq *AccountQuery) Order(o ...account.OrderOption) *AccountQuery {
aq.order = append(aq.order, o...)
return aq
}
// QueryEmails chains the current query on the "emails" edge.
func (aq *AccountQuery) QueryEmails() *EmailQuery {
query := (&EmailClient{config: aq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := aq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := aq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(account.Table, account.FieldID, selector),
sqlgraph.To(email.Table, email.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, account.EmailsTable, account.EmailsColumn),
)
fromU = sqlgraph.SetNeighbors(aq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Account entity from the query.
// Returns a *NotFoundError when no Account was found.
func (aq *AccountQuery) First(ctx context.Context) (*Account, error) {
nodes, err := aq.Limit(1).All(setContextOp(ctx, aq.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{account.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (aq *AccountQuery) FirstX(ctx context.Context) *Account {
node, err := aq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Account ID from the query.
// Returns a *NotFoundError when no Account ID was found.
func (aq *AccountQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = aq.Limit(1).IDs(setContextOp(ctx, aq.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{account.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (aq *AccountQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := aq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Account entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Account entity is found.
// Returns a *NotFoundError when no Account entities are found.
func (aq *AccountQuery) Only(ctx context.Context) (*Account, error) {
nodes, err := aq.Limit(2).All(setContextOp(ctx, aq.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{account.Label}
default:
return nil, &NotSingularError{account.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (aq *AccountQuery) OnlyX(ctx context.Context) *Account {
node, err := aq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Account ID in the query.
// Returns a *NotSingularError when more than one Account ID is found.
// Returns a *NotFoundError when no entities are found.
func (aq *AccountQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = aq.Limit(2).IDs(setContextOp(ctx, aq.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{account.Label}
default:
err = &NotSingularError{account.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (aq *AccountQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := aq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Accounts.
func (aq *AccountQuery) All(ctx context.Context) ([]*Account, error) {
ctx = setContextOp(ctx, aq.ctx, ent.OpQueryAll)
if err := aq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Account, *AccountQuery]()
return withInterceptors[[]*Account](ctx, aq, qr, aq.inters)
}
// AllX is like All, but panics if an error occurs.
func (aq *AccountQuery) AllX(ctx context.Context) []*Account {
nodes, err := aq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Account IDs.
func (aq *AccountQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
if aq.ctx.Unique == nil && aq.path != nil {
aq.Unique(true)
}
ctx = setContextOp(ctx, aq.ctx, ent.OpQueryIDs)
if err = aq.Select(account.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (aq *AccountQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := aq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (aq *AccountQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, aq.ctx, ent.OpQueryCount)
if err := aq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, aq, querierCount[*AccountQuery](), aq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (aq *AccountQuery) CountX(ctx context.Context) int {
count, err := aq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (aq *AccountQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, aq.ctx, ent.OpQueryExist)
switch _, err := aq.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 (aq *AccountQuery) ExistX(ctx context.Context) bool {
exist, err := aq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the AccountQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (aq *AccountQuery) Clone() *AccountQuery {
if aq == nil {
return nil
}
return &AccountQuery{
config: aq.config,
ctx: aq.ctx.Clone(),
order: append([]account.OrderOption{}, aq.order...),
inters: append([]Interceptor{}, aq.inters...),
predicates: append([]predicate.Account{}, aq.predicates...),
withEmails: aq.withEmails.Clone(),
// clone intermediate query.
sql: aq.sql.Clone(),
path: aq.path,
}
}
// WithEmails tells the query-builder to eager-load the nodes that are connected to
// the "emails" edge. The optional arguments are used to configure the query builder of the edge.
func (aq *AccountQuery) WithEmails(opts ...func(*EmailQuery)) *AccountQuery {
query := (&EmailClient{config: aq.config}).Query()
for _, opt := range opts {
opt(query)
}
aq.withEmails = query
return aq
}
// 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.Account.Query().
// GroupBy(account.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (aq *AccountQuery) GroupBy(field string, fields ...string) *AccountGroupBy {
aq.ctx.Fields = append([]string{field}, fields...)
grbuild := &AccountGroupBy{build: aq}
grbuild.flds = &aq.ctx.Fields
grbuild.label = account.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.Account.Query().
// Select(account.FieldCreatedAt).
// Scan(ctx, &v)
func (aq *AccountQuery) Select(fields ...string) *AccountSelect {
aq.ctx.Fields = append(aq.ctx.Fields, fields...)
sbuild := &AccountSelect{AccountQuery: aq}
sbuild.label = account.Label
sbuild.flds, sbuild.scan = &aq.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a AccountSelect configured with the given aggregations.
func (aq *AccountQuery) Aggregate(fns ...AggregateFunc) *AccountSelect {
return aq.Select().Aggregate(fns...)
}
func (aq *AccountQuery) prepareQuery(ctx context.Context) error {
for _, inter := range aq.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, aq); err != nil {
return err
}
}
}
for _, f := range aq.ctx.Fields {
if !account.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if aq.path != nil {
prev, err := aq.path(ctx)
if err != nil {
return err
}
aq.sql = prev
}
return nil
}
func (aq *AccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Account, error) {
var (
nodes = []*Account{}
_spec = aq.querySpec()
loadedTypes = [1]bool{
aq.withEmails != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Account).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Account{config: aq.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, aq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := aq.withEmails; query != nil {
if err := aq.loadEmails(ctx, query, nodes,
func(n *Account) { n.Edges.Emails = []*Email{} },
func(n *Account, e *Email) { n.Edges.Emails = append(n.Edges.Emails, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (aq *AccountQuery) loadEmails(ctx context.Context, query *EmailQuery, nodes []*Account, init func(*Account), assign func(*Account, *Email)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Account)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Email(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(account.EmailsColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.account_emails
if fk == nil {
return fmt.Errorf(`foreign-key "account_emails" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "account_emails" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (aq *AccountQuery) sqlCount(ctx context.Context) (int, error) {
_spec := aq.querySpec()
_spec.Node.Columns = aq.ctx.Fields
if len(aq.ctx.Fields) > 0 {
_spec.Unique = aq.ctx.Unique != nil && *aq.ctx.Unique
}
return sqlgraph.CountNodes(ctx, aq.driver, _spec)
}
func (aq *AccountQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(account.Table, account.Columns, sqlgraph.NewFieldSpec(account.FieldID, field.TypeUUID))
_spec.From = aq.sql
if unique := aq.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if aq.path != nil {
_spec.Unique = true
}
if fields := aq.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, account.FieldID)
for i := range fields {
if fields[i] != account.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := aq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := aq.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := aq.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := aq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (aq *AccountQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(aq.driver.Dialect())
t1 := builder.Table(account.Table)
columns := aq.ctx.Fields
if len(columns) == 0 {
columns = account.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if aq.sql != nil {
selector = aq.sql
selector.Select(selector.Columns(columns...)...)
}
if aq.ctx.Unique != nil && *aq.ctx.Unique {
selector.Distinct()
}
for _, p := range aq.predicates {
p(selector)
}
for _, p := range aq.order {
p(selector)
}
if offset := aq.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 := aq.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// AccountGroupBy is the group-by builder for Account entities.
type AccountGroupBy struct {
selector
build *AccountQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (agb *AccountGroupBy) Aggregate(fns ...AggregateFunc) *AccountGroupBy {
agb.fns = append(agb.fns, fns...)
return agb
}
// Scan applies the selector query and scans the result into the given value.
func (agb *AccountGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, agb.build.ctx, ent.OpQueryGroupBy)
if err := agb.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*AccountQuery, *AccountGroupBy](ctx, agb.build, agb, agb.build.inters, v)
}
func (agb *AccountGroupBy) sqlScan(ctx context.Context, root *AccountQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(agb.fns))
for _, fn := range agb.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*agb.flds)+len(agb.fns))
for _, f := range *agb.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*agb.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := agb.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// AccountSelect is the builder for selecting fields of Account entities.
type AccountSelect struct {
*AccountQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (as *AccountSelect) Aggregate(fns ...AggregateFunc) *AccountSelect {
as.fns = append(as.fns, fns...)
return as
}
// Scan applies the selector query and scans the result into the given value.
func (as *AccountSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, as.ctx, ent.OpQuerySelect)
if err := as.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*AccountQuery, *AccountSelect](ctx, as.AccountQuery, as, as.inters, v)
}
func (as *AccountSelect) sqlScan(ctx context.Context, root *AccountQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(as.fns))
for _, fn := range as.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*as.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 := as.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

524
ent/account_update.go Normal file
View File

@ -0,0 +1,524 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"code.icod.de/auth/accountserver/ent/account"
"code.icod.de/auth/accountserver/ent/email"
"code.icod.de/auth/accountserver/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
)
// AccountUpdate is the builder for updating Account entities.
type AccountUpdate struct {
config
hooks []Hook
mutation *AccountMutation
}
// Where appends a list predicates to the AccountUpdate builder.
func (au *AccountUpdate) Where(ps ...predicate.Account) *AccountUpdate {
au.mutation.Where(ps...)
return au
}
// SetUpdatedAt sets the "updated_at" field.
func (au *AccountUpdate) SetUpdatedAt(t time.Time) *AccountUpdate {
au.mutation.SetUpdatedAt(t)
return au
}
// SetNickname sets the "nickname" field.
func (au *AccountUpdate) SetNickname(s string) *AccountUpdate {
au.mutation.SetNickname(s)
return au
}
// SetNillableNickname sets the "nickname" field if the given value is not nil.
func (au *AccountUpdate) SetNillableNickname(s *string) *AccountUpdate {
if s != nil {
au.SetNickname(*s)
}
return au
}
// SetName sets the "name" field.
func (au *AccountUpdate) SetName(s string) *AccountUpdate {
au.mutation.SetName(s)
return au
}
// SetNillableName sets the "name" field if the given value is not nil.
func (au *AccountUpdate) SetNillableName(s *string) *AccountUpdate {
if s != nil {
au.SetName(*s)
}
return au
}
// SetSecret sets the "secret" field.
func (au *AccountUpdate) SetSecret(b []byte) *AccountUpdate {
au.mutation.SetSecret(b)
return au
}
// SetAes sets the "aes" field.
func (au *AccountUpdate) SetAes(b []byte) *AccountUpdate {
au.mutation.SetAes(b)
return au
}
// SetX509 sets the "x509" field.
func (au *AccountUpdate) SetX509(b []byte) *AccountUpdate {
au.mutation.SetX509(b)
return au
}
// AddEmailIDs adds the "emails" edge to the Email entity by IDs.
func (au *AccountUpdate) AddEmailIDs(ids ...uuid.UUID) *AccountUpdate {
au.mutation.AddEmailIDs(ids...)
return au
}
// AddEmails adds the "emails" edges to the Email entity.
func (au *AccountUpdate) AddEmails(e ...*Email) *AccountUpdate {
ids := make([]uuid.UUID, len(e))
for i := range e {
ids[i] = e[i].ID
}
return au.AddEmailIDs(ids...)
}
// Mutation returns the AccountMutation object of the builder.
func (au *AccountUpdate) Mutation() *AccountMutation {
return au.mutation
}
// ClearEmails clears all "emails" edges to the Email entity.
func (au *AccountUpdate) ClearEmails() *AccountUpdate {
au.mutation.ClearEmails()
return au
}
// RemoveEmailIDs removes the "emails" edge to Email entities by IDs.
func (au *AccountUpdate) RemoveEmailIDs(ids ...uuid.UUID) *AccountUpdate {
au.mutation.RemoveEmailIDs(ids...)
return au
}
// RemoveEmails removes "emails" edges to Email entities.
func (au *AccountUpdate) RemoveEmails(e ...*Email) *AccountUpdate {
ids := make([]uuid.UUID, len(e))
for i := range e {
ids[i] = e[i].ID
}
return au.RemoveEmailIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (au *AccountUpdate) Save(ctx context.Context) (int, error) {
au.defaults()
return withHooks(ctx, au.sqlSave, au.mutation, au.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (au *AccountUpdate) SaveX(ctx context.Context) int {
affected, err := au.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (au *AccountUpdate) Exec(ctx context.Context) error {
_, err := au.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (au *AccountUpdate) ExecX(ctx context.Context) {
if err := au.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (au *AccountUpdate) defaults() {
if _, ok := au.mutation.UpdatedAt(); !ok {
v := account.UpdateDefaultUpdatedAt()
au.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (au *AccountUpdate) check() error {
if v, ok := au.mutation.Aes(); ok {
if err := account.AesValidator(v); err != nil {
return &ValidationError{Name: "aes", err: fmt.Errorf(`ent: validator failed for field "Account.aes": %w`, err)}
}
}
return nil
}
func (au *AccountUpdate) sqlSave(ctx context.Context) (n int, err error) {
if err := au.check(); err != nil {
return n, err
}
_spec := sqlgraph.NewUpdateSpec(account.Table, account.Columns, sqlgraph.NewFieldSpec(account.FieldID, field.TypeUUID))
if ps := au.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := au.mutation.UpdatedAt(); ok {
_spec.SetField(account.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := au.mutation.Nickname(); ok {
_spec.SetField(account.FieldNickname, field.TypeString, value)
}
if value, ok := au.mutation.Name(); ok {
_spec.SetField(account.FieldName, field.TypeString, value)
}
if value, ok := au.mutation.Secret(); ok {
_spec.SetField(account.FieldSecret, field.TypeBytes, value)
}
if value, ok := au.mutation.Aes(); ok {
_spec.SetField(account.FieldAes, field.TypeBytes, value)
}
if value, ok := au.mutation.X509(); ok {
_spec.SetField(account.FieldX509, field.TypeBytes, value)
}
if au.mutation.EmailsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.EmailsTable,
Columns: []string{account.EmailsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(email.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := au.mutation.RemovedEmailsIDs(); len(nodes) > 0 && !au.mutation.EmailsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.EmailsTable,
Columns: []string{account.EmailsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(email.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := au.mutation.EmailsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.EmailsTable,
Columns: []string{account.EmailsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(email.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if n, err = sqlgraph.UpdateNodes(ctx, au.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{account.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
au.mutation.done = true
return n, nil
}
// AccountUpdateOne is the builder for updating a single Account entity.
type AccountUpdateOne struct {
config
fields []string
hooks []Hook
mutation *AccountMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (auo *AccountUpdateOne) SetUpdatedAt(t time.Time) *AccountUpdateOne {
auo.mutation.SetUpdatedAt(t)
return auo
}
// SetNickname sets the "nickname" field.
func (auo *AccountUpdateOne) SetNickname(s string) *AccountUpdateOne {
auo.mutation.SetNickname(s)
return auo
}
// SetNillableNickname sets the "nickname" field if the given value is not nil.
func (auo *AccountUpdateOne) SetNillableNickname(s *string) *AccountUpdateOne {
if s != nil {
auo.SetNickname(*s)
}
return auo
}
// SetName sets the "name" field.
func (auo *AccountUpdateOne) SetName(s string) *AccountUpdateOne {
auo.mutation.SetName(s)
return auo
}
// SetNillableName sets the "name" field if the given value is not nil.
func (auo *AccountUpdateOne) SetNillableName(s *string) *AccountUpdateOne {
if s != nil {
auo.SetName(*s)
}
return auo
}
// SetSecret sets the "secret" field.
func (auo *AccountUpdateOne) SetSecret(b []byte) *AccountUpdateOne {
auo.mutation.SetSecret(b)
return auo
}
// SetAes sets the "aes" field.
func (auo *AccountUpdateOne) SetAes(b []byte) *AccountUpdateOne {
auo.mutation.SetAes(b)
return auo
}
// SetX509 sets the "x509" field.
func (auo *AccountUpdateOne) SetX509(b []byte) *AccountUpdateOne {
auo.mutation.SetX509(b)
return auo
}
// AddEmailIDs adds the "emails" edge to the Email entity by IDs.
func (auo *AccountUpdateOne) AddEmailIDs(ids ...uuid.UUID) *AccountUpdateOne {
auo.mutation.AddEmailIDs(ids...)
return auo
}
// AddEmails adds the "emails" edges to the Email entity.
func (auo *AccountUpdateOne) AddEmails(e ...*Email) *AccountUpdateOne {
ids := make([]uuid.UUID, len(e))
for i := range e {
ids[i] = e[i].ID
}
return auo.AddEmailIDs(ids...)
}
// Mutation returns the AccountMutation object of the builder.
func (auo *AccountUpdateOne) Mutation() *AccountMutation {
return auo.mutation
}
// ClearEmails clears all "emails" edges to the Email entity.
func (auo *AccountUpdateOne) ClearEmails() *AccountUpdateOne {
auo.mutation.ClearEmails()
return auo
}
// RemoveEmailIDs removes the "emails" edge to Email entities by IDs.
func (auo *AccountUpdateOne) RemoveEmailIDs(ids ...uuid.UUID) *AccountUpdateOne {
auo.mutation.RemoveEmailIDs(ids...)
return auo
}
// RemoveEmails removes "emails" edges to Email entities.
func (auo *AccountUpdateOne) RemoveEmails(e ...*Email) *AccountUpdateOne {
ids := make([]uuid.UUID, len(e))
for i := range e {
ids[i] = e[i].ID
}
return auo.RemoveEmailIDs(ids...)
}
// Where appends a list predicates to the AccountUpdate builder.
func (auo *AccountUpdateOne) Where(ps ...predicate.Account) *AccountUpdateOne {
auo.mutation.Where(ps...)
return auo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (auo *AccountUpdateOne) Select(field string, fields ...string) *AccountUpdateOne {
auo.fields = append([]string{field}, fields...)
return auo
}
// Save executes the query and returns the updated Account entity.
func (auo *AccountUpdateOne) Save(ctx context.Context) (*Account, error) {
auo.defaults()
return withHooks(ctx, auo.sqlSave, auo.mutation, auo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (auo *AccountUpdateOne) SaveX(ctx context.Context) *Account {
node, err := auo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (auo *AccountUpdateOne) Exec(ctx context.Context) error {
_, err := auo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (auo *AccountUpdateOne) ExecX(ctx context.Context) {
if err := auo.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (auo *AccountUpdateOne) defaults() {
if _, ok := auo.mutation.UpdatedAt(); !ok {
v := account.UpdateDefaultUpdatedAt()
auo.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (auo *AccountUpdateOne) check() error {
if v, ok := auo.mutation.Aes(); ok {
if err := account.AesValidator(v); err != nil {
return &ValidationError{Name: "aes", err: fmt.Errorf(`ent: validator failed for field "Account.aes": %w`, err)}
}
}
return nil
}
func (auo *AccountUpdateOne) sqlSave(ctx context.Context) (_node *Account, err error) {
if err := auo.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(account.Table, account.Columns, sqlgraph.NewFieldSpec(account.FieldID, field.TypeUUID))
id, ok := auo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Account.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := auo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, account.FieldID)
for _, f := range fields {
if !account.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != account.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := auo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := auo.mutation.UpdatedAt(); ok {
_spec.SetField(account.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := auo.mutation.Nickname(); ok {
_spec.SetField(account.FieldNickname, field.TypeString, value)
}
if value, ok := auo.mutation.Name(); ok {
_spec.SetField(account.FieldName, field.TypeString, value)
}
if value, ok := auo.mutation.Secret(); ok {
_spec.SetField(account.FieldSecret, field.TypeBytes, value)
}
if value, ok := auo.mutation.Aes(); ok {
_spec.SetField(account.FieldAes, field.TypeBytes, value)
}
if value, ok := auo.mutation.X509(); ok {
_spec.SetField(account.FieldX509, field.TypeBytes, value)
}
if auo.mutation.EmailsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.EmailsTable,
Columns: []string{account.EmailsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(email.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := auo.mutation.RemovedEmailsIDs(); len(nodes) > 0 && !auo.mutation.EmailsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.EmailsTable,
Columns: []string{account.EmailsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(email.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := auo.mutation.EmailsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.EmailsTable,
Columns: []string{account.EmailsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(email.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Account{config: auo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, auo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{account.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
auo.mutation.done = true
return _node, nil
}

517
ent/client.go Normal file
View File

@ -0,0 +1,517 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"code.icod.de/auth/accountserver/ent/migrate"
"github.com/google/uuid"
"code.icod.de/auth/accountserver/ent/account"
"code.icod.de/auth/accountserver/ent/email"
"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.
type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Account is the client for interacting with the Account builders.
Account *AccountClient
// Email is the client for interacting with the Email builders.
Email *EmailClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
client := &Client{config: newConfig(opts...)}
client.init()
return client
}
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Account = NewAccountClient(c.config)
c.Email = NewEmailClient(c.config)
}
type (
// config is the configuration for the client and its builder.
config struct {
// driver used for executing database requests.
driver dialect.Driver
// debug enable a debug logging.
debug bool
// log used for logging on debug mode.
log func(...any)
// hooks to execute on mutations.
hooks *hooks
// interceptors to execute on queries.
inters *inters
}
// Option function to configure the client.
Option func(*config)
)
// newConfig creates a new config for the client.
func newConfig(opts ...Option) config {
cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
cfg.options(opts...)
return cfg
}
// options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.debug {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Debug enables debug logging on the ent.Driver.
func Debug() Option {
return func(c *config) {
c.debug = true
}
}
// Log sets the logging function for debug mode.
func Log(fn func(...any)) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}
// Open opens a database/sql.DB specified by the driver name and
// the data source name, and returns a new client attached to it.
// Optional parameters can be added for configuring the client.
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
switch driverName {
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
drv, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
return NewClient(append(options, Driver(drv))...), nil
default:
return nil, fmt.Errorf("unsupported driver: %q", driverName)
}
}
// ErrTxStarted is returned when trying to start a new transaction from a transactional client.
var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction")
// Tx returns a new transactional client. The provided context
// is used until the transaction is committed or rolled back.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, ErrTxStarted
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Account: NewAccountClient(cfg),
Email: NewEmailClient(cfg),
}, nil
}
// BeginTx returns a transactional client with specified options.
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, errors.New("ent: cannot start a transaction within a transaction")
}
tx, err := c.driver.(interface {
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
}).BeginTx(ctx, opts)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{
ctx: ctx,
config: cfg,
Account: NewAccountClient(cfg),
Email: NewEmailClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Account.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
if c.debug {
return c
}
cfg := c.config
cfg.driver = dialect.Debug(c.driver, c.log)
client := &Client{config: cfg}
client.init()
return client
}
// Close closes the database connection and prevents new queries from starting.
func (c *Client) Close() error {
return c.driver.Close()
}
// 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.Account.Use(hooks...)
c.Email.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.Account.Intercept(interceptors...)
c.Email.Intercept(interceptors...)
}
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *AccountMutation:
return c.Account.mutate(ctx, m)
case *EmailMutation:
return c.Email.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
}
// AccountClient is a client for the Account schema.
type AccountClient struct {
config
}
// NewAccountClient returns a client for the Account from the given config.
func NewAccountClient(c config) *AccountClient {
return &AccountClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `account.Hooks(f(g(h())))`.
func (c *AccountClient) Use(hooks ...Hook) {
c.hooks.Account = append(c.hooks.Account, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `account.Intercept(f(g(h())))`.
func (c *AccountClient) Intercept(interceptors ...Interceptor) {
c.inters.Account = append(c.inters.Account, interceptors...)
}
// Create returns a builder for creating a Account entity.
func (c *AccountClient) Create() *AccountCreate {
mutation := newAccountMutation(c.config, OpCreate)
return &AccountCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Account entities.
func (c *AccountClient) CreateBulk(builders ...*AccountCreate) *AccountCreateBulk {
return &AccountCreateBulk{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 *AccountClient) MapCreateBulk(slice any, setFunc func(*AccountCreate, int)) *AccountCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &AccountCreateBulk{err: fmt.Errorf("calling to AccountClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*AccountCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &AccountCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Account.
func (c *AccountClient) Update() *AccountUpdate {
mutation := newAccountMutation(c.config, OpUpdate)
return &AccountUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *AccountClient) UpdateOne(a *Account) *AccountUpdateOne {
mutation := newAccountMutation(c.config, OpUpdateOne, withAccount(a))
return &AccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *AccountClient) UpdateOneID(id uuid.UUID) *AccountUpdateOne {
mutation := newAccountMutation(c.config, OpUpdateOne, withAccountID(id))
return &AccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Account.
func (c *AccountClient) Delete() *AccountDelete {
mutation := newAccountMutation(c.config, OpDelete)
return &AccountDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *AccountClient) DeleteOne(a *Account) *AccountDeleteOne {
return c.DeleteOneID(a.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *AccountClient) DeleteOneID(id uuid.UUID) *AccountDeleteOne {
builder := c.Delete().Where(account.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &AccountDeleteOne{builder}
}
// Query returns a query builder for Account.
func (c *AccountClient) Query() *AccountQuery {
return &AccountQuery{
config: c.config,
ctx: &QueryContext{Type: TypeAccount},
inters: c.Interceptors(),
}
}
// Get returns a Account entity by its id.
func (c *AccountClient) Get(ctx context.Context, id uuid.UUID) (*Account, error) {
return c.Query().Where(account.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *AccountClient) GetX(ctx context.Context, id uuid.UUID) *Account {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryEmails queries the emails edge of a Account.
func (c *AccountClient) QueryEmails(a *Account) *EmailQuery {
query := (&EmailClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := a.ID
step := sqlgraph.NewStep(
sqlgraph.From(account.Table, account.FieldID, id),
sqlgraph.To(email.Table, email.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, account.EmailsTable, account.EmailsColumn),
)
fromV = sqlgraph.Neighbors(a.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *AccountClient) Hooks() []Hook {
return c.hooks.Account
}
// Interceptors returns the client interceptors.
func (c *AccountClient) Interceptors() []Interceptor {
return c.inters.Account
}
func (c *AccountClient) mutate(ctx context.Context, m *AccountMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&AccountCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&AccountUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&AccountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&AccountDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Account mutation op: %q", m.Op())
}
}
// EmailClient is a client for the Email schema.
type EmailClient struct {
config
}
// NewEmailClient returns a client for the Email from the given config.
func NewEmailClient(c config) *EmailClient {
return &EmailClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `email.Hooks(f(g(h())))`.
func (c *EmailClient) Use(hooks ...Hook) {
c.hooks.Email = append(c.hooks.Email, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `email.Intercept(f(g(h())))`.
func (c *EmailClient) Intercept(interceptors ...Interceptor) {
c.inters.Email = append(c.inters.Email, interceptors...)
}
// Create returns a builder for creating a Email entity.
func (c *EmailClient) Create() *EmailCreate {
mutation := newEmailMutation(c.config, OpCreate)
return &EmailCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Email entities.
func (c *EmailClient) CreateBulk(builders ...*EmailCreate) *EmailCreateBulk {
return &EmailCreateBulk{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 *EmailClient) MapCreateBulk(slice any, setFunc func(*EmailCreate, int)) *EmailCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &EmailCreateBulk{err: fmt.Errorf("calling to EmailClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*EmailCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &EmailCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Email.
func (c *EmailClient) Update() *EmailUpdate {
mutation := newEmailMutation(c.config, OpUpdate)
return &EmailUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *EmailClient) UpdateOne(e *Email) *EmailUpdateOne {
mutation := newEmailMutation(c.config, OpUpdateOne, withEmail(e))
return &EmailUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *EmailClient) UpdateOneID(id uuid.UUID) *EmailUpdateOne {
mutation := newEmailMutation(c.config, OpUpdateOne, withEmailID(id))
return &EmailUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Email.
func (c *EmailClient) Delete() *EmailDelete {
mutation := newEmailMutation(c.config, OpDelete)
return &EmailDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *EmailClient) DeleteOne(e *Email) *EmailDeleteOne {
return c.DeleteOneID(e.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *EmailClient) DeleteOneID(id uuid.UUID) *EmailDeleteOne {
builder := c.Delete().Where(email.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &EmailDeleteOne{builder}
}
// Query returns a query builder for Email.
func (c *EmailClient) Query() *EmailQuery {
return &EmailQuery{
config: c.config,
ctx: &QueryContext{Type: TypeEmail},
inters: c.Interceptors(),
}
}
// Get returns a Email entity by its id.
func (c *EmailClient) Get(ctx context.Context, id uuid.UUID) (*Email, error) {
return c.Query().Where(email.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *EmailClient) GetX(ctx context.Context, id uuid.UUID) *Email {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryAccounts queries the accounts edge of a Email.
func (c *EmailClient) QueryAccounts(e *Email) *AccountQuery {
query := (&AccountClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := e.ID
step := sqlgraph.NewStep(
sqlgraph.From(email.Table, email.FieldID, id),
sqlgraph.To(account.Table, account.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, email.AccountsTable, email.AccountsColumn),
)
fromV = sqlgraph.Neighbors(e.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *EmailClient) Hooks() []Hook {
return c.hooks.Email
}
// Interceptors returns the client interceptors.
func (c *EmailClient) Interceptors() []Interceptor {
return c.inters.Email
}
func (c *EmailClient) mutate(ctx context.Context, m *EmailMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&EmailCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&EmailUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&EmailUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&EmailDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Email mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Account, Email []ent.Hook
}
inters struct {
Account, Email []ent.Interceptor
}
)

189
ent/email.go Normal file
View File

@ -0,0 +1,189 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"code.icod.de/auth/accountserver/ent/account"
"code.icod.de/auth/accountserver/ent/email"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/google/uuid"
)
// Email is the model entity for the Email schema.
type Email struct {
config `json:"-"`
// ID of the ent.
ID uuid.UUID `json:"id,omitempty"`
// Email holds the value of the "email" field.
Email string `json:"email,omitempty"`
// Primary holds the value of the "primary" field.
Primary bool `json:"primary,omitempty"`
// Verified holds the value of the "verified" field.
Verified bool `json:"verified,omitempty"`
// VerificationCode holds the value of the "verification_code" field.
VerificationCode string `json:"verification_code,omitempty"`
// ResetCode holds the value of the "reset_code" field.
ResetCode string `json:"reset_code,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the EmailQuery when eager-loading is set.
Edges EmailEdges `json:"edges"`
account_emails *uuid.UUID
selectValues sql.SelectValues
}
// EmailEdges holds the relations/edges for other nodes in the graph.
type EmailEdges struct {
// Accounts holds the value of the accounts edge.
Accounts *Account `json:"accounts,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// AccountsOrErr returns the Accounts value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e EmailEdges) AccountsOrErr() (*Account, error) {
if e.Accounts != nil {
return e.Accounts, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: account.Label}
}
return nil, &NotLoadedError{edge: "accounts"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Email) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case email.FieldPrimary, email.FieldVerified:
values[i] = new(sql.NullBool)
case email.FieldEmail, email.FieldVerificationCode, email.FieldResetCode:
values[i] = new(sql.NullString)
case email.FieldID:
values[i] = new(uuid.UUID)
case email.ForeignKeys[0]: // account_emails
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Email fields.
func (e *Email) 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 email.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
e.ID = *value
}
case email.FieldEmail:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field email", values[i])
} else if value.Valid {
e.Email = value.String
}
case email.FieldPrimary:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field primary", values[i])
} else if value.Valid {
e.Primary = value.Bool
}
case email.FieldVerified:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field verified", values[i])
} else if value.Valid {
e.Verified = value.Bool
}
case email.FieldVerificationCode:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field verification_code", values[i])
} else if value.Valid {
e.VerificationCode = value.String
}
case email.FieldResetCode:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field reset_code", values[i])
} else if value.Valid {
e.ResetCode = value.String
}
case email.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field account_emails", values[i])
} else if value.Valid {
e.account_emails = new(uuid.UUID)
*e.account_emails = *value.S.(*uuid.UUID)
}
default:
e.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Email.
// This includes values selected through modifiers, order, etc.
func (e *Email) Value(name string) (ent.Value, error) {
return e.selectValues.Get(name)
}
// QueryAccounts queries the "accounts" edge of the Email entity.
func (e *Email) QueryAccounts() *AccountQuery {
return NewEmailClient(e.config).QueryAccounts(e)
}
// Update returns a builder for updating this Email.
// Note that you need to call Email.Unwrap() before calling this method if this Email
// was returned from a transaction, and the transaction was committed or rolled back.
func (e *Email) Update() *EmailUpdateOne {
return NewEmailClient(e.config).UpdateOne(e)
}
// Unwrap unwraps the Email 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 (e *Email) Unwrap() *Email {
_tx, ok := e.config.driver.(*txDriver)
if !ok {
panic("ent: Email is not a transactional entity")
}
e.config.driver = _tx.drv
return e
}
// String implements the fmt.Stringer.
func (e *Email) String() string {
var builder strings.Builder
builder.WriteString("Email(")
builder.WriteString(fmt.Sprintf("id=%v, ", e.ID))
builder.WriteString("email=")
builder.WriteString(e.Email)
builder.WriteString(", ")
builder.WriteString("primary=")
builder.WriteString(fmt.Sprintf("%v", e.Primary))
builder.WriteString(", ")
builder.WriteString("verified=")
builder.WriteString(fmt.Sprintf("%v", e.Verified))
builder.WriteString(", ")
builder.WriteString("verification_code=")
builder.WriteString(e.VerificationCode)
builder.WriteString(", ")
builder.WriteString("reset_code=")
builder.WriteString(e.ResetCode)
builder.WriteByte(')')
return builder.String()
}
// Emails is a parsable slice of Email.
type Emails []*Email

121
ent/email/email.go Normal file
View File

@ -0,0 +1,121 @@
// Code generated by ent, DO NOT EDIT.
package email
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the email type in the database.
Label = "email"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldEmail holds the string denoting the email field in the database.
FieldEmail = "email"
// FieldPrimary holds the string denoting the primary field in the database.
FieldPrimary = "primary"
// FieldVerified holds the string denoting the verified field in the database.
FieldVerified = "verified"
// FieldVerificationCode holds the string denoting the verification_code field in the database.
FieldVerificationCode = "verification_code"
// FieldResetCode holds the string denoting the reset_code field in the database.
FieldResetCode = "reset_code"
// EdgeAccounts holds the string denoting the accounts edge name in mutations.
EdgeAccounts = "accounts"
// Table holds the table name of the email in the database.
Table = "emails"
// AccountsTable is the table that holds the accounts relation/edge.
AccountsTable = "emails"
// AccountsInverseTable is the table name for the Account entity.
// It exists in this package in order to avoid circular dependency with the "account" package.
AccountsInverseTable = "accounts"
// AccountsColumn is the table column denoting the accounts relation/edge.
AccountsColumn = "account_emails"
)
// Columns holds all SQL columns for email fields.
var Columns = []string{
FieldID,
FieldEmail,
FieldPrimary,
FieldVerified,
FieldVerificationCode,
FieldResetCode,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "emails"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"account_emails",
}
// 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 (
// DefaultPrimary holds the default value on creation for the "primary" field.
DefaultPrimary bool
// DefaultVerified holds the default value on creation for the "verified" field.
DefaultVerified bool
)
// OrderOption defines the ordering options for the Email 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()
}
// ByEmail orders the results by the email field.
func ByEmail(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldEmail, opts...).ToFunc()
}
// ByPrimary orders the results by the primary field.
func ByPrimary(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPrimary, opts...).ToFunc()
}
// ByVerified orders the results by the verified field.
func ByVerified(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldVerified, opts...).ToFunc()
}
// ByVerificationCode orders the results by the verification_code field.
func ByVerificationCode(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldVerificationCode, opts...).ToFunc()
}
// ByResetCode orders the results by the reset_code field.
func ByResetCode(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldResetCode, opts...).ToFunc()
}
// ByAccountsField orders the results by accounts field.
func ByAccountsField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newAccountsStep(), sql.OrderByField(field, opts...))
}
}
func newAccountsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(AccountsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, AccountsTable, AccountsColumn),
)
}

353
ent/email/where.go Normal file
View File

@ -0,0 +1,353 @@
// Code generated by ent, DO NOT EDIT.
package email
import (
"code.icod.de/auth/accountserver/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/google/uuid"
)
// ID filters vertices based on their ID field.
func ID(id uuid.UUID) predicate.Email {
return predicate.Email(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id uuid.UUID) predicate.Email {
return predicate.Email(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id uuid.UUID) predicate.Email {
return predicate.Email(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...uuid.UUID) predicate.Email {
return predicate.Email(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...uuid.UUID) predicate.Email {
return predicate.Email(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id uuid.UUID) predicate.Email {
return predicate.Email(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id uuid.UUID) predicate.Email {
return predicate.Email(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id uuid.UUID) predicate.Email {
return predicate.Email(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id uuid.UUID) predicate.Email {
return predicate.Email(sql.FieldLTE(FieldID, id))
}
// Email applies equality check predicate on the "email" field. It's identical to EmailEQ.
func Email(v string) predicate.Email {
return predicate.Email(sql.FieldEQ(FieldEmail, v))
}
// Primary applies equality check predicate on the "primary" field. It's identical to PrimaryEQ.
func Primary(v bool) predicate.Email {
return predicate.Email(sql.FieldEQ(FieldPrimary, v))
}
// Verified applies equality check predicate on the "verified" field. It's identical to VerifiedEQ.
func Verified(v bool) predicate.Email {
return predicate.Email(sql.FieldEQ(FieldVerified, v))
}
// VerificationCode applies equality check predicate on the "verification_code" field. It's identical to VerificationCodeEQ.
func VerificationCode(v string) predicate.Email {
return predicate.Email(sql.FieldEQ(FieldVerificationCode, v))
}
// ResetCode applies equality check predicate on the "reset_code" field. It's identical to ResetCodeEQ.
func ResetCode(v string) predicate.Email {
return predicate.Email(sql.FieldEQ(FieldResetCode, v))
}
// EmailEQ applies the EQ predicate on the "email" field.
func EmailEQ(v string) predicate.Email {
return predicate.Email(sql.FieldEQ(FieldEmail, v))
}
// EmailNEQ applies the NEQ predicate on the "email" field.
func EmailNEQ(v string) predicate.Email {
return predicate.Email(sql.FieldNEQ(FieldEmail, v))
}
// EmailIn applies the In predicate on the "email" field.
func EmailIn(vs ...string) predicate.Email {
return predicate.Email(sql.FieldIn(FieldEmail, vs...))
}
// EmailNotIn applies the NotIn predicate on the "email" field.
func EmailNotIn(vs ...string) predicate.Email {
return predicate.Email(sql.FieldNotIn(FieldEmail, vs...))
}
// EmailGT applies the GT predicate on the "email" field.
func EmailGT(v string) predicate.Email {
return predicate.Email(sql.FieldGT(FieldEmail, v))
}
// EmailGTE applies the GTE predicate on the "email" field.
func EmailGTE(v string) predicate.Email {
return predicate.Email(sql.FieldGTE(FieldEmail, v))
}
// EmailLT applies the LT predicate on the "email" field.
func EmailLT(v string) predicate.Email {
return predicate.Email(sql.FieldLT(FieldEmail, v))
}
// EmailLTE applies the LTE predicate on the "email" field.
func EmailLTE(v string) predicate.Email {
return predicate.Email(sql.FieldLTE(FieldEmail, v))
}
// EmailContains applies the Contains predicate on the "email" field.
func EmailContains(v string) predicate.Email {
return predicate.Email(sql.FieldContains(FieldEmail, v))
}
// EmailHasPrefix applies the HasPrefix predicate on the "email" field.
func EmailHasPrefix(v string) predicate.Email {
return predicate.Email(sql.FieldHasPrefix(FieldEmail, v))
}
// EmailHasSuffix applies the HasSuffix predicate on the "email" field.
func EmailHasSuffix(v string) predicate.Email {
return predicate.Email(sql.FieldHasSuffix(FieldEmail, v))
}
// EmailEqualFold applies the EqualFold predicate on the "email" field.
func EmailEqualFold(v string) predicate.Email {
return predicate.Email(sql.FieldEqualFold(FieldEmail, v))
}
// EmailContainsFold applies the ContainsFold predicate on the "email" field.
func EmailContainsFold(v string) predicate.Email {
return predicate.Email(sql.FieldContainsFold(FieldEmail, v))
}
// PrimaryEQ applies the EQ predicate on the "primary" field.
func PrimaryEQ(v bool) predicate.Email {
return predicate.Email(sql.FieldEQ(FieldPrimary, v))
}
// PrimaryNEQ applies the NEQ predicate on the "primary" field.
func PrimaryNEQ(v bool) predicate.Email {
return predicate.Email(sql.FieldNEQ(FieldPrimary, v))
}
// VerifiedEQ applies the EQ predicate on the "verified" field.
func VerifiedEQ(v bool) predicate.Email {
return predicate.Email(sql.FieldEQ(FieldVerified, v))
}
// VerifiedNEQ applies the NEQ predicate on the "verified" field.
func VerifiedNEQ(v bool) predicate.Email {
return predicate.Email(sql.FieldNEQ(FieldVerified, v))
}
// VerificationCodeEQ applies the EQ predicate on the "verification_code" field.
func VerificationCodeEQ(v string) predicate.Email {
return predicate.Email(sql.FieldEQ(FieldVerificationCode, v))
}
// VerificationCodeNEQ applies the NEQ predicate on the "verification_code" field.
func VerificationCodeNEQ(v string) predicate.Email {
return predicate.Email(sql.FieldNEQ(FieldVerificationCode, v))
}
// VerificationCodeIn applies the In predicate on the "verification_code" field.
func VerificationCodeIn(vs ...string) predicate.Email {
return predicate.Email(sql.FieldIn(FieldVerificationCode, vs...))
}
// VerificationCodeNotIn applies the NotIn predicate on the "verification_code" field.
func VerificationCodeNotIn(vs ...string) predicate.Email {
return predicate.Email(sql.FieldNotIn(FieldVerificationCode, vs...))
}
// VerificationCodeGT applies the GT predicate on the "verification_code" field.
func VerificationCodeGT(v string) predicate.Email {
return predicate.Email(sql.FieldGT(FieldVerificationCode, v))
}
// VerificationCodeGTE applies the GTE predicate on the "verification_code" field.
func VerificationCodeGTE(v string) predicate.Email {
return predicate.Email(sql.FieldGTE(FieldVerificationCode, v))
}
// VerificationCodeLT applies the LT predicate on the "verification_code" field.
func VerificationCodeLT(v string) predicate.Email {
return predicate.Email(sql.FieldLT(FieldVerificationCode, v))
}
// VerificationCodeLTE applies the LTE predicate on the "verification_code" field.
func VerificationCodeLTE(v string) predicate.Email {
return predicate.Email(sql.FieldLTE(FieldVerificationCode, v))
}
// VerificationCodeContains applies the Contains predicate on the "verification_code" field.
func VerificationCodeContains(v string) predicate.Email {
return predicate.Email(sql.FieldContains(FieldVerificationCode, v))
}
// VerificationCodeHasPrefix applies the HasPrefix predicate on the "verification_code" field.
func VerificationCodeHasPrefix(v string) predicate.Email {
return predicate.Email(sql.FieldHasPrefix(FieldVerificationCode, v))
}
// VerificationCodeHasSuffix applies the HasSuffix predicate on the "verification_code" field.
func VerificationCodeHasSuffix(v string) predicate.Email {
return predicate.Email(sql.FieldHasSuffix(FieldVerificationCode, v))
}
// VerificationCodeIsNil applies the IsNil predicate on the "verification_code" field.
func VerificationCodeIsNil() predicate.Email {
return predicate.Email(sql.FieldIsNull(FieldVerificationCode))
}
// VerificationCodeNotNil applies the NotNil predicate on the "verification_code" field.
func VerificationCodeNotNil() predicate.Email {
return predicate.Email(sql.FieldNotNull(FieldVerificationCode))
}
// VerificationCodeEqualFold applies the EqualFold predicate on the "verification_code" field.
func VerificationCodeEqualFold(v string) predicate.Email {
return predicate.Email(sql.FieldEqualFold(FieldVerificationCode, v))
}
// VerificationCodeContainsFold applies the ContainsFold predicate on the "verification_code" field.
func VerificationCodeContainsFold(v string) predicate.Email {
return predicate.Email(sql.FieldContainsFold(FieldVerificationCode, v))
}
// ResetCodeEQ applies the EQ predicate on the "reset_code" field.
func ResetCodeEQ(v string) predicate.Email {
return predicate.Email(sql.FieldEQ(FieldResetCode, v))
}
// ResetCodeNEQ applies the NEQ predicate on the "reset_code" field.
func ResetCodeNEQ(v string) predicate.Email {
return predicate.Email(sql.FieldNEQ(FieldResetCode, v))
}
// ResetCodeIn applies the In predicate on the "reset_code" field.
func ResetCodeIn(vs ...string) predicate.Email {
return predicate.Email(sql.FieldIn(FieldResetCode, vs...))
}
// ResetCodeNotIn applies the NotIn predicate on the "reset_code" field.
func ResetCodeNotIn(vs ...string) predicate.Email {
return predicate.Email(sql.FieldNotIn(FieldResetCode, vs...))
}
// ResetCodeGT applies the GT predicate on the "reset_code" field.
func ResetCodeGT(v string) predicate.Email {
return predicate.Email(sql.FieldGT(FieldResetCode, v))
}
// ResetCodeGTE applies the GTE predicate on the "reset_code" field.
func ResetCodeGTE(v string) predicate.Email {
return predicate.Email(sql.FieldGTE(FieldResetCode, v))
}
// ResetCodeLT applies the LT predicate on the "reset_code" field.
func ResetCodeLT(v string) predicate.Email {
return predicate.Email(sql.FieldLT(FieldResetCode, v))
}
// ResetCodeLTE applies the LTE predicate on the "reset_code" field.
func ResetCodeLTE(v string) predicate.Email {
return predicate.Email(sql.FieldLTE(FieldResetCode, v))
}
// ResetCodeContains applies the Contains predicate on the "reset_code" field.
func ResetCodeContains(v string) predicate.Email {
return predicate.Email(sql.FieldContains(FieldResetCode, v))
}
// ResetCodeHasPrefix applies the HasPrefix predicate on the "reset_code" field.
func ResetCodeHasPrefix(v string) predicate.Email {
return predicate.Email(sql.FieldHasPrefix(FieldResetCode, v))
}
// ResetCodeHasSuffix applies the HasSuffix predicate on the "reset_code" field.
func ResetCodeHasSuffix(v string) predicate.Email {
return predicate.Email(sql.FieldHasSuffix(FieldResetCode, v))
}
// ResetCodeIsNil applies the IsNil predicate on the "reset_code" field.
func ResetCodeIsNil() predicate.Email {
return predicate.Email(sql.FieldIsNull(FieldResetCode))
}
// ResetCodeNotNil applies the NotNil predicate on the "reset_code" field.
func ResetCodeNotNil() predicate.Email {
return predicate.Email(sql.FieldNotNull(FieldResetCode))
}
// ResetCodeEqualFold applies the EqualFold predicate on the "reset_code" field.
func ResetCodeEqualFold(v string) predicate.Email {
return predicate.Email(sql.FieldEqualFold(FieldResetCode, v))
}
// ResetCodeContainsFold applies the ContainsFold predicate on the "reset_code" field.
func ResetCodeContainsFold(v string) predicate.Email {
return predicate.Email(sql.FieldContainsFold(FieldResetCode, v))
}
// HasAccounts applies the HasEdge predicate on the "accounts" edge.
func HasAccounts() predicate.Email {
return predicate.Email(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, AccountsTable, AccountsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasAccountsWith applies the HasEdge predicate on the "accounts" edge with a given conditions (other predicates).
func HasAccountsWith(preds ...predicate.Account) predicate.Email {
return predicate.Email(func(s *sql.Selector) {
step := newAccountsStep()
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.Email) predicate.Email {
return predicate.Email(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Email) predicate.Email {
return predicate.Email(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Email) predicate.Email {
return predicate.Email(sql.NotPredicates(p))
}

324
ent/email_create.go Normal file
View File

@ -0,0 +1,324 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"code.icod.de/auth/accountserver/ent/account"
"code.icod.de/auth/accountserver/ent/email"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
)
// EmailCreate is the builder for creating a Email entity.
type EmailCreate struct {
config
mutation *EmailMutation
hooks []Hook
}
// SetEmail sets the "email" field.
func (ec *EmailCreate) SetEmail(s string) *EmailCreate {
ec.mutation.SetEmail(s)
return ec
}
// SetPrimary sets the "primary" field.
func (ec *EmailCreate) SetPrimary(b bool) *EmailCreate {
ec.mutation.SetPrimary(b)
return ec
}
// SetNillablePrimary sets the "primary" field if the given value is not nil.
func (ec *EmailCreate) SetNillablePrimary(b *bool) *EmailCreate {
if b != nil {
ec.SetPrimary(*b)
}
return ec
}
// SetVerified sets the "verified" field.
func (ec *EmailCreate) SetVerified(b bool) *EmailCreate {
ec.mutation.SetVerified(b)
return ec
}
// SetNillableVerified sets the "verified" field if the given value is not nil.
func (ec *EmailCreate) SetNillableVerified(b *bool) *EmailCreate {
if b != nil {
ec.SetVerified(*b)
}
return ec
}
// SetVerificationCode sets the "verification_code" field.
func (ec *EmailCreate) SetVerificationCode(s string) *EmailCreate {
ec.mutation.SetVerificationCode(s)
return ec
}
// SetNillableVerificationCode sets the "verification_code" field if the given value is not nil.
func (ec *EmailCreate) SetNillableVerificationCode(s *string) *EmailCreate {
if s != nil {
ec.SetVerificationCode(*s)
}
return ec
}
// SetResetCode sets the "reset_code" field.
func (ec *EmailCreate) SetResetCode(s string) *EmailCreate {
ec.mutation.SetResetCode(s)
return ec
}
// SetNillableResetCode sets the "reset_code" field if the given value is not nil.
func (ec *EmailCreate) SetNillableResetCode(s *string) *EmailCreate {
if s != nil {
ec.SetResetCode(*s)
}
return ec
}
// SetID sets the "id" field.
func (ec *EmailCreate) SetID(u uuid.UUID) *EmailCreate {
ec.mutation.SetID(u)
return ec
}
// SetAccountsID sets the "accounts" edge to the Account entity by ID.
func (ec *EmailCreate) SetAccountsID(id uuid.UUID) *EmailCreate {
ec.mutation.SetAccountsID(id)
return ec
}
// SetNillableAccountsID sets the "accounts" edge to the Account entity by ID if the given value is not nil.
func (ec *EmailCreate) SetNillableAccountsID(id *uuid.UUID) *EmailCreate {
if id != nil {
ec = ec.SetAccountsID(*id)
}
return ec
}
// SetAccounts sets the "accounts" edge to the Account entity.
func (ec *EmailCreate) SetAccounts(a *Account) *EmailCreate {
return ec.SetAccountsID(a.ID)
}
// Mutation returns the EmailMutation object of the builder.
func (ec *EmailCreate) Mutation() *EmailMutation {
return ec.mutation
}
// Save creates the Email in the database.
func (ec *EmailCreate) Save(ctx context.Context) (*Email, error) {
ec.defaults()
return withHooks(ctx, ec.sqlSave, ec.mutation, ec.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (ec *EmailCreate) SaveX(ctx context.Context) *Email {
v, err := ec.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ec *EmailCreate) Exec(ctx context.Context) error {
_, err := ec.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ec *EmailCreate) ExecX(ctx context.Context) {
if err := ec.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (ec *EmailCreate) defaults() {
if _, ok := ec.mutation.Primary(); !ok {
v := email.DefaultPrimary
ec.mutation.SetPrimary(v)
}
if _, ok := ec.mutation.Verified(); !ok {
v := email.DefaultVerified
ec.mutation.SetVerified(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (ec *EmailCreate) check() error {
if _, ok := ec.mutation.Email(); !ok {
return &ValidationError{Name: "email", err: errors.New(`ent: missing required field "Email.email"`)}
}
if _, ok := ec.mutation.Primary(); !ok {
return &ValidationError{Name: "primary", err: errors.New(`ent: missing required field "Email.primary"`)}
}
if _, ok := ec.mutation.Verified(); !ok {
return &ValidationError{Name: "verified", err: errors.New(`ent: missing required field "Email.verified"`)}
}
return nil
}
func (ec *EmailCreate) sqlSave(ctx context.Context) (*Email, error) {
if err := ec.check(); err != nil {
return nil, err
}
_node, _spec := ec.createSpec()
if err := sqlgraph.CreateNode(ctx, ec.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
if _spec.ID.Value != nil {
if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
_node.ID = *id
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
return nil, err
}
}
ec.mutation.id = &_node.ID
ec.mutation.done = true
return _node, nil
}
func (ec *EmailCreate) createSpec() (*Email, *sqlgraph.CreateSpec) {
var (
_node = &Email{config: ec.config}
_spec = sqlgraph.NewCreateSpec(email.Table, sqlgraph.NewFieldSpec(email.FieldID, field.TypeUUID))
)
if id, ok := ec.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := ec.mutation.Email(); ok {
_spec.SetField(email.FieldEmail, field.TypeString, value)
_node.Email = value
}
if value, ok := ec.mutation.Primary(); ok {
_spec.SetField(email.FieldPrimary, field.TypeBool, value)
_node.Primary = value
}
if value, ok := ec.mutation.Verified(); ok {
_spec.SetField(email.FieldVerified, field.TypeBool, value)
_node.Verified = value
}
if value, ok := ec.mutation.VerificationCode(); ok {
_spec.SetField(email.FieldVerificationCode, field.TypeString, value)
_node.VerificationCode = value
}
if value, ok := ec.mutation.ResetCode(); ok {
_spec.SetField(email.FieldResetCode, field.TypeString, value)
_node.ResetCode = value
}
if nodes := ec.mutation.AccountsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: email.AccountsTable,
Columns: []string{email.AccountsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.account_emails = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// EmailCreateBulk is the builder for creating many Email entities in bulk.
type EmailCreateBulk struct {
config
err error
builders []*EmailCreate
}
// Save creates the Email entities in the database.
func (ecb *EmailCreateBulk) Save(ctx context.Context) ([]*Email, error) {
if ecb.err != nil {
return nil, ecb.err
}
specs := make([]*sqlgraph.CreateSpec, len(ecb.builders))
nodes := make([]*Email, len(ecb.builders))
mutators := make([]Mutator, len(ecb.builders))
for i := range ecb.builders {
func(i int, root context.Context) {
builder := ecb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*EmailMutation)
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, ecb.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, ecb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, ecb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (ecb *EmailCreateBulk) SaveX(ctx context.Context) []*Email {
v, err := ecb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ecb *EmailCreateBulk) Exec(ctx context.Context) error {
_, err := ecb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ecb *EmailCreateBulk) ExecX(ctx context.Context) {
if err := ecb.Exec(ctx); err != nil {
panic(err)
}
}

88
ent/email_delete.go Normal file
View File

@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"code.icod.de/auth/accountserver/ent/email"
"code.icod.de/auth/accountserver/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// EmailDelete is the builder for deleting a Email entity.
type EmailDelete struct {
config
hooks []Hook
mutation *EmailMutation
}
// Where appends a list predicates to the EmailDelete builder.
func (ed *EmailDelete) Where(ps ...predicate.Email) *EmailDelete {
ed.mutation.Where(ps...)
return ed
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (ed *EmailDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, ed.sqlExec, ed.mutation, ed.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (ed *EmailDelete) ExecX(ctx context.Context) int {
n, err := ed.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (ed *EmailDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(email.Table, sqlgraph.NewFieldSpec(email.FieldID, field.TypeUUID))
if ps := ed.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, ed.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
ed.mutation.done = true
return affected, err
}
// EmailDeleteOne is the builder for deleting a single Email entity.
type EmailDeleteOne struct {
ed *EmailDelete
}
// Where appends a list predicates to the EmailDelete builder.
func (edo *EmailDeleteOne) Where(ps ...predicate.Email) *EmailDeleteOne {
edo.ed.mutation.Where(ps...)
return edo
}
// Exec executes the deletion query.
func (edo *EmailDeleteOne) Exec(ctx context.Context) error {
n, err := edo.ed.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{email.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (edo *EmailDeleteOne) ExecX(ctx context.Context) {
if err := edo.Exec(ctx); err != nil {
panic(err)
}
}

615
ent/email_query.go Normal file
View File

@ -0,0 +1,615 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"code.icod.de/auth/accountserver/ent/account"
"code.icod.de/auth/accountserver/ent/email"
"code.icod.de/auth/accountserver/ent/predicate"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
)
// EmailQuery is the builder for querying Email entities.
type EmailQuery struct {
config
ctx *QueryContext
order []email.OrderOption
inters []Interceptor
predicates []predicate.Email
withAccounts *AccountQuery
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 EmailQuery builder.
func (eq *EmailQuery) Where(ps ...predicate.Email) *EmailQuery {
eq.predicates = append(eq.predicates, ps...)
return eq
}
// Limit the number of records to be returned by this query.
func (eq *EmailQuery) Limit(limit int) *EmailQuery {
eq.ctx.Limit = &limit
return eq
}
// Offset to start from.
func (eq *EmailQuery) Offset(offset int) *EmailQuery {
eq.ctx.Offset = &offset
return eq
}
// 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 (eq *EmailQuery) Unique(unique bool) *EmailQuery {
eq.ctx.Unique = &unique
return eq
}
// Order specifies how the records should be ordered.
func (eq *EmailQuery) Order(o ...email.OrderOption) *EmailQuery {
eq.order = append(eq.order, o...)
return eq
}
// QueryAccounts chains the current query on the "accounts" edge.
func (eq *EmailQuery) QueryAccounts() *AccountQuery {
query := (&AccountClient{config: eq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := eq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := eq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(email.Table, email.FieldID, selector),
sqlgraph.To(account.Table, account.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, email.AccountsTable, email.AccountsColumn),
)
fromU = sqlgraph.SetNeighbors(eq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Email entity from the query.
// Returns a *NotFoundError when no Email was found.
func (eq *EmailQuery) First(ctx context.Context) (*Email, error) {
nodes, err := eq.Limit(1).All(setContextOp(ctx, eq.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{email.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (eq *EmailQuery) FirstX(ctx context.Context) *Email {
node, err := eq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Email ID from the query.
// Returns a *NotFoundError when no Email ID was found.
func (eq *EmailQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = eq.Limit(1).IDs(setContextOp(ctx, eq.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{email.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (eq *EmailQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := eq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Email entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Email entity is found.
// Returns a *NotFoundError when no Email entities are found.
func (eq *EmailQuery) Only(ctx context.Context) (*Email, error) {
nodes, err := eq.Limit(2).All(setContextOp(ctx, eq.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{email.Label}
default:
return nil, &NotSingularError{email.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (eq *EmailQuery) OnlyX(ctx context.Context) *Email {
node, err := eq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Email ID in the query.
// Returns a *NotSingularError when more than one Email ID is found.
// Returns a *NotFoundError when no entities are found.
func (eq *EmailQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = eq.Limit(2).IDs(setContextOp(ctx, eq.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{email.Label}
default:
err = &NotSingularError{email.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (eq *EmailQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := eq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Emails.
func (eq *EmailQuery) All(ctx context.Context) ([]*Email, error) {
ctx = setContextOp(ctx, eq.ctx, ent.OpQueryAll)
if err := eq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Email, *EmailQuery]()
return withInterceptors[[]*Email](ctx, eq, qr, eq.inters)
}
// AllX is like All, but panics if an error occurs.
func (eq *EmailQuery) AllX(ctx context.Context) []*Email {
nodes, err := eq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Email IDs.
func (eq *EmailQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
if eq.ctx.Unique == nil && eq.path != nil {
eq.Unique(true)
}
ctx = setContextOp(ctx, eq.ctx, ent.OpQueryIDs)
if err = eq.Select(email.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (eq *EmailQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := eq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (eq *EmailQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, eq.ctx, ent.OpQueryCount)
if err := eq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, eq, querierCount[*EmailQuery](), eq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (eq *EmailQuery) CountX(ctx context.Context) int {
count, err := eq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (eq *EmailQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, eq.ctx, ent.OpQueryExist)
switch _, err := eq.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 (eq *EmailQuery) ExistX(ctx context.Context) bool {
exist, err := eq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the EmailQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (eq *EmailQuery) Clone() *EmailQuery {
if eq == nil {
return nil
}
return &EmailQuery{
config: eq.config,
ctx: eq.ctx.Clone(),
order: append([]email.OrderOption{}, eq.order...),
inters: append([]Interceptor{}, eq.inters...),
predicates: append([]predicate.Email{}, eq.predicates...),
withAccounts: eq.withAccounts.Clone(),
// clone intermediate query.
sql: eq.sql.Clone(),
path: eq.path,
}
}
// WithAccounts tells the query-builder to eager-load the nodes that are connected to
// the "accounts" edge. The optional arguments are used to configure the query builder of the edge.
func (eq *EmailQuery) WithAccounts(opts ...func(*AccountQuery)) *EmailQuery {
query := (&AccountClient{config: eq.config}).Query()
for _, opt := range opts {
opt(query)
}
eq.withAccounts = query
return eq
}
// 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 {
// Email string `json:"email,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Email.Query().
// GroupBy(email.FieldEmail).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (eq *EmailQuery) GroupBy(field string, fields ...string) *EmailGroupBy {
eq.ctx.Fields = append([]string{field}, fields...)
grbuild := &EmailGroupBy{build: eq}
grbuild.flds = &eq.ctx.Fields
grbuild.label = email.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 {
// Email string `json:"email,omitempty"`
// }
//
// client.Email.Query().
// Select(email.FieldEmail).
// Scan(ctx, &v)
func (eq *EmailQuery) Select(fields ...string) *EmailSelect {
eq.ctx.Fields = append(eq.ctx.Fields, fields...)
sbuild := &EmailSelect{EmailQuery: eq}
sbuild.label = email.Label
sbuild.flds, sbuild.scan = &eq.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a EmailSelect configured with the given aggregations.
func (eq *EmailQuery) Aggregate(fns ...AggregateFunc) *EmailSelect {
return eq.Select().Aggregate(fns...)
}
func (eq *EmailQuery) prepareQuery(ctx context.Context) error {
for _, inter := range eq.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, eq); err != nil {
return err
}
}
}
for _, f := range eq.ctx.Fields {
if !email.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if eq.path != nil {
prev, err := eq.path(ctx)
if err != nil {
return err
}
eq.sql = prev
}
return nil
}
func (eq *EmailQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Email, error) {
var (
nodes = []*Email{}
withFKs = eq.withFKs
_spec = eq.querySpec()
loadedTypes = [1]bool{
eq.withAccounts != nil,
}
)
if eq.withAccounts != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, email.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Email).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Email{config: eq.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, eq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := eq.withAccounts; query != nil {
if err := eq.loadAccounts(ctx, query, nodes, nil,
func(n *Email, e *Account) { n.Edges.Accounts = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (eq *EmailQuery) loadAccounts(ctx context.Context, query *AccountQuery, nodes []*Email, init func(*Email), assign func(*Email, *Account)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Email)
for i := range nodes {
if nodes[i].account_emails == nil {
continue
}
fk := *nodes[i].account_emails
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(account.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 "account_emails" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (eq *EmailQuery) sqlCount(ctx context.Context) (int, error) {
_spec := eq.querySpec()
_spec.Node.Columns = eq.ctx.Fields
if len(eq.ctx.Fields) > 0 {
_spec.Unique = eq.ctx.Unique != nil && *eq.ctx.Unique
}
return sqlgraph.CountNodes(ctx, eq.driver, _spec)
}
func (eq *EmailQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(email.Table, email.Columns, sqlgraph.NewFieldSpec(email.FieldID, field.TypeUUID))
_spec.From = eq.sql
if unique := eq.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if eq.path != nil {
_spec.Unique = true
}
if fields := eq.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, email.FieldID)
for i := range fields {
if fields[i] != email.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := eq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := eq.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := eq.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := eq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (eq *EmailQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(eq.driver.Dialect())
t1 := builder.Table(email.Table)
columns := eq.ctx.Fields
if len(columns) == 0 {
columns = email.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if eq.sql != nil {
selector = eq.sql
selector.Select(selector.Columns(columns...)...)
}
if eq.ctx.Unique != nil && *eq.ctx.Unique {
selector.Distinct()
}
for _, p := range eq.predicates {
p(selector)
}
for _, p := range eq.order {
p(selector)
}
if offset := eq.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 := eq.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// EmailGroupBy is the group-by builder for Email entities.
type EmailGroupBy struct {
selector
build *EmailQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (egb *EmailGroupBy) Aggregate(fns ...AggregateFunc) *EmailGroupBy {
egb.fns = append(egb.fns, fns...)
return egb
}
// Scan applies the selector query and scans the result into the given value.
func (egb *EmailGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, egb.build.ctx, ent.OpQueryGroupBy)
if err := egb.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*EmailQuery, *EmailGroupBy](ctx, egb.build, egb, egb.build.inters, v)
}
func (egb *EmailGroupBy) sqlScan(ctx context.Context, root *EmailQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(egb.fns))
for _, fn := range egb.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*egb.flds)+len(egb.fns))
for _, f := range *egb.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*egb.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := egb.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// EmailSelect is the builder for selecting fields of Email entities.
type EmailSelect struct {
*EmailQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (es *EmailSelect) Aggregate(fns ...AggregateFunc) *EmailSelect {
es.fns = append(es.fns, fns...)
return es
}
// Scan applies the selector query and scans the result into the given value.
func (es *EmailSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, es.ctx, ent.OpQuerySelect)
if err := es.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*EmailQuery, *EmailSelect](ctx, es.EmailQuery, es, es.inters, v)
}
func (es *EmailSelect) sqlScan(ctx context.Context, root *EmailQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(es.fns))
for _, fn := range es.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*es.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 := es.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

491
ent/email_update.go Normal file
View File

@ -0,0 +1,491 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"code.icod.de/auth/accountserver/ent/account"
"code.icod.de/auth/accountserver/ent/email"
"code.icod.de/auth/accountserver/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
)
// EmailUpdate is the builder for updating Email entities.
type EmailUpdate struct {
config
hooks []Hook
mutation *EmailMutation
}
// Where appends a list predicates to the EmailUpdate builder.
func (eu *EmailUpdate) Where(ps ...predicate.Email) *EmailUpdate {
eu.mutation.Where(ps...)
return eu
}
// SetEmail sets the "email" field.
func (eu *EmailUpdate) SetEmail(s string) *EmailUpdate {
eu.mutation.SetEmail(s)
return eu
}
// SetNillableEmail sets the "email" field if the given value is not nil.
func (eu *EmailUpdate) SetNillableEmail(s *string) *EmailUpdate {
if s != nil {
eu.SetEmail(*s)
}
return eu
}
// SetPrimary sets the "primary" field.
func (eu *EmailUpdate) SetPrimary(b bool) *EmailUpdate {
eu.mutation.SetPrimary(b)
return eu
}
// SetNillablePrimary sets the "primary" field if the given value is not nil.
func (eu *EmailUpdate) SetNillablePrimary(b *bool) *EmailUpdate {
if b != nil {
eu.SetPrimary(*b)
}
return eu
}
// SetVerified sets the "verified" field.
func (eu *EmailUpdate) SetVerified(b bool) *EmailUpdate {
eu.mutation.SetVerified(b)
return eu
}
// SetNillableVerified sets the "verified" field if the given value is not nil.
func (eu *EmailUpdate) SetNillableVerified(b *bool) *EmailUpdate {
if b != nil {
eu.SetVerified(*b)
}
return eu
}
// SetVerificationCode sets the "verification_code" field.
func (eu *EmailUpdate) SetVerificationCode(s string) *EmailUpdate {
eu.mutation.SetVerificationCode(s)
return eu
}
// SetNillableVerificationCode sets the "verification_code" field if the given value is not nil.
func (eu *EmailUpdate) SetNillableVerificationCode(s *string) *EmailUpdate {
if s != nil {
eu.SetVerificationCode(*s)
}
return eu
}
// ClearVerificationCode clears the value of the "verification_code" field.
func (eu *EmailUpdate) ClearVerificationCode() *EmailUpdate {
eu.mutation.ClearVerificationCode()
return eu
}
// SetResetCode sets the "reset_code" field.
func (eu *EmailUpdate) SetResetCode(s string) *EmailUpdate {
eu.mutation.SetResetCode(s)
return eu
}
// SetNillableResetCode sets the "reset_code" field if the given value is not nil.
func (eu *EmailUpdate) SetNillableResetCode(s *string) *EmailUpdate {
if s != nil {
eu.SetResetCode(*s)
}
return eu
}
// ClearResetCode clears the value of the "reset_code" field.
func (eu *EmailUpdate) ClearResetCode() *EmailUpdate {
eu.mutation.ClearResetCode()
return eu
}
// SetAccountsID sets the "accounts" edge to the Account entity by ID.
func (eu *EmailUpdate) SetAccountsID(id uuid.UUID) *EmailUpdate {
eu.mutation.SetAccountsID(id)
return eu
}
// SetNillableAccountsID sets the "accounts" edge to the Account entity by ID if the given value is not nil.
func (eu *EmailUpdate) SetNillableAccountsID(id *uuid.UUID) *EmailUpdate {
if id != nil {
eu = eu.SetAccountsID(*id)
}
return eu
}
// SetAccounts sets the "accounts" edge to the Account entity.
func (eu *EmailUpdate) SetAccounts(a *Account) *EmailUpdate {
return eu.SetAccountsID(a.ID)
}
// Mutation returns the EmailMutation object of the builder.
func (eu *EmailUpdate) Mutation() *EmailMutation {
return eu.mutation
}
// ClearAccounts clears the "accounts" edge to the Account entity.
func (eu *EmailUpdate) ClearAccounts() *EmailUpdate {
eu.mutation.ClearAccounts()
return eu
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (eu *EmailUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, eu.sqlSave, eu.mutation, eu.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (eu *EmailUpdate) SaveX(ctx context.Context) int {
affected, err := eu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (eu *EmailUpdate) Exec(ctx context.Context) error {
_, err := eu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (eu *EmailUpdate) ExecX(ctx context.Context) {
if err := eu.Exec(ctx); err != nil {
panic(err)
}
}
func (eu *EmailUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := sqlgraph.NewUpdateSpec(email.Table, email.Columns, sqlgraph.NewFieldSpec(email.FieldID, field.TypeUUID))
if ps := eu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := eu.mutation.Email(); ok {
_spec.SetField(email.FieldEmail, field.TypeString, value)
}
if value, ok := eu.mutation.Primary(); ok {
_spec.SetField(email.FieldPrimary, field.TypeBool, value)
}
if value, ok := eu.mutation.Verified(); ok {
_spec.SetField(email.FieldVerified, field.TypeBool, value)
}
if value, ok := eu.mutation.VerificationCode(); ok {
_spec.SetField(email.FieldVerificationCode, field.TypeString, value)
}
if eu.mutation.VerificationCodeCleared() {
_spec.ClearField(email.FieldVerificationCode, field.TypeString)
}
if value, ok := eu.mutation.ResetCode(); ok {
_spec.SetField(email.FieldResetCode, field.TypeString, value)
}
if eu.mutation.ResetCodeCleared() {
_spec.ClearField(email.FieldResetCode, field.TypeString)
}
if eu.mutation.AccountsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: email.AccountsTable,
Columns: []string{email.AccountsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := eu.mutation.AccountsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: email.AccountsTable,
Columns: []string{email.AccountsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if n, err = sqlgraph.UpdateNodes(ctx, eu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{email.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
eu.mutation.done = true
return n, nil
}
// EmailUpdateOne is the builder for updating a single Email entity.
type EmailUpdateOne struct {
config
fields []string
hooks []Hook
mutation *EmailMutation
}
// SetEmail sets the "email" field.
func (euo *EmailUpdateOne) SetEmail(s string) *EmailUpdateOne {
euo.mutation.SetEmail(s)
return euo
}
// SetNillableEmail sets the "email" field if the given value is not nil.
func (euo *EmailUpdateOne) SetNillableEmail(s *string) *EmailUpdateOne {
if s != nil {
euo.SetEmail(*s)
}
return euo
}
// SetPrimary sets the "primary" field.
func (euo *EmailUpdateOne) SetPrimary(b bool) *EmailUpdateOne {
euo.mutation.SetPrimary(b)
return euo
}
// SetNillablePrimary sets the "primary" field if the given value is not nil.
func (euo *EmailUpdateOne) SetNillablePrimary(b *bool) *EmailUpdateOne {
if b != nil {
euo.SetPrimary(*b)
}
return euo
}
// SetVerified sets the "verified" field.
func (euo *EmailUpdateOne) SetVerified(b bool) *EmailUpdateOne {
euo.mutation.SetVerified(b)
return euo
}
// SetNillableVerified sets the "verified" field if the given value is not nil.
func (euo *EmailUpdateOne) SetNillableVerified(b *bool) *EmailUpdateOne {
if b != nil {
euo.SetVerified(*b)
}
return euo
}
// SetVerificationCode sets the "verification_code" field.
func (euo *EmailUpdateOne) SetVerificationCode(s string) *EmailUpdateOne {
euo.mutation.SetVerificationCode(s)
return euo
}
// SetNillableVerificationCode sets the "verification_code" field if the given value is not nil.
func (euo *EmailUpdateOne) SetNillableVerificationCode(s *string) *EmailUpdateOne {
if s != nil {
euo.SetVerificationCode(*s)
}
return euo
}
// ClearVerificationCode clears the value of the "verification_code" field.
func (euo *EmailUpdateOne) ClearVerificationCode() *EmailUpdateOne {
euo.mutation.ClearVerificationCode()
return euo
}
// SetResetCode sets the "reset_code" field.
func (euo *EmailUpdateOne) SetResetCode(s string) *EmailUpdateOne {
euo.mutation.SetResetCode(s)
return euo
}
// SetNillableResetCode sets the "reset_code" field if the given value is not nil.
func (euo *EmailUpdateOne) SetNillableResetCode(s *string) *EmailUpdateOne {
if s != nil {
euo.SetResetCode(*s)
}
return euo
}
// ClearResetCode clears the value of the "reset_code" field.
func (euo *EmailUpdateOne) ClearResetCode() *EmailUpdateOne {
euo.mutation.ClearResetCode()
return euo
}
// SetAccountsID sets the "accounts" edge to the Account entity by ID.
func (euo *EmailUpdateOne) SetAccountsID(id uuid.UUID) *EmailUpdateOne {
euo.mutation.SetAccountsID(id)
return euo
}
// SetNillableAccountsID sets the "accounts" edge to the Account entity by ID if the given value is not nil.
func (euo *EmailUpdateOne) SetNillableAccountsID(id *uuid.UUID) *EmailUpdateOne {
if id != nil {
euo = euo.SetAccountsID(*id)
}
return euo
}
// SetAccounts sets the "accounts" edge to the Account entity.
func (euo *EmailUpdateOne) SetAccounts(a *Account) *EmailUpdateOne {
return euo.SetAccountsID(a.ID)
}
// Mutation returns the EmailMutation object of the builder.
func (euo *EmailUpdateOne) Mutation() *EmailMutation {
return euo.mutation
}
// ClearAccounts clears the "accounts" edge to the Account entity.
func (euo *EmailUpdateOne) ClearAccounts() *EmailUpdateOne {
euo.mutation.ClearAccounts()
return euo
}
// Where appends a list predicates to the EmailUpdate builder.
func (euo *EmailUpdateOne) Where(ps ...predicate.Email) *EmailUpdateOne {
euo.mutation.Where(ps...)
return euo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (euo *EmailUpdateOne) Select(field string, fields ...string) *EmailUpdateOne {
euo.fields = append([]string{field}, fields...)
return euo
}
// Save executes the query and returns the updated Email entity.
func (euo *EmailUpdateOne) Save(ctx context.Context) (*Email, error) {
return withHooks(ctx, euo.sqlSave, euo.mutation, euo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (euo *EmailUpdateOne) SaveX(ctx context.Context) *Email {
node, err := euo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (euo *EmailUpdateOne) Exec(ctx context.Context) error {
_, err := euo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (euo *EmailUpdateOne) ExecX(ctx context.Context) {
if err := euo.Exec(ctx); err != nil {
panic(err)
}
}
func (euo *EmailUpdateOne) sqlSave(ctx context.Context) (_node *Email, err error) {
_spec := sqlgraph.NewUpdateSpec(email.Table, email.Columns, sqlgraph.NewFieldSpec(email.FieldID, field.TypeUUID))
id, ok := euo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Email.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := euo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, email.FieldID)
for _, f := range fields {
if !email.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != email.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := euo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := euo.mutation.Email(); ok {
_spec.SetField(email.FieldEmail, field.TypeString, value)
}
if value, ok := euo.mutation.Primary(); ok {
_spec.SetField(email.FieldPrimary, field.TypeBool, value)
}
if value, ok := euo.mutation.Verified(); ok {
_spec.SetField(email.FieldVerified, field.TypeBool, value)
}
if value, ok := euo.mutation.VerificationCode(); ok {
_spec.SetField(email.FieldVerificationCode, field.TypeString, value)
}
if euo.mutation.VerificationCodeCleared() {
_spec.ClearField(email.FieldVerificationCode, field.TypeString)
}
if value, ok := euo.mutation.ResetCode(); ok {
_spec.SetField(email.FieldResetCode, field.TypeString, value)
}
if euo.mutation.ResetCodeCleared() {
_spec.ClearField(email.FieldResetCode, field.TypeString)
}
if euo.mutation.AccountsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: email.AccountsTable,
Columns: []string{email.AccountsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := euo.mutation.AccountsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: email.AccountsTable,
Columns: []string{email.AccountsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Email{config: euo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, euo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{email.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
euo.mutation.done = true
return _node, nil
}

610
ent/ent.go Normal file
View File

@ -0,0 +1,610 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"code.icod.de/auth/accountserver/ent/account"
"code.icod.de/auth/accountserver/ent/email"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// ent aliases to avoid import conflicts in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
QueryContext = ent.QueryContext
Querier = ent.Querier
QuerierFunc = ent.QuerierFunc
Interceptor = ent.Interceptor
InterceptFunc = ent.InterceptFunc
Traverser = ent.Traverser
TraverseFunc = ent.TraverseFunc
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
type clientCtxKey struct{}
// FromContext returns a Client stored inside a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(clientCtxKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, clientCtxKey{}, c)
}
type txCtxKey struct{}
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
func TxFromContext(ctx context.Context) *Tx {
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
return tx
}
// NewTxContext returns a new context with the given Tx attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}
// OrderFunc applies an ordering on the sql selector.
// Deprecated: Use Asc/Desc functions or the package builders instead.
type OrderFunc func(*sql.Selector)
var (
initCheck sync.Once
columnCheck sql.ColumnCheck
)
// checkColumn checks if the column exists in the given table.
func checkColumn(table, column string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
account.Table: account.ValidColumn,
email.Table: email.ValidColumn,
})
})
return columnCheck(table, column)
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Asc(s.C(f)))
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Desc(s.C(f)))
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string {
return sql.As(fn(s), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return sql.Count("*")
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Max(s.C(field))
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Avg(s.C(field))
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Min(s.C(field))
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Sum(s.C(field))
}
}
// ValidationError returns when validating a field or edge fails.
type ValidationError struct {
Name string // Field or edge name.
err error
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.err.Error()
}
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validation error.
func IsValidationError(err error) bool {
if err == nil {
return false
}
var e *ValidationError
return errors.As(err, &e)
}
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
type NotFoundError struct {
label string
}
// Error implements the error interface.
func (e *NotFoundError) Error() string {
return "ent: " + e.label + " not found"
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
if err == nil {
return false
}
var e *NotFoundError
return errors.As(err, &e)
}
// MaskNotFound masks not found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
type NotSingularError struct {
label string
}
// Error implements the error interface.
func (e *NotSingularError) Error() string {
return "ent: " + e.label + " not singular"
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
if err == nil {
return false
}
var e *NotSingularError
return errors.As(err, &e)
}
// NotLoadedError returns when trying to get a node that was not loaded by the query.
type NotLoadedError struct {
edge string
}
// Error implements the error interface.
func (e *NotLoadedError) Error() string {
return "ent: " + e.edge + " edge was not loaded"
}
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotLoaded(err error) bool {
if err == nil {
return false
}
var e *NotLoadedError
return errors.As(err, &e)
}
// ConstraintError returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or
// field uniqueness.
type ConstraintError struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ConstraintError) Error() string {
return "ent: constraint failed: " + e.msg
}
// Unwrap implements the errors.Wrapper interface.
func (e *ConstraintError) Unwrap() error {
return e.wrap
}
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsConstraintError(err error) bool {
if err == nil {
return false
}
var e *ConstraintError
return errors.As(err, &e)
}
// selector embedded by the different Select/GroupBy builders.
type selector struct {
label string
flds *[]string
fns []AggregateFunc
scan func(context.Context, any) error
}
// ScanX is like Scan, but panics if an error occurs.
func (s *selector) ScanX(ctx context.Context, v any) {
if err := s.scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (s *selector) Strings(ctx context.Context) ([]string, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (s *selector) StringsX(ctx context.Context) []string {
v, err := s.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (s *selector) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = s.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (s *selector) StringX(ctx context.Context) string {
v, err := s.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (s *selector) Ints(ctx context.Context) ([]int, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (s *selector) IntsX(ctx context.Context) []int {
v, err := s.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (s *selector) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = s.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (s *selector) IntX(ctx context.Context) int {
v, err := s.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (s *selector) Float64sX(ctx context.Context) []float64 {
v, err := s.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = s.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (s *selector) Float64X(ctx context.Context) float64 {
v, err := s.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (s *selector) BoolsX(ctx context.Context) []bool {
v, err := s.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = s.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (s *selector) BoolX(ctx context.Context) bool {
v, err := s.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
// withHooks invokes the builder operation with the given hooks, if any.
func withHooks[V Value, M any, PM interface {
*M
Mutation
}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
if len(hooks) == 0 {
return exec(ctx)
}
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutationT, ok := any(m).(PM)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
// Set the mutation to the builder.
*mutation = *mutationT
return exec(ctx)
})
for i := len(hooks) - 1; i >= 0; i-- {
if hooks[i] == nil {
return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = hooks[i](mut)
}
v, err := mut.Mutate(ctx, mutation)
if err != nil {
return value, err
}
nv, ok := v.(V)
if !ok {
return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
}
return nv, nil
}
// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
if ent.QueryFromContext(ctx) == nil {
qc.Op = op
ctx = ent.NewQueryContext(ctx, qc)
}
return ctx
}
func querierAll[V Value, Q interface {
sqlAll(context.Context, ...queryHook) (V, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlAll(ctx)
})
}
func querierCount[Q interface {
sqlCount(context.Context) (int, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlCount(ctx)
})
}
func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
rv, err := qr.Query(ctx, q)
if err != nil {
return v, err
}
vt, ok := rv.(V)
if !ok {
return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
}
return vt, nil
}
func scanWithInterceptors[Q1 ent.Query, Q2 interface {
sqlScan(context.Context, Q1, any) error
}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
rv := reflect.ValueOf(v)
var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q1)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
return nil, err
}
if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
return rv.Elem().Interface(), nil
}
return v, nil
})
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
vv, err := qr.Query(ctx, rootQuery)
if err != nil {
return err
}
switch rv2 := reflect.ValueOf(vv); {
case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
case rv.Type() == rv2.Type():
rv.Elem().Set(rv2.Elem())
case rv.Elem().Type() == rv2.Type():
rv.Elem().Set(rv2)
}
return nil
}
// queryHook describes an internal hook for the different sqlAll methods.
type queryHook func(context.Context, *sqlgraph.QuerySpec)

84
ent/enttest/enttest.go Normal file
View File

@ -0,0 +1,84 @@
// Code generated by ent, DO NOT EDIT.
package enttest
import (
"context"
"code.icod.de/auth/accountserver/ent"
// required by schema hooks.
_ "code.icod.de/auth/accountserver/ent/runtime"
"code.icod.de/auth/accountserver/ent/migrate"
"entgo.io/ent/dialect/sql/schema"
)
type (
// TestingT is the interface that is shared between
// testing.T and testing.B and used by enttest.
TestingT interface {
FailNow()
Error(...any)
}
// Option configures client creation.
Option func(*options)
options struct {
opts []ent.Option
migrateOpts []schema.MigrateOption
}
)
// WithOptions forwards options to client creation.
func WithOptions(opts ...ent.Option) Option {
return func(o *options) {
o.opts = append(o.opts, opts...)
}
}
// WithMigrateOptions forwards options to auto migration.
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
return func(o *options) {
o.migrateOpts = append(o.migrateOpts, opts...)
}
}
func newOptions(opts []Option) *options {
o := &options{}
for _, opt := range opts {
opt(o)
}
return o
}
// Open calls ent.Open and auto-run migration.
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client {
o := newOptions(opts)
c, err := ent.Open(driverName, dataSourceName, o.opts...)
if err != nil {
t.Error(err)
t.FailNow()
}
migrateSchema(t, c, o)
return c
}
// NewClient calls ent.NewClient and auto-run migration.
func NewClient(t TestingT, opts ...Option) *ent.Client {
o := newOptions(opts)
c := ent.NewClient(o.opts...)
migrateSchema(t, c, o)
return c
}
func migrateSchema(t TestingT, c *ent.Client, o *options) {
tables, err := schema.CopyTables(migrate.Tables)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
}

211
ent/hook/hook.go Normal file
View File

@ -0,0 +1,211 @@
// Code generated by ent, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"code.icod.de/auth/accountserver/ent"
)
// The AccountFunc type is an adapter to allow the use of ordinary
// function as Account mutator.
type AccountFunc func(context.Context, *ent.AccountMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f AccountFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.AccountMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AccountMutation", m)
}
// The EmailFunc type is an adapter to allow the use of ordinary
// function as Email mutator.
type EmailFunc func(context.Context, *ent.EmailMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f EmailFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.EmailMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.EmailMutation", m)
}
// Condition is a hook condition function.
type Condition func(context.Context, ent.Mutation) bool
// And groups conditions with the AND operator.
func And(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if !first(ctx, m) || !second(ctx, m) {
return false
}
for _, cond := range rest {
if !cond(ctx, m) {
return false
}
}
return true
}
}
// Or groups conditions with the OR operator.
func Or(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if first(ctx, m) || second(ctx, m) {
return true
}
for _, cond := range rest {
if cond(ctx, m) {
return true
}
}
return false
}
}
// Not negates a given condition.
func Not(cond Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
return !cond(ctx, m)
}
}
// HasOp is a condition testing mutation operation.
func HasOp(op ent.Op) Condition {
return func(_ context.Context, m ent.Mutation) bool {
return m.Op().Is(op)
}
}
// HasAddedFields is a condition validating `.AddedField` on fields.
func HasAddedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.AddedField(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.AddedField(field); !exists {
return false
}
}
return true
}
}
// HasClearedFields is a condition validating `.FieldCleared` on fields.
func HasClearedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if exists := m.FieldCleared(field); !exists {
return false
}
for _, field := range fields {
if exists := m.FieldCleared(field); !exists {
return false
}
}
return true
}
}
// HasFields is a condition validating `.Field` on fields.
func HasFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.Field(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.Field(field); !exists {
return false
}
}
return true
}
}
// If executes the given hook under condition.
//
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
func If(hk ent.Hook, cond Condition) ent.Hook {
return func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if cond(ctx, m) {
return hk(next).Mutate(ctx, m)
}
return next.Mutate(ctx, m)
})
}
}
// On executes the given hook only for the given operation.
//
// hook.On(Log, ent.Delete|ent.Create)
func On(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, HasOp(op))
}
// Unless skips the given hook only for the given operation.
//
// hook.Unless(Log, ent.Update|ent.UpdateOne)
func Unless(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, Not(HasOp(op)))
}
// FixedError is a hook returning a fixed error.
func FixedError(err error) ent.Hook {
return func(ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) {
return nil, err
})
}
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []ent.Hook {
// return []ent.Hook{
// Reject(ent.Delete|ent.Update),
// }
// }
func Reject(op ent.Op) ent.Hook {
hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
return On(hk, op)
}
// Chain acts as a list of hooks and is effectively immutable.
// Once created, it will always hold the same set of hooks in the same order.
type Chain struct {
hooks []ent.Hook
}
// NewChain creates a new chain of hooks.
func NewChain(hooks ...ent.Hook) Chain {
return Chain{append([]ent.Hook(nil), hooks...)}
}
// Hook chains the list of hooks and returns the final hook.
func (c Chain) Hook() ent.Hook {
return func(mutator ent.Mutator) ent.Mutator {
for i := len(c.hooks) - 1; i >= 0; i-- {
mutator = c.hooks[i](mutator)
}
return mutator
}
}
// Append extends a chain, adding the specified hook
// as the last ones in the mutation flow.
func (c Chain) Append(hooks ...ent.Hook) Chain {
newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks))
newHooks = append(newHooks, c.hooks...)
newHooks = append(newHooks, hooks...)
return Chain{newHooks}
}
// Extend extends a chain, adding the specified chain
// as the last ones in the mutation flow.
func (c Chain) Extend(chain Chain) Chain {
return c.Append(chain.hooks...)
}

64
ent/migrate/migrate.go Normal file
View File

@ -0,0 +1,64 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
}
// NewSchema creates a new schema client.
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
return Create(ctx, s, Tables, opts...)
}
// Create creates all table resources using the given schema driver.
func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, tables...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
//
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err)
// }
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
}

61
ent/migrate/schema.go Normal file
View File

@ -0,0 +1,61 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// AccountsColumns holds the columns for the "accounts" table.
AccountsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID, Unique: true, Default: "gen_random_uuid()"},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "nickname", Type: field.TypeString},
{Name: "name", Type: field.TypeString},
{Name: "secret", Type: field.TypeBytes},
{Name: "aes", Type: field.TypeBytes, Size: 32},
{Name: "x509", Type: field.TypeBytes},
}
// AccountsTable holds the schema information for the "accounts" table.
AccountsTable = &schema.Table{
Name: "accounts",
Columns: AccountsColumns,
PrimaryKey: []*schema.Column{AccountsColumns[0]},
}
// EmailsColumns holds the columns for the "emails" table.
EmailsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID, Unique: true, Default: "gen_random_uuid()"},
{Name: "email", Type: field.TypeString},
{Name: "primary", Type: field.TypeBool, Default: false},
{Name: "verified", Type: field.TypeBool, Default: false},
{Name: "verification_code", Type: field.TypeString, Nullable: true},
{Name: "reset_code", Type: field.TypeString, Nullable: true},
{Name: "account_emails", Type: field.TypeUUID, Nullable: true},
}
// EmailsTable holds the schema information for the "emails" table.
EmailsTable = &schema.Table{
Name: "emails",
Columns: EmailsColumns,
PrimaryKey: []*schema.Column{EmailsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "emails_accounts_emails",
Columns: []*schema.Column{EmailsColumns[6]},
RefColumns: []*schema.Column{AccountsColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
AccountsTable,
EmailsTable,
}
)
func init() {
EmailsTable.ForeignKeys[0].RefTable = AccountsTable
}

1436
ent/mutation.go Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,13 @@
// Code generated by ent, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// Account is the predicate function for account builders.
type Account func(*sql.Selector)
// Email is the predicate function for email builders.
type Email func(*sql.Selector)

57
ent/runtime.go Normal file
View File

@ -0,0 +1,57 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"time"
"code.icod.de/auth/accountserver/ent/account"
"code.icod.de/auth/accountserver/ent/email"
"code.icod.de/auth/accountserver/ent/schema"
)
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
accountFields := schema.Account{}.Fields()
_ = accountFields
// accountDescCreatedAt is the schema descriptor for created_at field.
accountDescCreatedAt := accountFields[1].Descriptor()
// account.DefaultCreatedAt holds the default value on creation for the created_at field.
account.DefaultCreatedAt = accountDescCreatedAt.Default.(func() time.Time)
// accountDescUpdatedAt is the schema descriptor for updated_at field.
accountDescUpdatedAt := accountFields[2].Descriptor()
// account.DefaultUpdatedAt holds the default value on creation for the updated_at field.
account.DefaultUpdatedAt = accountDescUpdatedAt.Default.(func() time.Time)
// account.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
account.UpdateDefaultUpdatedAt = accountDescUpdatedAt.UpdateDefault.(func() time.Time)
// accountDescAes is the schema descriptor for aes field.
accountDescAes := accountFields[6].Descriptor()
// account.AesValidator is a validator for the "aes" field. It is called by the builders before save.
account.AesValidator = func() func([]byte) error {
validators := accountDescAes.Validators
fns := [...]func([]byte) error{
validators[0].(func([]byte) error),
validators[1].(func([]byte) error),
}
return func(aes []byte) error {
for _, fn := range fns {
if err := fn(aes); err != nil {
return err
}
}
return nil
}
}()
emailFields := schema.Email{}.Fields()
_ = emailFields
// emailDescPrimary is the schema descriptor for primary field.
emailDescPrimary := emailFields[2].Descriptor()
// email.DefaultPrimary holds the default value on creation for the primary field.
email.DefaultPrimary = emailDescPrimary.Default.(bool)
// emailDescVerified is the schema descriptor for verified field.
emailDescVerified := emailFields[3].Descriptor()
// email.DefaultVerified holds the default value on creation for the verified field.
email.DefaultVerified = emailDescVerified.Default.(bool)
}

10
ent/runtime/runtime.go Normal file
View File

@ -0,0 +1,10 @@
// Code generated by ent, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in code.icod.de/auth/accountserver/ent/runtime.go
const (
Version = "v0.14.0" // Version of ent codegen.
Sum = "h1:EO3Z9aZ5bXJatJeGqu/EVdnNr6K4mRq3rWe5owt0MC4=" // Sum of ent codegen.
)

213
ent/tx.go Normal file
View File

@ -0,0 +1,213 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Account is the client for interacting with the Account builders.
Account *AccountClient
// Email is the client for interacting with the Email builders.
Email *EmailClient
// lazily loaded.
client *Client
clientOnce sync.Once
// ctx lives for the life of the transaction. It is
// the same context used by the underlying connection.
ctx context.Context
}
type (
// Committer is the interface that wraps the Commit method.
Committer interface {
Commit(context.Context, *Tx) error
}
// The CommitFunc type is an adapter to allow the use of ordinary
// function as a Committer. If f is a function with the appropriate
// signature, CommitFunc(f) is a Committer that calls f.
CommitFunc func(context.Context, *Tx) error
// CommitHook defines the "commit middleware". A function that gets a Committer
// and returns a Committer. For example:
//
// hook := func(next ent.Committer) ent.Committer {
// return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Commit(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
CommitHook func(Committer) Committer
)
// Commit calls f(ctx, m).
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
txDriver := tx.config.driver.(*txDriver)
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
return txDriver.tx.Commit()
})
txDriver.mu.Lock()
hooks := append([]CommitHook(nil), txDriver.onCommit...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Commit(tx.ctx, tx)
}
// OnCommit adds a hook to call on commit.
func (tx *Tx) OnCommit(f CommitHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onCommit = append(txDriver.onCommit, f)
txDriver.mu.Unlock()
}
type (
// Rollbacker is the interface that wraps the Rollback method.
Rollbacker interface {
Rollback(context.Context, *Tx) error
}
// The RollbackFunc type is an adapter to allow the use of ordinary
// function as a Rollbacker. If f is a function with the appropriate
// signature, RollbackFunc(f) is a Rollbacker that calls f.
RollbackFunc func(context.Context, *Tx) error
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
// and returns a Rollbacker. For example:
//
// hook := func(next ent.Rollbacker) ent.Rollbacker {
// return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Rollback(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
RollbackHook func(Rollbacker) Rollbacker
)
// Rollback calls f(ctx, m).
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
txDriver := tx.config.driver.(*txDriver)
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
return txDriver.tx.Rollback()
})
txDriver.mu.Lock()
hooks := append([]RollbackHook(nil), txDriver.onRollback...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Rollback(tx.ctx, tx)
}
// OnRollback adds a hook to call on rollback.
func (tx *Tx) OnRollback(f RollbackHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onRollback = append(txDriver.onRollback, f)
txDriver.mu.Unlock()
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
tx.clientOnce.Do(func() {
tx.client = &Client{config: tx.config}
tx.client.init()
})
return tx.client
}
func (tx *Tx) init() {
tx.Account = NewAccountClient(tx.config)
tx.Email = NewEmailClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// 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: Account.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
type txDriver struct {
// the driver we started the transaction from.
drv dialect.Driver
// tx is the underlying transaction.
tx dialect.Tx
// completion hooks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
}
// newTx creates a new transactional driver.
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
tx, err := drv.Tx(ctx)
if err != nil {
return nil, err
}
return &txDriver{tx: tx, drv: drv}, nil
}
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
// from the internal builders. Should be called only by the internal builders.
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
// Dialect returns the dialect of the driver we started the transaction from.
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
// Close is a nop close.
func (*txDriver) Close() error { return nil }
// Commit is a nop commit for the internal builders.
// User must call `Tx.Commit` in order to commit the transaction.
func (*txDriver) Commit() error { return nil }
// Rollback is a nop rollback for the internal builders.
// User must call `Tx.Rollback` in order to rollback the transaction.
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)

28
go.sum
View File

@ -1,14 +1,32 @@
ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43 h1:GwdJbXydHCYPedeeLt4x/lrlIISQ4JTH1mRWuE5ZZ14=
ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43/go.mod h1:uj3pm+hUTVN/X5yfdBexHlZv+1Xu5u5ZbZx7+CDavNU=
entgo.io/ent v0.14.0 h1:EO3Z9aZ5bXJatJeGqu/EVdnNr6K4mRq3rWe5owt0MC4=
entgo.io/ent v0.14.0/go.mod h1:qCEmo+biw3ccBn9OyL4ZK5dfpwg++l1Gxwac5B1206A=
github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8=
github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw=
github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4=
github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/hcl/v2 v2.13.0 h1:0Apadu1w6M11dyGFxWnmhhcMjkbAiKCv7G1r/2QgCNc=
github.com/hashicorp/hcl/v2 v2.13.0/go.mod h1:e4z5nxYlWNPdDSNYX+ph14EvWYMFm3eP0zIUqPc2jr0=
github.com/idc77/gomail v0.0.0-20240819113050-ac97008b42eb h1:eoCCdEgNvIAO3+sb7drW2gV36JOkILxyJllfEUHoo1A=
github.com/idc77/gomail v0.0.0-20240819113050-ac97008b42eb/go.mod h1:iRMDvqBOUICvDAsSzKcIBfFLghLJ1EeXBe6tH7Mmv6U=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM=
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
@ -18,6 +36,16 @@ github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/zclconf/go-cty v1.8.0 h1:s4AvqaeQzJIu3ndv4gVIhplVD0krU+bgrcLSVUnaWuA=
github.com/zclconf/go-cty v1.8.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk=
golang.org/x/mod v0.15.0 h1:SernR4v+D55NyBH2QiEQrlBAnj1ECL6AGrA5+dPaMY8=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/tools v0.18.0 h1:k8NLag8AGHnn+PHbl7g43CtqZAwG60vZkLqgyZgIHgQ=
golang.org/x/tools v0.18.0/go.mod h1:GL7B4CwcLLeo59yx/9UWWuNOW1n3VZ4f5axWfML7Lcg=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=